hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
23413e6c24b97a74d161d0f5d41c54e012d485c2
883
// // WAColligateController.swift // OSChina // // Created by walker on 2017/11/7. // Copyright © 2017年 walker. All rights reserved. // import UIKit class WAColligateController: WAViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // 设置UI setupUI() } } // MARK: - 设置页面 extension WAColligateController { /// 设置UI private func setupUI() { // 设置导航栏 setupNavigation() } // 添加collectionview /// 设置导航栏 private func setupNavigation() { let searchButton = UIButton() searchButton.setImage(UIImage(named:"navigationbar-search"), for: UIControlState.normal) searchButton.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchButton) } }
21.02381
96
0.622877
fbd963c101a49f9183e32cdcffbe93236303d8b4
4,354
// // ViewController.swift // iSpend-iOS // // Created by Srdjan Tubin on 21.09.19. // Copyright © 2019 serj. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var tfUsername: UITextField! @IBOutlet weak var tfPassword: UITextField! @IBOutlet weak var btnLogin: UIButton! override func viewDidLoad() { super.viewDidLoad() tfUsername.delegate = self tfPassword.delegate = self } @IBAction func login(_ sender: Any) { doLogin { result in switch result { case .success(let response): print(response) self.showMessage(title: "iSpend Login Success", message: response) case .failure(let error): print(error.localizedDescription) self.showMessage(title: "iSpend Login Error", message: error.localizedDescription) } } } func doLogin(completion: @escaping (Result<String, Error>) -> Void) { let username = tfUsername.text! let password = tfPassword.text! if (username == "" || password == "") { showMessage(title: "iSpend Login", message: "Error! Credentials empty.") return } let url = URL(string: "http://www.serjspends.de/users/login")! var request = URLRequest(url: url) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let parameters: [String: Any] = [ "username": username, "password": password ] request.httpBody = parameters.percentEscaped().data(using: .utf8) URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { DispatchQueue.main.async { completion(.failure(error)) } return } guard let data = data, let response = response as? HTTPURLResponse, error == nil else { // check for fundamental networking error print("error", error ?? "Unknown error") return } guard (200 ... 299) ~= response.statusCode else { // check for http errors print("statusCode should be 2xx, but is \(response.statusCode)") print("response = \(response)") return } let responseString = String(data: data, encoding: .utf8) print("responseString = \(responseString!)") DispatchQueue.main.async { completion(.success(responseString!)) } }.resume() } func showMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: .default)) self.present(alertController, animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { tfUsername.resignFirstResponder() tfPassword.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { //labelField.text = inputTextField.text } } extension Dictionary { func percentEscaped() -> String { return map { (key, value) in let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" return escapedKey + "=" + escapedValue } .joined(separator: "&") } } extension CharacterSet { static let urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed = CharacterSet.urlQueryAllowed allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") return allowed }() }
35.983471
122
0.580156
e43f331879e404591a650b71f8854e97c2b0abe0
1,079
// // SifVsIncentive.swift // Cosmostation // // Created by 정용주 on 2021/06/22. // Copyright © 2021 wannabit. All rights reserved. // import Foundation public struct SifIncentive { var user: SifUserIncentive? init(_ dictionary: NSDictionary?) { if let rawUser = dictionary?["user"] as? NSDictionary { self.user = SifUserIncentive.init(rawUser) } } } public struct SifUserIncentive { var totalClaimableCommissionsAndClaimableRewards: Double? var totalRewardsOnDepositedAssetsAtMaturity: Double? var maturityAPY: Double? var maturityDateISO: String? init(_ dictionary: NSDictionary?) { self.totalClaimableCommissionsAndClaimableRewards = dictionary?["totalClaimableCommissionsAndClaimableRewards"] as? Double ?? 0 self.totalRewardsOnDepositedAssetsAtMaturity = dictionary?["totalRewardsOnDepositedAssetsAtMaturity"] as? Double ?? 0 self.maturityAPY = dictionary?["maturityAPY"] as? Double ?? 0 self.maturityDateISO = dictionary?["maturityDateISO"] as? String ?? "" } }
31.735294
135
0.70899
d6dd3abf7eb03ddd89777faf7c0375c0e4d35ee0
694
// swift-tools-version:5.0 import Foundation import PackageDescription let package = Package( name: "SnapshotTesting", platforms: [ .iOS(.v10), .macOS(.v10_10), .tvOS(.v10) ], products: [ .library( name: "SnapshotTesting", targets: ["SnapshotTesting"]), ], targets: [ .target( name: "SnapshotTesting", dependencies: []), .testTarget( name: "SnapshotTestingTests", dependencies: ["SnapshotTesting"]), ] ) if ProcessInfo.processInfo.environment.keys.contains("PF_DEVELOP") { package.dependencies.append( contentsOf: [ .package(url: "https://github.com/yonaskolb/XcodeGen.git", .exact("2.13.1")), ] ) }
20.411765
83
0.62536
480f9c8563fe2063ac9d51c38cc5506cbffa0a53
1,565
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public class ConstraintMakerFinalizable { internal let description: ConstraintDescription internal init(_ description: ConstraintDescription) { self.description = description } public var constraint: Constraint { return self.description.constraint! } }
35.568182
81
0.729712
918be06671ec84004e594a715606ae7e451ab4fd
3,077
// // iBeaconPacket.swift // BluenetLibIOS // // Created by Alex de Mulder on 17/06/16. // Copyright © 2016 Alex de Mulder. All rights reserved. // import Foundation import CoreLocation import SwiftyJSON import BluenetShared open class iBeaconContainer { var UUID : Foundation.UUID; var referenceId = "" var region : CLBeaconRegion var major : CLBeaconMajorValue? var minor : CLBeaconMinorValue? public init(referenceId: String, uuid: String) { self.UUID = Foundation.UUID(uuidString : uuid)! self.referenceId = referenceId self.region = CLBeaconRegion(proximityUUID: self.UUID, identifier: referenceId) } public init(referenceId: String, uuid: String, major: NSNumber) { self.UUID = Foundation.UUID(uuidString : uuid)! self.referenceId = referenceId self.major = major.uint16Value self.region = CLBeaconRegion(proximityUUID: self.UUID, major: self.major!, identifier: referenceId) } public init(referenceId: String, uuid: String, major: NSNumber, minor: NSNumber) { self.UUID = Foundation.UUID(uuidString : uuid)! self.referenceId = referenceId self.major = major.uint16Value self.minor = minor.uint16Value self.region = CLBeaconRegion(proximityUUID: self.UUID, major: self.major!, minor: self.minor!, identifier: referenceId) } } open class iBeaconPacket: iBeaconPacketProtocol { open var uuid : String open var major: NSNumber open var minor: NSNumber open var rssi : NSNumber open var distance : NSNumber open var idString: String open var referenceId: String init(uuid: String, major: NSNumber, minor: NSNumber, distance: NSNumber, rssi: NSNumber, referenceId: String) { self.uuid = uuid self.major = major self.minor = minor self.rssi = rssi self.distance = distance self.referenceId = referenceId // we claim that the uuid, major and minor combination is unique. self.idString = uuid + ".Maj:" + String(describing: major) + ".Min:" + String(describing: minor) } open func getJSON() -> JSON { var dataDict = [String : Any]() dataDict["id"] = self.idString dataDict["uuid"] = self.uuid dataDict["major"] = self.major dataDict["minor"] = self.minor dataDict["distance"] = self.distance dataDict["rssi"] = self.rssi dataDict["referenceId"] = self.referenceId return JSON(dataDict) } open func stringify() -> String { return JSONUtils.stringify(self.getJSON()) } open func getDictionary() -> NSDictionary { let returnDict : [String: Any] = [ "id" : self.idString, "uuid" : self.uuid, "major" : self.major, "minor" : self.minor, "rssi" : self.rssi, "distance" : self.distance, "referenceId" : self.referenceId, ] return returnDict as NSDictionary } }
32.734043
127
0.624309
896e929905c041079768e38211a77289d26f8d6f
1,086
/** * SimLib * Copyright (c) Andrii Myk 2020 * Licensed under the MIT license (see LICENSE file) */ import Foundation public struct Simulator: Decodable { public enum State: String, Decodable { case shutdown = "Shutdown" case booted = "Booted" } public let state: State public let name: String public let udid: String public let isAvailable: Bool public let runtime: String public let availabilityError: String? } extension Simulator { init?(runtime: String, dictionary: [String: Any]) { guard let state = State(rawValue: dictionary["state"] as? String ?? ""), let udid = dictionary["udid"] as? String, let name = dictionary["name"] as? String, let isAvailable = dictionary["isAvailable"] as? Bool else { return nil } self.runtime = runtime self.name = name self.state = state self.udid = udid self.isAvailable = isAvailable self.availabilityError = dictionary["availabilityError"] as? String } }
25.857143
80
0.616022
f4533318872a36bcf5e1a05e4e5c4572315af44f
1,152
//// Copyright 2019 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import ArcGIS extension AGSPopupAttachmentSize { private static let userDefaultsKey = "AGSPopupAttachmentSize.StaticUserDefaultKey" func storeDefaultPopupAttachmentSize() { UserDefaults.standard.set(self.rawValue, forKey: AGSPopupAttachmentSize.userDefaultsKey) } static func retrieveDefaultPopupAttachmentSize() -> AGSPopupAttachmentSize { let storedRaw = UserDefaults.standard.integer(forKey: AGSPopupAttachmentSize.userDefaultsKey) return AGSPopupAttachmentSize(rawValue: storedRaw) ?? .actual } }
37.16129
101
0.747396
ebd34b81a17c10b5660ef7fd3314b32fd19c5a8e
4,319
// // Result+Alamofire.swift // // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// `Result` that always has an `Error` `Failure` type. public typealias AFResult<T> = Result<T, Error> // MARK: - Internal APIs extension Result { /// Returns the associated value if the result is a success, `nil` otherwise. var success: Success? { guard case .success(let value) = self else { return nil } return value } /// Returns the associated error value if the result is a failure, `nil` otherwise. var failure: Failure? { guard case .failure(let error) = self else { return nil } return error } /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. /// /// - Parameters: /// - value: A value. /// - error: An `Error`. init(value: Success, error: Failure?) { if let error = error { self = .failure(error) } else { self = .success(value) } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: Result<Data, Error> = .success(Data(...)) /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> Result<NewSuccess, Error> { switch self { case .success(let value): do { return try .success(transform(value)) } catch { return .failure(error) } case .failure(let error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: Result<Data, Error> = .success(Data(...)) /// let possibleObject = possibleData.tryMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same success. func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> Result<Success, Error> { switch self { case .failure(let error): do { return try .failure(transform(error)) } catch { return .failure(error) } case .success(let value): return .success(value) } } }
39.263636
117
0.628849
d510f13b203b59996d47c23db1bb1f9bb868ca9c
285
import Foundation import ArgumentParser import SignalHandling struct ConditionLock : ParsableCommand { func run() throws { try Sigaction(handler: .ansiC({ _ in ConditionLock.exit() })).install(on: .terminated) NSConditionLock(condition: 0).lock(whenCondition: 1) } }
15.833333
88
0.733333
ff1ddae15528e72036d6660b010365d0fed8ec88
260
// // CZSignedNumericExtension.swift // letaoshijie // // Created by chaozheng on 2021/10/11. // import Foundation public extension SignedNumeric { /// SwifterSwift: String. var cz_string: String { return String(describing: self) } }
15.294118
39
0.669231
ccb2c04b93a4a43d5a6a4eb32d2a9d652c865254
1,192
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * * 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 private class NKDateFormatter { static var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) return dateFormatter }() } extension NSDate { func toJSONDate() -> NSString { return NKDateFormatter.dateFormatter.stringFromDate(self) } }
25.361702
74
0.693792
699ade766a5fa54f3870cb888b9d6250b7bdf1a0
205
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(FormworksTests.allTests), testCase(ManualLayoutTests.allTests), ] } #endif
18.636364
45
0.682927
3974eb8364483f8bbfdac5b6ba66b006b2db5dc4
22,966
// // Array+ExtendedCBORWebTokenTests.swift // // // Created by Thomas Kuleßa on 23.02.22. // @testable import CovPassCommon import XCTest class ArrayExtendedCBORWebTokenTests: XCTestCase { var singleDoseImmunizationJohnsonCert = CBORWebToken.mockVaccinationCertificate .mockVaccinationUVCI("1") .medicalProduct(.johnsonjohnson) .doseNumber(1) .seriesOfDoses(1) .extended(vaccinationQRCodeData: "1") var doubleDoseImmunizationJohnsonCert = CBORWebToken.mockVaccinationCertificate .mockVaccinationUVCI("1") .medicalProduct(.johnsonjohnson) .doseNumber(2) .seriesOfDoses(2) .extended(vaccinationQRCodeData: "1") var vaccinationWithTwoShotsOfVaccine = CBORWebToken.mockVaccinationCertificate .mockVaccinationUVCI("2") .medicalProduct(.biontech) .doseNumber(2) .seriesOfDoses(2) .extended(vaccinationQRCodeData: "2") let recoveryCert = CBORWebToken.mockRecoveryCertificate .mockRecoveryUVCI("3") .extended(vaccinationQRCodeData: "3") var someOtherCert1 = CBORWebToken.mockVaccinationCertificate .mockVaccinationUVCI("4") .medicalProduct(.biontech) .doseNumber(1) .seriesOfDoses(2) .extended(vaccinationQRCodeData: "4") var someOtherCert2 = CBORWebToken.mockTestCertificate .mockTestUVCI("5") .extended(vaccinationQRCodeData: "5") let recoveryCert2 = CBORWebToken.mockRecoveryCertificate .mockRecoveryUVCI("6") .extended(vaccinationQRCodeData: "6") let boosterCertificateAfterReIssue = CBORWebToken.mockVaccinationCertificate .mockVaccinationUVCI("7") .medicalProduct(.biontech) .doseNumber(2) .seriesOfDoses(1) .extended(vaccinationQRCodeData: "7") func testPartitionedByOwner_empty() { // Given let sut: [ExtendedCBORWebToken] = [] // When let partitions = sut.partitionedByOwner // Then XCTAssertTrue(partitions.isEmpty) } func testPartitionedByOwner() { // Given var token1Owner1 = CBORWebToken.mockVaccinationCertificate var token2Owner1 = CBORWebToken.mockVaccinationCertificate var tokenOwner2 = CBORWebToken.mockVaccinationCertificate var tokenOwner3 = CBORWebToken.mockVaccinationCertificate token1Owner1.hcert.dgc = .mock(name: .mustermann()) token2Owner1.hcert.dgc = .mock(name: .mustermann()) tokenOwner2.hcert.dgc = .mock(name: .yildirim()) tokenOwner3.hcert.dgc = .mock(name: .mustermann(), dob: Date()) let sut = [ token1Owner1.extended(), token2Owner1.extended(), tokenOwner2.extended(), tokenOwner3.extended() ] // When let partitions = sut.partitionedByOwner // Then XCTAssertEqual(partitions.count, 3) if partitions.count > 2 { XCTAssertTrue( (partitions[0].count == 2 && partitions[1].count == 1 && partitions[2].count == 1) || (partitions[0].count == 1 && partitions[1].count == 2 && partitions[2].count == 1) || (partitions[0].count == 1 && partitions[1].count == 1 && partitions[2].count == 2) ) } } func testBosterAfterOneShotImmunization() { // GIVEN let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let candidateForReissue = certs.filterBoosterAfterVaccinationAfterRecovery // THEN XCTAssertFalse(candidateForReissue.isEmpty) XCTAssertTrue(candidateForReissue.count == 2) XCTAssertTrue(candidateForReissue.contains(singleDoseImmunizationJohnsonCert)) XCTAssertTrue(candidateForReissue.contains(vaccinationWithTwoShotsOfVaccine)) XCTAssertFalse(candidateForReissue.contains(someOtherCert1)) XCTAssertFalse(candidateForReissue.contains(someOtherCert2)) } func testBoosteredWithJohnsonAlready() { // GIVEN let certs = [recoveryCert, singleDoseImmunizationJohnsonCert, doubleDoseImmunizationJohnsonCert, someOtherCert1] // WHEN let candidateForReissue = certs.filterBoosterAfterVaccinationAfterRecovery // THEN XCTAssertTrue(certs.qualifiedForReissue) XCTAssertFalse(candidateForReissue.isEmpty) XCTAssertEqual(candidateForReissue.count, 3) XCTAssertTrue(candidateForReissue.contains(singleDoseImmunizationJohnsonCert)) XCTAssertTrue(candidateForReissue.contains(doubleDoseImmunizationJohnsonCert)) XCTAssertTrue(candidateForReissue.contains(recoveryCert)) XCTAssertFalse(candidateForReissue.contains(someOtherCert1)) XCTAssertFalse(candidateForReissue.contains(someOtherCert2)) } func testBoosterAfterVaccinationAfterRecoveryWithoutRecovery() { // GIVEN let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let candidateForReissue = certs.filterBoosterAfterVaccinationAfterRecovery // THEN XCTAssertTrue(certs.qualifiedForReissue) XCTAssertFalse(candidateForReissue.isEmpty) XCTAssertTrue(candidateForReissue.count == 2) XCTAssertTrue(candidateForReissue.contains(singleDoseImmunizationJohnsonCert)) XCTAssertTrue(candidateForReissue.contains(vaccinationWithTwoShotsOfVaccine)) XCTAssertFalse(candidateForReissue.contains(someOtherCert1)) XCTAssertFalse(candidateForReissue.contains(someOtherCert2)) } func testBoosterAfterVaccinationAfterRecoveryWithRecovery() { // GIVEN let certs = [someOtherCert2, recoveryCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine, recoveryCert] // WHEN let candidateForReissue = certs.filterBoosterAfterVaccinationAfterRecovery // THEN XCTAssertTrue(certs.qualifiedForReissue) XCTAssertFalse(candidateForReissue.isEmpty) XCTAssertEqual(candidateForReissue.count, 4) XCTAssertTrue(candidateForReissue.contains(singleDoseImmunizationJohnsonCert)) XCTAssertTrue(candidateForReissue.contains(vaccinationWithTwoShotsOfVaccine)) XCTAssertTrue(candidateForReissue.contains(recoveryCert)) XCTAssertFalse(candidateForReissue.contains(someOtherCert1)) XCTAssertFalse(candidateForReissue.contains(someOtherCert2)) } func testIsNotReIssueCandidate() { // GIVEN let certs = [someOtherCert2, recoveryCert2, someOtherCert1, vaccinationWithTwoShotsOfVaccine, recoveryCert] // WHEN let candidateForReissue = certs.qualifiedForReissue // THEN XCTAssertFalse(candidateForReissue) } func testIsNotReIssueCandidate2() { // GIVEN let certs = [someOtherCert2, someOtherCert1] // WHEN let candidateForReissue = certs.qualifiedForReissue // THEN XCTAssertFalse(candidateForReissue) } func testIsNotReIssueCandidate3() { // GIVEN let certs = [recoveryCert, singleDoseImmunizationJohnsonCert] // WHEN let candidateForReissue = certs.qualifiedForReissue // THEN XCTAssertFalse(candidateForReissue) } func testIsNotReIssueCandidateBecauseReIssueAlmostDone() { // GIVEN var certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let candidateForReissue = certs.qualifiedForReissue // THEN XCTAssertTrue(candidateForReissue) // BUT WHEN certs.append(boosterCertificateAfterReIssue) let candidateForReissueAfterReissue = certs.qualifiedForReissue // THEN XCTAssertFalse(candidateForReissueAfterReissue) } func testAlreadySeen_Default() { // GIVEN let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueNewBadgeAlreadySeen = certs.reissueNewBadgeAlreadySeen // THEN XCTAssertNil(someOtherCert2.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen) XCTAssertFalse(reissueNewBadgeAlreadySeen) } func testAlreadySeen_OneCertAlreadySeen() { // GIVEN someOtherCert2.reissueProcessNewBadgeAlreadySeen = true let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueNewBadgeAlreadySeen = certs.reissueNewBadgeAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen) XCTAssertTrue(reissueNewBadgeAlreadySeen) } func testAlreadySeen_AllCertAlreadySeen() { // GIVEN someOtherCert2.reissueProcessNewBadgeAlreadySeen = true singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen = true someOtherCert1.reissueProcessNewBadgeAlreadySeen = true vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen = true let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueNewBadgeAlreadySeen = certs.reissueNewBadgeAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(someOtherCert1.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen) XCTAssertTrue(reissueNewBadgeAlreadySeen) } func testAlreadySeen_NoOfCertsAlreadySeen() { // GIVEN someOtherCert2.reissueProcessNewBadgeAlreadySeen = false singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen = false someOtherCert1.reissueProcessNewBadgeAlreadySeen = false vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen = false let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueNewBadgeAlreadySeen = certs.reissueNewBadgeAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(someOtherCert1.reissueProcessNewBadgeAlreadySeen) XCTAssertNotNil(vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen) XCTAssertFalse(reissueNewBadgeAlreadySeen) } func testAlreadySeen_OneOfCertsAlreadySeenFalse() { // GIVEN someOtherCert2.reissueProcessNewBadgeAlreadySeen = false let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueNewBadgeAlreadySeen = certs.reissueNewBadgeAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessNewBadgeAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessNewBadgeAlreadySeen) XCTAssertFalse(reissueNewBadgeAlreadySeen) } func testReissueProcessInitialAlreadySeen_Default() { // GIVEN let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueProcessInitialAlreadySeen = certs.reissueProcessInitialAlreadySeen let reissueProcessInitialNotAlreadySeen = certs.reissueProcessInitialNotAlreadySeen // THEN XCTAssertNil(someOtherCert2.reissueProcessInitialAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessInitialAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen) XCTAssertFalse(reissueProcessInitialAlreadySeen) XCTAssertTrue(reissueProcessInitialNotAlreadySeen) } func testReissueProcessInitialAlreadySeen_OneCertAlreadySeen() { // GIVEN someOtherCert2.reissueProcessInitialAlreadySeen = true let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueProcessInitialAlreadySeen = certs.reissueProcessInitialAlreadySeen let reissueProcessInitialNotAlreadySeen = certs.reissueProcessInitialNotAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessInitialAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessInitialAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen) XCTAssertTrue(reissueProcessInitialAlreadySeen) XCTAssertFalse(reissueProcessInitialNotAlreadySeen) } func testReissueProcessInitialAlreadySeen_AllCertAlreadySeen() { // GIVEN someOtherCert2.reissueProcessInitialAlreadySeen = true singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen = true someOtherCert1.reissueProcessInitialAlreadySeen = true vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen = true let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueProcessInitialAlreadySeen = certs.reissueProcessInitialAlreadySeen let reissueProcessInitialNotAlreadySeen = certs.reissueProcessInitialNotAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessInitialAlreadySeen) XCTAssertNotNil(singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen) XCTAssertNotNil(someOtherCert1.reissueProcessInitialAlreadySeen) XCTAssertNotNil(vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen) XCTAssertTrue(reissueProcessInitialAlreadySeen) XCTAssertFalse(reissueProcessInitialNotAlreadySeen) } func testReissueProcessInitialAlreadySeen_NoOfCertsAlreadySeen() { // GIVEN someOtherCert2.reissueProcessInitialAlreadySeen = false singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen = false someOtherCert1.reissueProcessInitialAlreadySeen = false vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen = false let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueProcessInitialAlreadySeen = certs.reissueProcessInitialAlreadySeen let reissueProcessInitialNotAlreadySeen = certs.reissueProcessInitialNotAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessInitialAlreadySeen) XCTAssertNotNil(singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen) XCTAssertNotNil(someOtherCert1.reissueProcessInitialAlreadySeen) XCTAssertNotNil(vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen) XCTAssertFalse(reissueProcessInitialAlreadySeen) XCTAssertTrue(reissueProcessInitialNotAlreadySeen) } func testReissueProcessInitialAlreadySeen_OneOfCertsAlreadySeenFalse() { // GIVEN someOtherCert2.reissueProcessInitialAlreadySeen = false let certs = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine] // WHEN let reissueProcessInitialAlreadySeen = certs.reissueProcessInitialAlreadySeen let reissueProcessInitialNotAlreadySeen = certs.reissueProcessInitialNotAlreadySeen // THEN XCTAssertNotNil(someOtherCert2.reissueProcessInitialAlreadySeen) XCTAssertNil(singleDoseImmunizationJohnsonCert.reissueProcessInitialAlreadySeen) XCTAssertNil(someOtherCert1.reissueProcessInitialAlreadySeen) XCTAssertNil(vaccinationWithTwoShotsOfVaccine.reissueProcessInitialAlreadySeen) XCTAssertFalse(reissueProcessInitialAlreadySeen) XCTAssertTrue(reissueProcessInitialNotAlreadySeen) } func testFilterCertificatesSamePerson() { // GIVEN let certOfJohnDoe = boosterCertificateAfterReIssue let certOfEllaKatami = CBORWebToken.mockVaccinationCertificateWithOtherName.extended() let certsOfJohnAndOneOfElla = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine, recoveryCert, recoveryCert2, certOfEllaKatami] // WHEN let filteredCertsForJohn = certsOfJohnAndOneOfElla.filterMatching(certOfJohnDoe) // THEN XCTAssertEqual(filteredCertsForJohn.count, 6) XCTAssertTrue(filteredCertsForJohn.contains(someOtherCert2)) XCTAssertTrue(filteredCertsForJohn.contains(singleDoseImmunizationJohnsonCert)) XCTAssertTrue(filteredCertsForJohn.contains(someOtherCert1)) XCTAssertTrue(filteredCertsForJohn.contains(vaccinationWithTwoShotsOfVaccine)) XCTAssertTrue(filteredCertsForJohn.contains(recoveryCert)) XCTAssertTrue(filteredCertsForJohn.contains(recoveryCert2)) XCTAssertFalse(filteredCertsForJohn.contains(certOfEllaKatami)) } func testFilterCertificatesSamePersonAlternative() { // GIVEN let certOfEllaKatami = CBORWebToken.mockVaccinationCertificateWithOtherName.extended() let certsOfJohnAndOneOfElla = [someOtherCert2, singleDoseImmunizationJohnsonCert, someOtherCert1, vaccinationWithTwoShotsOfVaccine, recoveryCert, recoveryCert2, certOfEllaKatami] // WHEN let filteredCertsForElla = certsOfJohnAndOneOfElla.filterMatching(certOfEllaKatami) // THEN XCTAssertEqual(filteredCertsForElla.count, 1) XCTAssertFalse(filteredCertsForElla.contains(someOtherCert2)) XCTAssertFalse(filteredCertsForElla.contains(singleDoseImmunizationJohnsonCert)) XCTAssertFalse(filteredCertsForElla.contains(someOtherCert1)) XCTAssertFalse(filteredCertsForElla.contains(vaccinationWithTwoShotsOfVaccine)) XCTAssertFalse(filteredCertsForElla.contains(recoveryCert)) XCTAssertFalse(filteredCertsForElla.contains(recoveryCert2)) XCTAssertTrue(filteredCertsForElla.contains(certOfEllaKatami)) } func testSortedByDnVacinationRecoveryAndTestCertficateMixed() { // GIVEN var certs = [singleDoseImmunizationJohnsonCert, recoveryCert, recoveryCert2, vaccinationWithTwoShotsOfVaccine] // WHEN certs = certs.sortedByDn // THEN XCTAssertEqual(certs[0], vaccinationWithTwoShotsOfVaccine) XCTAssertEqual(certs[1], singleDoseImmunizationJohnsonCert) XCTAssertEqual(certs[2], recoveryCert) XCTAssertEqual(certs[3], recoveryCert2) } func testFilter2of1s() { // GIVEN var certs = [singleDoseImmunizationJohnsonCert, recoveryCert, recoveryCert2, boosterCertificateAfterReIssue, vaccinationWithTwoShotsOfVaccine, doubleDoseImmunizationJohnsonCert] // WHEN certs = certs.filter2Of1 // THEN XCTAssertEqual(certs.count, 1) XCTAssertEqual(certs[0], boosterCertificateAfterReIssue) } } private extension DigitalGreenCertificate { static func mock(name: Name = .mustermann(), dob: Date? = nil) -> DigitalGreenCertificate { .init(nam: name, dob: dob, dobString: nil, v: nil, t: nil, r: nil, ver: "1.0") } } private extension Name { static func mustermann() -> Name { .init(gn: nil, fn: nil, gnt: nil, fnt: "MUSTERMANN") } static func yildirim() -> Name { .init(gn: nil, fn: nil, gnt: nil, fnt: "YILDIRIM") } }
41.908759
101
0.675128
eb924a3c8f8aecf0d98d121fdfb6f109b7bb1bc6
1,089
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SKRools", platforms: [ .iOS(.v13) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "SKRools", targets: ["SKRools"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), // No depency path added ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "SKRools", dependencies: []), .testTarget( name: "SKRoolsTests", dependencies: ["SKRools"]), ] )
33
122
0.603306
0aec8398e3233a80291fcf612a296f0452c12792
4,557
import Foundation import MixboxUiTestsFoundation import MixboxTestsFoundation import XCTest class IsSubviewMatcherTests: BaseMatcherTests { func test___match___matches___if_superview_matches() { let superview = ElementSnapshotStub { $0.accessibilityIdentifier = "superview" } let viewThatIsBeingMatched = ElementSnapshotStub { $0.accessibilityIdentifier = "subview" } superview.add(child: viewThatIsBeingMatched) assertMatches( matcher: IsSubviewMatcher(matcherBuilder.id == "superview"), value: viewThatIsBeingMatched ) } func test___match___mismatches___view_that_is_being_matched() { let superview = ElementSnapshotStub { $0.accessibilityIdentifier = "superview" $0.failForNotStubbedValues = false } let viewThatIsBeingMatched = ElementSnapshotStub { $0.accessibilityIdentifier = "viewThatIsBeingMatched" } superview.add(child: viewThatIsBeingMatched) assertMismatches( matcher: IsSubviewMatcher(matcherBuilder.id == "viewThatIsBeingMatched"), value: viewThatIsBeingMatched ) } func test___match___produces_correct_mismatch_description_0() { let superview0 = ElementSnapshotStub { $0.accessibilityIdentifier = "superview0" $0.isEnabled = false $0.failForNotStubbedValues = false } let superview1 = ElementSnapshotStub { $0.accessibilityIdentifier = "superview1" $0.isEnabled = true $0.failForNotStubbedValues = false } let superview2 = ElementSnapshotStub { $0.accessibilityIdentifier = "superview2" $0.isEnabled = false $0.failForNotStubbedValues = false } let viewThatIsBeingMatched = ElementSnapshotStub { $0.accessibilityIdentifier = "viewThatIsBeingMatched" $0.failForNotStubbedValues = false } superview0.add(child: superview1) superview1.add(child: superview2) superview2.add(child: viewThatIsBeingMatched) assertMismatches( matcher: IsSubviewMatcher(matcherBuilder.id == "non_existent_id" && matcherBuilder.isEnabled == true), value: viewThatIsBeingMatched, percentageOfMatching: 0.5, description: """ не найден superview, который матчится матчером "Всё из [ Имеет проперти id: equals to non_existent_id Имеет проперти isEnabled: equals to true ]", лучший кандидат зафейлился: Всё из [ (x) value is not equal to 'non_existent_id', actual value: 'superview1' (v) Имеет проперти isEnabled: equals to true ] """ ) } func test___match___produces_correct_mismatch_description_1() { let superview = ElementSnapshotStub { $0.accessibilityIdentifier = "superview0" $0.failForNotStubbedValues = false } let viewThatIsBeingMatched = ElementSnapshotStub { $0.accessibilityIdentifier = "viewThatIsBeingMatched" $0.failForNotStubbedValues = false } superview.add(child: viewThatIsBeingMatched) assertMismatches( matcher: IsSubviewMatcher(matcherBuilder.id == "non_existent_id"), value: viewThatIsBeingMatched, percentageOfMatching: 0, description: """ не найден superview, который матчится матчером "Имеет проперти id: equals to non_existent_id", лучший кандидат зафейлился: value is not equal to 'non_existent_id', actual value: 'superview0' """ ) } func test___description___is_correct() { let superview = ElementSnapshotStub { $0.accessibilityIdentifier = "superview" } let viewThatIsBeingMatched = ElementSnapshotStub { $0.accessibilityIdentifier = "subview" } superview.add(child: viewThatIsBeingMatched) assertDescriptionIsCorrect( matcher: IsSubviewMatcher(matcherBuilder.id == "superview"), value: viewThatIsBeingMatched, description: """ Является сабвью { Имеет проперти id: equals to superview } """ ) } }
35.88189
202
0.610928
e4677979104510d03359826f3b79bf05247c6986
423
// // DetailView.swift // NewsApp // // Created by Ritaban Mitra on 09/08/20. // Copyright © 2020 Ritaban Mitra. All rights reserved. // import SwiftUI struct DetailView: View { let url: String? var body: some View { WebView(urlString: url) } } struct DetailView_Previews: PreviewProvider { static var previews: some View { DetailView(url: "https://www.google.com") } }
16.92
56
0.631206
615488fc734919cd09291e4ece0517ec0957c4c5
6,098
import Foundation import UIKit import AsyncDisplayKit import Display import TelegramPresentationData private let titleFont = Font.regular(17.0) enum BotPaymentFieldContentType { case generic case name case phoneNumber case email case address } final class BotPaymentFieldItemNode: BotPaymentItemNode, UITextFieldDelegate { private let title: String var text: String { get { return self.textField.textField.text ?? "" } set(value) { self.textField.textField.text = value } } private let contentType: BotPaymentFieldContentType private let placeholder: String private let titleNode: ASTextNode private let textField: TextFieldNode private var theme: PresentationTheme? var focused: (() -> Void)? var textUpdated: (() -> Void)? var returnPressed: (() -> Void)? init(title: String, placeholder: String, text: String = "", contentType: BotPaymentFieldContentType = .generic) { self.title = title self.placeholder = placeholder self.contentType = contentType self.titleNode = ASTextNode() self.titleNode.maximumNumberOfLines = 1 self.textField = TextFieldNode() self.textField.textField.font = titleFont self.textField.textField.returnKeyType = .next self.textField.textField.text = text switch contentType { case .generic: break case .name: self.textField.textField.autocorrectionType = .no self.textField.textField.keyboardType = .asciiCapable case .address: self.textField.textField.autocorrectionType = .no case .phoneNumber: self.textField.textField.keyboardType = .phonePad if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { self.textField.textField.textContentType = .telephoneNumber } case .email: self.textField.textField.keyboardType = .emailAddress if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { self.textField.textField.textContentType = .emailAddress } } super.init(needsBackground: true) self.addSubnode(self.titleNode) self.addSubnode(self.textField) self.textField.textField.addTarget(self, action: #selector(self.editingChanged), for: [.editingChanged]) self.textField.textField.delegate = self } override func measureInset(theme: PresentationTheme, width: CGFloat) -> CGFloat { if self.theme !== theme { self.theme = theme self.titleNode.attributedText = NSAttributedString(string: self.title, font: titleFont, textColor: theme.list.itemPrimaryTextColor) self.textField.textField.textColor = theme.list.itemPrimaryTextColor self.textField.textField.attributedPlaceholder = NSAttributedString(string: placeholder, font: titleFont, textColor: theme.list.itemPlaceholderTextColor) self.textField.textField.keyboardAppearance = theme.rootController.keyboardColor.keyboardAppearance self.textField.textField.tintColor = theme.list.itemAccentColor } let leftInset: CGFloat = 16.0 let titleSize = self.titleNode.measure(CGSize(width: width - leftInset - 70.0, height: CGFloat.greatestFiniteMagnitude)) if titleSize.width.isZero { return 0.0 } else { return leftInset + titleSize.width + 17.0 } } override func layoutContents(theme: PresentationTheme, width: CGFloat, measuredInset: CGFloat, transition: ContainedViewLayoutTransition) -> CGFloat { if self.theme !== theme { self.theme = theme self.titleNode.attributedText = NSAttributedString(string: self.title, font: titleFont, textColor: theme.list.itemPrimaryTextColor) self.textField.textField.keyboardAppearance = theme.rootController.keyboardColor.keyboardAppearance self.textField.textField.tintColor = theme.list.itemAccentColor } let leftInset: CGFloat = 16.0 let titleSize = self.titleNode.measure(CGSize(width: width - leftInset - 70.0, height: CGFloat.greatestFiniteMagnitude)) transition.updateFrame(node: self.titleNode, frame: CGRect(origin: CGPoint(x: leftInset, y: 11.0), size: titleSize)) var textInset = leftInset if !titleSize.width.isZero { textInset += titleSize.width + 18.0 } textInset = max(measuredInset, textInset) transition.updateFrame(node: self.textField, frame: CGRect(origin: CGPoint(x: textInset, y: 3.0), size: CGSize(width: max(1.0, width - textInset - 8.0), height: 40.0))) return 44.0 } func activateInput() { self.textField.textField.becomeFirstResponder() } @objc func editingChanged() { self.textUpdated?() } func textFieldDidBeginEditing(_ textField: UITextField) { self.focused?() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.returnPressed?() return false } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if !string.isEmpty { if case .name = self.contentType { if let lowerBound = textField.position(from: textField.beginningOfDocument, offset: range.lowerBound), let upperBound = textField.position(from: textField.beginningOfDocument, offset: range.upperBound), let fieldRange = textField.textRange(from: lowerBound, to: upperBound) { textField.replace(fieldRange, withText: string.uppercased()) self.editingChanged() return false } } } return true } }
39.341935
291
0.638734
9bc3d9993c8f5a44ba6f8081aee26ff2b7169384
896
/*: [back to Cardinal page](@previous) ## Ordinals If you want ordinals (1st, 2nd, 3rd...) then a .stringsdict is no use to you, you need NSNumberFormatter */ import Foundation let fmtr = NumberFormatter() fmtr.numberStyle = .ordinal let s1 = fmtr.string(from: 1) let s2 = fmtr.string(from: 2) let s3 = fmtr.string(from: 3) let s4 = fmtr.string(from: 4) let s101 = fmtr.string(from: 101) let s111 = fmtr.string(from: 111) // or (look in the Debugger Console for output for i: NSNumber in [1,2,3,4,101,111] { if let result = fmtr.string(from: i) { print(result) } } fmtr.locale = Locale(identifier: "fr") let f1 = fmtr.string(from: 1) let f2 = fmtr.string(from: 2) let f101 = fmtr.string(from: 101) let f111 = fmtr.string(from: 111) print("\nen Francais") for i: NSNumber in [1,2,3,4,101,111] { if let result = fmtr.string(from: i) { print(result) } }
21.853659
105
0.657366
2fdd99d7380fa8f8c43a3912c5d058e1e5269945
582
// // Evalution.swift // GG // // Created by Student on 2017-06-18. // Copyright © 2017 Danny. All rights reserved. // import Foundation import SpriteKit //Fitness Function func EvalutionMod (Time: TimeInterval, Food:Int) -> CGFloat { //Undergo a Binary F6 Function let Fitness: CGFloat = CGFloat (Time/100) + CGFloat (Food * 20) return Fitness } func areEqual (NewWeight: [CGFloat], OldWeight:[CGFloat]) -> Bool { for bits in 0...1199 { if NewWeight [bits] != OldWeight [bits] { return false } } return true }
18.774194
67
0.620275
46e382be9b25d5f46303e90530cc3032a6056ef7
5,288
import ObjectBox enum TestErrors: Error { case testFailed(message: String) } class Author: Entity, CustomDebugStringConvertible { var id: Id = 0 var name: String // objectbox: backlink = "author" var books: ToMany<Book> = nil init(name: String = "") { self.name = name } public var debugDescription: String { return "Author { \(id.value): \(name) }\n" } } class Book: Entity, CustomDebugStringConvertible { var id: Id = 0 var name: String var author: ToOne<Author> = nil init(name: String = "") { self.name = name } public var debugDescription: String { return "Book { \(id.value): \(name) by \(String(describing: author.target)) }\n" } } func main(_ args: [String]) throws -> Int32 { print("note: Starting \(args.first ?? "???") tests:") let storeFolder = URL(fileURLWithPath: "/tmp/tooltestDB50/") try? FileManager.default.removeItem(atPath: storeFolder.path) try FileManager.default.createDirectory(at: storeFolder, withIntermediateDirectories: false) print("note: Creating DB at \(storeFolder.path)") let store = try Store(directoryPath: storeFolder.path) print("note: Getting boxes") let authorBox = store.box(for: Author.self) let bookBox = store.box(for: Book.self) do { print("note: Adding Books:") let symptomsOfAHeartbreak = Book(name: "Symptoms of a Heartbreak") // Sona Charaipotra let everlastingRose = Book(name: "The Everlasting Rose") // Dhonielle Clayton let theBelles = Book(name: "The Belles") // Dhonielle Clayton let theArtOfAsking = Book(name: "The Art of Asking") // Amanda Palmer let allBooks = [symptomsOfAHeartbreak, everlastingRose, theBelles, theArtOfAsking] try bookBox.put(allBooks) print("note: Adding Authors:") let sona = Author(name: "Sona Charaipotra") let dhonielle = Author(name: "Dhonielle Clayton") let amanda = Author(name: "Amanda Palmer") try authorBox.put([sona, dhonielle, amanda]) print("note: Adding Relation 1:") sona.books.replace([symptomsOfAHeartbreak]) try sona.books.applyToDb() print("note: Adding Relation 2:") dhonielle.books.replace([everlastingRose, theBelles]) try dhonielle.books.applyToDb() print("note: Adding Relation 3:") amanda.books.replace([theArtOfAsking]) try amanda.books.applyToDb() try bookBox.put(allBooks) // We edited the authors, but the books contain the ToOne that needs persisting. print("note: Testing forward:") let dhoniellesBooks = try bookBox.query().link(Book.author) { Author.name == dhonielle.name }.build().find() if dhoniellesBooks.count != 2 { throw TestErrors.testFailed(message: "Book count wrong. Expected 2, found \(dhoniellesBooks.count)") } if dhoniellesBooks.first(where: { $0.name == everlastingRose.name }) == nil { throw TestErrors.testFailed(message: "Book missing: \(everlastingRose)") } if dhoniellesBooks.first(where: { $0.name == theBelles.name }) == nil { throw TestErrors.testFailed(message: "Book missing: \(theBelles)") } print("note: Testing backlink:") let bellesAskingAuthors = try authorBox.query().link(Author.books) { Book.name == theBelles.name || Book.name == theArtOfAsking.name }.build().find() if bellesAskingAuthors.count != 2 { throw TestErrors.testFailed(message: "Author count wrong. Expected 2, found \(bellesAskingAuthors.count)") } if bellesAskingAuthors.first(where: { $0.name == dhonielle.name }) == nil { throw TestErrors.testFailed(message: "Author missing: \(dhonielle)") } if bellesAskingAuthors.first(where: { $0.name == amanda.name }) == nil { throw TestErrors.testFailed(message: "Author missing: \(amanda)") } // This is mainly to ensure compilation isn't broken, but might as well verify that delete works: print("note: Doing remove test.") try authorBox.remove(amanda.id) if let amandaRead = try authorBox.get(amanda.id) { throw TestErrors.testFailed(message: "Deletion failed: \(amandaRead)") } // This is mainly to ensure compilation isn't broken, but might as well verify that delete works: print("note: Multi-remove test.") let deletions = try authorBox.remove([amanda.id, dhonielle.id]) if deletions != 1 { // Amanda has already been deleted. throw TestErrors.testFailed(message: "Expected 1 deletion, got \(deletions)") } if let dhonielleRead = try authorBox.get(dhonielle.id) { throw TestErrors.testFailed(message: "Deletion failed: \(dhonielleRead)") } } catch TestErrors.testFailed(let message) { print("error: \(message)") return 1 } catch { print("error: \(error)") return 1 } print("note: Ran \(args.count > 1 ? args[1] : "???") tests.") try? FileManager.default.removeItem(atPath: storeFolder.path) return 0 }
38.318841
118
0.625
29a04efdd01eb3df1a4001df8f63b24863e78116
4,568
// // AutoCompleteViewDataSource.swift // TogglDesktop // // Created by Nghia Tran on 3/25/19. // Copyright © 2019 Alari. All rights reserved. // import Foundation protocol AutoCompleteViewDataSourceDelegate: class { func autoCompleteSelectionDidChange(sender: AutoCompleteViewDataSource, item: Any) } class AutoCompleteViewDataSource: NSObject { // MARK: Variables private let maxHeight: CGFloat = 600.0 private(set) var items: [Any] = [] private(set) var autoCompleteView: AutoCompleteView? private(set) var textField: NSTextField = NSTextField(frame: .zero) var autoCompleteTextField: AutoCompleteTextField? { textField as? AutoCompleteTextField } weak var delegate: AutoCompleteViewDataSourceDelegate? var count: Int { return items.count } var tableView: NSTableView { return autoCompleteView?.tableView ?? NSTableView() } // MARK: Init init(items: [Any], updateNotificationName: Notification.Name) { super.init() self.items = items NotificationCenter.default.addObserver(self, selector: #selector(self.receiveDataSourceNotifiation(_:)), name: updateNotificationName, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Public func setup(with textField: AutoCompleteTextField) { self.textField = textField self.autoCompleteView = textField.autoCompleteView self.autoCompleteView?.defaultTextField.isHidden = true commonSetup() } func setup(with autoCompleteView: AutoCompleteView) { self.autoCompleteView = autoCompleteView textField = autoCompleteView.defaultTextField textField.isHidden = false autoCompleteView.placeholderBox.isHidden = false commonSetup() } private func commonSetup() { autoCompleteView?.prepare(with: self) registerCustomeCells() tableView.delegate = self tableView.dataSource = self } func registerCustomeCells() { // Should override } func render(with items: [Any]) { self.items = items tableView.reloadData() sizeToFit() } func filter(with text: String) { // Should override } @objc func receiveDataSourceNotifiation(_ noti: Notification) { guard let items = noti.object as? [Any] else { return } render(with: items) // If there is new data during searching on auto-complete // We should filter gain if autoCompleteTextField?.state == .expand && !textField.stringValue.isEmpty { filter(with: textField.stringValue) } } func selectSelectedRow() { selectRow(at: tableView.selectedRow) } func selectRow(at index: Int) { guard let item = items[safe: index] else { return } delegate?.autoCompleteSelectionDidChange(sender: self, item: item) } func sizeToFit() { if items.isEmpty { autoCompleteView?.update(height: 0.0) return } // Get total height of all cells let totalHeight = items.enumerated().reduce(into: 0.0) { (height, item) in return height += tableView(tableView, heightOfRow: item.offset) } // Get suitable height // 0 <= height <= maxHeight var suitableHeight = CGFloat.minimum(CGFloat.maximum(0, totalHeight), maxHeight) // Padding if let scrollView = tableView.enclosingScrollView { suitableHeight += scrollView.contentInsets.bottom + scrollView.contentInsets.top } autoCompleteView?.update(height: suitableHeight) } func keyboardDidEnter() { // Override } } extension AutoCompleteViewDataSource: NSTableViewDataSource, NSTableViewDelegate { func numberOfRows(in tableView: NSTableView) -> Int { return items.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { return nil } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 44.0 } func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return true } func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { return AutoCompleteRowView() } }
28.372671
106
0.634413
46b198bbded3043ad1660c4d23b29e5c3552030b
28,634
//===--- Mirror.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// A representation of the substructure and display style of an instance of /// any type. /// /// A mirror describes the parts that make up a particular instance, such as /// the instance's stored properties, collection or tuple elements, or its /// active enumeration case. Mirrors also provide a "display style" property /// that suggests how this mirror might be rendered. /// /// Playgrounds and the debugger use the `Mirror` type to display /// representations of values of any type. For example, when you pass an /// instance to the `dump(_:_:_:_:)` function, a mirror is used to render that /// instance's runtime contents. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "▿ Point /// // - x: 21 /// // - y: 30" /// /// To customize the mirror representation of a custom type, add conformance to /// the `CustomReflectable` protocol. public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// The representation to use for ancestor classes. /// /// A class that conforms to the `CustomReflectable` protocol can control how /// its mirror represents ancestor classes by initializing the mirror /// with an `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generates a default mirror for all ancestor classes. /// /// This case is the default when initializing a `Mirror` instance. /// /// When you use this option, a subclass's mirror generates default mirrors /// even for ancestor classes that conform to the `CustomReflectable` /// protocol. To avoid dropping the customization provided by ancestor /// classes, an override of `customMirror` should pass /// `.customized({ super.customMirror })` as `ancestorRepresentation` when /// initializing its mirror. case generated /// Uses the nearest ancestor's implementation of `customMirror` to create /// a mirror for that ancestor. /// /// Other classes derived from such an ancestor are given a default mirror. /// The payload for this option should always be `{ super.customMirror }`: /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppresses the representation of all ancestor classes. /// /// In a mirror created with this ancestor representation, the /// `superclassMirror` property is `nil`. case suppressed } /// Creates a mirror that reflects on the given instance. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, the /// resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// If the dynamic type of `subject` has value semantics, subsequent /// mutations of `subject` will not observable in `Mirror`. In general, /// though, the observability of mutations is unspecified. /// /// - Parameter subject: The instance for which to create a mirror. public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror(internalReflecting: subject) } } /// An element of the reflected instance's structure. /// /// When the `label` component in not `nil`, it may represent the name of a /// stored property or an active `enum` case. If you pass strings to the /// `descendant(_:_:)` method, labels are used for lookup. public typealias Child = (label: String?, value: Any) /// The type used to represent substructure. /// /// When working with a mirror that reflects a bidirectional or random access /// collection, you may find it useful to "upgrade" instances of this type /// to `AnyBidirectionalCollection` or `AnyRandomAccessCollection`. For /// example, to display the last twenty children of a mirror if they can be /// accessed efficiently, you write the following code: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// for element in b.suffix(20) { /// print(element) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a mirror's subject is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the mirror is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } internal static func _noSuperclassMirror() -> Mirror? { return nil } @_semantics("optimize.sil.specialize.generic.never") @inline(never) internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { Mirror(internalReflecting: subject, subjectType: superclass) } case .customized(let makeAncestor): return { let ancestor = makeAncestor() if superclass == ancestor.subjectType || ancestor._defaultDescendantRepresentation == .suppressed { return ancestor } else { return Mirror(internalReflecting: subject, subjectType: superclass, customAncestor: ancestor) } } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Creates a mirror representing the given subject with a specified /// structure. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - children: The structure to use for the mirror. The collection /// traversal modeled by `children` is captured so that the resulting /// mirror's children may be upgraded to a bidirectional or random /// access collection later. See the `children` property for details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. public init<Subject, C: Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Element == Child { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Creates a mirror representing the given subject with unlabeled children. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror, particularly for custom /// types that are collections. The labels of the resulting mirror's /// `children` collection are all `nil`. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - unlabeledChildren: The children to use for the mirror. The collection /// traversal modeled by `unlabeledChildren` is captured so that the /// resulting mirror's children may be upgraded to a bidirectional or /// random access collection later. See the `children` property for /// details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. public init<Subject, C: Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = unlabeledChildren.lazy.map { Child(label: nil, value: $0) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Creates a mirror representing the given subject using a dictionary /// literal for the structure. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror. Pass a dictionary literal /// with string keys as `children`. Although an *actual* dictionary is /// arbitrarily-ordered, when you create a mirror with a dictionary literal, /// the ordering of the mirror's `children` will exactly match that of the /// literal you pass. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - children: A dictionary literal to use as the structure for the /// mirror. The `children` collection of the resulting mirror may be /// upgraded to a random access collection later. See the `children` /// property for details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. public init<Subject>( _ subject: Subject, children: KeyValuePairs<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when this mirror /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// A suggested display style for the reflected subject. public let displayStyle: DisplayStyle? /// A mirror of the subject's superclass, if one exists. public var superclassMirror: Mirror? { return _makeSuperclassMirror() } internal let _makeSuperclassMirror: () -> Mirror? internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflecting:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable: CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. public protocol MirrorPath { // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and // you shouldn't be able to create conformances. } extension Int: MirrorPath {} extension String: MirrorPath {} extension Mirror { internal struct _Dummy: CustomReflectable { internal init(mirror: Mirror) { self.mirror = mirror } internal var mirror: Mirror internal var customMirror: Mirror { return mirror } } /// Returns a specific descendant of the reflected subject, or `nil` if no /// such descendant exists. /// /// Pass a variadic list of string and integer arguments. Each string /// argument selects the first child with a matching label. Each integer /// argument selects the child at that offset. For example, passing /// `1, "two", 3` as arguments to `myMirror.descendant(_:_:)` is equivalent /// to: /// /// var result: Any? = nil /// let children = myMirror.children /// if let i0 = children.index( /// children.startIndex, offsetBy: 1, limitedBy: children.endIndex), /// i0 != children.endIndex /// { /// let grandChildren = Mirror(reflecting: children[i0].value).children /// if let i1 = grandChildren.firstIndex(where: { $0.label == "two" }) { /// let greatGrandChildren = /// Mirror(reflecting: grandChildren[i1].value).children /// if let i2 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, /// limitedBy: greatGrandChildren.endIndex), /// i2 != greatGrandChildren.endIndex /// { /// // Success! /// result = greatGrandChildren[i2].value /// } /// } /// } /// /// This function is suitable for exploring the structure of a mirror in a /// REPL or playground, but is not intended to be efficient. The efficiency /// of finding each element in the argument list depends on the argument /// type and the capabilities of the each level of the mirror's `children` /// collections. Each string argument requires a linear search, and unless /// the underlying collection supports random-access traversal, each integer /// argument also requires a linear operation. /// /// - Parameters: /// - first: The first mirror path component to access. /// - rest: Any remaining mirror path components. /// - Returns: The descendant of this mirror specified by the given mirror /// path components if such a descendant exists; otherwise, `nil`. public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.firstIndex { $0.label == label } ?? children.endIndex } else if let offset = e as? Int { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- General Utilities ------------------------------------------------===// extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } // These overloads serve as fast paths for init(describing:), but they // also preserve source compatibility for clients which accidentally // used init(stringInterpolationSegment:) through constructs like // myArray.map(String.init). /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" @inlinable public init<Subject: CustomStringConvertible>(describing instance: Subject) { self = instance.description } /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" @inlinable public init<Subject: TextOutputStreamable>(describing instance: Subject) { self.init() instance.write(to: &self) } /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" @inlinable public init<Subject>(describing instance: Subject) where Subject: CustomStringConvertible & TextOutputStreamable { self = instance.description } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror: CustomStringConvertible { public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror: CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: [:]) } }
40.443503
106
0.658343
11da35e4f0ad6d378d70ecec300c551adf5f97e5
952
// // Logging.swift // RouterExample // // Created by John Liedtke on 8/7/18. // Copyright © 2018 theholygrail.io. All rights reserved. // import ELRouter import Foundation import os.log class Logger: ELRouter.Logger { static let shared = Logger() @available (iOS 10, *) private static let osLog = OSLog(subsystem: "com.routerExample", category: "ELRouter") func log(_ flag: LogFlag, _ message: @autoclosure () -> String) { if #available(iOS 10, *) { os_log("%@", log: Logger.osLog, type: getOSType(for: flag), message()) } else { NSLog("@", message()) } } @available(iOS 10, *) private func getOSType(for flag: LogFlag) -> OSLogType { switch flag { case .fatal, .error: return .error case .warning: return .fault case .info: return .info case .debug, .verbose: return .debug default: return .default } } }
25.052632
90
0.593487
e4812b36c6edf53d1c021f8de7c1a222973a72d7
1,685
// // ViewController.swift // tipster // // Created by Diana C on 12/9/16. // Copyright © 2016 Diana C. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var percentControl: UISegmentedControl! let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func onControlValueChange(_ sender: Any) { calculate() } @IBAction func calculateTip(_ sender: Any) { calculate() } func calculate() { let tipPercentages = [0.18, 0.2, 0.25] let bill = Double(billField.text!) ?? 0 let tip = bill * tipPercentages[percentControl.selectedSegmentIndex] let total = tip + bill tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) let percentIndex = defaults.integer(forKey: "percentIndex") percentControl.selectedSegmentIndex = percentIndex } }
26.328125
80
0.631454
e24c15f574c8ca2c4e9f5c729526df5f91c2731a
15,822
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import struct Foundation.Data import class Foundation.NSData /// The wrapper class for encoding Codable classes to Query dictionary class QueryEncoder { /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey: Any] = [:] /// Are we encoding for EC2 open var ec2: Bool = false /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let userInfo: [CodingUserInfoKey: Any] let ec2: Bool } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(userInfo: self.userInfo, ec2: self.ec2) } public init() {} open func encode<T: Encodable>(_ value: T, name: String? = nil) throws -> [String: Any] { let encoder = _QueryEncoder(options: options) try value.encode(to: encoder) // encode generates a tree of dictionaries and arrays. We need to flatten this into a single dictionary with keys joined together return flatten(encoder.result) } /// Flatten dictionary and array tree into one dictionary /// - Parameter container: The root container private func flatten(_ container: _QueryEncoderKeyedContainer?) -> [String: Any] { var result: [String: Any] = [:] func flatten(dictionary: [String: Any], path: String) { for (key, value) in dictionary { switch value { case let keyed as _QueryEncoderKeyedContainer: flatten(dictionary: keyed.values, path: "\(path)\(key).") case let unkeyed as _QueryEncoderUnkeyedContainer: flatten(array: unkeyed.values, path: "\(path)\(key).") default: result["\(path)\(key)"] = value } } } func flatten(array: [Any], path: String) { for iterator in array.enumerated() { switch iterator.element { case let keyed as _QueryEncoderKeyedContainer: flatten(dictionary: keyed.values, path: "\(path)\(iterator.offset + 1).") case let unkeyed as _QueryEncoderUnkeyedContainer: flatten(array: unkeyed.values, path: "\(path)\(iterator.offset + 1)") default: result["\(path)\(iterator.offset + 1)"] = iterator.element } } } if let container = container { flatten(dictionary: container.values, path: "") } return result } } /// class for holding a keyed container (dictionary). Need to encapsulate dictionary in class so we can be sure we are /// editing the dictionary we push onto the stack private class _QueryEncoderKeyedContainer { private(set) var values: [String: Any] = [:] func addChild(path: String, child: Any) { values[path] = child } } /// class for holding unkeyed container (array). Need to encapsulate array in class so we can be sure we are /// editing the array we push onto the stack private class _QueryEncoderUnkeyedContainer { private(set) var values: [Any] = [] func addChild(_ child: Any) { values.append(child) } } /// storage for Query Encoder. Stores a stack of QueryEncoder containers, plus leaf objects private struct _QueryEncoderStorage { /// the container stack private var containers: [Any] = [] /// initializes self with no containers init() {} /// push a new container onto the storage mutating func pushKeyedContainer() -> _QueryEncoderKeyedContainer { let container = _QueryEncoderKeyedContainer() containers.append(container) return container } /// push a new container onto the storage mutating func pushUnkeyedContainer() -> _QueryEncoderUnkeyedContainer { let container = _QueryEncoderUnkeyedContainer() containers.append(container) return container } mutating func push(container: Any) { containers.append(container) } /// pop a container from the storage @discardableResult mutating func popContainer() -> Any { return containers.removeLast() } } /// Internal QueryEncoder class. Does all the heavy lifting private class _QueryEncoder: Encoder { var codingPath: [CodingKey] /// the encoder's storage var storage: _QueryEncoderStorage /// options var options: QueryEncoder._Options /// resultant query array var result: _QueryEncoderKeyedContainer? /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey: Any] { return self.options.userInfo } /// Initialization /// - Parameters: /// - options: options /// - containerCodingMapType: Container encoding for the top level object init(options: QueryEncoder._Options) { self.storage = _QueryEncoderStorage() self.options = options self.codingPath = [] self.result = nil } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { let newContainer = storage.pushKeyedContainer() if self.result == nil { self.result = newContainer } return KeyedEncodingContainer(KEC(referencing: self, container: newContainer)) } struct KEC<Key: CodingKey>: KeyedEncodingContainerProtocol { var codingPath: [CodingKey] { return encoder.codingPath } let container: _QueryEncoderKeyedContainer let encoder: _QueryEncoder /// Initialization /// - Parameter referencing: encoder that created this init(referencing: _QueryEncoder, container: _QueryEncoderKeyedContainer) { self.encoder = referencing self.container = container } mutating func encode(_ value: Any, key: String) { container.addChild(path: ec2Encode(key), child: value) } mutating func encodeNil(forKey key: Key) throws { encode("", key: key.stringValue) } mutating func encode(_ value: Bool, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Int, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Int8, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Int16, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Int32, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: Int64, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: UInt, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: UInt8, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: UInt16, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: UInt32, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode(_ value: UInt64, forKey key: Key) throws { encode(value, key: key.stringValue) } mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let childContainer = try encoder.box(value) container.addChild(path: ec2Encode(key.stringValue), child: childContainer) } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let keyedContainer = _QueryEncoderKeyedContainer() container.addChild(path: ec2Encode(key.stringValue), child: keyedContainer) let kec = KEC<NestedKey>(referencing: self.encoder, container: keyedContainer) return KeyedEncodingContainer(kec) } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let unkeyedContainer = _QueryEncoderUnkeyedContainer() container.addChild(path: ec2Encode(key.stringValue), child: unkeyedContainer) return UKEC(referencing: self.encoder, container: unkeyedContainer) } mutating func superEncoder() -> Encoder { return encoder } mutating func superEncoder(forKey key: Key) -> Encoder { return encoder } func ec2Encode(_ string: String) -> String { if encoder.options.ec2 { return string.uppercaseFirst() } return string } } func unkeyedContainer() -> UnkeyedEncodingContainer { let container = storage.pushUnkeyedContainer() return UKEC(referencing: self, container: container) } struct UKEC: UnkeyedEncodingContainer { var codingPath: [CodingKey] { return encoder.codingPath } let container: _QueryEncoderUnkeyedContainer let encoder: _QueryEncoder var count: Int init(referencing: _QueryEncoder, container: _QueryEncoderUnkeyedContainer) { self.encoder = referencing self.container = container self.count = 0 } mutating func encodeResult(_ value: Any) { count += 1 container.addChild(value) } mutating func encodeNil() throws { encodeResult("") } mutating func encode(_ value: Bool) throws { encodeResult(value) } mutating func encode(_ value: String) throws { encodeResult(value) } mutating func encode(_ value: Double) throws { encodeResult(value) } mutating func encode(_ value: Float) throws { encodeResult(value) } mutating func encode(_ value: Int) throws { encodeResult(value) } mutating func encode(_ value: Int8) throws { encodeResult(value) } mutating func encode(_ value: Int16) throws { encodeResult(value) } mutating func encode(_ value: Int32) throws { encodeResult(value) } mutating func encode(_ value: Int64) throws { encodeResult(value) } mutating func encode(_ value: UInt) throws { encodeResult(value) } mutating func encode(_ value: UInt8) throws { encodeResult(value) } mutating func encode(_ value: UInt16) throws { encodeResult(value) } mutating func encode(_ value: UInt32) throws { encodeResult(value) } mutating func encode(_ value: UInt64) throws { encodeResult(value) } mutating func encode<T: Encodable>(_ value: T) throws { count += 1 self.encoder.codingPath.append(_QueryKey(index: count)) defer { self.encoder.codingPath.removeLast() } let childContainer = try encoder.box(value) container.addChild(childContainer) } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { count += 1 self.encoder.codingPath.append(_QueryKey(index: count)) defer { self.encoder.codingPath.removeLast() } let keyedContainer = _QueryEncoderKeyedContainer() container.addChild(keyedContainer) let kec = KEC<NestedKey>(referencing: self.encoder, container: keyedContainer) return KeyedEncodingContainer(kec) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { count += 1 let unkeyedContainer = _QueryEncoderUnkeyedContainer() container.addChild(unkeyedContainer) return UKEC(referencing: self.encoder, container: unkeyedContainer) } mutating func superEncoder() -> Encoder { return encoder } } } extension _QueryEncoder: SingleValueEncodingContainer { func encodeResult(_ value: Any) { storage.push(container: value) } func encodeNil() throws { encodeResult("") } func encode(_ value: Bool) throws { encodeResult(value) } func encode(_ value: String) throws { encodeResult(value) } func encode(_ value: Double) throws { encodeResult(value) } func encode(_ value: Float) throws { encodeResult(value) } func encode(_ value: Int) throws { encodeResult(value) } func encode(_ value: Int8) throws { encodeResult(value) } func encode(_ value: Int16) throws { encodeResult(value) } func encode(_ value: Int32) throws { encodeResult(value) } func encode(_ value: Int64) throws { encodeResult(value) } func encode(_ value: UInt) throws { encodeResult(value) } func encode(_ value: UInt8) throws { encodeResult(value) } func encode(_ value: UInt16) throws { encodeResult(value) } func encode(_ value: UInt32) throws { encodeResult(value) } func encode(_ value: UInt64) throws { encodeResult(value) } func encode<T: Encodable>(_ value: T) throws { try value.encode(to: self) } func singleValueContainer() -> SingleValueEncodingContainer { return self } } extension _QueryEncoder { func box(_ data: Data) throws -> Any { try encode(data.base64EncodedString()) return storage.popContainer() } func box(_ value: Encodable) throws -> Any { let type = Swift.type(of: value) if type == Data.self || type == NSData.self { return try self.box(value as! Data) } else { try value.encode(to: self) return storage.popContainer() } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// private struct _QueryKey: CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "\(index)" self.intValue = index } fileprivate static let `super` = _QueryKey(stringValue: "super")! } extension String { func uppercaseFirst() -> String { guard self.count > 0 else { return self } return String(self[self.startIndex]).uppercased() + self[index(after: startIndex)...] } }
38.402913
164
0.633675
489bdf943efc6fd73b10bfe4f2ee321cbe69f3ce
126
// TODO: Remove uses of advance() extension Strideable { mutating func advance() { self = advanced(by: 1) } }
18
33
0.603175
deeee10e05589c8cab34c2749fd5aafd45a52dd9
2,267
// // BookExtension.swift // toBook // // Created by Mac on 16/12/18. // Copyright © 2016年 Mac. All rights reserved. // import UIKit import SDWebImage extension UIImage { //将image转换为size大小 func resizeToSize(size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) //联系上下文 drawInRect(CGRectMake(0, 0, size.width, size.height)) //重新图片调整大小 let newImage = UIGraphicsGetImageFromCurrentImageContext() //从上下文获取得到的图片 UIGraphicsEndImageContext() //关闭上下文 return newImage } } extension UIImageView { func setResizeImageWith(URLString: String , width:CGFloat) { let URL = NSURL(string: URLString) //获取url地址 let key = SDWebImageManager.sharedManager().cacheKeyForURL(URL) ?? "" //从缓存中获取图片 //判断缓存中是否有照片 if var cacheImage = SDImageCache.sharedImageCache().imageFromCacheForKey(key) { if cacheImage.size.width > width { let size = CGSizeMake(width, cacheImage.size.height * (width/cacheImage.size.width)) cacheImage = cacheImage.resizeToSize(size) } self.image = cacheImage }else{ SDWebImageDownloader.sharedDownloader().downloadImageWithURL(URL, options: SDWebImageDownloaderOptions.AllowInvalidSSLCertificates, progress: nil, completed: { ( var forimage, data, error, result) in if forimage != nil && forimage!.size.width > width { let size = CGSizeMake(width, forimage!.size.height * (width/forimage!.size.width)) forimage = forimage!.resizeToSize(size) } self.image = forimage }) } } } // SDWebImageDownloader.sharedDownloader().downloadImageWithURL(URL, options: .AllowInvalidSSLCertificates, progress: nil, completed: { (var image, data, error, result) -> Void in // if image != nil && image.size.width > width { // let size = CGSizeMake(width, image.size.height * (width / image.size.width)) // // image = image.resizeToSize(size) // } // self.image = image // }) // } // } //}
36.564516
211
0.59506
648b5628b3719b18950e3ca8c49bd4cd33ee453e
12,807
// // MessagesController.swift // PipeLineChat // // Created by Tuncay Cansız on 30.08.2019. // Copyright © 2019 Tuncay Cansız. All rights reserved. // import UIKit import Firebase // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class MessagesController: UITableViewController { let cellId = "cellId" override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleDeleteAllMessage)) let image = UIImage(named: "NewMessage") navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleNewMessage)) checkIfUserIsLoggedIn() tableView.register(UserCell.self, forCellReuseIdentifier: cellId) } var messages = [Message]() var messagesDictionary = [String: Message]() //To delete the message on the TableView by sliding it to the left. //TableView üzerinde ki mesajları sola kaydırarak silmek için. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard let uid = Auth.auth().currentUser?.uid else { return } let message = self.messages[indexPath.row] if let chatPartnerId = message.chatPartnerId() { Database.database().reference().child("user-messages").child(uid).child(chatPartnerId).removeValue(completionBlock: { (error, ref) in if error != nil { print("Failed to delete message:", error!) return } self.messagesDictionary.removeValue(forKey: chatPartnerId) self.attemptReloadOfTable() }) } } //Observes/checks user messages. //Kullanıcı mesajlarını gözlemler/kontrol eder. func observeUserMessages() { guard let uid = Auth.auth().currentUser?.uid else { return } let ref = Database.database().reference().child("user-messages").child(uid) ref.observe(.childAdded, with: { (snapshot) in let userId = snapshot.key Database.database().reference().child("user-messages").child(uid).child(userId).observe(.childAdded, with: { (snapshot) in let messageId = snapshot.key self.fetchMessageWithMessageId(messageId) }, withCancel: nil) }, withCancel: nil) ref.observe(.childRemoved, with: { (snapshot) in //print(snapshot.key) //print(self.messagesDictionary) self.messagesDictionary.removeValue(forKey: snapshot.key) self.attemptReloadOfTable() }, withCancel: nil) } // Deletes all messages in the user id. //Kullanıcı id'sinde bulunan tüm mesajları siler. @objc func handleDeleteAllMessage(){ guard let uid = Auth.auth().currentUser?.uid else { return } let alert = UIAlertController(title: "Do you want to delete all conversations before you sign out?", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Delete", style: .destructive, handler: { (action) in Database.database().reference().child("user-messages").child(uid).removeValue { (error, ref) in if error != nil { print("Failed to delete message:", error!) return } self.messagesDictionary.removeValue(forKey: uid) self.attemptReloadOfTable() } self.handleLogout() })) alert.addAction(UIAlertAction.init(title: "No", style: .default, handler: { (action) in self.handleLogout() })) self.present(alert, animated: true, completion: nil) } //Fetch messages with message id. //Mesaj id ile mesajları getirir. fileprivate func fetchMessageWithMessageId(_ messageId: String) { let messagesReference = Database.database().reference().child("messages").child(messageId) messagesReference.observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { let message = Message(dictionary: dictionary) if let chatPartnerId = message.chatPartnerId() { self.messagesDictionary[chatPartnerId] = message } self.attemptReloadOfTable() } }, withCancel: nil) } //Checks messages at 0.1 second intervals. //Mesaj listesini 0.1 saniye aralıklarla kontrol eder. fileprivate func attemptReloadOfTable() { self.timer?.invalidate() self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false) } var timer: Timer? //Check the message list, edit the list if there are changes. //Mesaj listesini kontrol eder, değişiklik varsa listeyi düzenler. @objc func handleReloadTable() { self.messages = Array(self.messagesDictionary.values) self.messages.sort(by: { (message1, message2) -> Bool in return message1.timestamp?.int32Value > message2.timestamp?.int32Value }) //this will crash because of background thread, so lets call this on dispatch_async main thread DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell let message = messages[indexPath.row] cell.message = message return cell } //Returns the height of the element for each element in the TableView. //TableView üzerinde ki herbir eleman için elemanın yükselik değerini döndürür. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 72 } //Allows us to select objects on the TableView. //TableView üzerindeki nesneleri seçmemizi sağlar. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let message = messages[indexPath.row] guard let chatPartnerId = message.chatPartnerId() else { return } let ref = Database.database().reference().child("users").child(chatPartnerId) ref.observeSingleEvent(of: .value, with: { (snapshot) in guard let dictionary = snapshot.value as? [String: AnyObject] else { return } let user = User(dictionary: dictionary) user.id = chatPartnerId self.showChatControllerForUser(user) }, withCancel: nil) } //Fetch the NewMessageController page. //NewMessageController sayfasını çağırır. @objc func handleNewMessage() { let newMessageController = NewMessageController() newMessageController.messagesController = self let navController = UINavigationController(rootViewController: newMessageController) present(navController, animated: true, completion: nil) } //Controls the user's session. //Kullanıcının oturumunu kontrol eder. func checkIfUserIsLoggedIn() { if Auth.auth().currentUser?.uid == nil { perform(#selector(handleLogout), with: nil, afterDelay: 0) } else { fetchUserAndSetupNavBarTitle() } } //Fetch user name. //Kullanıcı isim bilgisini getirir. func fetchUserAndSetupNavBarTitle() { guard let uid = Auth.auth().currentUser?.uid else { return //for some reason uid = nil } Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { let user = User(dictionary: dictionary) self.setupNavBarWithUser(user) } }, withCancel: nil) } //The user name and photo to be brought to Navbara are positioned. //Navbar'a getirilecek isim bilgisi ve fotoğraf konumlandırılıyor. func setupNavBarWithUser(_ user: User) { messages.removeAll() messagesDictionary.removeAll() tableView.reloadData() observeUserMessages() let titleView = UIView() titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false titleView.addSubview(containerView) NSLayoutConstraint.activate([containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor), containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor) ]) let profileImageView = UIImageView() profileImageView.translatesAutoresizingMaskIntoConstraints = false profileImageView.contentMode = .scaleAspectFill profileImageView.layer.cornerRadius = 15 profileImageView.clipsToBounds = true if let profileImageUrl = user.profileImageUrl { profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl) } containerView.addSubview(profileImageView) NSLayoutConstraint.activate([profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor), profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor), profileImageView.widthAnchor.constraint(equalToConstant: 30), profileImageView.heightAnchor.constraint(equalToConstant: 30) ]) let nameLabel = UILabel() nameLabel.text = user.name nameLabel.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(nameLabel) NSLayoutConstraint.activate([nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8), nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor), nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor), nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor) ]) self.navigationItem.titleView = titleView } //Fetch the ChatLogController page. //ChatLogController sayfasını çağırır. func showChatControllerForUser(_ user: User) { let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout()) chatLogController.user = user navigationController?.pushViewController(chatLogController, animated: true) } //User's closed the session and fetch the LoginController page. //Kullanıcı oturumu kapatır, LoginController sayfası çağırılır. @objc func handleLogout() { do { try Auth.auth().signOut() } catch let logoutError { print(logoutError) } let loginController = LoginController() loginController.messagesController = self present(loginController, animated: true, completion: nil) } }
39.527778
150
0.62583
38b162971efa8a85c452360cca4853d0398ab256
404
// // Yoshi.swift // SSBUNotes // // Created by maxence on 11/12/2021. // import UIKit extension CharacterData { static let yoshi = Character( id: 5, url_name: "yoshi", name: "Yoshi", background_color: UIColor(named: "yoshi_background_color") ?? .black, icon: UIImage(named: "yoshi_icon") ?? UIImage(), image: UIImage(named: "yoshi_image") ?? UIImage(), note: "" ) }
18.363636
73
0.626238
7a658afe004dc81a2379b08d5ffb9ebd3b68db89
6,857
// // FitBitProfile.swift // fibi // // Created by Kyryl Horbushko on 28.07.2020. // Copyright © 2020 Kyryl Horbushko. All rights reserved. // import Foundation /* { "user": { "age": 31, "ambassador": false, "avatar": "https://static0.fitbit.com/images/profile/defaultProfile_100.png", "avatar150": "https://static0.fitbit.com/images/profile/defaultProfile_150.png", "avatar640": "https://static0.fitbit.com/images/profile/defaultProfile_640.png", "averageDailySteps": 5602, "challengesBeta": true, "clockTimeDisplayFormat": "12hour", "corporate": false, "corporateAdmin": false, "dateOfBirth": "1988-08-30", "displayName": "Kyryl H.", "displayNameSetting": "name", "distanceUnit": "METRIC", "encodedId": "8MHHY7", "features": { "exerciseGoal": true }, "firstName": "Kyryl", "foodsLocale": "en_US", "fullName": "Kyryl Horbushko", "gender": "MALE", "glucoseUnit": "en_US", "height": 172.0, "heightUnit": "METRIC", "isBugReportEnabled": false, "isChild": false, "isCoach": false, "languageLocale": "en_US", "lastName": "Horbushko", "legalTermsAcceptRequired": false, "locale": "en_US", "memberSince": "2020-07-01", "mfaEnabled": false, "offsetFromUTCMillis": 10800000, "sdkDeveloper": false, "sleepTracking": "Normal", "startDayOfWeek": "SUNDAY", "strideLengthRunning": 106.5, "strideLengthRunningType": "default", "strideLengthWalking": 71.4, "strideLengthWalkingType": "default", "swimUnit": "METRIC", "timezone": "Europe/Kiev", "topBadges": [ { "badgeType":"DAILY_FLOORS", "dateTime":"2012-04-27", "image50px":"http://www.fitbit.com/images/dash/badge_daily_floors10.png", "image75px":"http://www.fitbit.com/images/dash/75px/badge_daily_floors10.png", "timesAchieved":3, "value":10 } ], "waterUnit": "en_US", "waterUnitName": "fl oz", "weight": 82.0, "weightUnit": "METRIC" } } */ /// The Get Profile endpoint returns a user's profile. The authenticated owner receives all values. Access to other user's profile is not available. If you wish to retrieve the profile information of the authenticated owner's friends, use the Get Friends API. Numerical values are returned in the unit system specified in the Accept-Language header. /// /// ## Considerations: /// /// - The field is present at all times. It contains one of the following: /// /// - The user's fullName. /// /// - A portion of user's email address before the at sign, "@". This is used in the case where the fullName field is empty. /// /// - The Units fields (<glucoseUnit>, etc.) represent default unit settings of the user's Web UI. The field is also used as a default for all other body measurements (such as neck, bicep, etc.). /// /// - The field indicates the local website version currently used (such as, en_US, en_GB, etc.). /// /// more - https://dev.fitbit.com/build/reference/web-api/user/ /// public final class FitBitProfile: Codable { public let age: Int public let ambassador: Bool public let avatar: String public let averageDailySteps: Int public let dateOfBirth: Date public let displayName: String public let displayNameSetting: String public let distanceUnit: MeasurementSystem public let encodedId: String public let features: FitBitUserFeatures public let firstName: String public let foodsLocale: String public let fullName: String public let gender: Gender public let glucoseUnit: MeasurementSystem public let height: Int public let heightUnit: MeasurementSystem public let sleepTracking: String public let startDayOfWeek: String public let lastName: String public let legalTermsAcceptRequired: Bool public let locale: String public let timezone: String public let weight: Int public let weightUnit: MeasurementSystem public let clockTimeDisplayFormat: ClockDisplayFormat private enum Key: String, CodingKey { case user case age case ambassador case avatar case averageDailySteps case dateOfBirth case displayName case displayNameSetting case distanceUnit case encodedId case features case firstName case foodsLocale case fullName case gender case glucoseUnit case height case heightUnit case sleepTracking case startDayOfWeek case lastName case legalTermsAcceptRequired case locale case timezone case weight case weightUnit case clockTimeDisplayFormat } required public init(from decoder: Decoder) throws { var container = try decoder.container(keyedBy: Key.self) if let subContainer = try? container.nestedContainer(keyedBy: Key.self, forKey: .user) { container = subContainer } age = try container.decode(.age) ambassador = try container.decode(.ambassador) avatar = try container.decode(.avatar) averageDailySteps = try container.decode(.averageDailySteps) dateOfBirth = try container.decode(.dateOfBirth) displayName = try container.decode(.displayName) displayNameSetting = try container.decode(.displayNameSetting) distanceUnit = try container.decode(.distanceUnit) encodedId = try container.decode(.encodedId) features = try container.decode(.features) firstName = try container.decode(.firstName) foodsLocale = try container.decode(.foodsLocale) fullName = try container.decode(.fullName) gender = try container.decode(.gender) glucoseUnit = try container.decode(.glucoseUnit) height = try container.decode(.height) heightUnit = try container.decode(.heightUnit) sleepTracking = try container.decode(.sleepTracking) startDayOfWeek = try container.decode(.startDayOfWeek) lastName = try container.decode(.lastName) legalTermsAcceptRequired = try container.decode(.legalTermsAcceptRequired) locale = try container.decode(.locale) timezone = try container.decode(.timezone) weight = try container.decode(.weight) weightUnit = try container.decode(.weightUnit) clockTimeDisplayFormat = try container.decode(.clockTimeDisplayFormat) } } public final class FitBitUserFeatures: Codable { public let exerciseGoal: Bool } public enum Gender: String, Codable { case male = "MALE" case female = "FEMALE" case unknown = "NA" } public enum ClockDisplayFormat: String, Codable { case hour12 = "12hour" case hour24 = "24hour" } public enum MeasurementSystem: String, Codable { case metric = "METRIC" case imperial = "en_US" case any = "any" case us = "us" case stone = "stone" }
32.042056
349
0.680473
db6cea50d1420c90b36d124382f124c4034f0cef
1,828
import UIKit class TabLine: UIViewController, FormLine { var actionDelegate: ActionDelegate? private let tabBtn = UISegmentedControl() private var tabOptions: Array<String> = [] private let radioController: RadioButtonController = RadioButtonController() let multiFormName: String? let multiFormValue: String? /** - Parameters: - selected: The (pre)selected tab value - tabs: The available tab options - multiFormName: The name of the multi form this element is part of (if any) - multiFormValue: The value of the sub form this element is part of (if any) */ init(selected: String, tabs: Dictionary<String, String>, multiFormName: String?, multiFormValue: String?) { self.multiFormName = multiFormName self.multiFormValue = multiFormValue super.init(nibName: nil, bundle: nil) var index = 0 for (key, value) in tabs { tabBtn.insertSegment(withTitle: value, at: index, animated: false) tabOptions.append(key) if key == selected { tabBtn.selectedSegmentIndex = index } index += 1 } /// Attach selectedTabChanged function to the tab button tabBtn.addTarget(self, action: #selector(selectedTabChanged), for: .valueChanged) } @objc func selectedTabChanged(sender: UIButton) { let payload = [ "params": tabOptions[tabBtn.selectedSegmentIndex] ] actionDelegate?.sendAction(actionType: .switch_login_tabs, withLoadingIndicator: true, additionalPayload: payload) } override func viewDidLoad() { tabBtn.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tabBtn) NSLayoutConstraint.activate([ view.heightAnchor.constraint(equalTo: tabBtn.heightAnchor), tabBtn.widthAnchor.constraint(equalTo: view.widthAnchor), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
27.69697
116
0.736324
de546e57e1eaea0a4f4a7d686f8d1ecc6527bf5e
3,464
// Created by Francisco Diaz on 3/25/20. // // Copyright (c) 2020 Francisco Diaz // // Distributed under the MIT License // // 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 ArgumentParser import Foundation import SwiftInspectorAnalyzers final class TypealiasCommand: ParsableCommand { static var configuration = CommandConfiguration( commandName: "typealias", abstract: "Finds information related to the declaration of a typelias" ) @Option(help: Help.name) var name: String = "" @Option(help: "The absolute path to the file to inspect") var path: String /// Runs the command func run() throws { let cachedSyntaxTree = CachedSyntaxTree() let analyzer = TypealiasAnalyzer(cachedSyntaxTree: cachedSyntaxTree) let fileURL = URL(fileURLWithPath: path) let outputArray = try FileManager.default.swiftFiles(at: fileURL) .reduce(Set<String>()) { result, url in let statements = try analyzer.analyze(fileURL: url) let output = filterOutput(statements).map { outputString(from: $0) } return result.union(output) } let output = outputArray.filter { !$0.isEmpty }.joined(separator: "\n") print(output) } /// Validates if the arguments of this command are valid func validate() throws { guard !path.isEmpty else { throw InspectorError.emptyArgument(argumentName: "--path") } let pathURL = URL(fileURLWithPath: path) guard FileManager.default.isSwiftFile(at: pathURL) else { throw InspectorError.invalidArgument(argumentName: "--path", value: path) } } /// Filters the output based on command line inputs private func filterOutput(_ output: [TypealiasStatement]) -> [TypealiasStatement] { guard !name.isEmpty else { return output } return output.filter { $0.name == name } } private func outputString(from statement: TypealiasStatement) -> String { guard !name.isEmpty else { return statement.name } return "\(statement.name) \(statement.identifiers.joined(separator: " "))" } } private struct Help { static var name: ArgumentHelp { ArgumentHelp("Used to filter by the name of the typelias", discussion: """ If a value is passed, it outputs the name of the typealias and the information of the identifiers being declared in that typealias. """ ) } }
35.71134
95
0.700058
7abcd71f92c819492f5db52eb699f38d731d5da4
559
// // CardHolder.swift // import Foundation open class CardHolder: JSONEncodable { public var name: String? public var identification: CardHolderIdentification? public init() {} // MARK: JSONEncodable open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["name"] = self.name nillableDictionary["identification"] = self.identification?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } }
24.304348
85
0.670841
0e64cb58aedb9d6c62104f43cf25707d4c64e706
1,145
import UIKit import CoreLocation import MapboxStatic class ViewController: UIViewController { // You can also specify the access token with the `MGLMapboxAccessToken` key in Info.plist. let accessToken = "pk.eyJ1IjoianVzdGluIiwiYSI6IlpDbUJLSUEifQ.4mG8vhelFMju6HpIY-Hi5A" var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(frame: view.bounds) imageView.backgroundColor = UIColor.blackColor() view.addSubview(imageView) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let options = SnapshotOptions( mapIdentifiers: ["justin.tm2-basemap"], centerCoordinate: CLLocationCoordinate2D(latitude: 45, longitude: -122), zoomLevel: 6, size: imageView.bounds.size) Snapshot(options: options, accessToken: accessToken).image { [weak self] (image, error) in guard error == nil else { print(error) return } self?.imageView.image = image } } }
30.131579
98
0.634061
0e92ce6279ff9bc10600378eb7c18ce2eeebde8e
2,526
import UIKit import UIKit final class TransferStatusCell: UITableViewCell { static let identifier = String(describing: TransferStatusCell.self) private enum ViewLayout { static let iconSize = CGSize(width: 24, height: 24) } private let icon: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() private let titleLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 16) return label }() private let subtitleLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 16) return label }() private lazy var separatorView: UIView = { let view = UIView() view.backgroundColor = .lightGray return view }() private let stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal return stackView }() private let subtitleStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.spacing = 8 return stackView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupView() setupConstraints() } required init?(coder: NSCoder) { fatalError() } // MARK: - Configure func configure(with item: TransferStatusItem, uiConfig: UIConfig?) { self.titleLabel.text = item.title self.subtitleLabel.text = item.subtitle self.icon.image = item.icon self.selectionStyle = .none self.backgroundColor = uiConfig?.uiBackgroundPrimaryColor self.titleLabel.textColor = uiConfig?.textPrimaryColor self.subtitleLabel.textColor = uiConfig?.textPrimaryColor } // MARKL - Setup View private func setupView() { subtitleStackView.addArrangedSubview(icon) subtitleStackView.addArrangedSubview(subtitleLabel) stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(UIView()) stackView.addArrangedSubview(subtitleStackView) addSubview(stackView) addSubview(separatorView) } private func setupConstraints() { stackView.snp.makeConstraints { constraints in constraints.edges.equalToSuperview().inset(17) } separatorView.snp.makeConstraints { constraints in constraints.bottom.equalToSuperview().inset(4) constraints.height.equalTo(1) constraints.leading.equalTo(15) constraints.trailing.equalToSuperview() } } }
27.16129
77
0.702296
75d19b6ad6163edb11c4a911d346a3c4faf22015
13,893
// MXSegment.swift // // Copyright (c) 2017 Maxime Epain // // 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 /// A segment button embed in MXSegmentedControl public class MXSegment: UIButton { /// The Image position in segment related to title. /// /// - top: Image will be placed on top of the title. /// - left: Image will be placed at the left of the title. /// - bottom: Image will be placed below the title. /// - right: Image will be placed at the right of the title. public enum ImagePosition { case top case left case bottom case right } /// The image position related to the title. public var imagePosition = ImagePosition.top /// Padding between segment title and image public var padding: CGFloat = 8 /// The segment width public var width: CGFloat { get { if _width == UIView.noIntrinsicMetric { return intrinsicContentSize.width } return _width } set { _width = newValue } } private var _width: CGFloat = UIView.noIntrinsicMetric @discardableResult public func set(width: CGFloat) -> MXSegment { self.width = width return self } @discardableResult public func set(image position: ImagePosition) -> MXSegment { self.imagePosition = position return self } @discardableResult public func set(padding: CGFloat) -> MXSegment { self.padding = padding return self } @discardableResult public func set(title: String?, for state: UIControl.State = .normal) -> MXSegment { super.setTitle(title, for: state) return self } @discardableResult public func set(title color: UIColor?, for state: UIControl.State = .normal) -> MXSegment { super.setTitleColor(color, for: state) return self } @discardableResult public func set(image: UIImage?, for state: UIControl.State = .normal) -> MXSegment { super.setImage(image, for: state) return self } @discardableResult public func set(background image: UIImage?, for state: UIControl.State = .normal) -> MXSegment { super.setBackgroundImage(image, for: state) return self } @discardableResult public func set(attributedTitle: NSAttributedString?, for state: UIControl.State = .normal) -> MXSegment { super.setAttributedTitle(attributedTitle, for: state) return self } } // MARK: - Layouts extension MXSegment { /// :nodoc: public override func layoutSubviews() { super.layoutSubviews() guard let titleLabel = titleLabel, let imageView = imageView else { return } guard !titleLabel.frame.isEmpty, !imageView.frame.isEmpty else { return } switch imagePosition { case .top: layoutTop(imageView, titleLabel) case .left: layoutLeft(imageView, titleLabel) case .bottom: layoutBottom(imageView, titleLabel) case .right: layoutRight(imageView, titleLabel) } } /// :nodoc: public override var intrinsicContentSize: CGSize { let titleSize = titleLabel?.intrinsicContentSize let imageSize = imageView?.intrinsicContentSize var size = CGSize.zero switch imagePosition { case .top, .bottom: if let titleSize = titleSize { size.height += titleSize.height size.height += titleEdgeInsets.top size.height += titleEdgeInsets.bottom var width = titleSize.width width += titleEdgeInsets.left width += titleEdgeInsets.right size.width = width } if let imageSize = imageSize { size.height += imageSize.height size.height += imageEdgeInsets.top size.height += imageEdgeInsets.bottom var width = imageSize.width width += imageEdgeInsets.left width += imageEdgeInsets.right size.width = max(size.width, width) } if titleLabel != nil || imageView != nil { size.height += padding } case .left, .right: if let titleSize = titleSize { size.width += titleSize.width size.width += titleEdgeInsets.left size.width += titleEdgeInsets.right var height = titleSize.height height += titleEdgeInsets.top height += titleEdgeInsets.bottom size.height = height } if let imageSize = imageSize { size.width += imageSize.height size.width += imageEdgeInsets.left size.width += imageEdgeInsets.right var height = imageSize.height height += imageEdgeInsets.top height += imageEdgeInsets.bottom size.height = max(size.height, height) } if titleLabel != nil || imageView != nil { size.width += padding } } if titleLabel != nil || imageView != nil { size.width += contentEdgeInsets.left size.width += contentEdgeInsets.right size.height += contentEdgeInsets.top size.height += contentEdgeInsets.bottom } return size } private func layoutTop(_ imageView: UIImageView, _ titleLabel: UILabel) { let contentRect = self.contentRect(forBounds: bounds) let imageSize = imageView.intrinsicContentSize let titleSize = titleLabel.intrinsicContentSize // Compute Image View Frame var width = contentRect.width width -= imageEdgeInsets.left width -= imageEdgeInsets.right width = min(width, imageSize.width) var height = contentRect.height height -= imageEdgeInsets.top height -= imageEdgeInsets.bottom height -= titleEdgeInsets.top height -= titleEdgeInsets.bottom height -= titleSize.height height -= padding height = min(height, imageSize.height) var x = max(contentRect.minX + imageEdgeInsets.left, contentRect.midX - width / 2) var y = max(contentRect.minY + imageEdgeInsets.top, contentRect.midY - (height + titleSize.height + padding) / 2) imageView.frame = CGRect(x: x, y: y, width: width, height: height) // // Compute Title Label Frame x = max(contentRect.minX + titleEdgeInsets.left, contentRect.midX - titleSize.width / 2) y = imageView.frame.maxY y += imageEdgeInsets.bottom y += padding y += titleEdgeInsets.top width = contentRect.width width -= titleEdgeInsets.left width -= titleEdgeInsets.right width = min(width, titleSize.width) titleLabel.frame = CGRect(x: x, y: y, width: width, height: titleSize.height) // } private func layoutBottom(_ imageView: UIImageView, _ titleLabel: UILabel) { let contentRect = self.contentRect(forBounds: bounds) let imageSize = imageView.intrinsicContentSize let titleSize = titleLabel.intrinsicContentSize // Compute Title Label Frame var width = contentRect.width width -= titleEdgeInsets.left width -= titleEdgeInsets.right width = min(width, titleSize.width) var height = contentRect.height height -= imageEdgeInsets.top height -= imageEdgeInsets.bottom height -= titleEdgeInsets.top height -= titleEdgeInsets.bottom height -= titleSize.height height -= padding height = min(height, imageSize.height) var x = max(contentRect.minX + titleEdgeInsets.left, contentRect.midX - titleSize.width / 2) var y = max(contentRect.minY + titleEdgeInsets.top, contentRect.midY - (height + titleSize.height + padding) / 2) titleLabel.frame = CGRect(x: x, y: y, width: width, height: titleSize.height) // // Compute Image View Frame width = contentRect.width width -= imageEdgeInsets.left width -= imageEdgeInsets.right width = min(width, imageSize.width) x = max(contentRect.minX + imageEdgeInsets.left, contentRect.midX - width / 2) y = titleLabel.frame.maxY y += titleEdgeInsets.bottom y += padding y += imageEdgeInsets.top imageView.frame = CGRect(x: x, y: y, width: width, height: height) // } private func layoutLeft(_ imageView: UIImageView, _ titleLabel: UILabel) { let contentRect = self.contentRect(forBounds: bounds) let imageSize = imageView.intrinsicContentSize let titleSize = titleLabel.intrinsicContentSize // Compute Image View Frame var width = contentRect.width width -= imageEdgeInsets.left width -= imageEdgeInsets.right width -= titleEdgeInsets.left width -= titleEdgeInsets.right width -= padding width = min(width, imageSize.width) var height = contentRect.height height -= imageEdgeInsets.top height -= imageEdgeInsets.bottom height = min(height, imageSize.height) var x = max(contentRect.minX + imageEdgeInsets.left, contentRect.midX - (width + titleSize.width + padding) / 2) var y = max(contentRect.minY + imageEdgeInsets.top, contentRect.midY - height / 2) imageView.frame = CGRect(x: x, y: y, width: width, height: height) // // Compute Title Label Frame y = max(contentRect.minY + titleEdgeInsets.top, contentRect.midY - titleSize.height / 2) x = imageView.frame.maxX x += imageEdgeInsets.right x += padding x += titleEdgeInsets.left height = contentRect.height height -= titleEdgeInsets.top height -= titleEdgeInsets.bottom height = min(height, titleSize.height) width = contentRect.maxX width -= titleEdgeInsets.right width -= x titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) // } private func layoutRight(_ imageView: UIImageView, _ titleLabel: UILabel) { let contentRect = self.contentRect(forBounds: bounds) let imageSize = imageView.intrinsicContentSize let titleSize = titleLabel.intrinsicContentSize // Compute Title Label Frame var width = contentRect.width width -= imageEdgeInsets.left width -= imageEdgeInsets.right width -= titleEdgeInsets.left width -= titleEdgeInsets.right width -= padding width -= imageSize.width var height = contentRect.height height -= titleEdgeInsets.top height -= titleEdgeInsets.bottom height = min(height, titleSize.height) var x = max(contentRect.minX + titleEdgeInsets.left, contentRect.midX - (imageSize.width + width + padding) / 2) var y = max(contentRect.minY + titleEdgeInsets.top, contentRect.midY - height / 2) titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) // // Compute Image View Frame x += width x += titleEdgeInsets.right x += padding x += imageEdgeInsets.left y = max(contentRect.minY + imageEdgeInsets.top, contentRect.midY - imageSize.height / 2) width = contentRect.maxX width -= imageEdgeInsets.left width -= imageEdgeInsets.right width = min(width, imageSize.width) height = contentRect.height height -= imageEdgeInsets.top height -= imageEdgeInsets.bottom height = min(height, imageSize.height) imageView.frame = CGRect(x: x, y: y, width: width, height: height) // } }
34.645885
129
0.582811
214d40bc944a637f460dcba88f0195430a1d2606
378
// // Copyright © 2020 Optimize Fitness Inc. // Licensed under the MIT license // https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE // import Foundation import MinervaCoordinator import PanModal import UIKit public protocol PanModalCoordinatorPresentable: BaseCoordinatorPresentable { var panModalPresentableVC: PanModalPresentable & UIViewController { get } }
25.2
76
0.812169
67ee0231dc0e6825463204183d27e1d6efec81b0
654
// // WeightQuery.swift // Introspective // // Created by Bryan Nova on 8/29/18. // Copyright © 2018 Bryan Nova. All rights reserved. // import Foundation import HealthKit import Samples // sourcery: AutoMockable public protocol WeightQuery: Query {} public final class WeightQueryImpl: HealthKitQuery<Weight>, WeightQuery { final override func initFromHKSample(_ hkSample: HKSample) -> Weight { precondition(hkSample is HKQuantitySample, "Wrong type of health kit sample for weight") var weight: Weight = Weight() DispatchQueue.global(qos: .userInitiated).sync { weight = Weight(hkSample as! HKQuantitySample) } return weight } }
24.222222
90
0.746177
de23cd06e7ab50e1123c841b520c220207b66153
148
import Foundation public class FrameworkCFile { public init() {} public func hello() -> String { "FrameworkCFile.hello()" } }
14.8
35
0.614865
ed04496055ce45b20f245ffa2699a64c34318405
3,215
// // AppDelegate.swift // InstagramDemo // // Created by Timothy Mak on 3/2/17. // Copyright © 2017 Timothy Mak. All rights reserved. // import UIKit import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Parse.initialize( with: ParseClientConfiguration(block: { (configuration:ParseMutableClientConfiguration) -> Void in configuration.applicationId = "Instagram-Demo" configuration.clientKey = "sleepysleptsleepilysheep" // set to nil assuming you have not set clientKey configuration.server = "https://enigmatic-sands-32545.herokuapp.com/parse" }) ) if PFUser.current() != nil { print("There is a current user") let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "TabBarController") window?.rootViewController = vc } else { print("There is no current user") let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateInitialViewController() window?.rootViewController = vc } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
44.652778
285
0.702644
726b9b73b6a7f3825d04140d861c47fce39d676b
1,121
// RUN: %empty-directory(%t) // RUN: %target-clang -fmodules -c -o %t/ErrorBridgedStaticImpl.o %S/Inputs/ErrorBridgedStaticImpl.m // RUN: %target-build-swift -static-stdlib -o %t/ErrorBridgedStatic %t/ErrorBridgedStaticImpl.o %s -import-objc-header %S/Inputs/ErrorBridgedStaticImpl.h // RUN: strip %t/ErrorBridgedStatic // RUN: %target-run %t/ErrorBridgedStatic // REQUIRES: rdar50279940 // REQUIRES: executable_test // REQUIRES: objc_interop // REQUIRES: static_stdlib import StdlibUnittest class Bar: Foo { override func foo(_ x: Int32) throws { try super.foo(5) } override func foothrows(_ x: Int32) throws { try super.foothrows(5) } } var ErrorBridgingStaticTests = TestSuite("ErrorBridging with static libs") ErrorBridgingStaticTests.test("round-trip Swift override of ObjC method") { do { try (Bar() as Foo).foo(5) } catch { } } ErrorBridgingStaticTests.test("round-trip Swift override of throwing ObjC method") { do { try (Bar() as Foo).foothrows(5) } catch { print(error) expectEqual(error._domain, "abcd") expectEqual(error._code, 1234) } } runAllTests()
26.069767
153
0.714541
331101363d2a29daef745ed0a7076fcfdd2dd43e
4,193
// // SKPhoto.swift // SKViewExample // // Created by suzuki_keishi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit @objc public protocol SKPhotoProtocol: NSObjectProtocol { var underlyingImage: UIImage! { get } var caption: String! { get } var index: Int { get set} var contentMode: UIViewContentMode { get set } func loadUnderlyingImageAndNotify() func checkCache() } // MARK: - SKPhoto open class SKPhoto: NSObject, SKPhotoProtocol { open var underlyingImage: UIImage! open var photoURL: String! open var contentMode: UIViewContentMode = .scaleAspectFill open var shouldCachePhotoURLImage: Bool = false open var caption: String! open var index: Int = 0 override init() { super.init() } convenience init(image: UIImage) { self.init() underlyingImage = image } convenience init(url: String) { self.init() photoURL = url } convenience init(url: String, holder: UIImage?) { self.init() photoURL = url underlyingImage = holder } open func checkCache() { guard let photoURL = photoURL else { return } guard shouldCachePhotoURLImage else { return } if SKCache.sharedCache.imageCache is SKRequestResponseCacheable { let request = URLRequest(url: URL(string: photoURL)!) if let img = SKCache.sharedCache.imageForRequest(request) { underlyingImage = img } } else { if let img = SKCache.sharedCache.imageForKey(photoURL) { underlyingImage = img } } } open func loadUnderlyingImageAndNotify() { if underlyingImage != nil { loadUnderlyingImageComplete() return } if photoURL != nil { // Fetch Image let session = URLSession(configuration: URLSessionConfiguration.default) if let nsURL = URL(string: photoURL) { var task: URLSessionDataTask! task = session.dataTask(with: nsURL, completionHandler: { [weak self] (data, response, error) in if let _self = self { if error != nil { DispatchQueue.main.async { _self.loadUnderlyingImageComplete() } } if let data = data, let response = response, let image = UIImage(data: data) { if _self.shouldCachePhotoURLImage { if SKCache.sharedCache.imageCache is SKRequestResponseCacheable { SKCache.sharedCache.setImageData(data, response: response, request: task.originalRequest!) } else { SKCache.sharedCache.setImage(image, forKey: _self.photoURL) } } DispatchQueue.main.async { _self.underlyingImage = image _self.loadUnderlyingImageComplete() } } session.finishTasksAndInvalidate() } }) task.resume() } } } open func loadUnderlyingImageComplete() { NotificationCenter.default.post(name: Notification.Name(rawValue: SKPHOTO_LOADING_DID_END_NOTIFICATION), object: self) } } // MARK: - Static Function extension SKPhoto { public static func photoWithImage(_ image: UIImage) -> SKPhoto { return SKPhoto(image: image) } public static func photoWithImageURL(_ url: String) -> SKPhoto { return SKPhoto(url: url) } public static func photoWithImageURL(_ url: String, holder: UIImage?) -> SKPhoto { return SKPhoto(url: url, holder: holder) } }
31.526316
126
0.531839
dd870e8448daeb07a2b8e320691623779482c675
1,995
// // XML.swift // Gabi // // Created by Jan Timar on 08/02/2020. // import Foundation public final class XML { /// Xml node name public let name: String /// Xml attributes if any contain public let attributes: [String: String] /// Child nodes if any contain public var nodes = [XML]() /// Node value public var value: String? /// Element CDATA public var cData: String? /// Parent node, this reference must be weak to avoid retain cycles, /// when you dealloc some node, his childs will be automatically deallocated too public weak var parentNode: XML? public init( name: String, attributes: [String: String] = [:] ) { self.name = name self.attributes = attributes } } extension XML: CustomStringConvertible { public var description: String { var prefix = "" var parentNode = self.parentNode while parentNode != nil { prefix.append(" ") parentNode = parentNode?.parentNode } return """ \(prefix)Name: \(name) \(prefix)Attributes: \(attributes) \(prefix)Value: \(value?.replacingOccurrences(of: "\n", with: " ") ?? "-") \(prefix)Childs: \(prefix)\(nodes) """ } } extension XML: Sequence { /// Return all child nodes with specific `keys` public subscript(name: String) -> [XML] { return filter { $0.name == name } } /// Enable use `flatMap` `forEach` `map` ... on `Xml` to iterate child nodes __consuming public func makeIterator() -> XMLIterator { return XMLIterator(nodes: nodes) } /// Return first child with same `name` public func first(name: String) -> XML? { return first(where: { $0.name == name }) } } public struct XMLIterator: IteratorProtocol { // MARK: - Private properties private var nodes: [XML] private var index = 0 init(nodes: [XML]) { self.nodes = nodes } // MARK: - IteratorProtocol public typealias Element = XML public mutating func next() -> XML? { guard nodes.count > index else { return nil } let node = nodes[index] index += 1 return node } }
21.684783
81
0.657143
872a2e45386c671ef0d473472a72f231d5d219c3
8,528
// // Router.swift // Biu // // Created by Ayari on 2019/09/29. // Copyright © 2019 Ayari. All rights reserved. // import Foundation import Alamofire import UIKit enum Router: URLRequestConvertible { case login(username: String, password: String) case signup(username: String, password: String, name: String) case getSongTickets(songid: String) case getSongsDetails(songid: [String]) case getSongDetails(songid: String) case getLrc(songid: String) case addLike(songid: String) case delLike(songid: String) case search(query: String) case getFMData(category: Int) case getMyList case getNewList case getHotList case updateSelfInfo case getLike static let biuBaseAPIAndroid = getConfig(withName: "Android", cat: "Basic") static let biuBaseAPIPWA = getConfig(withName: "PWA", cat: "Basic") static let biuBaseAPIWeb = getConfig(withName: "Web", cat: "Basic") static let biuBaseAPIAvatar = getConfig(withName: "Avatar", cat: "App") static let biuBaseAPICover = getConfig(withName: "Cover", cat: "App") static let biuBaseAPIFMCover = getConfig(withName: "FMCover", cat: "App") static let biuBaseAPISignup = getConfig(withName: "Signup", cat: "App") static let biuBaseAPIFM = getConfig(withName: "FM", cat: "App") static let PublicHeaders: [String: String] = [ "Accept": "application/json, text/plain, */*", "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Biu/\(Constants.build ?? "Undefined") (\(UIDevice.current.model); \(UIDevice.current.systemName) \(UIDevice.current.systemVersion))" ] var headers: [String: String] { switch self { case .login: return ["Referer": Router.biuBaseAPIPWA] case .signup: return ["Referer": Router.biuBaseAPISignup] case .getFMData: return ["Referer": Router.biuBaseAPIFM] case .getLrc: return ["Referer": Router.biuBaseAPIFM] default: return [:] } } var baseURLString: String { switch self { case .login: return Router.biuBaseAPIAndroid case .updateSelfInfo: return Router.biuBaseAPIAndroid case .getMyList: return Router.biuBaseAPIAndroid case .getNewList: return Router.biuBaseAPIAndroid case .getHotList: return Router.biuBaseAPIAndroid case .getSongTickets: return Router.biuBaseAPIAndroid case .getSongDetails: return Router.biuBaseAPIAndroid case .getSongsDetails: return Router.biuBaseAPIAndroid case .getLike: return Router.biuBaseAPIAndroid case .addLike: return Router.biuBaseAPIAndroid case .delLike: return Router.biuBaseAPIAndroid case .search: return Router.biuBaseAPIAndroid case .getFMData: return Router.biuBaseAPIWeb case .getLrc: return Router.biuBaseAPIWeb case .signup: return Router.biuBaseAPIWeb } } var method: HTTPMethod { switch self { case .signup: return .post case .login: return .post case .updateSelfInfo: return .post case .getLike: return .post case .getMyList: return .post case .getNewList: return .post case .getHotList: return .post case .getSongTickets: return .post case .getSongDetails: return .post case .getSongsDetails: return .post case .addLike: return .post case .search: return .post case .delLike: return .post case .getFMData: return .get case .getLrc: return .get } } var path: String { switch self { case .getLike: return getConfig(withName: "GetLike", cat: "Route") case .updateSelfInfo: return getConfig(withName: "UpdateSelfInfo", cat: "Route") case .login: return getConfig(withName: "Login", cat: "Route") case .getMyList: return getConfig(withName: "GetMyList", cat: "Route") case .getNewList: return getConfig(withName: "GetNewList", cat: "Route") case .getHotList: return getConfig(withName: "GetHotList", cat: "Route") case .getSongTickets: return getConfig(withName: "GetSongTickets", cat: "Route") case .getSongDetails: return getConfig(withName: "GetSongDetails", cat: "Route") case .getSongsDetails: return getConfig(withName: "GetSongDetails", cat: "Route") case .addLike: return getConfig(withName: "AddLike", cat: "Route") case .delLike: return getConfig(withName: "DelLike", cat: "Route") case .search: return getConfig(withName: "Search", cat: "Route") case .getFMData: return getConfig(withName: "GetFMData", cat: "Route") case .getLrc: return getConfig(withName: "GetLrc", cat: "Route") case .signup: return getConfig(withName: "Signup", cat: "Route") } } var parameters: Parameters { switch self { case .signup(let username, let password, let name): return [ "email": username, "password": password, "password2": password, "name": name, "qq": "", "gender": "X" ] case .getLike: return [ "token": Variable.token ?? "", "lid": Variable.likecollect ?? "" ] case .updateSelfInfo: return [ "token": Variable.token ?? "" ] case .login(let username, let password): return [ "email": username, "password": password ] case .getMyList: return [ "token": Variable.token ?? "", "uid": Variable.uid ?? "" ] case .getNewList: return [ "token": Variable.token ?? "", "uid": Variable.uid ?? "" ] case .getHotList: return [ "token": Variable.token ?? "", "uid": Variable.uid ?? "" ] case .search(let query): return [ "token": Variable.token ?? "", "uid": Variable.uid ?? "", "search": query ] case .getSongTickets(let songid): return [ "token": Variable.token ?? "", "sid": songid ] case .getSongDetails(let songid): return [ "token": Variable.token ?? "", "sid": songid ] case .getSongsDetails(let songid): return [ "token": Variable.token ?? "", "sid": String(songid.joined(separator: ",")) ] case .addLike(let songid): return [ "token": Variable.token ?? "", "sid": songid ] case .delLike(let songid): return [ "token": Variable.token ?? "", "sid": songid ] case .getFMData(let category): return [ "datacenter": "0", "rid": String(category), "_r": String(Double.random(in: 0...1)) ] case .getLrc(let songid): return [ "sid": songid ] } } // MARK: - URLRequestConvertible func asURLRequest() throws -> URLRequest { let url = try baseURLString.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(path)) urlRequest.httpMethod = method.rawValue headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) } Router.PublicHeaders.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) } urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) debugPrint("Requested: \(urlRequest)") return urlRequest } }
32.30303
155
0.535999
ac0d7194e7ac1ec0a3fa5922126278509a7a005f
4,272
// // HTTPEncoder.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 29/12/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation class HTTPEncoder { /** Given a HTTPRequest instance performs the body encoding based on a Content-Type request header. This class only supports two different encodings: "application/x-www-form-urlencoded" and "application/json". If the request does not contain any "Content-Type" header the body is not encoded and the return value is nil. @param request to encode @return encoded body based on the request headers or nil if there is no any valid Content-Type configured. */ static func encodeBody(_ request: HTTPRequest) -> Data? { let contentType = request.headers?["Content-Type"] ?? "" switch contentType { case "application/x-www-form-urlencoded": return query(request.body).data( using: String.Encoding.utf8, allowLossyConversion: false) case "application/json": if let body = request.body { let options = JSONSerialization.WritingOptions() return try? JSONSerialization.data(withJSONObject: body, options: options) } else { return nil } default: return nil } } // The x-www-form-urlencoded code comes from this repository https://github.com/Alamofire/Alamofire private static func query(_ parameters: [String: AnyObject]?) -> String { guard let parameters = parameters else { return "" } var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(key, String(describing: value)) } return (components.map { "\($0)=\($1)" }).joined(separator: "&") } private static func queryComponents(_ key: String, _ value: String?) -> [(String, String)] { var components: [(String, String)] = [] if let value = value { components.append((escape(key), escape("\(value)"))) } else { components.append((escape(key), "")) } return components } private static func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = (CharacterSet.urlQueryAllowed as NSCharacterSet) .mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharacters(in: generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //=================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //=================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex)! let substring = string[startIndex..<endIndex] escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? String(substring) index = endIndex } } return escaped } }
37.147826
120
0.574438
0abf031f172bd1bb2c8fd626d120b74c8d0a5828
2,765
// // AppDelegate.swift // ParseChat // // Created by Hoang on 2/21/18. // Copyright © 2018 Hoang. All rights reserved. // import UIKit import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Parse.initialize(with: ParseClientConfiguration(block: { (configuration: ParseMutableClientConfiguration) in configuration.applicationId = "Codepath-Parse-Test" configuration.server = "http://testparsecodepath.herokuapp.com/parse" })) if let currentUser = PFUser.current() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let chatViewController = storyboard.instantiateViewController(withIdentifier: "ChatViewController") window?.rootViewController = chatViewController } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.864407
285
0.736347
1d7f94d8e4697d09b2c17045dfce127e3d7e7b54
278
// // NotificationHelper.swift // HealthMonitor // // Created by apple on 23/09/20. // Copyright © 2020 Knila IT Solutions. All rights reserved. // import Foundation extension NSNotification.Name { static let intervalChanged = NSNotification.Name("intervalChanged") }
19.857143
71
0.733813
db190fd23cc9b47b4bceb5229101e64861836760
158
public class ColorBurnBlend: BasicOperation { public init() { super.init(fragmentFunctionName:"colorBurnBlendFragment", numberOfInputs:2) } }
26.333333
83
0.727848
5d0056e103d8b1c5fd039f209bad5d5a57a027fa
465
// // YLAmuseViewModel.swift // YLDouYuZB // // Created by yl on 2016/10/18. // Copyright © 2016年 yl. All rights reserved. // import UIKit class YLAmuseViewModel : YLBaseViewModel{ } //MARK: -数据请求 extension YLAmuseViewModel { // 发送请求 func requestAmuseData(finisedCallback : @escaping () -> ()){ requestBaseAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotRoom/2", finisedCallback: finisedCallback); } }
21.136364
141
0.688172
e05935120f6de6c12548e699e36befb8b90ef9d6
23,224
/* License Agreement for FDA My Studies Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &quot;Software&quot;), 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. Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”). THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import ResearchKit import IQKeyboardManagerSwift import IQKeyboardManagerSwift import ActionSheetPicker_3_0 let kFetalKickCounterStepDefaultIdentifier = "defaultIdentifier" let kTapToRecordKick = "TAP TO RECORD A KICK" let kConfirmMessage = "You have recorded " let kConfirmMessage2 = " Proceed to submitting count and time?" let kGreaterValueMessage = "This activity records the time it takes to feel " let kProceedTitle = "Proceed" let kFetalKickStartTimeStamp = "FetalKickStartTimeStamp" let kFetalKickActivityId = "FetalKickActivityId" let kFetalkickStudyId = "FetalKickStudyId" let kFetalKickCounterValue = "FetalKickCounterValue" let kFetalKickCounterRunId = "FetalKickCounterRunid" let kSelectTimeLabel = "Select Time" class FetalKickCounterStepViewController: ORKStepViewController { var backgroundTaskIdentifier: UIBackgroundTaskIdentifier? @IBOutlet weak var startButton: UIButton? // button to start task as well as increment the counter @IBOutlet weak var startTitleLabel: UILabel? // displays the title @IBOutlet weak var timerLabel: UILabel? // displays the current timer Value @IBOutlet weak var counterTextField: UITextField? // displays current kick counts @IBOutlet weak var editCounterButton: UIButton? // used to edit the counter value @IBOutlet weak var seperatorLineView: UIView? // separator line @IBOutlet weak var submitButton: UIButton? // button to submit response to server @IBOutlet weak var editTimerButton: UIButton? var kickCounter: Int? = 0 // counter var timer: Timer? = Timer() // timer for the task var timerValue: Int? = 0 // TimerValue var totalTime: Int? = 0 // Total duration var maxKicksAllowed: Int? = 0 var taskResult: FetalKickCounterTaskResult = FetalKickCounterTaskResult(identifier: kFetalKickCounterStepDefaultIdentifier) // MARK: ORKStepViewController overriden methods override init(step: ORKStep?) { super.init(step: step) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() var initialTime = 0 let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(appBecameActive), name: UIApplication.didBecomeActiveNotification, object: nil) submitButton?.layer.borderColor = kUicolorForButtonBackground if let step = step as? FetalKickCounterStep { let ud = UserDefaults.standard let activityId = ud.value(forKey: kFetalKickActivityId ) as! String? var differenceInSec = 0 var autoStartTimer = false if ud.bool(forKey: "FKC") && activityId != nil && activityId == Study.currentActivity?.actvityId { let previousTimerStartDate = ud.object(forKey: kFetalKickStartTimeStamp) as! Date let currentDate = Date() differenceInSec = Int(currentDate.timeIntervalSince(previousTimerStartDate)) autoStartTimer = true } if differenceInSec >= 0 { initialTime = initialTime + differenceInSec } print("difference \(differenceInSec)") //Setting the maximum time allowed for the task self.totalTime = step.counDownTimer! //10 //Setting the maximum Kicks allowed self.maxKicksAllowed = step.totalCounts! //Calculating time in required Format let hours = Int(initialTime) / 3600 let minutes = Int(initialTime) / 60 % 60 let seconds = Int(initialTime) % 60 self.timerValue = initialTime //self.totalTime // step.counDownTimer! self.timerLabel?.text = (hours < 10 ? "0\(hours):" : "\(hours):") + (minutes < 10 ? "0\(minutes):" : "\(minutes):") + (seconds < 10 ? "0\(seconds)" : "\(seconds)") //self.taskResult.duration = self.totalTime! if autoStartTimer{ let previousKicks: Int? = ud.value(forKey: kFetalKickCounterValue ) as? Int self.kickCounter = (previousKicks == nil ? 0 : previousKicks!) //Update Step Counter Value self.setCounter() self.startButtonAction(UIButton()) } backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { }) // enables the IQKeyboardManager // IQKeyboardManager.sharedManager().enable = true // adding guesture to view to support outside tap let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FetalKickCounterStepViewController.handleTap(_:))) gestureRecognizer.delegate = self self.view.addGestureRecognizer(gestureRecognizer) } } override func hasNextStep() -> Bool { super.hasNextStep() return true } override func goForward(){ super.goForward() } override var result: ORKStepResult? { let orkResult = super.result orkResult?.results = [self.taskResult] return orkResult } // MARK:Helper Methods /* updates the timer value */ func setCounterValue(){ if self.kickCounter! < 10 { counterTextField?.text = "00" + "\(self.kickCounter!)" } else if self.kickCounter! >= 10 && self.kickCounter! < 100 { counterTextField?.text = "0" + "\(self.kickCounter!)" } else { counterTextField?.text = "\(self.kickCounter!)" } } /** Updates the timer Value */ @objc func setCounter() { DispatchQueue.global(qos: .background).async { if self.timerValue! < 0 { self.timerValue = 0 self.timer?.invalidate() self.timer = nil DispatchQueue.main.async { self.startButton?.isHidden = true self.startTitleLabel?.isHidden = true self.submitButton?.isHidden = false } } else { self.timerValue = self.timerValue! + 1 } if self.timerValue! >= 0 { DispatchQueue.main.async { if self.timerValue! > self.totalTime! { self.setResults() self.showAlertOnCompletion() } else { self.editCounterButton?.isHidden = false self.setTimerValue() } } } } } /** Updates the UI with timer value */ func setTimerValue(){ let hours = Int(self.timerValue!) / 3600 let minutes = Int(self.timerValue!) / 60 % 60 let seconds = Int(self.timerValue!) % 60 self.timerLabel?.text = (hours < 10 ? "0\(hours):" : "\(hours):") + (minutes < 10 ? "0\(minutes):" : "\(minutes):") + (seconds < 10 ? "0\(seconds)" : "\(seconds)") self.taskResult.totalKickCount = self.kickCounter! } /* handleTap method detects the tap gesture event @param sender is tapguesture instance */ @objc func handleTap(_ sender: UITapGestureRecognizer) { counterTextField?.resignFirstResponder() } /** stores the details of ongoing Fetal Kick task in local datatbase */ @objc func appMovedToBackground() { let ud = UserDefaults.standard if ud.object(forKey: kFetalKickStartTimeStamp) != nil{ ud.set(true, forKey: "FKC") ud.set(Study.currentActivity?.actvityId, forKey: kFetalKickActivityId) ud.set(Study.currentStudy?.studyId, forKey: kFetalkickStudyId) ud.set(self.kickCounter, forKey: kFetalKickCounterValue) //check if runid is saved if ud.object(forKey: kFetalKickCounterRunId) == nil { ud.set(Study.currentActivity?.currentRun.runId, forKey: kFetalKickCounterRunId) } ud.synchronize() } } /** Resets the keys when app becomes Active */ @objc func appBecameActive() { let ud = UserDefaults.standard ud.set(false, forKey: "FKC") ud.synchronize() } /** Alerts User if Kick counts or time is exceeded */ func showAlertForGreaterValues(){ let message = kGreaterValueMessage + "\(self.maxKicksAllowed!) kicks, " + "please enter " + "\(self.maxKicksAllowed!) kicks only" Utilities.showAlertWithTitleAndMessage(title: NSLocalizedString(kMessage, comment: "") as NSString, message: message as NSString) } /** Updates results for the Task */ func setResults() { self.timer?.invalidate() self.timer = nil self.editTimerButton?.isHidden = false self.taskResult.totalKickCount = self.kickCounter == nil ? 0 : self.kickCounter! self.taskResult.duration = self.timerValue == nil ? 0 : self.timerValue! } func getTimerArray() -> Array<Any>{ let hoursMax = Int(self.totalTime!) / 3600 var hoursArray: Array<String> = [] var minutesArray: Array<String> = [] var secondsArray: Array<String> = [] var i = 0 while i <= hoursMax{ hoursArray.append("\(i)" + " h") minutesArray.append("\(i)" + " m") secondsArray.append("\(i)" + " s") i += 1 } i = hoursMax + 1 while i <= 59{ minutesArray.append("\(i)" + " m") secondsArray.append("\(i)" + " s") i += 1 } return [hoursArray,minutesArray,secondsArray] } func getIndexes() -> Array<Any>{ let hoursIndex = Int(self.timerValue!) / 3600 let minutesIndex = Int(self.timerValue!) / 60 % 60 let secondsIndex = Int(self.timerValue!) % 60 return [(hoursIndex > 0 ? hoursIndex : 0) ,(minutesIndex > 0 ? minutesIndex : 0) ,(secondsIndex > 0 ? secondsIndex : 0)] } /** Alerts user on completion */ func showAlertOnCompletion(){ DispatchQueue.main.async{ self.startButton?.isHidden = true self.startTitleLabel?.isHidden = true self.submitButton?.isHidden = false } let timeConsumed = (self.timerLabel?.text!) let message = kConfirmMessage + "\(self.kickCounter!) kicks in " + "\(timeConsumed!)." + kConfirmMessage2 UIUtilities.showAlertMessageWithTwoActionsAndHandler(NSLocalizedString(kMessageString, comment: ""), errorMessage: NSLocalizedString(message, comment: ""), errorAlertActionTitle: NSLocalizedString(kProceedTitle, comment: ""), errorAlertActionTitle2: NSLocalizedString(kTitleCancel, comment: ""), viewControllerUsed: self, action1: { self.goForward() }, action2: { }) } // MARK:Button Actions @IBAction func editCounterButtonAction(_ sender: UIButton){ counterTextField?.isUserInteractionEnabled = true counterTextField?.isHidden = false seperatorLineView?.isHidden = false counterTextField?.becomeFirstResponder() } @IBAction func startButtonAction(_ sender: UIButton){ if Int((self.counterTextField?.text)!)! == 0 { if self.timer == nil { // first time self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(FetalKickCounterStepViewController.setCounter), userInfo: nil, repeats: true) //save start time stamp let ud = UserDefaults.standard if ud.object(forKey: kFetalKickStartTimeStamp) == nil { ud.set(Date(),forKey: kFetalKickStartTimeStamp) } ud.synchronize() RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common) // start button image and start title changed startButton?.setImage(UIImage(named: "kick_btn1.png"), for: .normal) startTitleLabel?.text = NSLocalizedString(kTapToRecordKick, comment: "") } else { self.kickCounter = self.kickCounter! + 1 editCounterButton?.isHidden = false self.counterTextField?.text = self.kickCounter! < 10 ? ("0\(self.kickCounter!)" == "00" ? "000" : "00\(self.kickCounter!)") : (self.kickCounter! >= 100 ? "\(self.kickCounter!)" : "0\(self.kickCounter!)" ) } } else { if self.kickCounter! < self.maxKicksAllowed! { self.kickCounter = self.kickCounter! + 1 editCounterButton?.isHidden = false self.counterTextField?.text = self.kickCounter! < 10 ? ("0\(self.kickCounter!)" == "00" ? "000" : "00\(self.kickCounter!)") : (self.kickCounter! >= 100 ? "\(self.kickCounter!)" : "0\(self.kickCounter!)" ) if self.kickCounter == self.maxKicksAllowed! { self.setResults() self.showAlertOnCompletion() } } else if self.kickCounter! == self.maxKicksAllowed! { self.setResults() self.showAlertOnCompletion() } else if self.kickCounter! > self.maxKicksAllowed! { self.showAlertForGreaterValues() } } } @IBAction func submitButtonAction(_ sender: UIButton) { self.taskResult.duration = self.timerValue! self.taskResult.totalKickCount = self.kickCounter == nil ? 0 : self.kickCounter! self.perform(#selector(self.goForward)) } @IBAction func editTimerButtonAction(_ sender: UIButton){ let timerArray = self.getTimerArray() let defaultTime = self.getIndexes() let acp = ActionSheetMultipleStringPicker(title: kSelectTimeLabel, rows: timerArray, initialSelection: defaultTime, doneBlock: { picker, values, indexes in let result: Array<String> = (indexes as! Array<String>) let hours = result.first?.components(separatedBy: CharacterSet.init(charactersIn: " h")) let minutes = result[1].components(separatedBy: CharacterSet.init(charactersIn: " m")) let seconds = result.last?.components(separatedBy: CharacterSet.init(charactersIn: " s")) let hoursValue: Int = hours?.count != 0 ? Int(hours!.first!)! : 0 let minuteValue: Int = minutes.count != 0 ? Int(minutes.first!)! : 0 let secondsValue: Int = seconds?.count != 0 ? Int(seconds!.first!)! : 0 self.timerValue = hoursValue * 3600 + minuteValue * 60 + secondsValue if hoursValue * 3600 + minuteValue * 60 + secondsValue > self.totalTime! { let hours = Int(self.totalTime!) / 3600 let minutes = Int(self.totalTime!) / 60 % 60 let seconds = Int(self.totalTime!) % 60 let value = (hours < 10 ? "0\(hours):" : "\(hours):") + (minutes < 10 ? "0\(minutes):" : "\(minutes):") + (seconds < 10 ? "0\(seconds)" : "\(seconds)") Utilities.showAlertWithTitleAndMessage(title: kMessage as NSString, message: ("Please select a valid time(Max " + value + ")") as NSString) } else { self.setTimerValue() } return }, cancel: { ActionMultipleStringCancelBlock in return }, origin: sender) acp?.setTextColor(kUIColorForSubmitButtonBackground) acp?.pickerBackgroundColor = UIColor.white acp?.toolbarBackgroundColor = UIColor.white acp?.toolbarButtonsColor = kUIColorForSubmitButtonBackground acp?.show() } } class FetalKickCounterStepType : ORKActiveStep { static func stepViewControllerClass() -> FetalKickCounterStepViewController.Type { return FetalKickCounterStepViewController.self } } /* FetalKickCounterTaskResult holds the tak result @param totalKickCount contains the Kick count @param duration is the task duration */ open class FetalKickCounterTaskResult: ORKResult { open var totalKickCount: Int = 0 open var duration: Int = 0 override open var description: String { get { return "hitCount:\(totalKickCount), duration:\(duration)" } } override open var debugDescription: String { get { return "hitCount:\(totalKickCount), duration:\(duration)" } } } // MARK: GetureRecognizer delegate extension FetalKickCounterStepViewController: UIGestureRecognizerDelegate{ func gestureRecognizer(_: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith shouldRecognizeSimultaneouslyWithGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } // MARK:TextField Delegates extension FetalKickCounterStepViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { if (textField == counterTextField) { if (textField.text?.count)! > 0 { if Int(textField.text!)! == 0 { textField.text = "" } } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == counterTextField) { counterTextField?.resignFirstResponder() if textField.text?.count == 0 { textField.text = "000" self.kickCounter = 000 } } return true } func textFieldDidEndEditing(_ textField: UITextField) { if textField == counterTextField! && ( Utilities.isValidValue(someObject: counterTextField?.text as AnyObject?) == false || Int((counterTextField?.text)!)! <= 0) { counterTextField?.resignFirstResponder() if textField.text?.count == 0 || (Int((counterTextField?.text)!) != nil) { textField.text = "000" self.kickCounter = 000 } } else { self.kickCounter = Int((counterTextField?.text)!) if textField.text?.count == 2 { counterTextField?.text = "0" + textField.text! self.kickCounter = (Int((counterTextField?.text)!)) } else if (textField.text?.count)! >= 3 { let finalValue = (Int((counterTextField?.text)!)) if finalValue! < 10 { counterTextField?.text = "00" + "\(finalValue!)" } else if finalValue! >= 10 && finalValue! < 100 { counterTextField?.text = "0" + "\(finalValue!)" } else { counterTextField?.text = "\(finalValue!)" } } else if textField.text?.count == 1 { let finalValue = (Int((counterTextField?.text)!)) counterTextField?.text = "00" + "\(finalValue!)" } if self.kickCounter == self.maxKicksAllowed! { self.setResults() self.showAlertOnCompletion() } } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let finalString = textField.text! + string if textField == counterTextField && finalString.count > 0 { if Int(finalString)! <= self.maxKicksAllowed! { return true } else { self.showAlertForGreaterValues() return false } } else { return true } } }
37.039872
233
0.565493
fe0cb1d62a302502cd674cf31f49d7082b109702
1,351
//:## Models import PlaygroundSupport // Enable support for asynchronous completion handlers PlaygroundPage.current.needsIndefiniteExecution = true import LanguageTranslatorV3 let languageTranslator = setupLanguageTranslatorV3() var modelID: String = "" //:### List models languageTranslator.listModels() { response, error in guard let models = response?.result else { print(error?.localizedDescription ?? "unknown error") return } print(models) } //:### Create model let glossary = Bundle.main.url(forResource: "glossary", withExtension: "tmx") languageTranslator.createModel(baseModelID: "en-es", name: "custom-en-es", forcedGlossary: glossary) { response, error in guard let model = response?.result else { print(error?.localizedDescription ?? "unknown error") return } modelID = model.modelID print(model) } //:### Get model details languageTranslator.getModel(modelID: modelID) { response, error in guard let model = response?.result else { print(error?.localizedDescription ?? "unknown error") return } print(model) } //:### Delete model languageTranslator.deleteModel(modelID: modelID) { _, error in if let error = error { print(error.localizedDescription) return } print("model deleted") }
20.164179
102
0.679497
1da5da16ef3d0889b4db7dc8aceae62e09d5533d
1,678
// // PanGestureSpliteLineView.swift // JSONConverter // // Created by DevYao on 2020/9/16. // Copyright © 2020 DevYao. All rights reserved. // import Cocoa class PanGestureIndicatorView: NSView { var causor: NSCursor = NSCursor.resizeLeftRight var dragging: Bool = false override func awakeFromNib() { super.awakeFromNib() let area = NSTrackingArea(rect: self.bounds, options: [.enabledDuringMouseDrag, .mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow, .inVisibleRect], owner: self, userInfo: nil) addTrackingArea(area) } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let color = NSColor(named: "LineColor") color?.setFill() bounds.fill() } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) causor.set() becomeFirstResponder() } override func mouseExited(with event: NSEvent) { super.mouseEntered(with: event) if dragging { causor.set() }else { NSCursor.arrow.set() } } override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) causor.set() becomeFirstResponder() } override func cursorUpdate(with event: NSEvent) { super.cursorUpdate(with: event) causor.set() } override func mouseDragged(with event: NSEvent) { super.mouseDragged(with: event) dragging = true } override func mouseUp(with event: NSEvent) { super.mouseUp(with: event) dragging = false } }
25.424242
189
0.610846
bb170c97bbcf378826ae046bab94a59d136307e8
7,268
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 XCTest import Mustache class LocalizerTests: XCTestCase { lazy var localizableBundle: Bundle = Bundle(path: Bundle(for: type(of: self)).path(forResource: "LocalizerTestsBundle", ofType: nil)!)! lazy var localizer: StandardLibrary.Localizer = StandardLibrary.Localizer(bundle: self.localizableBundle, table: nil) func testLocalizableBundle() { let testable = localizableBundle.localizedString(forKey: "testable?", value:"", table:nil) XCTAssertEqual(testable, "YES") } func testLocalizer() { let template = try! Template(string: "{{localize(string)}}") let value: [String: Any] = ["localize": localizer, "string": "testable?"] let rendering = try! template.render(value) XCTAssertEqual(rendering, "YES") } func testLocalizerFromTable() { let template = try! Template(string: "{{localize(string)}}") let localizer = StandardLibrary.Localizer(bundle: localizableBundle, table: "Table") let value: [String: Any] = ["localize": localizer, "string": "table_testable?"] let rendering = try! template.render(value) XCTAssertEqual(rendering, "YES") } func testLocalizerAsRenderingObjectWithoutArgumentDoesNotNeedPercentEscapedLocalizedString() { var template = try! Template(string: "{{#localize}}%d{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) var rendering = try! template.render() XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "%d", value: nil, table: nil), "ha ha percent d %d") XCTAssertEqual(rendering, "ha ha percent d %d") template = try! Template(string: "{{#localize}}%@{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) rendering = try! template.render() XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "%@", value: nil, table: nil), "ha ha percent @ %@") XCTAssertEqual(rendering, "ha ha percent @ %@") } func testLocalizerAsRenderingObjectWithoutArgumentNeedsPercentEscapedLocalizedString() { var template = try! Template(string: "{{#localize}}%d {{foo}}{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) var rendering = try! template.render(["foo": "bar"]) XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "%%d %@", value: nil, table: nil), "ha ha percent d %%d %@") XCTAssertEqual(rendering, "ha ha percent d %d bar") template = try! Template(string: "{{#localize}}%@ {{foo}}{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) rendering = try! template.render(["foo": "bar"]) XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "%%@ %@", value: nil, table: nil), "ha ha percent @ %%@ %@") XCTAssertEqual(rendering, "ha ha percent @ %@ bar") } func testLocalizerAsFilter() { let template = try! Template(string: "{{localize(foo)}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) let rendering = try! template.render(["foo": "bar"]) XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "bar", value: nil, table: nil), "translated_bar") XCTAssertEqual(rendering, "translated_bar") } func testLocalizerAsRenderable() { let template = try! Template(string: "{{#localize}}bar{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) let rendering = try! template.render() XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "bar", value: nil, table: nil), "translated_bar") XCTAssertEqual(rendering, "translated_bar") } func testLocalizerAsRenderableWithArgument() { let template = try! Template(string: "{{#localize}}..{{foo}}..{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) let rendering = try! template.render(["foo": "bar"]) XCTAssertEqual(self.localizer.bundle.localizedString(forKey: "..%@..", value: nil, table: nil), "!!%@!!") XCTAssertEqual(rendering, "!!bar!!") } func testLocalizerAsRenderableWithArgumentAndConditions() { let template = try! Template(string: "{{#localize}}.{{foo}}.{{^false}}{{baz}}{{/}}.{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) let rendering = try! template.render(["foo": "bar", "baz": "truc"]) XCTAssertEqual(self.localizer.bundle.localizedString(forKey: ".%@.%@.", value: nil, table: nil), "!%@!%@!") XCTAssertEqual(rendering, "!bar!truc!") } func testLocalizerRendersHTMLEscapedValuesOfHTMLTemplates() { var template = try! Template(string: "{{#localize}}..{{foo}}..{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) var rendering = try! template.render(["foo": "&"]) XCTAssertEqual(rendering, "!!&amp;!!") template = try! Template(string: "{{#localize}}..{{{foo}}}..{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) rendering = try! template.render(["foo": "&"]) XCTAssertEqual(rendering, "!!&!!") } func testLocalizerRendersUnescapedValuesOfTextTemplates() { var template = try! Template(string: "{{% CONTENT_TYPE:TEXT }}{{#localize}}..{{foo}}..{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) var rendering = try! template.render(["foo": "&"]) XCTAssertEqual(rendering, "!!&!!") template = try! Template(string: "{{% CONTENT_TYPE:TEXT }}{{#localize}}..{{{foo}}}..{{/}}") template.baseContext = template.baseContext.extendedContext(["localize": localizer]) rendering = try! template.render(["foo": "&"]) XCTAssertEqual(rendering, "!!&!!") } }
53.441176
139
0.663456
eb57b02c07b9293a8800d2f28af02612e57af0f5
6,663
import Cocoa import Combine class DeviceViewModel { private let device: AuraUSBDevice let connectionState: AnyPublisher<AuraDeviceConnectionState, Never> init(device: AuraUSBDevice) { self.device = device connectionState = device.$connectionState.eraseToAnyPublisher() } } class DeviceViewController: NSViewController { @IBOutlet private var connectedStatusLabel: NSTextField! @IBOutlet private var effectsPopUpButton: NSPopUpButton! @IBOutlet private var colorWellsStackView: NSStackView! @IBOutlet private var gradientView: GradientView! @IBOutlet private var gradientControlsStackView: NSStackView! @IBOutlet private var speedPopUpButton: NSPopUpButton! @IBOutlet private var speedLabel: NSTextField! private var cancellableSet: Set<AnyCancellable> = [] var viewModel: DeviceViewModel! var selectedDevice: AuraUSBDevice? let defaultPalette = [NSColor]([ .goodRed, .blue, ]) private var currentEffect: Effect! private var currentColors = [NSColor]() private var currentColorsVisibleCount: Int = 1 private var effects = [Effect]() override func viewDidLoad() { super.viewDidLoad() viewModel.connectionState .receive(on: DispatchQueue.main) .map { $0.description } .assign(to: \.stringValue, on: connectedStatusLabel) .store(in: &cancellableSet) // set up effects list effects = [ DirectEffect(name: "Rolling Gradient", builder: { colors -> DirectCommand in RollingGradientDirectCommand(colors: colors) }, colorMode: .dynamic), DirectEffect(name: "Gradient", builder: { colors -> DirectCommand in GradientDirectCommand(colors: colors) }, colorMode: .dynamic), DirectEffect(name: "Spaced", builder: { colors -> DirectCommand in SpacedDirectCommand(color: colors.first ?? .red) }, colorMode: .count(1)) ] + AuraEffect.effects.map { BuiltInEffect(mode: $0) } effectsPopUpButton.removeAllItems() for effect in effects { effectsPopUpButton.addItem(withTitle: effect.name) } // set defaults currentColors = (0..<defaultPalette.count).map { idx in defaultPalette[idx % defaultPalette.count] } currentEffect = effects.first! effectsPopUpButton.selectItem(at: 0) currentColorsVisibleCount = currentEffect.colorMode.count updateColorsStackView() updateGradient() } @objc func handleColor(sender: Any) { guard let colorWell = sender as? NSColorWell else { return } currentColors[colorWell.tag] = colorWell.color update() updateGradient() } @IBAction func handleEffect(sender: Any) { let idx = effectsPopUpButton.indexOfSelectedItem guard idx >= 0, idx < effects.count else { return } currentEffect = effects[idx] currentColorsVisibleCount = currentEffect.colorMode.count update() updateColorsStackView() } @IBAction func handleSpeed(sender: Any) { update() } @IBAction func handleAddColor(sender: Any) { currentColorsVisibleCount += 1 updateColorsStackView() } @IBAction func handleRemoveColor(sender: Any) { currentColorsVisibleCount -= 1 if currentColorsVisibleCount < 0 { currentColorsVisibleCount = 0 } updateColorsStackView() } private func run(effect: Command, speed: Int) { // TODO: should this come from an arg? guard let sd = selectedDevice else { return } try? DeviceManager.shared .effectRunner .run( command: effect, on: sd, speed: speed ) } private func update() { let commandColors = currentColors .map { CommandColor(color: $0) } .prefix(currentColorsVisibleCount) let command: Command command = currentEffect.command(for: Array(commandColors)) speedPopUpButton!.isHidden = !command.isAnimated speedLabel!.isHidden = !command.isAnimated let speed: Int switch (speedPopUpButton!.selectedItem!.title) { case "Fast": speed = 7 case "Medium": speed = 4 default: speed = 1 } run(effect: command, speed: speed) } private func updateGradient() { gradientView.update( with: Array(currentColors.prefix(currentColorsVisibleCount)) ) } private func updateColorsStackView() { let count = currentColorsVisibleCount if count > currentColors.count { for idx in currentColors.count..<count { currentColors.append(defaultPalette[idx % defaultPalette.count]) } } if count > colorWellsStackView.arrangedSubviews.count { for idx in colorWellsStackView.arrangedSubviews.count..<count { let colorWell = NSColorWell(frame: .init(x: 0, y: 0, width: 44, height: 44)) colorWell.tag = idx colorWell.color = currentColors[idx] colorWell.target = self colorWell.action = #selector(handleColor(sender:)) colorWell.isBordered = true colorWellsStackView.addArrangedSubview(colorWell) handleColor(sender: colorWell) } } else { for _ in count..<colorWellsStackView.arrangedSubviews.count { if colorWellsStackView.arrangedSubviews.count > 0 { colorWellsStackView.removeView( colorWellsStackView.arrangedSubviews[colorWellsStackView.arrangedSubviews.count - 1] ) } } } gradientControlsStackView.isHidden = currentEffect.colorMode != .dynamic updateGradient() } } fileprivate extension NSColor { static var goodRed: NSColor { self.init(calibratedRed: 255 / 255, green: 0 / 255, blue: 25 / 255, alpha: 1) } } fileprivate extension AuraDeviceConnectionState { var description: String { switch self { case .connected: return "Connected" case .disconnected: return "Disconnected" case .connecting: return "Connecting..." } } }
29.745536
108
0.602131
9c9f8aac1cec25d317e8c3be2bc17f688a20be9e
601
// // Copyright © 2016 Apparata AB. All rights reserved. // #if canImport(UIKit) import UIKit public struct Gradient { /// Location is in the range [0, 1] public typealias Point = (UIColor, Double) public var points: [Point] public var reversed: Gradient { let reversedPoints = points.reversed().map { ($0.0, 1.0 - $0.1) } return Gradient(points: reversedPoints) } public init(points: Point...) { self.points = points } public init(points: [Point]) { self.points = points } } #endif
18.212121
54
0.565724
0e58368312e998b0294bd70ee9ba96546fde268c
3,807
import Foundation import azureSwiftRuntime public protocol FunctionsRetrieveDefaultDefinition { var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var resourceGroupName : String { get set } var jobName : String { get set } var functionName : String { get set } var apiVersion : String { get set } var functionRetrieveDefaultDefinitionParameters : FunctionRetrieveDefaultDefinitionParametersProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (FunctionProtocol?, Error?) -> Void) -> Void ; } extension Commands.Functions { // RetrieveDefaultDefinition retrieves the default definition of a function based on the parameters specified. internal class RetrieveDefaultDefinitionCommand : BaseCommand, FunctionsRetrieveDefaultDefinition { public var subscriptionId : String public var resourceGroupName : String public var jobName : String public var functionName : String public var apiVersion = "2016-03-01" public var functionRetrieveDefaultDefinitionParameters : FunctionRetrieveDefaultDefinitionParametersProtocol? public init(subscriptionId: String, resourceGroupName: String, jobName: String, functionName: String) { self.subscriptionId = subscriptionId self.resourceGroupName = resourceGroupName self.jobName = jobName self.functionName = functionName super.init() self.method = "Post" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}/RetrieveDefaultDefinition" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{jobName}"] = String(describing: self.jobName) self.pathParameters["{functionName}"] = String(describing: self.functionName) self.queryParameters["api-version"] = String(describing: self.apiVersion) self.body = functionRetrieveDefaultDefinitionParameters } public override func encodeBody() throws -> Data? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let encoder = try CoderFactory.encoder(for: mimeType) let encodedValue = try encoder.encode(functionRetrieveDefaultDefinitionParameters as? FunctionRetrieveDefaultDefinitionParametersData?) return encodedValue } throw DecodeError.unknownMimeType } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(FunctionData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (FunctionProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: FunctionData?, error: Error?) in completionHandler(result, error) } } } }
51.445946
204
0.662727
fcb9d7ae7f18c43a6d63caba20af0216b6079585
2,540
// // SceneDelegate.swift // OdometerPodTest // // Created by Mark on 10/18/19. // Copyright © 2019 Inukshuk, LLC. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.561404
147
0.715748
cc77ccb509830dff8ddd01732b424805fff2746d
2,146
// // AppDelegate.swift // GestureDemo // // Created by liufengting on 16/5/13. // Copyright © 2016年 liufengting. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.659574
285
0.754893
f7c242e5c96fcbcdb5449ec25cc2635e60cb33f0
4,674
// // WaveProgressView.swift // WaveProgressView // // Created by Syunsuke Nakao on 2019/05/12. // Copyright © 2019 Syunsuke Nakao. All rights reserved. // import UIKit class WaveView: UIView { private let frontWaveLine: UIBezierPath = UIBezierPath() private let backWaveLine: UIBezierPath = UIBezierPath() private let frontWaveLayer: CAShapeLayer = CAShapeLayer() private let backWaveSubLayer: CAShapeLayer = CAShapeLayer() private var timer = Timer() private var drawSeconds: CGFloat = 0.0 private var drawElapsedTime: CGFloat = 0.0 private var width: CGFloat private var height: CGFloat private var xAxis: CGFloat private var yAxis: CGFloat private var maskLayer: CALayer? // MARK: Possible to mask the WaveAnimationView just by setting an image containing Solid and Alpha Areas. open var maskImage: UIImage? { didSet { //mask maskLayer = CALayer() maskLayer?.frame = self.frame maskLayer?.contents = maskImage?.cgImage self.layer.mask = maskLayer } } // 0.0 .. 1.0 are avaliable, default is 0.5 open var progress: Float { willSet { self.xAxis = self.height - self.height*CGFloat(min(max(newValue, 0),1)) } } open var waveHeight: CGFloat = 15 //3.0 .. about 50.0 are standard. open var waveDelay: CGFloat = 300 //0.0 .. about 500.0 are standard. open var frontColor: UIColor! open var backColor: UIColor! private override init(frame: CGRect) { self.width = frame.width self.height = frame.height self.xAxis = floor(height/2) self.yAxis = 0.0 self.progress = 0.5 super.init(frame: frame) } public convenience init(frame: CGRect, color: UIColor) { self.init(frame: frame) self.frontColor = color self.backColor = color } //Possible to set fillColors separately. public convenience init(frame: CGRect, frontColor: UIColor, backColor: UIColor) { self.init(frame: frame) self.frontColor = backColor self.backColor = frontColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func draw(_ rect: CGRect) { wave(layer: backWaveSubLayer, path: backWaveLine, color: backColor, delay: waveDelay) wave(layer: frontWaveLayer, path: frontWaveLine, color: frontColor, delay: 0) } //0.0 .. 1.0 are avaliable open func setProgress(_ point: Float) { let setPoint:CGFloat = CGFloat(min(max(point, 0),1)) self.progress = Float(setPoint) } //Start wave Animation open func startAnimation() { timer = Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: #selector(waveAnimation), userInfo: nil, repeats: true) } //MARK: Please be sure to call this method at ViewDidDisAppear or deinit in ViewController. //If it isn't called, Memory Leaks occurs by Timer open func stopAnimation() { timer.invalidate() } @objc private func waveAnimation() { self.setNeedsDisplay() } @objc private func wave(layer: CAShapeLayer, path: UIBezierPath, color: UIColor, delay:CGFloat) { path.removeAllPoints() drawWave(layer: layer, path: path, color: color, delay: delay) drawSeconds += 0.009 drawElapsedTime = drawSeconds*CGFloat(Double.pi) if drawElapsedTime >= CGFloat(Double.pi) { drawSeconds = 0.0 drawElapsedTime = 0.0 } } private func drawWave(layer: CAShapeLayer,path: UIBezierPath,color: UIColor,delay:CGFloat) { drawSin(path: path,time: drawElapsedTime/0.5, delay: delay) path.addLine(to: CGPoint(x: width+10, y: height)) path.addLine(to: CGPoint(x: 0, y: height)) path.close() layer.fillColor = color.cgColor layer.path = path.cgPath self.layer.insertSublayer(layer, at: 0) } private func drawSin(path: UIBezierPath, time: CGFloat, delay: CGFloat) { let unit:CGFloat = 100.0 let zoom:CGFloat = 1.0 var x = time var y = sin(x)/zoom let start = CGPoint(x: yAxis, y: unit*y+xAxis) path.move(to: start) var i = yAxis while i <= width+10 { x = time+(-yAxis+i)/unit/zoom y = sin(x - delay)/self.waveHeight path.addLine(to: CGPoint(x: i, y: unit*y+xAxis)) i += 10 } } }
29.396226
137
0.611468
ded0c213c3a8acf390eded2c68974beb01199596
899
// // BBSRoomCollectionViewCell.swift // Social // // Created by Ivan Fabijanović on 24/11/15. // Copyright © 2015 Bellabeat. All rights reserved. // import UIKit internal let CellIdentifierRoom = "roomCell" internal class BBSRoomCollectionViewCell: BBSBaseCollectionViewCell { // MARK: - Outlets @IBOutlet weak var roomTitleLabel: UILabel! // MARK: - Properties internal var room: BBSRoomModel? { didSet { self.observerContainer.dispose() if let room = self.room { self.observerContainer.add(room.name.bindTo(self.roomTitleLabel.rx_text)) } } } // MARK: - Methods override func applyTheme(theme: BBSUITheme) { self.roomTitleLabel.font = UIFont(name: theme.contentFontName, size: 34.0) self.roomTitleLabel.textColor = theme.contentTextColor } }
23.657895
89
0.6396
67feec37d76724bbd18d79bffde7abb6a72b79db
526
// // Lock.swift // RxSwift // // Created by 野村 憲男 on 4/13/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation internal final class SpinLock { private var lock = OS_SPINLOCK_INIT func wait(@noescape action: () -> ()) { OSSpinLockLock(&lock) action() OSSpinLockUnlock(&lock) } func wait<T>(@noescape action: () -> T) -> T{ OSSpinLockLock(&lock) let result = action() OSSpinLockUnlock(&lock) return result } }
19.481481
57
0.581749
2f5a50715f286d0e8c5e44757a03de891ab3c414
1,168
// // GradientView.swift // CountiesUITests // // Created by Stephen Anthony on 25/04/2020. // Copyright © 2020 Darjeeling Apps. All rights reserved. // import UIKit /// A view that draws a vertical gradient. @IBDesignable class GradientView: UIView { /// The colour at the top of the gradient. @IBInspectable var topColour: UIColor? { didSet { configureGradient() } } /// The colour at the bottom of the gradient. @IBInspectable var bottomColour: UIColor? { didSet { configureGradient() } } override class var layerClass: AnyClass { return CAGradientLayer.self } private var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } private func configureGradient() { gradientLayer.colors = [topColour.clearifNil, bottomColour.clearifNil].map { $0.cgColor } } } private extension Optional where Wrapped == UIColor { var clearifNil: UIColor { switch self { case .some(let colour): return colour case .none: return UIColor.clear } } }
22.901961
97
0.611301
1a1ee8d685ed164f87740968bd22420b14a82c0a
23,994
// // RAReorderableLayout.swift // RAReorderableLayout // // Created by Ryo Aoyama on 10/12/14. // Copyright (c) 2014 Ryo Aoyama. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } @objc public protocol RAReorderableLayoutDelegate: UICollectionViewDelegateFlowLayout { @objc optional func collectionView(_ collectionView: UICollectionView, atIndexPath: IndexPath, willMoveToIndexPath toIndexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, atIndexPath: IndexPath, didMoveToIndexPath toIndexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, allowMoveAtIndexPath indexPath: IndexPath) -> Bool @objc optional func collectionView(_ collectionView: UICollectionView, atIndexPath: IndexPath, canMoveToIndexPath: IndexPath) -> Bool @objc optional func collectionView(_ collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, willBeginDraggingItemAtIndexPath indexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, didBeginDraggingItemAtIndexPath indexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, willEndDraggingItemToIndexPath indexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, didEndDraggingItemToIndexPath indexPath: IndexPath) } @objc public protocol RAReorderableLayoutDataSource: UICollectionViewDataSource { @objc optional func collectionView(_ collectionView: UICollectionView, reorderingItemAlphaInSection section: Int) -> CGFloat @objc optional func scrollTrigerEdgeInsetsInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets @objc optional func scrollTrigerPaddingInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets @objc optional func scrollSpeedValueInCollectionView(_ collectionView: UICollectionView) -> CGFloat } open class RAReorderableLayout: UICollectionViewFlowLayout { fileprivate enum ScrollDirection { case upward case downward case anchor fileprivate func scrollValue(speedValue: CGFloat, percentage: CGFloat) -> CGFloat { var value: CGFloat = 0.0 switch self { case .upward: value = -speedValue case .downward: value = speedValue case .anchor: return 0 } let proofedPercentage: CGFloat = max(min(1.0, percentage), 0) return value * proofedPercentage } } open weak var delegate: RAReorderableLayoutDelegate? { set { collectionView?.delegate = delegate } get { return collectionView?.delegate as? RAReorderableLayoutDelegate } } open weak var datasource: RAReorderableLayoutDataSource? { set { collectionView?.delegate = delegate } get { return collectionView?.dataSource as? RAReorderableLayoutDataSource } } fileprivate var displayLink: CADisplayLink? fileprivate var longPress: UILongPressGestureRecognizer? fileprivate var panGesture: UIPanGestureRecognizer? fileprivate var continuousScrollDirection = ScrollDirection.anchor fileprivate var cellFakeView: RACellFakeView? fileprivate var panTranslation: CGPoint? fileprivate var fakeCellCenter: CGPoint? open var trigerInsets = UIEdgeInsets(top: 100.0, left: 100.0, bottom: 100.0, right: 100.0) open var trigerPadding = UIEdgeInsets.zero open var scrollSpeedValue = CGFloat(10.0) fileprivate var offsetFromTop: CGFloat { let contentOffset = collectionView!.contentOffset return scrollDirection == .vertical ? contentOffset.y : contentOffset.x } fileprivate var insetsTop: CGFloat { let contentInsets = collectionView!.contentInset return scrollDirection == .vertical ? contentInsets.top : contentInsets.left } fileprivate var insetsEnd: CGFloat { let contentInsets = collectionView!.contentInset return scrollDirection == .vertical ? contentInsets.bottom : contentInsets.right } fileprivate var contentLength: CGFloat { let contentSize = collectionView!.contentSize return scrollDirection == .vertical ? contentSize.height : contentSize.width } fileprivate var collectionViewLength: CGFloat { let collectionViewSize = collectionView!.bounds.size return scrollDirection == .vertical ? collectionViewSize.height : collectionViewSize.width } fileprivate var fakeCellTopEdge: CGFloat? { if let fakeCell = cellFakeView { return scrollDirection == .vertical ? fakeCell.frame.minY : fakeCell.frame.minX } return nil } fileprivate var fakeCellEndEdge: CGFloat? { if let fakeCell = cellFakeView { return scrollDirection == .vertical ? fakeCell.frame.maxY : fakeCell.frame.maxX } return nil } fileprivate var trigerInsetTop: CGFloat { return scrollDirection == .vertical ? trigerInsets.top : trigerInsets.left } fileprivate var trigerInsetEnd: CGFloat { return scrollDirection == .vertical ? trigerInsets.top : trigerInsets.left } fileprivate var trigerPaddingTop: CGFloat { if scrollDirection == .vertical { return trigerPadding.top } else { return trigerPadding.left } } fileprivate var trigerPaddingEnd: CGFloat { if scrollDirection == .vertical { return trigerPadding.bottom } else { return trigerPadding.right } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureObserver() } override init() { super.init() configureObserver() } deinit { removeObserver(self, forKeyPath: "collectionView") } override open func prepare() { super.prepare() // scroll triger insets if let insets = self.datasource?.scrollTrigerEdgeInsetsInCollectionView?(self.collectionView!) { trigerInsets = insets } // scroll trier padding if let padding = self.datasource?.scrollTrigerPaddingInCollectionView?(self.collectionView!) { trigerPadding = padding } // scroll speed value if let speed = self.datasource?.scrollSpeedValueInCollectionView?(self.collectionView!) { scrollSpeedValue = speed } } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil } for attribute in attributes where attribute.representedElementCategory == .cell && (attribute.indexPath == cellFakeView?.indexPath) { attribute.alpha = datasource?.collectionView?(collectionView!, reorderingItemAlphaInSection: attribute.indexPath.section) ?? 0 } return attributes } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "collectionView" { setUpGestureRecognizers() } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } fileprivate func configureObserver() { addObserver(self, forKeyPath: "collectionView", options: [], context: nil) } fileprivate func setUpDisplayLink() { guard displayLink == nil else { return } displayLink = CADisplayLink(target: self, selector: #selector(RAReorderableLayout.continuousScroll)) displayLink!.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } fileprivate func invalidateDisplayLink() { continuousScrollDirection = .anchor displayLink?.invalidate() displayLink = nil } // begein scroll fileprivate func beginScrollIfNeeded() { guard nil != cellFakeView else { return } let offset = offsetFromTop let trigerInsetTop = self.trigerInsetTop let trigerInsetEnd = self.trigerInsetEnd let paddingTop = self.trigerPaddingTop let paddingEnd = self.trigerPaddingEnd let length = self.collectionViewLength let fakeCellTopEdge = self.fakeCellTopEdge let fakeCellEndEdge = self.fakeCellEndEdge if fakeCellTopEdge <= offset + paddingTop + trigerInsetTop { self.continuousScrollDirection = .upward self.setUpDisplayLink() } else if fakeCellEndEdge >= offset + length - paddingEnd - trigerInsetEnd { self.continuousScrollDirection = .downward self.setUpDisplayLink() } else { self.invalidateDisplayLink() } } // move item fileprivate func moveItemIfNeeded() { var atIndexPath: IndexPath? var toIndexPath: IndexPath? if let fakeCell = cellFakeView { atIndexPath = fakeCell.indexPath toIndexPath = collectionView!.indexPathForItem(at: cellFakeView!.center) } if nil == atIndexPath || nil == toIndexPath || (atIndexPath! == toIndexPath) { return } // can move item if let canMove = delegate?.collectionView?(collectionView!, atIndexPath: atIndexPath!, canMoveToIndexPath: toIndexPath!) { if !canMove { return } } // will move item delegate?.collectionView?(collectionView!, atIndexPath: atIndexPath!, willMoveToIndexPath: toIndexPath!) let attribute = layoutAttributesForItem(at: toIndexPath!)! collectionView!.performBatchUpdates({ () -> Void in self.cellFakeView!.indexPath = toIndexPath self.cellFakeView!.cellFrame = attribute.frame self.cellFakeView!.changeBoundsIfNeeded(attribute.bounds) self.collectionView!.deleteItems(at: [atIndexPath!]) self.collectionView!.insertItems(at: [toIndexPath!]) // did move item self.delegate?.collectionView?(self.collectionView!, atIndexPath: atIndexPath!, didMoveToIndexPath: toIndexPath!) }, completion:nil) } internal func continuousScroll() { guard nil != cellFakeView else { return } let percentage = calcTrigerPercentage() var scrollRate = continuousScrollDirection.scrollValue(speedValue: scrollSpeedValue, percentage: percentage) let offset = self.offsetFromTop let insetTop = self.insetsTop let insetEnd = self.insetsEnd let length = self.collectionViewLength let contentLength = self.contentLength if contentLength + insetTop + insetEnd <= length { return } if offset + scrollRate <= -insetTop { scrollRate = -insetTop - offset } else if offset + scrollRate >= contentLength + insetEnd - length { scrollRate = contentLength + insetEnd - length - offset } collectionView!.performBatchUpdates({ () -> Void in switch self.scrollDirection { case .vertical: self.fakeCellCenter?.y += scrollRate self.cellFakeView?.center.y = self.fakeCellCenter!.y + self.panTranslation!.y self.collectionView?.contentOffset.y += scrollRate case .horizontal: self.fakeCellCenter?.x += scrollRate self.cellFakeView?.center.x = self.fakeCellCenter!.x + self.panTranslation!.x self.collectionView?.contentOffset.x += scrollRate } }, completion: nil) moveItemIfNeeded() } fileprivate func calcTrigerPercentage() -> CGFloat { guard nil != cellFakeView else { return 0 } let offset = self.offsetFromTop let offsetEnd = self.offsetFromTop + self.collectionViewLength let insetTop = self.insetsTop let trigerInsetTop = self.trigerInsetTop let trigerInsetEnd = self.trigerInsetEnd let paddingEnd = self.trigerPaddingEnd var percentage: CGFloat = 0 switch continuousScrollDirection { case .upward: if let fakeCellEdge = fakeCellTopEdge { percentage = 1.0 - ((fakeCellEdge - (offset + trigerPaddingTop)) / trigerInsetTop) } case .downward: if let fakeCellEdge = fakeCellEndEdge { percentage = 1.0 - (((insetTop + offsetEnd - paddingEnd) - (fakeCellEdge + insetTop)) / trigerInsetEnd) } case .anchor: () } // 0 <= percentage <= 1.0 percentage = max(0, min(1.0, percentage)) return percentage } // gesture recognizers fileprivate func setUpGestureRecognizers() { guard nil != collectionView else { return } longPress = UILongPressGestureRecognizer(target: self, action: #selector(RAReorderableLayout.handleLongPress(_:))) panGesture = UIPanGestureRecognizer(target: self, action: #selector(RAReorderableLayout.handlePanGesture(_:))) longPress?.delegate = self panGesture?.delegate = self panGesture?.maximumNumberOfTouches = 1 if let gestures = collectionView?.gestureRecognizers { for case let gesture as UILongPressGestureRecognizer in gestures { gesture.require(toFail: self.longPress!) } } collectionView?.addGestureRecognizer(longPress!) collectionView?.addGestureRecognizer(panGesture!) } open func cancelDrag() { cancelDrag(toIndexPath: nil) } fileprivate func cancelDrag(toIndexPath: IndexPath!) { guard nil != cellFakeView else { return } // will end drag item delegate?.collectionView?(collectionView!, collectionViewLayout: self, willEndDraggingItemToIndexPath: toIndexPath) collectionView?.scrollsToTop = true fakeCellCenter = nil invalidateDisplayLink() cellFakeView!.pushBackView { () -> Void in self.cellFakeView!.removeFromSuperview() self.cellFakeView = nil self.invalidateLayout() // did end drag item self.delegate?.collectionView?(self.collectionView!, collectionViewLayout: self, didEndDraggingItemToIndexPath: toIndexPath) } } } // MARK: - RAReorderableLayout: UIGestureRecognizerDelegate extension RAReorderableLayout: UIGestureRecognizerDelegate { // gesture recognize delegate public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // allow move item if let indexPath = collectionView?.indexPathForItem(at: gestureRecognizer.location(in: collectionView)) { if delegate?.collectionView?(collectionView!, allowMoveAtIndexPath: indexPath) == false { return false } } if gestureRecognizer.isEqual(longPress) { if collectionView!.panGestureRecognizer.state != .possible && collectionView!.panGestureRecognizer.state != .failed { return false } } else if gestureRecognizer.isEqual(panGesture) { if longPress!.state == .possible || longPress!.state == .failed { return false } } return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isEqual(longPress) { if otherGestureRecognizer.isEqual(panGesture) { return true } } else if gestureRecognizer.isEqual(panGesture) { return otherGestureRecognizer.isEqual(longPress) } else if gestureRecognizer.isEqual(collectionView?.panGestureRecognizer) { if longPress!.state != .possible || longPress!.state != .failed { return false } } return true } } // MARK: - RAReorderableLayout: Target-Action internal extension RAReorderableLayout { // long press gesture internal func handleLongPress(_ longPress: UILongPressGestureRecognizer!) { var indexPathOptional = collectionView?.indexPathForItem(at: longPress.location(in: collectionView)) ?? nil if nil != cellFakeView { indexPathOptional = cellFakeView!.indexPath } guard let indexPath = indexPathOptional else { return } switch longPress.state { case .began: // will begin drag item delegate?.collectionView?(collectionView!, collectionViewLayout: self, willBeginDraggingItemAtIndexPath: indexPath) collectionView?.scrollsToTop = false let currentCell: UICollectionViewCell? = collectionView?.cellForItem(at: indexPath) cellFakeView = RACellFakeView(cell: currentCell!) cellFakeView!.indexPath = indexPath cellFakeView!.originalCenter = currentCell?.center cellFakeView!.cellFrame = layoutAttributesForItem(at: indexPath)!.frame collectionView?.addSubview(cellFakeView!) fakeCellCenter = cellFakeView!.center invalidateLayout() cellFakeView!.pushFowardView() // did begin drag item delegate?.collectionView?(collectionView!, collectionViewLayout: self, didBeginDraggingItemAtIndexPath: indexPath) case .ended, .cancelled: cancelDrag(toIndexPath: indexPath) default: () } } // pan gesture internal func handlePanGesture(_ pan: UIPanGestureRecognizer!) { panTranslation = pan.translation(in: collectionView!) if nil != cellFakeView && nil != fakeCellCenter && nil != panTranslation { switch pan.state { case .changed: cellFakeView!.center.x = fakeCellCenter!.x + panTranslation!.x cellFakeView!.center.y = fakeCellCenter!.y + panTranslation!.y beginScrollIfNeeded() moveItemIfNeeded() case .ended, .cancelled: invalidateDisplayLink() default: () } } } } // MARK: - RACellFakeView private class RACellFakeView: UIView { weak var cell: UICollectionViewCell? var cellFakeImageView: UIImageView? var cellFakeHightedView: UIImageView? fileprivate var indexPath: IndexPath? fileprivate var originalCenter: CGPoint? fileprivate var cellFrame: CGRect? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(cell: UICollectionViewCell) { super.init(frame: cell.frame) self.cell = cell layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowOpacity = 0 layer.shadowRadius = 5.0 layer.shouldRasterize = false cellFakeImageView = UIImageView(frame: self.bounds) cellFakeImageView?.contentMode = .scaleAspectFill cellFakeImageView?.autoresizingMask = [.flexibleWidth , .flexibleHeight] cellFakeHightedView = UIImageView(frame: self.bounds) cellFakeHightedView?.contentMode = .scaleAspectFill cellFakeHightedView?.autoresizingMask = [.flexibleWidth , .flexibleHeight] cell.isHighlighted = true cellFakeHightedView?.image = getCellImage() cell.isHighlighted = false cellFakeImageView?.image = getCellImage() addSubview(cellFakeImageView!) addSubview(cellFakeHightedView!) } func changeBoundsIfNeeded(_ bounds: CGRect) { if self.bounds.equalTo(bounds) { return } UIView.animate(withDuration: 0.3, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in self.bounds = bounds }, completion: nil) } func pushFowardView() { UIView.animate(withDuration: 0.3, delay: 0, options: .beginFromCurrentState, animations: { self.center = self.originalCenter! self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) self.cellFakeHightedView!.alpha = 0; let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity") shadowAnimation.fromValue = 0 shadowAnimation.toValue = 0.7 shadowAnimation.isRemovedOnCompletion = false shadowAnimation.fillMode = kCAFillModeForwards self.layer.add(shadowAnimation, forKey: "applyShadow") }, completion: { (finished) -> Void in self.cellFakeHightedView!.removeFromSuperview() }) } func pushBackView(_ completion: (()->Void)?) { UIView.animate(withDuration: 0.3, delay: 0, options: .beginFromCurrentState, animations: { self.transform = CGAffineTransform.identity self.frame = self.cellFrame! let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity") shadowAnimation.fromValue = 0.7 shadowAnimation.toValue = 0 shadowAnimation.isRemovedOnCompletion = false shadowAnimation.fillMode = kCAFillModeForwards self.layer.add(shadowAnimation, forKey: "removeShadow") }, completion: { (finished) -> Void in completion?() }) } fileprivate func getCellImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(cell!.bounds.size, false, UIScreen.main.scale * 2) cell!.drawHierarchy(in: cell!.bounds, afterScreenUpdates: true) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
37.027778
179
0.636826
39add053fbfddfe17474767ef85e66d590a7acc3
567
// // CollectionViewCell.swift // CGVProject // // Created by PigFactory on 26/11/2018. // Copyright © 2018 PigFactory. All rights reserved. // import UIKit import Kingfisher class MoviePosterCollectionViewCell: UICollectionViewCell { @IBOutlet weak var posterView: UIImageView! //데이터 처리 #2 - poster model에 저장된 이미지 주소를 불러와서 collectionViewCell 안의 이미지뷰에 넣어준다. var model: MoviePosterCollectionViewCellModel! { didSet { posterView.kf.setImage(with: URL(string: model.moviePosterImageUrl)) } } }
21
82
0.677249
f86f433cf9480ea7d79f54af50436ed221b78c8c
19,836
// // 🦠 Corona-Warn-App // import XCTest import ExposureNotification class ENAUITests_01b_Statistics: CWATestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.setDefaults() app.setLaunchArgument(LaunchArguments.onboarding.isOnboarded, to: true) app.setLaunchArgument(LaunchArguments.onboarding.setCurrentOnboardingVersion, to: true) app.setLaunchArgument(LaunchArguments.infoScreen.userNeedsToBeInformedAboutHowRiskDetectionWorks, to: false) } func test_AddStatisticsButton_maximumNumberOfCards() { app.setLaunchArgument(LaunchArguments.statistics.maximumRegionsSelected, to: true) let addButtonIdentifier = AccessibilityIdentifiers.LocalStatistics.addLocalIncidencesButton let localStatisticsViewTitle = AccessibilityIdentifiers.LocalStatistics.localStatisticsCard app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() app.swipeUp(velocity: .slow) let statisticsCell = app.cells[AccessibilityIdentifiers.Statistics.General.tableViewCell] XCTAssertTrue(statisticsCell.waitForExistence(timeout: .medium)) let localStatisticCell = statisticsCell.staticTexts[localStatisticsViewTitle] XCTAssertTrue(localStatisticCell.waitForExistence(timeout: .long)) statisticsCell.swipeRight() // check for the text for the add button let addButton = app.buttons[addButtonIdentifier] let expectTitle = AccessibilityLabels.localized(AppStrings.Statistics.AddCard.disabledAddTitle) XCTAssertEqual(addButton.label, expectTitle, "label should show the disabled message") XCTAssertFalse(addButton.isEnabled, "button should be disabled after 5 cards") } func test_AddStatisticsButton_flow() { let addButton = AccessibilityIdentifiers.LocalStatistics.addLocalIncidencesButton let modifyButton = AccessibilityIdentifiers.LocalStatistics.modifyLocalIncidencesButton let localStatisticsViewTitle = AccessibilityIdentifiers.LocalStatistics.localStatisticsCard app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() // Wait and check for the navbar to make sure App is really launched, otherwise the swipe will do nothing let leftNavbarButton = app.images[AccessibilityIdentifiers.Home.leftBarButtonDescription] XCTAssertTrue(leftNavbarButton.waitForExistence(timeout: .medium)) app.swipeUp(velocity: .slow) let statisticsCell = app.cells[AccessibilityIdentifiers.Statistics.General.tableViewCell] XCTAssertTrue(statisticsCell.waitForExistence(timeout: .medium)) statisticsCell.swipeRight() // Management card(s) pt.1 - addition XCTAssertTrue(self.app.buttons[addButton].waitForExistence(timeout: .medium)) XCTAssertTrue(statisticsCell.buttons[addButton].isHittable) XCTAssertFalse(statisticsCell.buttons[modifyButton].isHittable) // assuming empty statistics statisticsCell.buttons[addButton].waitAndTap() // Data selection XCTAssertTrue(app.tables[AccessibilityIdentifiers.LocalStatistics.selectState].waitForExistence(timeout: .long)) // Tap on some data entry. Then we should be on select district screen. app.cells.element(boundBy: 1).waitAndTap() XCTAssertTrue(app.tables[AccessibilityIdentifiers.LocalStatistics.selectDistrict].waitForExistence(timeout: .long)) // Tap on some data entry. Then we should be back on the homescreen. app.cells.element(boundBy: 14).waitAndTap() // the Local statistics card will appear. XCTAssertTrue(statisticsCell.waitForExistence(timeout: .long)) app.swipeDown(velocity: .slow) // glitch let localStatisticCell = statisticsCell.staticTexts[localStatisticsViewTitle] XCTAssertTrue(localStatisticCell.waitForExistence(timeout: .long)) let deleteButton = statisticsCell.buttons[AccessibilityIdentifiers.General.deleteButton].firstMatch XCTAssertFalse(deleteButton.isHittable) // Management card(s) pt.2 - removal XCTAssertTrue(statisticsCell.waitForExistence(timeout: .extraLong)) XCTAssertTrue(statisticsCell.isHittable) statisticsCell.swipeRight() // because of ui reset XCTAssertTrue(statisticsCell.buttons[addButton].isHittable) XCTAssertTrue(statisticsCell.buttons[modifyButton].isHittable) statisticsCell.buttons[modifyButton].waitAndTap() XCTAssertTrue(deleteButton.waitForExistence(timeout: .long)) XCTAssertTrue(deleteButton.isHittable) deleteButton.waitAndTap() XCTAssertFalse(localStatisticCell.isHittable) XCTAssertFalse(statisticsCell.buttons[modifyButton].isHittable) } func test_StatisticsCardTitles() throws { // flow for 2.13 and later versions // GIVEN let title1 = AccessibilityIdentifiers.Statistics.Combined7DayIncidence.title let title2 = AccessibilityIdentifiers.Statistics.IntensiveCare.title let title3 = AccessibilityIdentifiers.Statistics.Infections.title let title4 = AccessibilityIdentifiers.Statistics.KeySubmissions.title let title5 = AccessibilityIdentifiers.Statistics.ReproductionNumber.title let title6 = AccessibilityIdentifiers.Statistics.AtLeastOneVaccination.title let title7 = AccessibilityIdentifiers.Statistics.FullyVaccinated.title let title8 = AccessibilityIdentifiers.Statistics.BoosterVaccination.title let title9 = AccessibilityIdentifiers.Statistics.Doses.title let layoutDirection = UIView.userInterfaceLayoutDirection(for: UIView().semanticContentAttribute) // WHEN app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() app.swipeUp(velocity: .slow) // THEN switch layoutDirection { case .rightToLeft: XCTAssertTrue(self.app.staticTexts[title9].waitForExistence(timeout: .medium)) app.staticTexts[title9].swipeLeft() XCTAssertTrue(self.app.staticTexts[title8].waitForExistence(timeout: .medium)) app.staticTexts[title8].swipeLeft() XCTAssertTrue(self.app.staticTexts[title7].waitForExistence(timeout: .medium)) app.staticTexts[title7].swipeLeft() XCTAssertTrue(self.app.staticTexts[title6].waitForExistence(timeout: .medium)) app.staticTexts[title6].swipeLeft() XCTAssertTrue(self.app.staticTexts[title5].waitForExistence(timeout: .medium)) app.staticTexts[title5].swipeLeft() XCTAssertTrue(self.app.staticTexts[title4].waitForExistence(timeout: .medium)) app.staticTexts[title4].swipeLeft() XCTAssertTrue(self.app.staticTexts[title3].waitForExistence(timeout: .medium)) app.staticTexts[title3].swipeLeft() XCTAssertTrue(self.app.staticTexts[title2].waitForExistence(timeout: .medium)) app.staticTexts[title2].swipeLeft() XCTAssertTrue(self.app.staticTexts[title1].waitForExistence(timeout: .medium)) app.staticTexts[title1].swipeRight() default: app.swipeLeft() XCTAssertTrue(self.app.staticTexts[title1].waitForExistence(timeout: .extraLong)) app.staticTexts[title1].swipeLeft() XCTAssertTrue(self.app.staticTexts[title2].waitForExistence(timeout: .medium)) app.staticTexts[title2].swipeLeft() XCTAssertTrue(self.app.staticTexts[title3].waitForExistence(timeout: .medium)) app.staticTexts[title3].swipeLeft() XCTAssertTrue(self.app.staticTexts[title4].waitForExistence(timeout: .medium)) app.staticTexts[title4].swipeLeft() XCTAssertTrue(self.app.staticTexts[title5].waitForExistence(timeout: .medium)) app.staticTexts[title5].swipeLeft() XCTAssertTrue(self.app.staticTexts[title6].waitForExistence(timeout: .medium)) app.staticTexts[title6].swipeLeft() XCTAssertTrue(self.app.staticTexts[title7].waitForExistence(timeout: .medium)) app.staticTexts[title7].swipeLeft() XCTAssertTrue(self.app.staticTexts[title8].waitForExistence(timeout: .medium)) app.staticTexts[title8].swipeLeft() XCTAssertTrue(self.app.staticTexts[title9].waitForExistence(timeout: .medium)) app.staticTexts[title9].swipeRight() } } func test_StatisticsCardInfoButtons() throws { // GIVEN let title1 = AccessibilityIdentifiers.Statistics.Combined7DayIncidence.title let title2 = AccessibilityIdentifiers.Statistics.IntensiveCare.title let title3 = AccessibilityIdentifiers.Statistics.Infections.title let title4 = AccessibilityIdentifiers.Statistics.KeySubmissions.title let title5 = AccessibilityIdentifiers.Statistics.ReproductionNumber.title let title6 = AccessibilityIdentifiers.Statistics.AtLeastOneVaccination.title let title7 = AccessibilityIdentifiers.Statistics.FullyVaccinated.title let title8 = AccessibilityIdentifiers.Statistics.BoosterVaccination.title let title9 = AccessibilityIdentifiers.Statistics.Doses.title let layoutDirection = UIView.userInterfaceLayoutDirection(for: UIView().semanticContentAttribute) // WHEN app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() app.swipeUp(velocity: .slow) // THEN switch layoutDirection { case .rightToLeft: cardDosesInfoScreenTest(title9) app.staticTexts[title8].swipeLeft() cardBoosterVaccinationInfoScreen(title8) app.staticTexts[title8].swipeLeft() cardFullyVaccinatedInfoScreenTest(title7) app.staticTexts[title7].swipeLeft() cardAtLeastOneVaccinationInfoScreenTest(title6) app.staticTexts[title6].swipeLeft() cardReproductionNumberInfoScreenTest(title5) app.staticTexts[title5].swipeLeft() cardKeySubmissionsInfoScreenTest(title4) app.staticTexts[title4].swipeLeft() cardInfectionsInfoScreenTest(title3) app.staticTexts[title3].swipeLeft() cardIntensiveCareInfoScreenTest(title2) app.staticTexts[title2].swipeLeft() cardCombinedIncidencesInfoScreenTest(title1) app.staticTexts[title1].swipeRight() default: app.swipeLeft() cardCombinedIncidencesInfoScreenTest(title1) app.staticTexts[title1].swipeLeft() cardIntensiveCareInfoScreenTest(title2) app.staticTexts[title2].swipeLeft() cardInfectionsInfoScreenTest(title3) app.staticTexts[title3].swipeLeft() cardKeySubmissionsInfoScreenTest(title4) app.staticTexts[title4].swipeLeft() cardReproductionNumberInfoScreenTest(title5) app.staticTexts[title5].swipeLeft() cardAtLeastOneVaccinationInfoScreenTest(title6) app.staticTexts[title6].swipeLeft() cardFullyVaccinatedInfoScreenTest(title7) app.staticTexts[title7].swipeLeft() cardBoosterVaccinationInfoScreen(title8) app.staticTexts[title8].swipeLeft() cardDosesInfoScreenTest(title9) app.staticTexts[title9].swipeRight() } } // MARK: - Screenshots func test_screenshot_local_statistics_card() throws { // GIVEN let incidenceTitle = AccessibilityIdentifiers.Statistics.Combined7DayIncidence.title let addStatisticsButtonTitle = AccessibilityIdentifiers.LocalStatistics.addLocalIncidencesButton let localStatisticsTitle = AccessibilityIdentifiers.LocalStatistics.localStatisticsCard // WHEN app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() app.swipeUp(velocity: .slow) XCTAssert(self.app.staticTexts[incidenceTitle].waitForExistence(timeout: .medium)) app.staticTexts[incidenceTitle].swipeRight() XCTAssert(app.buttons[addStatisticsButtonTitle].waitForExistence(timeout: .medium)) snapshot("statistics_add_local_statistics") app.buttons[addStatisticsButtonTitle].waitAndTap() XCTAssert(app.tables[AccessibilityIdentifiers.LocalStatistics.selectState].waitForExistence(timeout: .medium)) /* CAUTION: the mocked Local statistics only return districts within BadenWürttemberg so for the state always choose BadenWürttemberg 'i.e (boundBy: 1)' then you can select the whole state or a specific district */ app.tables[AccessibilityIdentifiers.LocalStatistics.selectState].cells.element(boundBy: 1).waitAndTap() XCTAssert(app.tables[AccessibilityIdentifiers.LocalStatistics.selectDistrict].waitForExistence(timeout: .medium)) app.tables[AccessibilityIdentifiers.LocalStatistics.selectDistrict].cells.element(boundBy: 2).waitAndTap() let moreCell = app.cells[AccessibilityIdentifiers.Home.MoreInfoCell.moreCell] let appInformationLabel = moreCell.buttons[AccessibilityIdentifiers.Home.MoreInfoCell.appInformationLabel] XCTAssertTrue(appInformationLabel.waitForExistence(timeout: .medium)) app.swipeDown(velocity: .slow) XCTAssert(self.app.staticTexts[localStatisticsTitle].waitForExistence(timeout: .medium)) snapshot("statistics_local_7day_values") } func test_screenshot_statistics_card_titles() throws { // GIVEN let combinedIncidenceTitle = AccessibilityIdentifiers.Statistics.Combined7DayIncidence.title let intensiveCareTitle = AccessibilityIdentifiers.Statistics.IntensiveCare.title let infectionsTitle = AccessibilityIdentifiers.Statistics.Infections.title let keySubmissionsTitle = AccessibilityIdentifiers.Statistics.KeySubmissions.title let reproductionNumberTitle = AccessibilityIdentifiers.Statistics.ReproductionNumber.title let atLeastOneVaccinationTitle = AccessibilityIdentifiers.Statistics.AtLeastOneVaccination.title let fullyVaccinatedTitle = AccessibilityIdentifiers.Statistics.FullyVaccinated.title let boosterVaccinationTitle = AccessibilityIdentifiers.Statistics.BoosterVaccination.title let dosesTitle = AccessibilityIdentifiers.Statistics.Doses.title let layoutDirection = UIView.userInterfaceLayoutDirection(for: UIView().semanticContentAttribute) var screenshotCounter = 0 // WHEN app.setPreferredContentSizeCategory(accessibility: .normal, size: .S) app.launch() app.swipeUp(velocity: .slow) // THEN switch layoutDirection { case .rightToLeft: XCTAssert(self.app.staticTexts[dosesTitle].waitForExistence(timeout: .medium)) app.staticTexts[dosesTitle].swipeLeft() XCTAssert(self.app.staticTexts[boosterVaccinationTitle].waitForExistence(timeout: .medium)) app.staticTexts[boosterVaccinationTitle].swipeLeft() XCTAssert(self.app.staticTexts[fullyVaccinatedTitle].waitForExistence(timeout: .medium)) app.staticTexts[fullyVaccinatedTitle].swipeLeft() XCTAssert(self.app.staticTexts[atLeastOneVaccinationTitle].waitForExistence(timeout: .medium)) app.staticTexts[atLeastOneVaccinationTitle].swipeLeft() XCTAssert(self.app.staticTexts[reproductionNumberTitle].waitForExistence(timeout: .medium)) app.staticTexts[reproductionNumberTitle].swipeLeft() XCTAssert(self.app.staticTexts[keySubmissionsTitle].waitForExistence(timeout: .medium)) app.staticTexts[keySubmissionsTitle].swipeLeft() XCTAssert(self.app.staticTexts[infectionsTitle].waitForExistence(timeout: .medium)) app.staticTexts[infectionsTitle].swipeLeft() XCTAssert(self.app.staticTexts[intensiveCareTitle].waitForExistence(timeout: .medium)) app.staticTexts[intensiveCareTitle].swipeLeft() XCTAssert(self.app.staticTexts[combinedIncidenceTitle].waitForExistence(timeout: .medium)) app.staticTexts[combinedIncidenceTitle].swipeRight() default: app.swipeLeft() XCTAssert(self.app.staticTexts[combinedIncidenceTitle].waitForExistence(timeout: .medium)) snapshot("statistics_7day_combined_incidences") app.staticTexts[combinedIncidenceTitle].swipeLeft() XCTAssert(self.app.staticTexts[intensiveCareTitle].waitForExistence(timeout: .medium)) snapshot("statistics_intensive_care") app.staticTexts[intensiveCareTitle].swipeLeft() XCTAssert(self.app.staticTexts[infectionsTitle].waitForExistence(timeout: .medium)) snapshot("statistics_confirmed_new_infections") app.staticTexts[infectionsTitle].swipeLeft() XCTAssert(self.app.staticTexts[keySubmissionsTitle].waitForExistence(timeout: .medium)) snapshot("statistics_key_submissions") app.staticTexts[keySubmissionsTitle].swipeLeft() XCTAssert(self.app.staticTexts[reproductionNumberTitle].waitForExistence(timeout: .medium)) snapshot("statistics_7Day_rvalue") app.staticTexts[reproductionNumberTitle].swipeLeft() XCTAssert(self.app.staticTexts[atLeastOneVaccinationTitle].waitForExistence(timeout: .medium)) snapshot("statistics_at_least_one_vaccination") app.staticTexts[atLeastOneVaccinationTitle].swipeLeft() XCTAssert(self.app.staticTexts[fullyVaccinatedTitle].waitForExistence(timeout: .medium)) snapshot("statistics_fully_vaccinated") app.staticTexts[fullyVaccinatedTitle].swipeLeft() XCTAssert(self.app.staticTexts[boosterVaccinationTitle].waitForExistence(timeout: .medium)) snapshot("statistics_booster_vaccination") app.staticTexts[boosterVaccinationTitle].swipeLeft() XCTAssert(self.app.staticTexts[dosesTitle].waitForExistence(timeout: .medium)) snapshot("statistics_doses") app.staticTexts[dosesTitle].swipeRight() cardBoosterVaccinationOpenInfoScreen(boosterVaccinationTitle) snapshot("statistics_info_screen_\(String(format: "%04d", (screenshotCounter.inc() )))") app.swipeUp(velocity: .slow) snapshot("statistics_info_screen_\(String(format: "%04d", (screenshotCounter.inc() )))") } } // MARK: - Private private func cardCombinedIncidencesInfoScreenTest(_ title1: String) { XCTAssertTrue(app.staticTexts[title1].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.Combined7DayIncidence.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardIntensiveCareInfoScreenTest(_ title3: String) { XCTAssertTrue(app.staticTexts[title3].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.IntensiveCare.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardInfectionsInfoScreenTest(_ title4: String) { XCTAssertTrue(app.staticTexts[title4].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.Infections.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardKeySubmissionsInfoScreenTest(_ title5: String) { XCTAssertTrue(app.staticTexts[title5].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.KeySubmissions.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardReproductionNumberInfoScreenTest(_ title6: String) { XCTAssertTrue(app.staticTexts[title6].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.ReproductionNumber.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardAtLeastOneVaccinationInfoScreenTest(_ title7: String) { XCTAssertTrue(app.staticTexts[title7].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.AtLeastOneVaccination.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardFullyVaccinatedInfoScreenTest(_ title8: String) { XCTAssertTrue(app.staticTexts[title8].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.FullyVaccinated.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardDosesInfoScreenTest(_ title9: String) { XCTAssertTrue(app.staticTexts[title9].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.Doses.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardBoosterVaccinationInfoScreen(_ title9: String) { XCTAssert(app.staticTexts[title9].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.BoosterVaccination.infoButton].waitAndTap() app.buttons["AppStrings.AccessibilityLabel.close"].waitAndTap() } private func cardBoosterVaccinationOpenInfoScreen(_ title: String) { XCTAssert(app.staticTexts[title].waitForExistence(timeout: .medium)) app.buttons[AccessibilityIdentifiers.Statistics.BoosterVaccination.infoButton].waitAndTap() } }
45.081818
117
0.807975
db1cf2dc0b90456e79727c2a7df6b984e4d74ee4
2,975
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import ChronoxorFbe // Fast Binary Encoding StructList final model public class StructListFinalModel: Model { private let _model: FinalModelStructList public override init(buffer: Buffer = Buffer()) { _model = FinalModelStructList(buffer: buffer, offset: 8) super.init(buffer: buffer) } // Model type public var fbeType: Int = fbeTypeConst static let fbeTypeConst: Int = FinalModelStructList.fbeTypeConst // Check if the struct value is valid public func verify() -> Bool { if (buffer.offset + _model.fbeOffset) > buffer.size { return false } let fbeStructSize = Int(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { return false } return ((8 + _model.verify()) == fbeStructSize) } // Serialize the struct value public func serialize(value: StructList) throws -> Int { let fbeInitialSize = buffer.size let fbeStructType = fbeType var fbeStructSize = 8 + _model.fbeAllocationSize(value: value) let fbeStructOffset = try buffer.allocate(size: fbeStructSize) - buffer.offset if (buffer.offset + fbeStructOffset + fbeStructSize) > buffer.size { assertionFailure("Model is broken!") return 0 } fbeStructSize = try _model.set(value: value) + 8 try buffer.resize(size: fbeInitialSize + fbeStructSize) write(offset: _model.fbeOffset - 8, value: UInt32(fbeStructSize)) write(offset: _model.fbeOffset - 4, value: UInt32(fbeStructType)) return fbeStructSize } // Deserialize the struct value public func deserialize() -> StructList { var value = StructList(); _ = deserialize(value: &value); return value } public func deserialize(value: inout StructList) -> Int { if (buffer.offset + _model.fbeOffset) > buffer.size { assertionFailure("Model is broken!") return 0 } let fbeStructSize = Int32(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int32(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { assertionFailure("Model is broken!") return 8 } var fbeSize = Size() value = _model.get(size: &fbeSize, fbeValue: &value) return 8 + fbeSize.value } // Move to the next struct value public func next(prev: Int) { _model.fbeShift(size: prev) } }
34.195402
118
0.605378
503eeee97ac2c1df61c3c927739407f328d0cc31
323
// // SDPViewExternalConfiguratorProtocol.swift // Swift-data-processor // // Created by Dmytro Platov on 7/25/18. // Copyright © 2018 Dmytro Platov. All rights reserved. // import Foundation protocol SDPViewExternalConfiguratorProtocol: class{ var externalConfigurator: SDPViewExternalConfigurator? {get set} }
21.533333
68
0.767802
383ffc6e30bfc80f63d9389b34703abc2cee076e
701
// // Copyright (c) Vatsal Manot // import CoreData import Merge import Swallow extension _CoreData.DatabaseRecord { public struct Reference: DatabaseRecordReference { public typealias RecordContext = _CoreData.DatabaseRecordContext private let nsManagedObject: NSManagedObject public var recordID: RecordContext.RecordID { .init(managedObjectID: nsManagedObject.objectID) } public var zoneID: RecordContext.Zone.ID { nsManagedObject.objectID.persistentStore!.identifier } init(managedObject: NSManagedObject) { self.nsManagedObject = managedObject } } }
25.035714
72
0.654779
bf9f7713542464f98cb27f9b925a04085a7575bd
3,740
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import GRPC import Logging import NIO /// Makes streaming requests and listens to responses ping-pong style. /// Iterations can be limited by config. final class AsyncPingPongRequestMaker: RequestMaker { private let client: Grpc_Testing_BenchmarkServiceClient private let requestMessage: Grpc_Testing_SimpleRequest private let logger: Logger private let stats: StatsWithLock /// If greater than zero gives a limit to how many messages are exchanged before termination. private let messagesPerStream: Int /// Stops more requests being made after stop is requested. private var stopRequested = false /// Initialiser to gather requirements. /// - Parameters: /// - config: config from the driver describing what to do. /// - client: client interface to the server. /// - requestMessage: Pre-made request message to use possibly repeatedly. /// - logger: Where to log useful diagnostics. /// - stats: Where to record statistics on latency. init(config: Grpc_Testing_ClientConfig, client: Grpc_Testing_BenchmarkServiceClient, requestMessage: Grpc_Testing_SimpleRequest, logger: Logger, stats: StatsWithLock) { self.client = client self.requestMessage = requestMessage self.logger = logger self.stats = stats self.messagesPerStream = Int(config.messagesPerStream) } /// Initiate a request sequence to the server - in this case the sequence is streaming requests to the server and waiting /// to see responses before repeating ping-pong style. The number of iterations can be limited by config. /// - returns: A future which completes when the request-response sequence is complete. func makeRequest() -> EventLoopFuture<GRPCStatus> { var startTime = grpcTimeNow() var messagesSent = 1 var streamingCall: BidirectionalStreamingCall< Grpc_Testing_SimpleRequest, Grpc_Testing_SimpleResponse >? /// Handle a response from the server - potentially triggers making another request. /// Will execute on the event loop which deals with thread safety concerns. func handleResponse(response: Grpc_Testing_SimpleResponse) { streamingCall!.eventLoop.preconditionInEventLoop() let endTime = grpcTimeNow() self.stats.add(latency: endTime - startTime) if !self.stopRequested, self.messagesPerStream == 0 || messagesSent < self.messagesPerStream { messagesSent += 1 startTime = endTime // Use end of previous request as the start of the next. streamingCall!.sendMessage(self.requestMessage, promise: nil) } else { streamingCall!.sendEnd(promise: nil) } } // Setup the call. streamingCall = self.client.streamingCall(handler: handleResponse) // Kick start with initial request streamingCall!.sendMessage(self.requestMessage, promise: nil) return streamingCall!.status } /// Request termination of the request-response sequence. func requestStop() { // Flag stop as requested - this will prevent any more requests being made. self.stopRequested = true } }
38.958333
123
0.729144
08801136ab15da6799910e490616f23639b4ef2b
887
// // BBMetalFlipFilter.swift // BBMetalImage // // Created by Kaibo Lu on 4/12/19. // Copyright © 2019 Kaibo Lu. All rights reserved. // import Metal /// Flips image horizontally and/or vertically public class BBMetalFlipFilter: BBMetalBaseFilter { /// Whether to flip horizontally or not public var horizontal: Bool /// Whether to flip vertically or not public var vertical: Bool public init(horizontal: Bool = false, vertical: Bool = false) { self.horizontal = horizontal self.vertical = vertical super.init(kernelFunctionName: "flipKernel") } public override func updateParameters(for encoder: MTLComputeCommandEncoder, texture: BBMetalTexture) { encoder.setBytes(&horizontal, length: MemoryLayout<Bool>.size, index: 0) encoder.setBytes(&vertical, length: MemoryLayout<Bool>.size, index: 1) } }
30.586207
107
0.695603
715aeb7da86ec43177c9eba4ea6cf5910a1d669f
3,170
// // AlbumsAPIStoreTests.swift // VIPDemo // // Created by Shagun Madhikarmi on 11/10/2016. // Copyright © 2016 ustwo. All rights reserved. // import XCTest @testable import VIPDemo // MARK: - AlbumsAPIStoreTests final class AlbumsAPIStoreTests: XCTestCase { // MARK: - Tests func testFetchAlbumsShouldSendTopArtistAlbumsRequest() { // Given let networkClientSpy = AlbumsNetworkClientSpy() let store = AlbumsAPIStore(networkClient: networkClientSpy) // When let artistId = "cc197bad-dc9c-440d-a5b5-d52ba2e14234" store.fetchAlbums(artistId: artistId) { album, error in } // Then XCTAssertTrue(networkClientSpy.sendRequestCalled) } func testFetchAlbumsShouldReturnTopAlbums() { // Given let networkClientSpy = AlbumsNetworkClientSpy() let store = AlbumsAPIStore(networkClient: networkClientSpy) // When let artistId = "cc197bad-dc9c-440d-a5b5-d52ba2e14234" let expectationFetchAlbums = expectation(description: "fetchAlbums") store.fetchAlbums(artistId: artistId) { albums, error in if albums?.count == 5 && error == nil { expectationFetchAlbums.fulfill() } } // Then waitForExpectations(timeout: 0.1, handler: nil) } func testFetchAlbumsShouldReturnError() { // Given let networkClientSpy = AlbumsNetworkClientErrorSpy() let store = AlbumsAPIStore(networkClient: networkClientSpy) // When let artistId = "cc197bad-dc9c-440d-a5b5-d52ba2e14234" let expectationFetchAlbums = expectation(description: "fetchAlbums") store.fetchAlbums(artistId: artistId) { albums, error in if albums == nil && error != nil { expectationFetchAlbums.fulfill() } } // Then waitForExpectations(timeout: 0.1, handler: nil) } } // MARK: - AlbumsNetworkClientSpy final class AlbumsNetworkClientSpy: NetworkClientProtocol { var sendRequestCalled = false func sendRequest(request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { sendRequestCalled = true let bundle = Bundle(for: AlbumsAPIStoreTests.self) if let path = bundle.path(forResource: "top_albums", ofType: "json") { let url = URL(fileURLWithPath: path) do { let data = try Data(contentsOf: url, options: Data.ReadingOptions.mappedIfSafe) completion(data, nil, nil) } catch { } } } } // MARK: - AlbumsNetworkClientError enum AlbumsNetworkClientError: Error { case generic } // MARK: - AlbumsNetworkClientErrorSpy final class AlbumsNetworkClientErrorSpy: NetworkClientProtocol { var sendRequestCalled = false func sendRequest(request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { sendRequestCalled = true let error = AlbumsNetworkClientError.generic completion(nil, nil, error) } }
20.718954
102
0.629022
5d6cd9ffc4858dbb2cc253b6bc122f99e24f8220
3,617
// // SegmentAnalyticsTracker.swift // edX // // Created by Akiva Leffert on 9/15/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation class SegmentAnalyticsTracker : NSObject, OEXAnalyticsTracker { private let GoogleCategoryKey = "category" private let GoogleLabelKey = "label" private let GoogleActionKey = "action" private let GoogleDeviceKey = "device_model" var currentOrientationValue : String { return UIApplication.shared.statusBarOrientation.isLandscape ? OEXAnalyticsValueOrientationLandscape : OEXAnalyticsValueOrientationPortrait } func identifyUser(_ user : OEXUserDetails?) { if let userID = user?.userId { var traits : [String:AnyObject] = [:] if let email = user?.email { traits[key_email] = email as AnyObject } if let username = user?.username { traits[key_username] = username as AnyObject } SEGAnalytics.shared().identify(userID.description, traits:traits) } } func clearIdentifiedUser() { SEGAnalytics.shared().reset() } func trackEvent(_ event: OEXAnalyticsEvent, forComponent component: String?, withProperties properties: [String : Any]) { var context = [key_app_name : value_app_name] if let component = component { context[key_component] = component } if let courseID = event.courseID { context[key_course_id] = courseID } if let browserURL = event.openInBrowserURL { context[key_open_in_browser] = browserURL } var info : [String : Any] = [ key_data : properties, key_context : context, key_name : event.name, OEXAnalyticsKeyOrientation : currentOrientationValue ] info[GoogleCategoryKey] = event.category info[GoogleLabelKey] = event.label info[GoogleDeviceKey] = UIDevice.deviceModel if let userID = OEXSession.shared()?.currentUser?.userId { info[AnalyticsEventDataKey.UserID.rawValue] = userID } SEGAnalytics.shared().track(event.displayName, properties: info) } func trackScreen(withName screenName: String, courseID: String?, value: String?, additionalInfo info: [String : String]?) { var properties: [String:Any] = [ key_context: [ key_app_name: value_app_name ] ] if let value = value { properties[GoogleActionKey] = value as NSObject } if let userID = OEXSession.shared()?.currentUser?.userId { properties[AnalyticsEventDataKey.UserID.rawValue] = userID } SEGAnalytics.shared().screen(screenName, properties: properties) // remove used id from properties because custom event will add it again if let _ = OEXSession.shared()?.currentUser?.userId { properties.removeValue(forKey: AnalyticsEventDataKey.UserID.rawValue) } // adding additional info to event if let info = info, info.count > 0 { properties = properties.concat(dictionary: info as [String : NSObject]) } let event = OEXAnalyticsEvent() event.displayName = screenName event.label = screenName event.category = OEXAnalyticsCategoryScreen event.name = OEXAnalyticsEventScreen; event.courseID = courseID trackEvent(event, forComponent: nil, withProperties: properties) } }
34.447619
147
0.624827
4a5320374b3d582fafbe99704bf261314285b7c7
3,482
// // This source file is part of the carousell/pickle open source project // // Copyright © 2017 Carousell and the project authors // Licensed under Apache License v2.0 // // See https://github.com/carousell/pickle/blob/master/LICENSE for license information // See https://github.com/carousell/pickle/graphs/contributors for the list of project authors // import XCTest class UITests: XCTestCase { private lazy var app: XCUIApplication = XCUIApplication() private var cancelButton: XCUIElement { return app.navigationBars.buttons["Cancel"] } private var doneButton: XCUIElement { return app.navigationBars.buttons["Done"] } // MARK: - override func setUp() { super.setUp() continueAfterFailure = false app.launch() } private func showImagePicker(named name: String) { app.tables.cells.staticTexts[name].tap() addUIInterruptionMonitor(withDescription: "Photos Permission") { alert -> Bool in let button = alert.buttons["OK"] if button.exists { button.tap() return true } return false } // Need to interact with the app for the handler to fire app.tap() // Workaround to tap the permission alert button found via the springboard let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let button = springboard.buttons["OK"] if button.exists { button.tap() } } func testDefaultStates() { showImagePicker(named: "Default appearance") XCTAssert(cancelButton.isEnabled) XCTAssertFalse(doneButton.isEnabled) cancelButton.tap() } func testImageSelections() { showImagePicker(named: "Default appearance") let cells = app.collectionViews.children(matching: .cell) let first = cells.element(boundBy: 0) let second = cells.element(boundBy: 1) let third = cells.element(boundBy: 2) let forth = cells.element(boundBy: 3) let fifth = cells.element(boundBy: 4) // Select and deselect an image first.tap() XCTAssert(first.isSelected) XCTAssert(doneButton.isEnabled) XCTAssert(first.identifier == "1") first.tap() XCTAssertFalse(first.isSelected) XCTAssertFalse(doneButton.isEnabled) XCTAssert(first.identifier.isEmpty) // Select images in sequence second.tap() XCTAssert(second.identifier == "1") third.tap() XCTAssert(third.identifier == "2") forth.tap() XCTAssert(forth.identifier == "3") // Reorder selections third.tap() XCTAssert(second.identifier == "1") XCTAssert(forth.identifier == "2") third.tap() XCTAssert(third.identifier == "3") fifth.tap() XCTAssert(fifth.identifier == "4") doneButton.tap() } func testSwitchingAlbums() { showImagePicker(named: "Default appearance") app.navigationBars.staticTexts["Camera Roll"].tap() app.tables.cells.staticTexts["Favorites"].tap() XCTAssert(app.collectionViews.cells.count == 0) app.navigationBars["Favorites"].staticTexts["Favorites"].tap() app.tables.cells.staticTexts["Camera Roll"].tap() XCTAssert(app.collectionViews.cells.count == 5) cancelButton.tap() } }
28.308943
95
0.624067
8787ad35ad8ceaa21dfb853ad1179b4624276de3
1,578
// // String+Hex.swift // MEWwalletKit // // Created by Mikhail Nikanorov on 4/25/19. // Copyright © 2019 MyEtherWallet Inc. All rights reserved. // import Foundation private let _nonHexCharacterSet = CharacterSet(charactersIn: "0123456789ABCDEF").inverted extension String { func isHex() -> Bool { var rawHex = self rawHex.removeHexPrefix() rawHex = rawHex.uppercased() return (rawHex.rangeOfCharacter(from: _nonHexCharacterSet) == nil) } func isHexWithPrefix() -> Bool { guard self.hasHexPrefix() else { return false } return self.isHex() } mutating func removeHexPrefix() { if self.hasPrefix("0x") { let indexStart = self.index(self.startIndex, offsetBy: 2) self = String(self[indexStart...]) } } mutating func addHexPrefix() { if !self.hasPrefix("0x") { self = "0x" + self } } mutating func alignHexBytes() { guard self.isHex(), self.count % 2 != 0 else { return } let hasPrefix = self.hasPrefix("0x") if hasPrefix { self.removeHexPrefix() } self = "0" + self if hasPrefix { self.addHexPrefix() } } func hasHexPrefix() -> Bool { return self.hasPrefix("0x") } func stringRemoveHexPrefix() -> String { var string = self string.removeHexPrefix() return string } func stringAddHexPrefix() -> String { var string = self string.addHexPrefix() return string } func stringWithAlignedHexBytes() -> String { var string = self string.alignHexBytes() return string } }
21.04
89
0.629911
2f8d579dd701f2f73771d04b6774899046f906bd
2,132
// // AppDelegate.swift // SideMenu // // Created by 賢瑭 何 on 2016/5/22. // Copyright © 2016年 Donny. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.361702
285
0.752814
1450d0a2b8f740ceb059a8773957d7cc5d94f555
2,867
// // DoraCircleProgressView.swift // hoonpay // // Created by 李胜锋 on 2017/10/10. // Copyright © 2017年 lishengfeng. All rights reserved. // import Foundation import UIKit ///自定义彩色圆形进度条 public class DoraCircleProgressView : UIView { public var progress:CGFloat = 0 public var lineWidth:CGFloat = 12.0 public var fillColor:UIColor = UIColor.clear public var trackColor:UIColor = UIColor.lightGray public var progressColor:UIColor = UIColor.red public var trackLayer:CAShapeLayer? public var progressLayer:CAShapeLayer? public func setProgress(_ progress:CGFloat, animated:Bool = false) { self.progress = progress self.drawTrackLayer() self.drawProgressLayer() // CATransaction.setDisableActions(!animated) let function = CAMediaTimingFunctionName.easeIn CATransaction.setAnimationTimingFunction(CAMediaTimingFunction.init(name: function)) // CATransaction.setAnimationDuration(5) CATransaction.begin() progressLayer?.strokeEnd = progress CATransaction.commit() } // 背景圆 private func drawTrackLayer() { if trackLayer != nil { trackLayer?.removeFromSuperlayer() trackLayer = nil } trackLayer = self.drawLayer(strokeColor: trackColor) trackLayer?.fillColor = fillColor.cgColor self.layer.insertSublayer(trackLayer!, at: 0) // self.layer.addSublayer(trackLayer!) } //进度圆 private func drawProgressLayer() { if progressLayer != nil { progressLayer?.removeFromSuperlayer() progressLayer = nil } // 1.画背景圆 progressLayer = self.drawLayer(strokeColor: progressColor) progressLayer?.strokeEnd = 0.0 self.layer.addSublayer(progressLayer!) } //画圆圈 private func drawLayer(strokeColor:UIColor) -> CAShapeLayer { var layer:CAShapeLayer // 1.画背景圆 let center = CGPoint.init(x: self.dora_width / 2.0, y: self.dora_height / 2.0) let radius = (self.dora_width - lineWidth) / 2.0 let path = UIBezierPath.init(arcCenter: center, radius: radius, startAngle: CGFloat.pi / 180 * -90, endAngle: CGFloat.pi / 180 * (360 - 90), clockwise: true) layer = CAShapeLayer.init() layer.frame = self.bounds layer.fillColor = UIColor.clear.cgColor layer.strokeColor = strokeColor.cgColor layer.opacity = 1 layer.lineCap = CAShapeLayerLineCap.round layer.lineWidth = lineWidth layer.path = path.cgPath return layer } }
30.178947
92
0.596442
268e83bdff2e11602e9d73b3a7585816377f1630
1,442
// // ViewController.swift // Tumblr // // Created by Gordon on 9/13/18. // Copyright © 2018 Gordon. All rights reserved. // import UIKit enum PhotoKeys { static let originalSize = "original_size" static let Url = "url" } class ViewController: UIViewController { @IBOutlet weak var PhotoDetailsViewController: UIImageView! var post: [String: Any]? override func viewDidLoad() { super.viewDidLoad() if let post = post { if let photos = post["photos"] as? [[String: Any]] { let photo = photos[0] let originalSize = photo["original_size"] as! [String: Any] let urlString = originalSize["url"] as! String let url = URL(string: urlString) PhotoDetailsViewController.af_setImage(withURL: url!) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
25.298246
106
0.597087
485cf897472905137258a63c3ef5bfc4fedb9add
530
// // Images.swift // ConnectOng // // Created by Alley Pereira on 11/02/21. // Copyright © 2021 Alley Pereira. All rights reserved. // import Foundation import CloudKit // swiftlint:disable identifier_name class Images { var id: CKRecord.ID var imageURL: CKAsset init?(record: CKRecord) { guard let imageURL = record["imageURL"] as? CKAsset else { return nil} id = record.recordID self.imageURL = imageURL } init(id: CKRecord.ID, imageURLAsset: CKAsset) { self.id = id self.imageURL = imageURLAsset } }
17.666667
72
0.701887
8f307762b2eaa7aa98c8044c57a355edcd3ee77e
4,097
// // ServiceAPIKeyTableViewCell.swift // Notifire // // Created by David Bielik on 10/11/2018. // Copyright © 2018 David Bielik. All rights reserved. // import UIKit protocol ServiceAPIKeyCellDelegate: class { func shouldReloadServiceCell() } class ServiceAPIKeyTableViewCell: ReusableBaseTableViewCell { // MARK: - Properties weak var delegate: ServiceAPIKeyCellDelegate? var serviceKey: String? { didSet { updateUI() } } // MARK: Views let keyTextField: BorderedTextField = { let textField = BorderedTextField() textField.isSecureTextEntry = true textField.isEnabled = false textField.font = UIFont.systemFont(ofSize: 16) return textField }() var keyTextFieldHeight: NSLayoutConstraint! let keyLabel = CopyableLabel(style: .secureInformation) lazy var visibilityButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(didPressVisibilityButton), for: .touchUpInside) return button }() // MARK: - Inherited override func setup() { layout() updateUI() } override func layoutSubviews() { super.layoutSubviews() backgroundColor = .compatibleSystemBackground updateUI() } // MARK: - Private private func layout() { contentView.add(subview: keyTextField) keyTextField.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor).isActive = true keyTextField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Size.Cell.extendedSideMargin).isActive = true let bottomConstraint = keyTextField.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -Size.Cell.extendedSideMargin) bottomConstraint.priority = UILayoutPriority(850) bottomConstraint.isActive = true contentView.add(subview: keyLabel) keyLabel.leadingAnchor.constraint(equalTo: keyTextField.layoutMarginsGuide.leadingAnchor).isActive = true keyLabel.trailingAnchor.constraint(equalTo: keyTextField.layoutMarginsGuide.trailingAnchor).isActive = true keyLabel.topAnchor.constraint(equalTo: keyTextField.layoutMarginsGuide.topAnchor).isActive = true keyLabel.bottomAnchor.constraint(equalTo: keyTextField.layoutMarginsGuide.bottomAnchor).isActive = true contentView.add(subview: visibilityButton) visibilityButton.leadingAnchor.constraint(equalTo: keyTextField.trailingAnchor, constant: Size.Cell.extendedSideMargin).isActive = true visibilityButton.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor).isActive = true visibilityButton.centerYAnchor.constraint(equalTo: keyLabel.firstBaselineAnchor).isActive = true visibilityButton.widthAnchor.constraint(equalTo: visibilityButton.heightAnchor).isActive = true visibilityButton.heightAnchor.constraint(equalToConstant: Size.iconSize).isActive = true } private func updateUI() { if let key = serviceKey { keyTextField.text = "" let paragraph = NSMutableParagraphStyle() paragraph.hyphenationFactor = 0 let attributedString = NSAttributedString(string: key, attributes: [.paragraphStyle: paragraph]) keyLabel.attributedText = attributedString keyLabel.isUserInteractionEnabled = true visibilityButton.setImage(#imageLiteral(resourceName: "visibility_on").withRenderingMode(.alwaysTemplate), for: .normal) visibilityButton.tintColor = .primary } else { keyTextField.text = String(repeating: "*", count: 20) keyLabel.text = "" keyLabel.isUserInteractionEnabled = false visibilityButton.setImage(#imageLiteral(resourceName: "visibility_off").withRenderingMode(.alwaysTemplate), for: .normal) visibilityButton.tintColor = .gray } } @objc private func didPressVisibilityButton() { self.delegate?.shouldReloadServiceCell() } }
40.564356
143
0.708323
dba2e051f7069c8a4cff43cc256069a52c4ee4d1
985
// // UIStackViewTests.swift // UIStackViewTests // // Created by Oleg Tverdokhleb on 18/09/16. // Copyright © 2016 oltv00. All rights reserved. // import XCTest @testable import UIStackView class UIStackViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.621622
111
0.638579
67dd30a55416710821f9d9f578dcf228a4195bca
819
// // CombineRealm // // Created by Yaroslav Zhurakovskiy on 07.11.2019. // Copyright © 2019 Yaroslav Zhurakovskiy. All rights reserved. // import RealmSwift public extension Results { func observeElementsPublisher() -> ObserveElementsPublisher<Element> { return ObserveElementsPublisher(results: self) } func observeChangePublisher() -> ObserveChangePublisher<Element> { return ObserveChangePublisher(results: self) } } public extension Realm { func objectsPublisher<Element: Object>(_ type: Element.Type) -> ObserveElementsPublisher<Element> { return objects(type).observeElementsPublisher() } } public extension RealmSwift.Object { func observePublisher() -> ObserveObjectPublisher { return ObserveObjectPublisher(object: self) } }
26.419355
103
0.714286
874253cc6fb7f7782d65702496738aaffd05b605
2,153
// // MIT License // Copyright (c) 2021 Orange // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the Software), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // import Foundation import OrangeDesignSystem import SwiftUI struct ComponentList: View { let applicationDescription = ApplicationDescription(applicationName: "ODS Demo App", applicationVersion: "1.0") var body: some View { NavigationView { List { NavigationLink("Colors", destination: ColorList()).font(ODSFontStyle.title3.font()) NavigationLink("Fonts", destination: FontList()).font(ODSFontStyle.title3.font()) NavigationLink("Standard buttons", destination: StandardButtonsList()).font(ODSFontStyle.title3.font()) NavigationLink("Shape buttons", destination: ShapeButtonsList()).font(ODSFontStyle.title3.font()) NavigationLink("About component", destination: AboutView() .environmentObject(applicationDescription)) .font(ODSFontStyle.title3.font()) } .navigationBarTitleDisplayMode(.inline) .navigationTitle("Components") } } }
45.808511
119
0.70785
7a776ced188085f05310643f579de5d8f070d227
612
// // DisposeBag.swift // Yomu // // Created by Sendy Halim on 6/16/16. // Copyright © 2016 Sendy Halim. All rights reserved. // import RxSwift import Swiftz precedencegroup YomuAddToDisposeBagPrecedence { associativity: left lowerThan: MonadPrecedenceLeft higherThan: AssignmentPrecedence } infix operator ==> : YomuAddToDisposeBagPrecedence func ==> (disposable: Disposable, disposeBag: DisposeBag) { disposable.disposed(by: disposeBag) } infix operator ~>> : YomuAddToDisposeBagPrecedence func ~>> (disposable: Disposable?, disposeBag: DisposeBag) { disposable >>- { $0 ==> disposeBag } }
21.103448
60
0.738562
141131940626d828efd280ea32cfb0819d9d5951
8,202
// // Date+EasyAdd.swift // EasyKit // // Created by Fanxx on 2018/3/23. // Copyright © 2018年 fanxx. All rights reserved. // import Foundation ///日期单位 public enum EasyDateUnit: Int, Comparable { ///年 case year = 6 ///月 case month = 5 ///日 case day = 4 ///时 case hour = 3 ///分 case minute = 2 ///秒 case second = 1 ///毫秒 case nanosecond = 0 public static func < (lhs: EasyDateUnit, rhs: EasyDateUnit) -> Bool { return lhs.rawValue < rhs.rawValue } } ///日期值 public enum EasyDateValue: Equatable { ///年 case year(Int) ///月 case month(Int) ///日 case day(Int) ///时 case hour(Int) ///分 case minute(Int) ///秒 case second(Int) ///毫秒 case nanosecond(Int) } ///常用格式化参数 public enum EasyDateFormat: CustomStringConvertible { case date(_ separator: String) case time(_ separator: String) case datetime(_ dateSeparator:String,_ timeSeparator:String,_ partSeparator: String) public var description: String { switch self { case let .date(sp): return "yyyy\(sp)MM\(sp)dd" case let .time(sp): return "HH\(sp)mm\(sp)ss" case let .datetime(s1,s2,s3): return "yyyy\(s1)MM\(s1)dd\(s3)HH\(s2)mm\(s2)ss" } } } extension EasyDateFormat { ///yyyy-MM-dd public static var date: EasyDateFormat { return .date("-")} ///HH:mm:ss public static var time: EasyDateFormat { return .time(":")} ///yyyy-MM-dd HH:mm:ss public static var datetime: EasyDateFormat { return .datetime("-", ":", " ")} } extension EasyCoding where Base == Date { ///转成objc对象 public var objc: NSDate { return self.base as NSDate } ///实例 public static func instance(_ values: EasyDateValue...) -> Date { var components = DateComponents() for value in values { switch value { case let .year(value): components.year = value case let .month(value): components.month = value case let .day(value): components.day = value case let .hour(value): components.hour = value case let .minute(value): components.minute = value case let .second(value): components.second = value case let .nanosecond(value): components.nanosecond = value } } return Calendar.current.date(from: components)! } public func string(_ format: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone? = nil, locale: Locale? = .current) -> String { let formatter = DateFormatter() formatter.dateFormat = format if let tz = timeZone { formatter.timeZone = tz } formatter.locale = locale return formatter.string(from: self.base) } public func format(_ format: EasyDateFormat) -> String { return self.string(format.description) } ///两个日期相差 public func since(_ date: Date, for unit: EasyDateUnit) -> Int { switch unit { case .nanosecond: return Int(self.base.timeIntervalSince(date) * 1000) case .second: return Int(self.base.timeIntervalSince(date)) case .minute: return Int(self.base.timeIntervalSince(date) / 60) case .hour: return Int(self.base.timeIntervalSince(date) / 60 / 60) case .day: let comp = Set<Calendar.Component>(arrayLiteral: Calendar.Component.day) return Calendar.current.dateComponents(comp, from: date, to: self.base).day ?? 0 case .month: let comp = Set<Calendar.Component>(arrayLiteral: Calendar.Component.month) return Calendar.current.dateComponents(comp, from: date, to: self.base).month ?? 0 case .year: let comp = Set<Calendar.Component>(arrayLiteral: Calendar.Component.year) return Calendar.current.dateComponents(comp, from: date, to: self.base).year ?? 0 } } } extension EasyCoding where Base == String { ///实例 public func date(_ format: String = "yyyy-MM-dd HH:mm:ss") -> Date { let formatter = DateFormatter() formatter.dateFormat = format return formatter.date(from: self.base) ?? Date() } ///实例 public func date(format: EasyDateFormat) -> Date { return self.date(format.description) } } extension EasyCoding where Base == TimeInterval { ///将秒显示为天时分秒的剩余时长描述,start至少为天, fixed代表固定会出现的单位,若高于fixed的单位值为0时不出现 public func remainingDuration(_ endDesc:String = "已结束",start: EasyDateUnit = .day, end: EasyDateUnit = .minute, fixed: EasyDateUnit = .hour) -> String { let timeString = NSMutableString() var time = self.base if time > 0 { let day = Int(time / 24 / 60 / 60) time = time - Double(day * 24 * 60 * 60) let hour = Int(time / 60 / 60) time = time - Double(hour * 60 * 60) let minute = Int(time / 60) time = time - Double(minute * 60) let second = Int(time) time = time - Double(second) let nanosecond = Int(time * 1000) if start >= .day { if day > 0 { timeString.append("\(day)天") }else if fixed >= .day{ timeString.append("0天") } } if start >= .hour && end <= .hour { if hour > 0 { timeString.append(hour >= 10 ? "\(hour)时" : "0\(hour)时") }else if fixed >= .hour { timeString.append("00时") } } if start >= .minute && end <= .minute { if minute > 0 { timeString.append(minute >= 10 ? "\(minute)分" : "0\(minute)分") }else if fixed >= .minute { timeString.append("00分") } } if start >= .second && end <= .second { if second > 0 { timeString.append(second >= 10 ? "\(second)秒" : "0\(second)秒") }else if fixed >= .second { timeString.append("00秒") } } if start >= .nanosecond && end <= .nanosecond { if nanosecond > 100 { timeString.append("\(nanosecond)毫秒") }else if nanosecond > 10 { timeString.append("0\(nanosecond)毫秒") }else if nanosecond > 0 { timeString.append("00\(nanosecond)毫秒") }else if fixed >= .nanosecond { timeString.append("000毫秒") } } }else{ timeString.append(endDesc) } return timeString as String } ///转为时:分:秒的显示格式 public func timeString(withChinese: Bool = false) -> String { let timeString = NSMutableString() var time = self.base let separators = withChinese ? ["小时","分","秒"] : [":",":",""] if time > 0 { let hour = Int(time / 60 / 60) time = time - Double(hour * 60 * 60) let minute = Int(time / 60) time = time - Double(minute * 60) let second = Int(time) time = time - Double(second) // let nanosecond = Int(time * 1000) if hour > 0 { if withChinese { timeString.append("\(hour)\(separators[0])") }else{ timeString.append(hour >= 10 ? "\(hour)\(separators[0])" : "0\(hour)\(separators[0])") } } if minute > 0 { timeString.append(minute >= 10 ? "\(minute)\(separators[1])" : "0\(minute)\(separators[1])") }else { timeString.append("00\(separators[1])") } if second > 0 { timeString.append(second >= 10 ? "\(second)\(separators[2])" : "0\(second)\(separators[2])") }else { timeString.append("00\(separators[2])") } }else{ timeString.append("00\(separators[1])00\(separators[2])") } return timeString as String } }
35.506494
156
0.529871
62265f62cab30dc2b17a875f6b4d2a315fb9d673
5,198
// // UITextFieldAdditions.swift // Pods-TypographyKit_Example // // Created by Ross Butler on 9/7/17. // import Foundation extension UITextField { public var letterCase: LetterCase { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase) as! LetterCase } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase, newValue, .OBJC_ASSOCIATION_RETAIN) self.text = self.text?.letterCase(newValue) } } @objc public var fontTextStyle: UIFont.TextStyle { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle) as! UIFont.TextStyle } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle, newValue, .OBJC_ASSOCIATION_RETAIN) if let typography = Typography(for: newValue) { self.typography = typography } } } @objc public var fontTextStyleName: String { get { return fontTextStyle.rawValue } set { fontTextStyle = UIFont.TextStyle(rawValue: newValue) } } public var typography: Typography { get { // swiftlint:disable:next force_cast return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography) as! Typography } set { objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography, newValue, .OBJC_ASSOCIATION_RETAIN) if let newFont = newValue.font(UIApplication.shared.preferredContentSizeCategory) { self.font = newFont } if let textColor = newValue.textColor { self.textColor = textColor } if let letterCase = newValue.letterCase { self.letterCase = letterCase } NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } } // MARK: Functions public func attributedText(_ text: NSAttributedString?, style: UIFont.TextStyle, letterCase: LetterCase = .regular, textColor: UIColor? = nil) { let contentSizeCategory = UIApplication.shared.preferredContentSizeCategory let fontAttributeKey = NSAttributedString.Key.font let typography = Typography(for: style) if let textColor = textColor { self.textColor = textColor } guard let text = text else { return } self.attributedText = text let mutableText = NSMutableAttributedString(attributedString: text) mutableText.enumerateAttributes(in: NSRange(location: 0, length: text.string.count), options: [], using: { value, range, _ in if let fontAttribute = value[fontAttributeKey] as? UIFont, let newPointSize = typography?.font(contentSizeCategory)?.pointSize, let newFont = UIFont(name: fontAttribute.fontName, size: newPointSize) { mutableText.removeAttribute(fontAttributeKey, range: range) mutableText.addAttribute(fontAttributeKey, value: newFont, range: range) } }) self.attributedText = mutableText } public func text(_ text: String?, style: UIFont.TextStyle, letterCase: LetterCase? = nil, textColor: UIColor? = nil) { if let text = text { self.text = text } if var typography = Typography(for: style) { // Only override letterCase and textColor if explicitly specified if let textColor = textColor { typography.textColor = textColor } if let letterCase = letterCase { typography.letterCase = letterCase } self.typography = typography } } @objc private func contentSizeCategoryDidChange(_ notification: NSNotification) { if let newValue = notification.userInfo?[UIContentSizeCategory.newValueUserInfoKey] as? UIContentSizeCategory { self.font = self.typography.font(newValue) self.setNeedsLayout() } } }
39.984615
120
0.540977
f9f7191b674a3f4a57e0c4d9a999b7df9221b733
8,002
import Foundation @testable import Shared import XCTest class ActiveStateManagerTests: XCTestCase { var manager: ActiveStateManager! var observer: MockActiveStateObserver! var notificationCenter: NotificationCenter! override func setUp() { // pretend like we're in catalyst for these tests Current.isCatalyst = true notificationCenter = NotificationCenter.default observer = MockActiveStateObserver() manager = ActiveStateManager() manager.register(observer: observer) super.setUp() } override func tearDown() { Current.isCatalyst = false super.tearDown() } func testInitialStateIsActive() { XCTAssertTrue(manager.canTrackActiveStatus) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isFastUserSwitched) XCTAssertFalse(manager.states.isIdle) XCTAssertFalse(manager.states.isLocked) XCTAssertFalse(manager.states.isScreensavering) XCTAssertFalse(manager.states.isSleeping) XCTAssertFalse(manager.states.isScreenOff) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testObserverRemoval() { manager.unregister(observer: observer) notificationCenter.post(name: .init(rawValue: "com.apple.screensaver.didstart"), object: nil) XCTAssertFalse(observer.didUpdate) manager.register(observer: observer) notificationCenter.post(name: .init(rawValue: "com.apple.screensaver.didstop"), object: nil) XCTAssertTrue(observer.didUpdate) } func testScreensaver() { notificationCenter.post(name: .init(rawValue: "com.apple.screensaver.didstart"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isScreensavering) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "com.apple.screensaver.didstop"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isScreensavering) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testLock() { notificationCenter.post(name: .init(rawValue: "com.apple.screenIsLocked"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isLocked) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "com.apple.screenIsUnlocked"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isLocked) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testSleep() { notificationCenter.post(name: .init(rawValue: "NSWorkspaceWillSleepNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isSleeping) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "NSWorkspaceDidWakeNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isSleeping) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testScreenOff() { notificationCenter.post(name: .init(rawValue: "NSWorkspaceScreensDidSleepNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isScreenOff) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "NSWorkspaceScreensDidWakeNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isScreenOff) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testFUS() { notificationCenter.post(name: .init(rawValue: "NSWorkspaceSessionDidResignActiveNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isFastUserSwitched) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "NSWorkspaceSessionDidBecomeActiveNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isFastUserSwitched) XCTAssertEqual(manager.idleTimer?.isValid, true) } func testTerminate() { notificationCenter.post(name: .init("NonMac_terminationWillBeginNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isTerminating) XCTAssertNil(manager.idleTimer) } func testIdleTimeWithoutAnythingElse() { Current.device.idleTime = { .init(value: 99, unit: .seconds) } manager.minimumIdleTime = .init(value: 100, unit: .seconds) XCTAssertNotNil(manager.idleTimer) manager.idleTimer?.fire() XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isIdle) Current.device.idleTime = { .init(value: 100, unit: .seconds) } manager.idleTimer?.fire() XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isIdle) XCTAssertNotNil(manager.idleTimer) observer.reset() Current.device.idleTime = { .init(value: 300, unit: .seconds) } manager.idleTimer?.fire() XCTAssertFalse(observer.didUpdate, "already posted for this idle period") XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isIdle) XCTAssertNotNil(manager.idleTimer) observer.reset() Current.device.idleTime = { .init(value: 10, unit: .seconds) } manager.idleTimer?.fire() XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isIdle) XCTAssertNotNil(manager.idleTimer) observer.reset() } func testIdleTimeThenAnotherEvent() { Current.device.idleTime = { .init(value: 100, unit: .seconds) } manager.minimumIdleTime = .init(value: 100, unit: .seconds) XCTAssertNotNil(manager.idleTimer) manager.idleTimer?.fire() XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isIdle) XCTAssertTrue(observer.didUpdate) notificationCenter.post(name: .init(rawValue: "NSWorkspaceSessionDidResignActiveNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertTrue(manager.states.isFastUserSwitched) XCTAssertNil(manager.idleTimer) observer.reset() notificationCenter.post(name: .init(rawValue: "NSWorkspaceSessionDidBecomeActiveNotification"), object: nil) XCTAssertTrue(observer.didUpdate) XCTAssertFalse(manager.isActive) XCTAssertFalse(manager.states.isFastUserSwitched) XCTAssertTrue(manager.states.isIdle) XCTAssertNotNil(manager.idleTimer) observer.reset() Current.device.idleTime = { .init(value: 99, unit: .seconds) } manager.idleTimer?.fire() XCTAssertTrue(observer.didUpdate) XCTAssertTrue(manager.isActive) XCTAssertFalse(manager.states.isIdle) XCTAssertNotNil(manager.idleTimer) observer.reset() } } class MockActiveStateObserver: ActiveStateObserver { var didUpdate = false func reset() { didUpdate = false } func activeStateDidChange(for manager: ActiveStateManager) { didUpdate = true } }
37.218605
116
0.697201
4871b2495e797f3486ab8c82ec2ccc96ceaa8f30
1,642
import SwiftUI import Shapes public struct StackedAreaChartStyle: ChartStyle { private let lineType: LineType private let colors: [Color] public func makeBody(configuration: Self.Configuration) -> some View { ZStack { ForEach(Array(configuration.dataMatrix.transpose().stacked().enumerated()), id: \.self.offset) { enumeratedData in colors[enumeratedData.offset % colors.count].clipShape( AreaChart( unitData: enumeratedData.element, lineType: self.lineType ) ) .zIndex(-Double(enumeratedData.offset)) } } .drawingGroup() } public init(_ lineType: LineType = .quadCurve, colors: [Color] = [.red, .orange, .yellow, .green, .blue, .purple]) { self.lineType = lineType self.colors = colors } } extension Collection where Element == [CGFloat] { func stacked() -> [[CGFloat]] { self.reduce([]) { (result, element) -> [[CGFloat]] in if let lastElement = result.last { return result + [zip(lastElement, element).compactMap(+)] } else { return [element] } } } } extension Array where Element == [CGFloat] { func transpose() -> [[CGFloat]] { let columnsCount = self.first?.count ?? 0 let rowCount = self.count return (0..<columnsCount).map { columnIndex in (0..<rowCount).map { rowIndex in return self[rowIndex][columnIndex] } } } }
30.981132
126
0.542022
228a61ed4debf993db960cb3c401f00dca05a597
873
// // AppDelegate.swift // MyQRCode // // Created by Kishikawa Katsumi on 2017/09/04. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import UIKit import Intents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if case INPreferences.siriAuthorizationStatus() = INSiriAuthorizationStatus.notDetermined { INPreferences.requestSiriAuthorization { status in switch status { case .authorized: print("authorized") case .denied, .restricted, .notDetermined: print("not authorized") } } } return true } }
28.16129
144
0.636884
7a1993f5414c23cf2eec6c1156f5a40111cd4779
5,132
// // 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 // // ProductsManager.swift // // Created by Andrés Boedo on 7/14/20. // import Foundation import StoreKit class ProductsManager: NSObject { private let productsRequestFactory: ProductsRequestFactory private var cachedProductsByIdentifier: [String: SKProduct] = [:] private let queue = DispatchQueue(label: "ProductsManager") private var productsByRequests: [SKRequest: Set<String>] = [:] private var completionHandlers: [Set<String>: [(Set<SKProduct>) -> Void]] = [:] init(productsRequestFactory: ProductsRequestFactory = ProductsRequestFactory()) { self.productsRequestFactory = productsRequestFactory } func products(withIdentifiers identifiers: Set<String>, completion: @escaping (Set<SKProduct>) -> Void) { guard identifiers.count > 0 else { completion([]) return } queue.async { [self] in let productsAlreadyCached = self.cachedProductsByIdentifier.filter { key, _ in identifiers.contains(key) } if productsAlreadyCached.count == identifiers.count { let productsAlreadyCachedSet = Set(productsAlreadyCached.values) Logger.debug(logLevel: .debug, scope: .productsManager, message: "Products Already Cached", info: ["product_ids": identifiers], error: nil) completion(productsAlreadyCachedSet) return } if let existingHandlers = self.completionHandlers[identifiers] { Logger.debug(logLevel: .debug, scope: .productsManager, message: "Found Existing Product Request", info: ["product_ids": identifiers], error: nil) self.completionHandlers[identifiers] = existingHandlers + [completion] return } Logger.debug(logLevel: .debug, scope: .productsManager, message: "Creating New Request", info: ["product_ids": identifiers], error: nil) let request = self.productsRequestFactory.request(productIdentifiers: identifiers) request.delegate = self self.completionHandlers[identifiers] = [completion] self.productsByRequests[request] = identifiers request.start() } } func cacheProduct(_ product: SKProduct) { queue.async { self.cachedProductsByIdentifier[product.productIdentifier] = product } } } extension ProductsManager: SKProductsRequestDelegate { func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { queue.async { [self] in Logger.debug(logLevel: .debug, scope: .productsManager, message: "Fetched Product", info: ["request": request.debugDescription], error: nil) guard let requestProducts = self.productsByRequests[request] else { Logger.debug(logLevel: .warn, scope: .productsManager, message: "Requested Products Not Found", info: ["request": request.debugDescription], error: nil) return } guard let completionBlocks = self.completionHandlers[requestProducts] else { Logger.debug(logLevel: .error, scope: .productsManager, message: "Completion Handler Not Found", info: ["products": requestProducts, "request": request.debugDescription], error: nil) return } self.completionHandlers.removeValue(forKey: requestProducts) self.productsByRequests.removeValue(forKey: request) self.cacheProducts(response.products) for completion in completionBlocks { completion(Set(response.products)) } } } func requestDidFinish(_ request: SKRequest) { Logger.debug(logLevel: .debug, scope: .productsManager, message: "Request Complete", info: ["request": request.debugDescription], error: nil) request.cancel() } func request(_ request: SKRequest, didFailWithError error: Error) { queue.async { [self] in Logger.debug(logLevel: .error, scope: .productsManager, message: "Request Failed", info: ["request": request.debugDescription], error: error) guard let products = self.productsByRequests[request] else { Logger.debug(logLevel: .error, scope: .productsManager, message: "Requested Products Not Found", info: ["request": request.debugDescription], error: error) return } guard let completionBlocks = self.completionHandlers[products] else { Logger.debug(logLevel: .error, scope: .productsManager, message: "Callback Not Found for Failed Request", info: ["request": request.debugDescription], error: error) return } self.completionHandlers.removeValue(forKey: products) self.productsByRequests.removeValue(forKey: request) for completion in completionBlocks { completion(Set()) } } request.cancel() } } private extension ProductsManager { func cacheProducts(_ products: [SKProduct]) { let productsByIdentifier = products.reduce(into: [:]) { resultDict, product in resultDict[product.productIdentifier] = product } cachedProductsByIdentifier = cachedProductsByIdentifier.merging(productsByIdentifier) } } class ProductsRequestFactory { func request(productIdentifiers: Set<String>) -> SKProductsRequest { return SKProductsRequest(productIdentifiers: productIdentifiers) } }
36.920863
186
0.747272
6acc7874265446b7cb02e9c2e589daa688ebcf5e
709
// // UnBlockResponseHandler.swift // FanapPodChatSDK // // Created by Hamed Hosseini on 2/17/21. // import Foundation class UnBlockResponseHandler : ResponseHandler{ static func handle(_ chatMessage: NewChatMessage, _ asyncMessage: AsyncMessage) { let chat = Chat.sharedInstance guard let callback = chat.callbacksManager.getCallBack(chatMessage.uniqueId)else {return} guard let data = chatMessage.content?.data(using: .utf8) else {return} guard let blockedResult = try? JSONDecoder().decode(BlockedUser.self, from: data) else{return} callback(.init(uniqueId: chatMessage.uniqueId ,result: blockedResult)) chat.callbacksManager.removeCallback(uniqueId: chatMessage.uniqueId) } }
29.541667
96
0.765867
29eab5da0a421063f5380aca5ec2606ab12d128d
1,332
// // ViewController.swift // CalcEx // // Created by Developer iOS on 13/10/16. // Copyright © 2016 Developer iOS. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet private weak var display: UILabel! private var userIsInMiddleOFTyping = false @IBAction func touchDigit(_ sender: UIButton) { let digit = sender.currentTitle! if(userIsInMiddleOFTyping) { let textCurrentlyDisplay = display.text! display.text! = textCurrentlyDisplay + digit }else{ display.text! = digit } userIsInMiddleOFTyping = true } private var displayValue: Double{ get{ return Double(display.text!)! } set{ display.text = String(newValue) } } private var brain = CalculatorBrain() @IBAction private func performOperation(_ sender: UIButton) { if userIsInMiddleOFTyping{ brain.setOprand(operand: displayValue) userIsInMiddleOFTyping = false } if let methamaticalSymol = sender.currentTitle{ brain.perforOperation(symbol: methamaticalSymol) } displayValue = brain.result } }
21.142857
65
0.578078
ac728fc4edd9f0521d08bfe8655938825780260e
9,278
// // OsxBullshit.swift // Pods // // Created by damouse on 4/12/16. // // Swift libraries are not technically supported on OSX targets-- Swift gets linked against twice // Functionally this means that type checks in either the library or the app fail when the // type originates on the other end. // // Does this look silly or wrong to you? Good, you're a sane swift developer. // Unfortunatly, type checking with a swift framework on OSX is not a sane endeveour. Trust // me when I say there's an outrageous amount of subtle nonsense going on here. // // Comments and Links: // See in swift repo: lib/irgen/runtimeFunctions // Looks like you might be able to hook with "MSHookFunciton" // Also check out stdlib/public/runtime/reflection, but I dont think these are accessible // Maybe try a mirror with this? import Foundation // An application-exportable converter function that allows osx targets to cast appropriately // Does this look silly or wrong to you? Good, you're a sane swift developer. // TODO: put an error log detailing what to put in here if the block hasn't been assigned on OSX public var externals: [ExternalType] = [] public func initTypes(types: ExternalType...) { externals = types } public protocol ExternalType { var ambiguousType: Any.Type { get } var name: String { get } func cast<A>(arg: A) -> Convertible? func castType<A>(a: A.Type) -> Convertible.Type? } // Wrapper around externally provided types. OSX applications should instantiate a set of these and pass them into initTypes public class External<T: Convertible>: ExternalType { public var name: String var typedType: T.Type public var ambiguousType: Any.Type public init(_ typed: T.Type, _ ambiguous: Any.Type) { typedType = typed ambiguousType = ambiguous name = "\(typed)" } public func cast<A>(arg: A) -> Convertible? { let ret = unsafeBitCast(arg, T.self) if let ret = ret as? Convertible { return ret } return nil } public func castType<A>(a: A.Type) -> Convertible.Type? { // This allows us to return the given type as a convertible... is this enough? if let z = T.self as? Convertible.Type { return z } return nil } } // Try to cast the given argument to convertible func asConvertible<A>(a: A) -> Convertible? { if let a = a as? Convertible { print("Initial cast") return a } for type in externals { if A.self == type.ambiguousType { let c = type.cast(a) return c } } return nil } // Check to make sure the given object is correctly recognized as a convertible public func checkConvertible<A>(a: A) { if let a = a as? Convertible { print("Initial cast") return } for type in externals { if A.self == type.ambiguousType { let c = type.cast(a) as! Convertible print("Caught external type \(type.name)") return } } print("Failed on \(a.dynamicType)") } // Encode the value of a variable to bytes and back again into the desired type func recode<A, T>(value: A, _ t: T.Type) -> T { if T.self == Bool.self { return encodeBool(value) as! T } if T.self == String.self { let r = encodeString(value) return r as! T } return encode(value, t) } // Switches the types of a primitive from app type to library types func switchTypes<A>(x: A) -> Any { #if os(OSX) switch "\(x.dynamicType)" { case "Int": return recode(x, Int.self) case "String": return recode(x, String.self) case "Double": return recode(x, Double.self) case "Float": return recode(x, Float.self) case "Bool": return recode(x, Bool.self) default: print("WARN: Unable to switch type: \(x.dynamicType)") return x } #else return x #endif } // Switch a type object to a library type func switchTypeObject<A>(x: A) -> Any.Type { #if os(OSX) switch "\(x)" { case "Int": return Int.self case "String": return String.self case "Double": return Double.self case "Float": return Float.self case "Bool": return Bool.self default: print("WARN: Unable to switch out type object: \(x)") return x as! Any.Type } #else return x as! Any.Type #endif } // Returns the bytes from a swift as NSData func encode<A, T>(var v:A, _ t: T.Type) -> T { return withUnsafePointer(&v) { p in let d = NSData(bytes: p, length: strideof(A)) let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T.Type)) d.getBytes(pointer) return pointer.move() } } // Booleans dont like the recode method as written. func encodeBool<A>(var v:A) -> Bool { return withUnsafePointer(&v) { p in let s = unsafeBitCast(p, UnsafePointer<Bool>.self) return s.memory ? true : false } } // Grab the pointer, copy out the bytes into a new string, and return it. Strings don't like the recode method as written. func encodeString<A>(var v:A) -> String { return withUnsafePointer(&v) { p in let s = unsafeBitCast(p, UnsafePointer<String>.self) let dat = s.memory.dataUsingEncoding(NSUTF8StringEncoding)! let ret = NSString(data: dat, encoding: NSUTF8StringEncoding) return ret as! String } } // Playground public func loop() { let s = "TARGET" let y = true rfloop(s) } public var crloop: ((Any) -> ())? = nil var count = 0 public protocol ExternalCaster { func recodeString(a: String) -> String // func recode<T>(a: Bool, t: T.Type) -> T func recode<A, T>(a: A, t: T.Type) -> T } public var caster: ExternalCaster? = nil public func rfloop<A>(a: A) { if let z = a as? String { print("Riffle has String") let s = caster!.recodeString(z) print("Riffle has \(s)") } print("Uh") } public func dmtest<A: Model>(a: A.Type) -> A? { let j: [String: Any] = ["name": "Anna", "age": 1000] print("Starting decereal") // let q = Tat.deserialize(j) as! Tat // print("Is ID assigned: \(q.xsid)") // // let c = Tat.decereal(j) // print("Crust decereal Tat: \(c)") let z = a.decereal(j) let m = z as! Model print("Crust decereal \(a): \(z)") // if let z = z as? A { // return z // } return z as! Model as! A } public protocol StubbedModel { static func decereal(from: [String: Any]) -> Any } class Tat: Model { var name = "Bob" } extension Model: StubbedModel { // Creates a new instance of this model object from the given json public static func decereal(from: [String: Any]) -> Any { guard let json = from as? [String: Any] else { print("WARN: model wasn't given a json! Instead received type: \(from.dynamicType)") return from } var ret = self.init() for n in ret.propertyNames() { let repr = "\(ret[n]!.dynamicType.representation())" // JSON is returning ints as doubles. Correct that and this isn't needed: Json.swift line 882 if repr == "int" { if let value = json[n] as? Double { ret[n] = Int(value) } else if let value = json[n] as? Float { ret[n] = Int(value) } else if let value = json[n] as? Int { ret[n] = value } else { Riffle.warn("Model deserialization unable to cast property \(json[n]): \(json[n].dynamicType)") } } // Silvery cant understand assignments where the asigner is an AnyObject, so else if let value = json[n] as? Bool where "\(repr)" == "bool" { ret[n] = value } else if let value = json[n] as? Double where "\(repr)" == "double" || "\(repr)" == "float" { ret[n] = value } else if let value = json[n] as? Float where "\(repr)" == "double" || "\(repr)" == "float" { ret[n] = value } else if let value = json[n] as? Int where "\(repr)" == "int" { ret[n] = value } else if let value = json[n] as? String { ret[n] = value } else if let value = json[n] as? [Any] { ret[n] = value } else if let value = json[n] as? [String: Any] { ret[n] = value } else { Riffle.warn("Model deserialization unable to cast property \(json[n]): \(json[n].dynamicType)") } } return ret } }
22.038005
124
0.552166
ffd67966363ccfd0f7848db1fc8238779d5cb28b
406
// // CAGradientLayer+Extension.swift // U17 // // Created by Lee on 2/22/20. // Copyright © 2020 Lee. All rights reserved. // import UIKit extension CAGradientLayer { convenience init(colors:[UIColor],rect:CGRect){ self.init() self.colors = colors.map({$0.cgColor}) startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x:1.0,y: 1.0); frame = rect } }
19.333333
51
0.598522
1a1cfc468a438a3825ba53871f6847fd1a23fbd6
36,141
// // Combine.swift // // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if canImport(Combine) import Combine import Dispatch import Foundation // MARK: - DataRequest / UploadRequest /// A Combine `Publisher` that publishes the `DataResponse<Value, AFError>` of the provided `DataRequest`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public struct DataResponsePublisher<Value>: Publisher { public typealias Output = DataResponse<Value, AFError> public typealias Failure = Never private typealias Handler = (@escaping (_ response: DataResponse<Value, AFError>) -> Void) -> DataRequest private let request: DataRequest private let responseHandler: Handler /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. /// /// - Parameters: /// - request: `DataRequest` for which to publish the response. /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. public init<Serializer: ResponseSerializer>(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) where Value == Serializer.SerializedObject { self.request = request responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } } /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. /// /// - Parameters: /// - request: `DataRequest` for which to publish the response. /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. public init<Serializer: DataResponseSerializerProtocol>(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) where Value == Serializer.SerializedObject { self.request = request responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } } /// Publishes only the `Result` of the `DataResponse` value. /// /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value. public func result() -> AnyPublisher<Result<Value, AFError>, Never> { map { $0.result }.eraseToAnyPublisher() } /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. /// /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream. public func value() -> AnyPublisher<Value, AFError> { setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher() } public func receive<S>(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { subscriber.receive(subscription: Inner(request: request, responseHandler: responseHandler, downstream: subscriber)) } private final class Inner<Downstream: Subscriber>: Subscription, Cancellable where Downstream.Input == Output { typealias Failure = Downstream.Failure @Protected private var downstream: Downstream? private let request: DataRequest private let responseHandler: Handler init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { self.request = request self.responseHandler = responseHandler self.downstream = downstream } func request(_ demand: Subscribers.Demand) { assert(demand > 0) guard let downstream = downstream else { return } self.downstream = nil responseHandler { response in _ = downstream.receive(response) downstream.receive(completion: .finished) }.resume() } func cancel() { request.cancel() downstream = nil } } } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public extension DataResponsePublisher where Value == Data? { /// Creates an instance which publishes a `DataResponse<Data?, AFError>` value without serialization. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) init(_ request: DataRequest, queue: DispatchQueue) { self.request = request responseHandler = { request.response(queue: queue, completionHandler: $0) } } } public extension DataRequest { /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. /// /// - Parameters: /// - serializer: `ResponseSerializer` used to serialize response `Data`. /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// /// - Returns: The `DataResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher<T> where Serializer.SerializedObject == T { DataResponsePublisher(self, queue: queue, serializer: serializer) } /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// - Returns: The `DataResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishData(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<Data> { publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyRequestMethods), on: queue) } /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding /// will be determined by the server response, falling back to the default HTTP character /// set, `ISO-8859-1`. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// /// - Returns: The `DataResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishString(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, encoding: String.Encoding? = nil, emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<String> { publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, encoding: encoding, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyRequestMethods), on: queue) } /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// /// - Returns: The `DataResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishDecodable<T: Decodable>(type _: T.Type = T.self, queue: DispatchQueue = .main, preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor, decoder: DataDecoder = JSONDecoder(), emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes, emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DataResponsePublisher<T> { publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, decoder: decoder, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyResponseMethods), on: queue) } /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. /// /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// /// - Returns: The `DataResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher<Data?> { DataResponsePublisher(self, queue: queue) } } // A Combine `Publisher` that publishes a sequence of `Stream<Value, AFError>` values received by the provided `DataStreamRequest`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public struct DataStreamPublisher<Value>: Publisher { public typealias Output = DataStreamRequest.Stream<Value, AFError> public typealias Failure = Never private typealias Handler = (@escaping DataStreamRequest.Handler<Value, AFError>) -> DataStreamRequest private let request: DataStreamRequest private let streamHandler: Handler /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. /// /// - Parameters: /// - request: `DataStreamRequest` for which to publish the response. /// - queue: `DispatchQueue` on which the `Stream<Value, AFError>` values will be published. `.main` by /// default. /// - serializer: `DataStreamSerializer` used to produce the published `Stream<Value, AFError>` values. public init<Serializer: DataStreamSerializer>(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) where Value == Serializer.SerializedObject { self.request = request streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } } /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. /// /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value. public func result() -> AnyPublisher<Result<Value, AFError>, Never> { compactMap { stream in switch stream.event { case let .stream(result): return result // If the stream has completed with an error, send the error value downstream as a `.failure`. case let .complete(completion): return completion.error.map(Result.failure) } } .eraseToAnyPublisher() } /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the /// `AFError` instance. /// /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream. public func value() -> AnyPublisher<Value, AFError> { result().setFailureType(to: AFError.self).flatMap { $0.publisher }.eraseToAnyPublisher() } public func receive<S>(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { subscriber.receive(subscription: Inner(request: request, streamHandler: streamHandler, downstream: subscriber)) } private final class Inner<Downstream: Subscriber>: Subscription, Cancellable where Downstream.Input == Output { typealias Failure = Downstream.Failure @Protected private var downstream: Downstream? private let request: DataStreamRequest private let streamHandler: Handler init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { self.request = request self.streamHandler = streamHandler self.downstream = downstream } func request(_ demand: Subscribers.Demand) { assert(demand > 0) guard let downstream = downstream else { return } self.downstream = nil streamHandler { stream in _ = downstream.receive(stream) if case .complete = stream.event { downstream.receive(completion: .finished) } }.resume() } func cancel() { request.cancel() downstream = nil } } } public extension DataStreamRequest { /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. /// /// - Parameters: /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. /// - Returns: The `DataStreamPublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishStream<Serializer: DataStreamSerializer>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataStreamPublisher<Serializer.SerializedObject> { DataStreamPublisher(self, queue: queue, serializer: serializer) } /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` /// unserialized. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. /// - Returns: The `DataStreamPublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher<Data> { publishStream(using: PassthroughStreamSerializer(), on: queue) } /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream /// `Data` values into `String` values. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. /// - Returns: The `DataStreamPublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher<String> { publishStream(using: StringStreamSerializer(), on: queue) } /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided /// parameters to serialize stream `Data` values into the provided type. /// /// - Parameters: /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. /// `PassthroughPreprocessor()` by default. /// - Returns: The `DataStreamPublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishDecodable<T: Decodable>(type _: T.Type = T.self, queue: DispatchQueue = .main, decoder: DataDecoder = JSONDecoder(), preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher<T> { publishStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), on: queue) } } /// A Combine `Publisher` that publishes the `DownloadResponse<Value, AFError>` of the provided `DownloadRequest`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public struct DownloadResponsePublisher<Value>: Publisher { public typealias Output = DownloadResponse<Value, AFError> public typealias Failure = Never private typealias Handler = (@escaping (_ response: DownloadResponse<Value, AFError>) -> Void) -> DownloadRequest private let request: DownloadRequest private let responseHandler: Handler /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. /// /// - Parameters: /// - request: `DownloadRequest` for which to publish the response. /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. public init<Serializer: ResponseSerializer>(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) where Value == Serializer.SerializedObject { self.request = request responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } } /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. /// /// - Parameters: /// - request: `DownloadRequest` for which to publish the response. /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public init<Serializer: DownloadResponseSerializerProtocol>(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) where Value == Serializer.SerializedObject { self.request = request responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } } /// Publishes only the `Result` of the `DownloadResponse` value. /// /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value. public func result() -> AnyPublisher<Result<Value, AFError>, Never> { map { $0.result }.eraseToAnyPublisher() } /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. /// /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream. public func value() -> AnyPublisher<Value, AFError> { setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher() } public func receive<S>(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { subscriber.receive(subscription: Inner(request: request, responseHandler: responseHandler, downstream: subscriber)) } private final class Inner<Downstream: Subscriber>: Subscription, Cancellable where Downstream.Input == Output { typealias Failure = Downstream.Failure @Protected private var downstream: Downstream? private let request: DownloadRequest private let responseHandler: Handler init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { self.request = request self.responseHandler = responseHandler self.downstream = downstream } func request(_ demand: Subscribers.Demand) { assert(demand > 0) guard let downstream = downstream else { return } self.downstream = nil responseHandler { response in _ = downstream.receive(response) downstream.receive(completion: .finished) }.resume() } func cancel() { request.cancel() downstream = nil } } } public extension DownloadRequest { /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. /// /// - Parameters: /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T> where Serializer.SerializedObject == T { DownloadResponsePublisher(self, queue: queue, serializer: serializer) } /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and /// `DispatchQueue`. /// /// - Parameters: /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishResponse<Serializer: DownloadResponseSerializerProtocol, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T> where Serializer.SerializedObject == T { DownloadResponsePublisher(self, queue: queue, serializer: serializer) } /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the /// response. /// /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL> { publishResponse(using: URLResponseSerializer(), on: queue) } /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishData(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<Data> { publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyRequestMethods), on: queue) } /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding /// will be determined by the server response, falling back to the default HTTP character /// set, `ISO-8859-1`. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishString(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, encoding: String.Encoding? = nil, emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<String> { publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, encoding: encoding, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyRequestMethods), on: queue) } /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the /// response. /// /// - Parameters: /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` /// by default. /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. /// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by /// default. /// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of /// status code. `[.head]` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishDecodable<T: Decodable>(type _: T.Type = T.self, queue: DispatchQueue = .main, preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor, decoder: DataDecoder = JSONDecoder(), emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes, emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DownloadResponsePublisher<T> { publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, decoder: decoder, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyResponseMethods), on: queue) } } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public extension DownloadResponsePublisher where Value == URL? { /// Creates an instance which publishes a `DownloadResponse<URL?, AFError>` value without serialization. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) init(_ request: DownloadRequest, queue: DispatchQueue) { self.request = request responseHandler = { request.response(queue: queue, completionHandler: $0) } } } public extension DownloadRequest { /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. /// /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. /// /// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL?> { DownloadResponsePublisher(self, queue: queue) } } #endif
56.294393
174
0.585236
03aadf2c46a18f9ab184c32d3ae1f2661084381d
168
// // {Name}RouterInterface.swift // {project} // // Created by {author} on {date}. // import UIKit protocol {Name}RouterInterface: RouterPresenterInterface { }
12
58
0.678571
db34889cfe1d3f400062d02b0451ae4e9c994aa2
320
// // SplitViewDetailProtocol.swift // SplitViewWrapper // // Created by Rahil Patel on 6/21/19. // Copyright © 2019 RahilPatel. All rights reserved. // import Foundation import SwiftUI public protocol SplitViewDetailProtocol: View { associatedtype DataType: Identifiable var data: DataType? { get set } }
20
53
0.734375
bbac88e884a975bb58eaf43534b382e4433f28a3
3,112
// // utilityFunctions.swift // xmpp_plugin // // Created by xRStudio on 13/12/21. // import Foundation import Flutter //MARK:- Notifcation Observers public func postNotification(Name:Notification.Name, withObject: Any? = nil, userInfo:[AnyHashable : Any]? = nil){ NotificationCenter.default.post(name: Name, object: withObject, userInfo: userInfo) } public func getTimeStamp() -> Int64 { let value = NSDate().timeIntervalSince1970 * 1000 return Int64(value) } public func getCurretTime() -> String { let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS" return dateFormat.string(from: Date()) } func printLog<T>(_ message : T) { print(message) } func addLogger(_ logType : LogType, _ value : Any) { var vMess : String = "Time: \(getCurretTime().description)\n" vMess += "Action: \(logType.rawValue)\n" switch logType { case .receiveFromFlutter: if let data = value as? FlutterMethodCall { vMess += "NativeMethod: \(data.method)\n" vMess += "Content: \(data.arguments.debugDescription)\n\n" } default: vMess += "Time: \(getTimeStamp().description)\n" vMess += "Action: \(logType.rawValue)\n" vMess += "Content: \(value)\n\n" } printLog(vMess) //------------------------------------------------------ //Add Logger in log-file guard let objLogger = APP_DELEGATE.objXMPPLogger else { printLog("\(#function) | Not initialize XMPPLogger") return } if !objLogger.isLogEnable { printLog("\(#function) | XMPP Logger Disable.") } AppLogger.log(vMess) } class AppLogger { static var logFile: URL? { guard let objLogger = APP_DELEGATE.objXMPPLogger else { return nil } let url = URL(fileURLWithPath: objLogger.logPath) return url } static func log(_ message: String) { AppLogger.createLogFile(withMessage : message) } private static func createLogFile(withMessage message : String) { guard let logFile = AppLogger.logFile else { return } guard let data = (message + "\n").data(using: String.Encoding.utf8) else { return } if FileManager.default.fileExists(atPath: logFile.path) { if let fileHandle = try? FileHandle(forWritingTo: logFile) { fileHandle.seekToEndOfFile() fileHandle.write(data) fileHandle.closeFile() } } else { do { try data.write(to: logFile, options: .atomicWrite) } catch let err { print("\(#function) | err: \(err.localizedDescription) | filePath: \(logFile.absoluteString)") } } } /*func deleteLogFile() { guard let logFile = AppLogger.logFile else { return } let isFileExists = FileManager.default.fileExists(atPath: logFile.path) if !isFileExists { return } try? FileManager.default.removeItem(at: logFile) }*/ }
29.923077
114
0.593188
de11567bae69334db3622ad896e5473e64aafe5b
2,659
// // LoadSetting.swift // TipSang // // Created by Sang Vo Hoang on 2/27/16. // Copyright © 2016 Sang Vo Hoang. All rights reserved. // import Foundation //Setting Class is Class for load , save setting or restore default setting // Setting have some properites // SlideSwitch : Save State of SlideSwitch - Default: false // Tip1Percent : Current Percent of 1st Segment Tip - Default: 10 // Tip2Percent : Current Percent of 2nd Segment Tip - Default: 20 // Tip3Percent : Current Percent of 3rd Segment Tip - Default: 25 class Setting { func Default(){ let currentSetting = NSUserDefaults.standardUserDefaults() currentSetting.setBool(false, forKey: "SlideSwitch") currentSetting.setDouble(0.1, forKey:"Tip1Percent") currentSetting.setDouble(0.2, forKey:"Tip2Percent") currentSetting.setDouble(0.25, forKey:"Tip3Percent") currentSetting.setDouble(0.1, forKey:"TipSlideMin") currentSetting.setDouble(0.4, forKey:"TipSlideMax") currentSetting.synchronize() } func Save(slide:Bool,tipArray:[Double])-> Bool{ let currentSetting = NSUserDefaults.standardUserDefaults() // Validate var validated=true if tipArray.count == 5{ for tip in tipArray{ if tip < 0 || tip > 1 { validated = false break } } if tipArray[3]>=tipArray[4] { validated = false } } else { validated = false } if !validated { return false } // End Validate currentSetting.setBool(slide, forKey: "SlideSwitch") currentSetting.setDouble(tipArray[0], forKey:"Tip1Percent") currentSetting.setDouble(tipArray[1], forKey:"Tip2Percent") currentSetting.setDouble(tipArray[2], forKey:"Tip3Percent") currentSetting.setDouble(tipArray[3], forKey:"TipSlideMin") currentSetting.setDouble(tipArray[4], forKey:"TipSlideMax") currentSetting.synchronize() return true } func Load() -> (slide:Bool,tipArray:[Double]){ let currentSetting = NSUserDefaults.standardUserDefaults() if currentSetting.objectForKey("SlideSwitch") == nil { Default() } let tA = [currentSetting.doubleForKey("Tip1Percent"),currentSetting.doubleForKey("Tip2Percent"),currentSetting.doubleForKey("Tip3Percent"),currentSetting.doubleForKey("TipSlideMin"),currentSetting.doubleForKey("TipSlideMax")] print(tA) return (currentSetting.boolForKey("SlideSwitch"),tA) } }
37.450704
233
0.634449
ac40aceed35761b8a951e80244cfe19559ba6a06
1,275
// // tipCalculatorUITests.swift // tipCalculatorUITests // // Created by Korin Wong-Horiuchi on 7/13/16. // Copyright © 2016 Korin Wong-Horiuchi. All rights reserved. // import XCTest class tipCalculatorUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.459459
182
0.66902