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
7154ee415bcae6fa89e2ac4a0b0a79c4a0d4976f
4,663
// // ViewController.swift // PeopleAndAppleStockPrices // // Created by Alex Paul on 12/7/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit class ViewController: UIViewController { var singleUser = [PeopleInfo]() { didSet { userInfoData.reloadData() } } @IBOutlet weak var searchBar: UISearchBar! var searchString: String? = nil { didSet { print(searchString!) self.userInfoData.reloadData() } } @IBOutlet weak var userInfoData: UITableView! override func viewDidLoad() { super.viewDidLoad() setProtocols() // getData() loadDataFromJSON() } private var pictures = [UIImage]() { didSet { DispatchQueue.main.async { self.userInfoData.reloadData() } } } func loadDataFromJSON(){ let path = Bundle.main.path(forResource: "userinfo", ofType: "json") let url = URL(fileURLWithPath: path!) do { let data = try Data(contentsOf: url) let people = try UserInfoData.getUserInfo(data: data) self.singleUser = people }catch{ print(error) } } func getData() { UserAPIClient.getInfo(completionHandler: { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print(error.errorMessage()) case .success(let data): self.singleUser = data.sorted(by: { (name, name2) -> Bool in name.name.first < name2.name.first }) } } } )} func setProtocols() { userInfoData.dataSource = self userInfoData.delegate = self searchBar.delegate = self } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let indexPath = userInfoData.indexPathForSelectedRow, let destination = segue.destination as? DetailViewController else {return} var dataToSend = singleUser[indexPath.row] destination.pictureSelected = dataToSend } func searchPerson(keyword: String) -> [PeopleInfo]{ var userSearchResults : [PeopleInfo] { get { guard let searchString = searchString else { return singleUser } guard searchString != "" else { return singleUser } let results = singleUser.filter{$0.name.fullname.lowercased().contains(searchString.lowercased())} if results.count == 0 { return [] }else { return singleUser.filter{$0.name.fullname.lowercased().contains(searchString.lowercased())} } } } return userSearchResults } } extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchPerson(keyword: searchString ?? "").count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "userinfocell", for: indexPath) let userInfo = searchPerson(keyword: searchString ?? "")[indexPath.row] // let picturesPassed = pictures[indexPath.row] var dataToSet = singleUser[indexPath.row] cell.textLabel?.text = "\(dataToSet.name.first.capitalized) \(dataToSet.name.last.capitalized)" cell.detailTextLabel?.text = "\(userInfo.location!.street!.capitalized) \(userInfo.location!.city!.capitalized) \(userInfo.location!.state!.capitalized)" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150 } } extension ViewController : UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchString = searchBar.text searchPerson(keyword: searchString!) // searchString = searchBar.text } }
29.14375
169
0.540854
7a21041b34d0befd0960801949f0eea003a94667
4,637
// // SkeletonLayer.swift // SkeletonView-iOS // // Created by Juanpe Catalán on 02/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit struct SkeletonLayer { private var maskLayer: CALayer private weak var holder: UIView? var type: SkeletonType { return maskLayer is CAGradientLayer ? .gradient : .solid } var contentLayer: CALayer { return maskLayer } init(type: SkeletonType, colors: [UIColor], skeletonHolder holder: UIView) { self.holder = holder self.maskLayer = type.layer self.maskLayer.anchorPoint = .zero self.maskLayer.bounds = holder.definedMaxBounds self.maskLayer.cornerRadius = CGFloat(holder.skeletonCornerRadius) addTextLinesIfNeeded() self.maskLayer.tint(withColors: colors) } func update(usingColors colors: [UIColor]) { layoutIfNeeded() maskLayer.tint(withColors: colors) } func layoutIfNeeded() { if let bounds = holder?.definedMaxBounds { maskLayer.bounds = bounds } updateLinesIfNeeded() } func removeLayer(transition: SkeletonTransitionStyle, completion: (() -> Void)? = nil) { switch transition { case .none: maskLayer.removeFromSuperlayer() completion?() case .crossDissolve(let duration): maskLayer.setOpacity(from: 1, to: 0, duration: duration) { self.maskLayer.removeFromSuperlayer() completion?() } } } /// If there is more than one line, or custom preferences have been set for a single line, draw custom layers func addTextLinesIfNeeded() { guard let textView = holderAsTextView else { return } let config = SkeletonMultilinesLayerConfig(lines: textView.numberOfLines, lineHeight: textView.lineHeight, type: type, lastLineFillPercent: textView.lastLineFillingPercent, multilineCornerRadius: textView.multilineCornerRadius, multilineSpacing: textView.multilineSpacing, paddingInsets: textView.paddingInsets, alignment: textView.textAlignment, isRTL: holder?.isRTL ?? false, shouldCenterVertically: textView.shouldCenterTextVertically) maskLayer.addMultilinesLayers(for: config) } func updateLinesIfNeeded() { guard let textView = holderAsTextView else { return } let config = SkeletonMultilinesLayerConfig(lines: textView.numberOfLines, lineHeight: textView.lineHeight, type: type, lastLineFillPercent: textView.lastLineFillingPercent, multilineCornerRadius: textView.multilineCornerRadius, multilineSpacing: textView.multilineSpacing, paddingInsets: textView.paddingInsets, alignment: textView.textAlignment, isRTL: holder?.isRTL ?? false, shouldCenterVertically: textView.shouldCenterTextVertically) maskLayer.updateMultilinesLayers(for: config) } var holderAsTextView: SkeletonTextNode? { guard let textView = holder as? SkeletonTextNode, (textView.numberOfLines == -1 || textView.numberOfLines == 0 || textView.numberOfLines > 1 || textView.numberOfLines == 1 && !SkeletonAppearance.default.renderSingleLineAsView) else { return nil } return textView } } extension SkeletonLayer { func start(_ anim: SkeletonLayerAnimation? = nil, completion: (() -> Void)? = nil) { let animation = anim ?? type.defaultLayerAnimation(isRTL: holder?.isRTL ?? false) contentLayer.playAnimation(animation, key: "skeletonAnimation", completion: completion) } func stopAnimation() { contentLayer.stopAnimation(forKey: "skeletonAnimation") } }
40.675439
195
0.548846
e0ece9cc9cc5b15f855ad7825030b70d321afe2e
42,330
// Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file 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. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment // swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity // -- Generated Code; do not edit -- // // StepFunctionsClientProtocol.swift // StepFunctionsClient // import Foundation import StepFunctionsModel import SmokeAWSCore import SmokeHTTPClient /** Client Protocol for the StepFunctions service. */ public protocol StepFunctionsClientProtocol { typealias CreateActivitySyncType = ( _ input: StepFunctionsModel.CreateActivityInput) throws -> StepFunctionsModel.CreateActivityOutput typealias CreateActivityAsyncType = ( _ input: StepFunctionsModel.CreateActivityInput, _ completion: @escaping (Result<StepFunctionsModel.CreateActivityOutput, StepFunctionsError>) -> ()) throws -> () typealias CreateStateMachineSyncType = ( _ input: StepFunctionsModel.CreateStateMachineInput) throws -> StepFunctionsModel.CreateStateMachineOutput typealias CreateStateMachineAsyncType = ( _ input: StepFunctionsModel.CreateStateMachineInput, _ completion: @escaping (Result<StepFunctionsModel.CreateStateMachineOutput, StepFunctionsError>) -> ()) throws -> () typealias DeleteActivitySyncType = ( _ input: StepFunctionsModel.DeleteActivityInput) throws -> StepFunctionsModel.DeleteActivityOutput typealias DeleteActivityAsyncType = ( _ input: StepFunctionsModel.DeleteActivityInput, _ completion: @escaping (Result<StepFunctionsModel.DeleteActivityOutput, StepFunctionsError>) -> ()) throws -> () typealias DeleteStateMachineSyncType = ( _ input: StepFunctionsModel.DeleteStateMachineInput) throws -> StepFunctionsModel.DeleteStateMachineOutput typealias DeleteStateMachineAsyncType = ( _ input: StepFunctionsModel.DeleteStateMachineInput, _ completion: @escaping (Result<StepFunctionsModel.DeleteStateMachineOutput, StepFunctionsError>) -> ()) throws -> () typealias DescribeActivitySyncType = ( _ input: StepFunctionsModel.DescribeActivityInput) throws -> StepFunctionsModel.DescribeActivityOutput typealias DescribeActivityAsyncType = ( _ input: StepFunctionsModel.DescribeActivityInput, _ completion: @escaping (Result<StepFunctionsModel.DescribeActivityOutput, StepFunctionsError>) -> ()) throws -> () typealias DescribeExecutionSyncType = ( _ input: StepFunctionsModel.DescribeExecutionInput) throws -> StepFunctionsModel.DescribeExecutionOutput typealias DescribeExecutionAsyncType = ( _ input: StepFunctionsModel.DescribeExecutionInput, _ completion: @escaping (Result<StepFunctionsModel.DescribeExecutionOutput, StepFunctionsError>) -> ()) throws -> () typealias DescribeStateMachineSyncType = ( _ input: StepFunctionsModel.DescribeStateMachineInput) throws -> StepFunctionsModel.DescribeStateMachineOutput typealias DescribeStateMachineAsyncType = ( _ input: StepFunctionsModel.DescribeStateMachineInput, _ completion: @escaping (Result<StepFunctionsModel.DescribeStateMachineOutput, StepFunctionsError>) -> ()) throws -> () typealias DescribeStateMachineForExecutionSyncType = ( _ input: StepFunctionsModel.DescribeStateMachineForExecutionInput) throws -> StepFunctionsModel.DescribeStateMachineForExecutionOutput typealias DescribeStateMachineForExecutionAsyncType = ( _ input: StepFunctionsModel.DescribeStateMachineForExecutionInput, _ completion: @escaping (Result<StepFunctionsModel.DescribeStateMachineForExecutionOutput, StepFunctionsError>) -> ()) throws -> () typealias GetActivityTaskSyncType = ( _ input: StepFunctionsModel.GetActivityTaskInput) throws -> StepFunctionsModel.GetActivityTaskOutput typealias GetActivityTaskAsyncType = ( _ input: StepFunctionsModel.GetActivityTaskInput, _ completion: @escaping (Result<StepFunctionsModel.GetActivityTaskOutput, StepFunctionsError>) -> ()) throws -> () typealias GetExecutionHistorySyncType = ( _ input: StepFunctionsModel.GetExecutionHistoryInput) throws -> StepFunctionsModel.GetExecutionHistoryOutput typealias GetExecutionHistoryAsyncType = ( _ input: StepFunctionsModel.GetExecutionHistoryInput, _ completion: @escaping (Result<StepFunctionsModel.GetExecutionHistoryOutput, StepFunctionsError>) -> ()) throws -> () typealias ListActivitiesSyncType = ( _ input: StepFunctionsModel.ListActivitiesInput) throws -> StepFunctionsModel.ListActivitiesOutput typealias ListActivitiesAsyncType = ( _ input: StepFunctionsModel.ListActivitiesInput, _ completion: @escaping (Result<StepFunctionsModel.ListActivitiesOutput, StepFunctionsError>) -> ()) throws -> () typealias ListExecutionsSyncType = ( _ input: StepFunctionsModel.ListExecutionsInput) throws -> StepFunctionsModel.ListExecutionsOutput typealias ListExecutionsAsyncType = ( _ input: StepFunctionsModel.ListExecutionsInput, _ completion: @escaping (Result<StepFunctionsModel.ListExecutionsOutput, StepFunctionsError>) -> ()) throws -> () typealias ListStateMachinesSyncType = ( _ input: StepFunctionsModel.ListStateMachinesInput) throws -> StepFunctionsModel.ListStateMachinesOutput typealias ListStateMachinesAsyncType = ( _ input: StepFunctionsModel.ListStateMachinesInput, _ completion: @escaping (Result<StepFunctionsModel.ListStateMachinesOutput, StepFunctionsError>) -> ()) throws -> () typealias ListTagsForResourceSyncType = ( _ input: StepFunctionsModel.ListTagsForResourceInput) throws -> StepFunctionsModel.ListTagsForResourceOutput typealias ListTagsForResourceAsyncType = ( _ input: StepFunctionsModel.ListTagsForResourceInput, _ completion: @escaping (Result<StepFunctionsModel.ListTagsForResourceOutput, StepFunctionsError>) -> ()) throws -> () typealias SendTaskFailureSyncType = ( _ input: StepFunctionsModel.SendTaskFailureInput) throws -> StepFunctionsModel.SendTaskFailureOutput typealias SendTaskFailureAsyncType = ( _ input: StepFunctionsModel.SendTaskFailureInput, _ completion: @escaping (Result<StepFunctionsModel.SendTaskFailureOutput, StepFunctionsError>) -> ()) throws -> () typealias SendTaskHeartbeatSyncType = ( _ input: StepFunctionsModel.SendTaskHeartbeatInput) throws -> StepFunctionsModel.SendTaskHeartbeatOutput typealias SendTaskHeartbeatAsyncType = ( _ input: StepFunctionsModel.SendTaskHeartbeatInput, _ completion: @escaping (Result<StepFunctionsModel.SendTaskHeartbeatOutput, StepFunctionsError>) -> ()) throws -> () typealias SendTaskSuccessSyncType = ( _ input: StepFunctionsModel.SendTaskSuccessInput) throws -> StepFunctionsModel.SendTaskSuccessOutput typealias SendTaskSuccessAsyncType = ( _ input: StepFunctionsModel.SendTaskSuccessInput, _ completion: @escaping (Result<StepFunctionsModel.SendTaskSuccessOutput, StepFunctionsError>) -> ()) throws -> () typealias StartExecutionSyncType = ( _ input: StepFunctionsModel.StartExecutionInput) throws -> StepFunctionsModel.StartExecutionOutput typealias StartExecutionAsyncType = ( _ input: StepFunctionsModel.StartExecutionInput, _ completion: @escaping (Result<StepFunctionsModel.StartExecutionOutput, StepFunctionsError>) -> ()) throws -> () typealias StartSyncExecutionSyncType = ( _ input: StepFunctionsModel.StartSyncExecutionInput) throws -> StepFunctionsModel.StartSyncExecutionOutput typealias StartSyncExecutionAsyncType = ( _ input: StepFunctionsModel.StartSyncExecutionInput, _ completion: @escaping (Result<StepFunctionsModel.StartSyncExecutionOutput, StepFunctionsError>) -> ()) throws -> () typealias StopExecutionSyncType = ( _ input: StepFunctionsModel.StopExecutionInput) throws -> StepFunctionsModel.StopExecutionOutput typealias StopExecutionAsyncType = ( _ input: StepFunctionsModel.StopExecutionInput, _ completion: @escaping (Result<StepFunctionsModel.StopExecutionOutput, StepFunctionsError>) -> ()) throws -> () typealias TagResourceSyncType = ( _ input: StepFunctionsModel.TagResourceInput) throws -> StepFunctionsModel.TagResourceOutput typealias TagResourceAsyncType = ( _ input: StepFunctionsModel.TagResourceInput, _ completion: @escaping (Result<StepFunctionsModel.TagResourceOutput, StepFunctionsError>) -> ()) throws -> () typealias UntagResourceSyncType = ( _ input: StepFunctionsModel.UntagResourceInput) throws -> StepFunctionsModel.UntagResourceOutput typealias UntagResourceAsyncType = ( _ input: StepFunctionsModel.UntagResourceInput, _ completion: @escaping (Result<StepFunctionsModel.UntagResourceOutput, StepFunctionsError>) -> ()) throws -> () typealias UpdateStateMachineSyncType = ( _ input: StepFunctionsModel.UpdateStateMachineInput) throws -> StepFunctionsModel.UpdateStateMachineOutput typealias UpdateStateMachineAsyncType = ( _ input: StepFunctionsModel.UpdateStateMachineInput, _ completion: @escaping (Result<StepFunctionsModel.UpdateStateMachineOutput, StepFunctionsError>) -> ()) throws -> () /** Invokes the CreateActivity operation returning immediately and passing the response to a callback. - Parameters: - input: The validated CreateActivityInput object being passed to this operation. - completion: The CreateActivityOutput object or an error will be passed to this callback when the operation is complete. The CreateActivityOutput object will be validated before being returned to caller. The possible errors are: activityLimitExceeded, invalidName, tooManyTags. */ func createActivityAsync( input: StepFunctionsModel.CreateActivityInput, completion: @escaping (Result<StepFunctionsModel.CreateActivityOutput, StepFunctionsError>) -> ()) throws /** Invokes the CreateActivity operation waiting for the response before returning. - Parameters: - input: The validated CreateActivityInput object being passed to this operation. - Returns: The CreateActivityOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: activityLimitExceeded, invalidName, tooManyTags. */ func createActivitySync( input: StepFunctionsModel.CreateActivityInput) throws -> StepFunctionsModel.CreateActivityOutput /** Invokes the CreateStateMachine operation returning immediately and passing the response to a callback. - Parameters: - input: The validated CreateStateMachineInput object being passed to this operation. - completion: The CreateStateMachineOutput object or an error will be passed to this callback when the operation is complete. The CreateStateMachineOutput object will be validated before being returned to caller. The possible errors are: invalidArn, invalidDefinition, invalidLoggingConfiguration, invalidName, invalidTracingConfiguration, stateMachineAlreadyExists, stateMachineDeleting, stateMachineLimitExceeded, stateMachineTypeNotSupported, tooManyTags. */ func createStateMachineAsync( input: StepFunctionsModel.CreateStateMachineInput, completion: @escaping (Result<StepFunctionsModel.CreateStateMachineOutput, StepFunctionsError>) -> ()) throws /** Invokes the CreateStateMachine operation waiting for the response before returning. - Parameters: - input: The validated CreateStateMachineInput object being passed to this operation. - Returns: The CreateStateMachineOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, invalidDefinition, invalidLoggingConfiguration, invalidName, invalidTracingConfiguration, stateMachineAlreadyExists, stateMachineDeleting, stateMachineLimitExceeded, stateMachineTypeNotSupported, tooManyTags. */ func createStateMachineSync( input: StepFunctionsModel.CreateStateMachineInput) throws -> StepFunctionsModel.CreateStateMachineOutput /** Invokes the DeleteActivity operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DeleteActivityInput object being passed to this operation. - completion: The DeleteActivityOutput object or an error will be passed to this callback when the operation is complete. The DeleteActivityOutput object will be validated before being returned to caller. The possible errors are: invalidArn. */ func deleteActivityAsync( input: StepFunctionsModel.DeleteActivityInput, completion: @escaping (Result<StepFunctionsModel.DeleteActivityOutput, StepFunctionsError>) -> ()) throws /** Invokes the DeleteActivity operation waiting for the response before returning. - Parameters: - input: The validated DeleteActivityInput object being passed to this operation. - Returns: The DeleteActivityOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn. */ func deleteActivitySync( input: StepFunctionsModel.DeleteActivityInput) throws -> StepFunctionsModel.DeleteActivityOutput /** Invokes the DeleteStateMachine operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DeleteStateMachineInput object being passed to this operation. - completion: The DeleteStateMachineOutput object or an error will be passed to this callback when the operation is complete. The DeleteStateMachineOutput object will be validated before being returned to caller. The possible errors are: invalidArn. */ func deleteStateMachineAsync( input: StepFunctionsModel.DeleteStateMachineInput, completion: @escaping (Result<StepFunctionsModel.DeleteStateMachineOutput, StepFunctionsError>) -> ()) throws /** Invokes the DeleteStateMachine operation waiting for the response before returning. - Parameters: - input: The validated DeleteStateMachineInput object being passed to this operation. - Returns: The DeleteStateMachineOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn. */ func deleteStateMachineSync( input: StepFunctionsModel.DeleteStateMachineInput) throws -> StepFunctionsModel.DeleteStateMachineOutput /** Invokes the DescribeActivity operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DescribeActivityInput object being passed to this operation. - completion: The DescribeActivityOutput object or an error will be passed to this callback when the operation is complete. The DescribeActivityOutput object will be validated before being returned to caller. The possible errors are: activityDoesNotExist, invalidArn. */ func describeActivityAsync( input: StepFunctionsModel.DescribeActivityInput, completion: @escaping (Result<StepFunctionsModel.DescribeActivityOutput, StepFunctionsError>) -> ()) throws /** Invokes the DescribeActivity operation waiting for the response before returning. - Parameters: - input: The validated DescribeActivityInput object being passed to this operation. - Returns: The DescribeActivityOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: activityDoesNotExist, invalidArn. */ func describeActivitySync( input: StepFunctionsModel.DescribeActivityInput) throws -> StepFunctionsModel.DescribeActivityOutput /** Invokes the DescribeExecution operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DescribeExecutionInput object being passed to this operation. - completion: The DescribeExecutionOutput object or an error will be passed to this callback when the operation is complete. The DescribeExecutionOutput object will be validated before being returned to caller. The possible errors are: executionDoesNotExist, invalidArn. */ func describeExecutionAsync( input: StepFunctionsModel.DescribeExecutionInput, completion: @escaping (Result<StepFunctionsModel.DescribeExecutionOutput, StepFunctionsError>) -> ()) throws /** Invokes the DescribeExecution operation waiting for the response before returning. - Parameters: - input: The validated DescribeExecutionInput object being passed to this operation. - Returns: The DescribeExecutionOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: executionDoesNotExist, invalidArn. */ func describeExecutionSync( input: StepFunctionsModel.DescribeExecutionInput) throws -> StepFunctionsModel.DescribeExecutionOutput /** Invokes the DescribeStateMachine operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DescribeStateMachineInput object being passed to this operation. - completion: The DescribeStateMachineOutput object or an error will be passed to this callback when the operation is complete. The DescribeStateMachineOutput object will be validated before being returned to caller. The possible errors are: invalidArn, stateMachineDoesNotExist. */ func describeStateMachineAsync( input: StepFunctionsModel.DescribeStateMachineInput, completion: @escaping (Result<StepFunctionsModel.DescribeStateMachineOutput, StepFunctionsError>) -> ()) throws /** Invokes the DescribeStateMachine operation waiting for the response before returning. - Parameters: - input: The validated DescribeStateMachineInput object being passed to this operation. - Returns: The DescribeStateMachineOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, stateMachineDoesNotExist. */ func describeStateMachineSync( input: StepFunctionsModel.DescribeStateMachineInput) throws -> StepFunctionsModel.DescribeStateMachineOutput /** Invokes the DescribeStateMachineForExecution operation returning immediately and passing the response to a callback. - Parameters: - input: The validated DescribeStateMachineForExecutionInput object being passed to this operation. - completion: The DescribeStateMachineForExecutionOutput object or an error will be passed to this callback when the operation is complete. The DescribeStateMachineForExecutionOutput object will be validated before being returned to caller. The possible errors are: executionDoesNotExist, invalidArn. */ func describeStateMachineForExecutionAsync( input: StepFunctionsModel.DescribeStateMachineForExecutionInput, completion: @escaping (Result<StepFunctionsModel.DescribeStateMachineForExecutionOutput, StepFunctionsError>) -> ()) throws /** Invokes the DescribeStateMachineForExecution operation waiting for the response before returning. - Parameters: - input: The validated DescribeStateMachineForExecutionInput object being passed to this operation. - Returns: The DescribeStateMachineForExecutionOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: executionDoesNotExist, invalidArn. */ func describeStateMachineForExecutionSync( input: StepFunctionsModel.DescribeStateMachineForExecutionInput) throws -> StepFunctionsModel.DescribeStateMachineForExecutionOutput /** Invokes the GetActivityTask operation returning immediately and passing the response to a callback. - Parameters: - input: The validated GetActivityTaskInput object being passed to this operation. - completion: The GetActivityTaskOutput object or an error will be passed to this callback when the operation is complete. The GetActivityTaskOutput object will be validated before being returned to caller. The possible errors are: activityDoesNotExist, activityWorkerLimitExceeded, invalidArn. */ func getActivityTaskAsync( input: StepFunctionsModel.GetActivityTaskInput, completion: @escaping (Result<StepFunctionsModel.GetActivityTaskOutput, StepFunctionsError>) -> ()) throws /** Invokes the GetActivityTask operation waiting for the response before returning. - Parameters: - input: The validated GetActivityTaskInput object being passed to this operation. - Returns: The GetActivityTaskOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: activityDoesNotExist, activityWorkerLimitExceeded, invalidArn. */ func getActivityTaskSync( input: StepFunctionsModel.GetActivityTaskInput) throws -> StepFunctionsModel.GetActivityTaskOutput /** Invokes the GetExecutionHistory operation returning immediately and passing the response to a callback. - Parameters: - input: The validated GetExecutionHistoryInput object being passed to this operation. - completion: The GetExecutionHistoryOutput object or an error will be passed to this callback when the operation is complete. The GetExecutionHistoryOutput object will be validated before being returned to caller. The possible errors are: executionDoesNotExist, invalidArn, invalidToken. */ func getExecutionHistoryAsync( input: StepFunctionsModel.GetExecutionHistoryInput, completion: @escaping (Result<StepFunctionsModel.GetExecutionHistoryOutput, StepFunctionsError>) -> ()) throws /** Invokes the GetExecutionHistory operation waiting for the response before returning. - Parameters: - input: The validated GetExecutionHistoryInput object being passed to this operation. - Returns: The GetExecutionHistoryOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: executionDoesNotExist, invalidArn, invalidToken. */ func getExecutionHistorySync( input: StepFunctionsModel.GetExecutionHistoryInput) throws -> StepFunctionsModel.GetExecutionHistoryOutput /** Invokes the ListActivities operation returning immediately and passing the response to a callback. - Parameters: - input: The validated ListActivitiesInput object being passed to this operation. - completion: The ListActivitiesOutput object or an error will be passed to this callback when the operation is complete. The ListActivitiesOutput object will be validated before being returned to caller. The possible errors are: invalidToken. */ func listActivitiesAsync( input: StepFunctionsModel.ListActivitiesInput, completion: @escaping (Result<StepFunctionsModel.ListActivitiesOutput, StepFunctionsError>) -> ()) throws /** Invokes the ListActivities operation waiting for the response before returning. - Parameters: - input: The validated ListActivitiesInput object being passed to this operation. - Returns: The ListActivitiesOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidToken. */ func listActivitiesSync( input: StepFunctionsModel.ListActivitiesInput) throws -> StepFunctionsModel.ListActivitiesOutput /** Invokes the ListExecutions operation returning immediately and passing the response to a callback. - Parameters: - input: The validated ListExecutionsInput object being passed to this operation. - completion: The ListExecutionsOutput object or an error will be passed to this callback when the operation is complete. The ListExecutionsOutput object will be validated before being returned to caller. The possible errors are: invalidArn, invalidToken, stateMachineDoesNotExist, stateMachineTypeNotSupported. */ func listExecutionsAsync( input: StepFunctionsModel.ListExecutionsInput, completion: @escaping (Result<StepFunctionsModel.ListExecutionsOutput, StepFunctionsError>) -> ()) throws /** Invokes the ListExecutions operation waiting for the response before returning. - Parameters: - input: The validated ListExecutionsInput object being passed to this operation. - Returns: The ListExecutionsOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, invalidToken, stateMachineDoesNotExist, stateMachineTypeNotSupported. */ func listExecutionsSync( input: StepFunctionsModel.ListExecutionsInput) throws -> StepFunctionsModel.ListExecutionsOutput /** Invokes the ListStateMachines operation returning immediately and passing the response to a callback. - Parameters: - input: The validated ListStateMachinesInput object being passed to this operation. - completion: The ListStateMachinesOutput object or an error will be passed to this callback when the operation is complete. The ListStateMachinesOutput object will be validated before being returned to caller. The possible errors are: invalidToken. */ func listStateMachinesAsync( input: StepFunctionsModel.ListStateMachinesInput, completion: @escaping (Result<StepFunctionsModel.ListStateMachinesOutput, StepFunctionsError>) -> ()) throws /** Invokes the ListStateMachines operation waiting for the response before returning. - Parameters: - input: The validated ListStateMachinesInput object being passed to this operation. - Returns: The ListStateMachinesOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidToken. */ func listStateMachinesSync( input: StepFunctionsModel.ListStateMachinesInput) throws -> StepFunctionsModel.ListStateMachinesOutput /** Invokes the ListTagsForResource operation returning immediately and passing the response to a callback. - Parameters: - input: The validated ListTagsForResourceInput object being passed to this operation. - completion: The ListTagsForResourceOutput object or an error will be passed to this callback when the operation is complete. The ListTagsForResourceOutput object will be validated before being returned to caller. The possible errors are: invalidArn, resourceNotFound. */ func listTagsForResourceAsync( input: StepFunctionsModel.ListTagsForResourceInput, completion: @escaping (Result<StepFunctionsModel.ListTagsForResourceOutput, StepFunctionsError>) -> ()) throws /** Invokes the ListTagsForResource operation waiting for the response before returning. - Parameters: - input: The validated ListTagsForResourceInput object being passed to this operation. - Returns: The ListTagsForResourceOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, resourceNotFound. */ func listTagsForResourceSync( input: StepFunctionsModel.ListTagsForResourceInput) throws -> StepFunctionsModel.ListTagsForResourceOutput /** Invokes the SendTaskFailure operation returning immediately and passing the response to a callback. - Parameters: - input: The validated SendTaskFailureInput object being passed to this operation. - completion: The SendTaskFailureOutput object or an error will be passed to this callback when the operation is complete. The SendTaskFailureOutput object will be validated before being returned to caller. The possible errors are: invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskFailureAsync( input: StepFunctionsModel.SendTaskFailureInput, completion: @escaping (Result<StepFunctionsModel.SendTaskFailureOutput, StepFunctionsError>) -> ()) throws /** Invokes the SendTaskFailure operation waiting for the response before returning. - Parameters: - input: The validated SendTaskFailureInput object being passed to this operation. - Returns: The SendTaskFailureOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskFailureSync( input: StepFunctionsModel.SendTaskFailureInput) throws -> StepFunctionsModel.SendTaskFailureOutput /** Invokes the SendTaskHeartbeat operation returning immediately and passing the response to a callback. - Parameters: - input: The validated SendTaskHeartbeatInput object being passed to this operation. - completion: The SendTaskHeartbeatOutput object or an error will be passed to this callback when the operation is complete. The SendTaskHeartbeatOutput object will be validated before being returned to caller. The possible errors are: invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskHeartbeatAsync( input: StepFunctionsModel.SendTaskHeartbeatInput, completion: @escaping (Result<StepFunctionsModel.SendTaskHeartbeatOutput, StepFunctionsError>) -> ()) throws /** Invokes the SendTaskHeartbeat operation waiting for the response before returning. - Parameters: - input: The validated SendTaskHeartbeatInput object being passed to this operation. - Returns: The SendTaskHeartbeatOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskHeartbeatSync( input: StepFunctionsModel.SendTaskHeartbeatInput) throws -> StepFunctionsModel.SendTaskHeartbeatOutput /** Invokes the SendTaskSuccess operation returning immediately and passing the response to a callback. - Parameters: - input: The validated SendTaskSuccessInput object being passed to this operation. - completion: The SendTaskSuccessOutput object or an error will be passed to this callback when the operation is complete. The SendTaskSuccessOutput object will be validated before being returned to caller. The possible errors are: invalidOutput, invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskSuccessAsync( input: StepFunctionsModel.SendTaskSuccessInput, completion: @escaping (Result<StepFunctionsModel.SendTaskSuccessOutput, StepFunctionsError>) -> ()) throws /** Invokes the SendTaskSuccess operation waiting for the response before returning. - Parameters: - input: The validated SendTaskSuccessInput object being passed to this operation. - Returns: The SendTaskSuccessOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidOutput, invalidToken, taskDoesNotExist, taskTimedOut. */ func sendTaskSuccessSync( input: StepFunctionsModel.SendTaskSuccessInput) throws -> StepFunctionsModel.SendTaskSuccessOutput /** Invokes the StartExecution operation returning immediately and passing the response to a callback. - Parameters: - input: The validated StartExecutionInput object being passed to this operation. - completion: The StartExecutionOutput object or an error will be passed to this callback when the operation is complete. The StartExecutionOutput object will be validated before being returned to caller. The possible errors are: executionAlreadyExists, executionLimitExceeded, invalidArn, invalidExecutionInput, invalidName, stateMachineDeleting, stateMachineDoesNotExist. */ func startExecutionAsync( input: StepFunctionsModel.StartExecutionInput, completion: @escaping (Result<StepFunctionsModel.StartExecutionOutput, StepFunctionsError>) -> ()) throws /** Invokes the StartExecution operation waiting for the response before returning. - Parameters: - input: The validated StartExecutionInput object being passed to this operation. - Returns: The StartExecutionOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: executionAlreadyExists, executionLimitExceeded, invalidArn, invalidExecutionInput, invalidName, stateMachineDeleting, stateMachineDoesNotExist. */ func startExecutionSync( input: StepFunctionsModel.StartExecutionInput) throws -> StepFunctionsModel.StartExecutionOutput /** Invokes the StartSyncExecution operation returning immediately and passing the response to a callback. - Parameters: - input: The validated StartSyncExecutionInput object being passed to this operation. - completion: The StartSyncExecutionOutput object or an error will be passed to this callback when the operation is complete. The StartSyncExecutionOutput object will be validated before being returned to caller. The possible errors are: invalidArn, invalidExecutionInput, invalidName, stateMachineDeleting, stateMachineDoesNotExist, stateMachineTypeNotSupported. */ func startSyncExecutionAsync( input: StepFunctionsModel.StartSyncExecutionInput, completion: @escaping (Result<StepFunctionsModel.StartSyncExecutionOutput, StepFunctionsError>) -> ()) throws /** Invokes the StartSyncExecution operation waiting for the response before returning. - Parameters: - input: The validated StartSyncExecutionInput object being passed to this operation. - Returns: The StartSyncExecutionOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, invalidExecutionInput, invalidName, stateMachineDeleting, stateMachineDoesNotExist, stateMachineTypeNotSupported. */ func startSyncExecutionSync( input: StepFunctionsModel.StartSyncExecutionInput) throws -> StepFunctionsModel.StartSyncExecutionOutput /** Invokes the StopExecution operation returning immediately and passing the response to a callback. - Parameters: - input: The validated StopExecutionInput object being passed to this operation. - completion: The StopExecutionOutput object or an error will be passed to this callback when the operation is complete. The StopExecutionOutput object will be validated before being returned to caller. The possible errors are: executionDoesNotExist, invalidArn. */ func stopExecutionAsync( input: StepFunctionsModel.StopExecutionInput, completion: @escaping (Result<StepFunctionsModel.StopExecutionOutput, StepFunctionsError>) -> ()) throws /** Invokes the StopExecution operation waiting for the response before returning. - Parameters: - input: The validated StopExecutionInput object being passed to this operation. - Returns: The StopExecutionOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: executionDoesNotExist, invalidArn. */ func stopExecutionSync( input: StepFunctionsModel.StopExecutionInput) throws -> StepFunctionsModel.StopExecutionOutput /** Invokes the TagResource operation returning immediately and passing the response to a callback. - Parameters: - input: The validated TagResourceInput object being passed to this operation. - completion: The TagResourceOutput object or an error will be passed to this callback when the operation is complete. The TagResourceOutput object will be validated before being returned to caller. The possible errors are: invalidArn, resourceNotFound, tooManyTags. */ func tagResourceAsync( input: StepFunctionsModel.TagResourceInput, completion: @escaping (Result<StepFunctionsModel.TagResourceOutput, StepFunctionsError>) -> ()) throws /** Invokes the TagResource operation waiting for the response before returning. - Parameters: - input: The validated TagResourceInput object being passed to this operation. - Returns: The TagResourceOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, resourceNotFound, tooManyTags. */ func tagResourceSync( input: StepFunctionsModel.TagResourceInput) throws -> StepFunctionsModel.TagResourceOutput /** Invokes the UntagResource operation returning immediately and passing the response to a callback. - Parameters: - input: The validated UntagResourceInput object being passed to this operation. - completion: The UntagResourceOutput object or an error will be passed to this callback when the operation is complete. The UntagResourceOutput object will be validated before being returned to caller. The possible errors are: invalidArn, resourceNotFound. */ func untagResourceAsync( input: StepFunctionsModel.UntagResourceInput, completion: @escaping (Result<StepFunctionsModel.UntagResourceOutput, StepFunctionsError>) -> ()) throws /** Invokes the UntagResource operation waiting for the response before returning. - Parameters: - input: The validated UntagResourceInput object being passed to this operation. - Returns: The UntagResourceOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, resourceNotFound. */ func untagResourceSync( input: StepFunctionsModel.UntagResourceInput) throws -> StepFunctionsModel.UntagResourceOutput /** Invokes the UpdateStateMachine operation returning immediately and passing the response to a callback. - Parameters: - input: The validated UpdateStateMachineInput object being passed to this operation. - completion: The UpdateStateMachineOutput object or an error will be passed to this callback when the operation is complete. The UpdateStateMachineOutput object will be validated before being returned to caller. The possible errors are: invalidArn, invalidDefinition, invalidLoggingConfiguration, invalidTracingConfiguration, missingRequiredParameter, stateMachineDeleting, stateMachineDoesNotExist. */ func updateStateMachineAsync( input: StepFunctionsModel.UpdateStateMachineInput, completion: @escaping (Result<StepFunctionsModel.UpdateStateMachineOutput, StepFunctionsError>) -> ()) throws /** Invokes the UpdateStateMachine operation waiting for the response before returning. - Parameters: - input: The validated UpdateStateMachineInput object being passed to this operation. - Returns: The UpdateStateMachineOutput object to be passed back from the caller of this operation. Will be validated before being returned to caller. - Throws: invalidArn, invalidDefinition, invalidLoggingConfiguration, invalidTracingConfiguration, missingRequiredParameter, stateMachineDeleting, stateMachineDoesNotExist. */ func updateStateMachineSync( input: StepFunctionsModel.UpdateStateMachineInput) throws -> StepFunctionsModel.UpdateStateMachineOutput }
56.742627
256
0.739452
d689d59411fe87ad058e3c2763421cab38280e4a
179
import UIKit import Macaw class SVGExampleView: MacawView { required init?(coder aDecoder: NSCoder) { super.init(node: SVGParser.parse(path: "tiger"), coder: aDecoder) } }
16.272727
67
0.731844
f5a73896dfb677f446db35b1e74f018872462832
543
// // WBStorageDetailArmorWeaponTypeTableCell.swift // GoWWorldBosses // // Created by Austin Chen on 2017-03-12. // Copyright © 2017 Austin Chen. All rights reserved. // import UIKit class WBStorageDetailArmorWeaponTypeTableCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.72
65
0.697974
6467d6d2500c8df1cd74ff947c8172960cda587e
8,174
// Copyright © 2020 Saleem Abdulrasool <[email protected]> // SPDX-License-Identifier: BSD-3-Clause import WinSDK import SwiftCOM private let WICImagingFactory: SwiftCOM.IWICImagingFactory? = try? IWICImagingFactory.CreateInstance(class: CLSID_WICImagingFactory) extension Image { /// A configuration object that contains the traits that the system uses when /// selecting the current image variant. public class Configuration { // MARK - Modifying a Configuration Object /// Returns a configuration object that applies the specified configuration /// values on top of the current object's values. public func applying(_ otherConfiguration: Image.Configuration?) -> Self { fatalError("\(#function) not yet implemented") } /// Returns a new configuration object that merges the current traits with /// the traits from the specified trait collection. public func withTraitCollection(_ traitCollection: TraitCollection?) -> Self { fatalError("\(#function) not yet implemented") } // MARK - Getting the Configuration Traits /// The traits associated with the image configuration. public private(set) var traitCollection: TraitCollection? } } extension Image { /// Constants that indicate which weight variant of a symbol image to use. public enum SymbolWeight: Int { // MARK - Symbol Image Weights /// An unspecified symbol image weight. case unspecified /// An ultralight weight. case ultraLight /// A thin weight case thin /// A light weight. case light /// A regular weight. case regular /// A medium weight. case medium /// A semibold weight. case semibold /// A bold weight. case bold /// A heavy weight. case heavy /// An ultra-heavy weight. case black } } extension Image.SymbolWeight { // MARK - Getting the Font Weight /// The font weight for the specified symbol weight. public func fontWeight() -> Font.Weight { fatalError("\(#function) not yet implemented") } } extension Image { public enum SymbolScale: Int { // MARK - Symbol Image Scales /// The default scale variant that matches the system usage. case `default` /// An unspecified scale. case unspecified /// The small variant of the symbol image. case small /// The medium variant of the symbol image. case medium /// The large variant of the symbol image. case large } } extension Image { /// An object that contains the specific font, size, style, and weight /// attributes to apply to a symbol image. public class SymbolConfiguration: Image.Configuration { // MARK - Creating a Symbol Configuration Object /// Creates a configuration object with the specified point-size information. public convenience init(pointSize: Double) { self.init(pointSize: pointSize, weight: .regular) } /// Creates a configuration object with the specified point-size and weight /// information. public convenience init(pointSize: Double, weight: Image.SymbolWeight) { self.init(pointSize: pointSize, weight: .regular, scale: .default) } /// Creates a configuration object with the specified point-size, weight, /// and scale information. public convenience init(pointSize: Double, weight: Image.SymbolWeight, scale: Image.SymbolScale) { fatalError("\(#function) not yet implemented") } /// Creates a configuration object with the specified scale information. public convenience init(scale: Image.SymbolScale) { fatalError("\(#function) not yet implemented") } /// Creates a configuration object with the specified font text style /// information. public convenience init(textStyle: Font.TextStyle) { self.init(textStyle: textStyle, scale: .default) } /// Creates a configuration object with the specified font text style and /// scale information. public convenience init(textStyle: Font.TextStyle, scale: Image.SymbolScale) { fatalError("\(#function) not yet implemented") } /// Creates a configuration object with the specified weight information. public convenience init(weight: Image.SymbolWeight) { fatalError("\(#function) not yet implemented") } /// Creates a configuration object with the specified font information. public convenience init(font: Font) { self.init(font: font, scale: .default) } /// Creates a configuration object with the specified font and scale /// information. public convenience init(font: Font, scale: Image.SymbolScale) { fatalError("\(#function) not yet implemented") } // MARK - Getting an Unspecified Configuration /// A symbol configuration object that contains unspecified values for all /// attributes. public class var unspecified: Image.SymbolConfiguration { fatalError("\(#function) not yet implemented") } // MARK - Removing Configuration Attributes /// Returns a copy of the current symbol configuration object without /// point-size and weight information. public func configurationWithoutPointSizeAndWeight() -> Self { fatalError("\(#function) not yet implemented") } /// Returns a copy of the current symbol configuration object without scale /// information. public func configurationWithoutScale() -> Self { fatalError("\(#function) not yet implemented") } /// Returns a copy of the current symbol configuration object without font /// text style information. public func configurationWithoutTextStyle() -> Self { fatalError("\(#function) not yet implemented") } /// Returns a copy of the current symbol configuration object without weight /// information. public func configurationWithoutWeight() -> Self { fatalError("\(#function) not yet implemented") } // MARK - Comparing Symbol Image Configurations /// Returns a boolean value that indicates whether the configuration objects /// are equivalent. public func isEqual(to otherConfiguration: Image.SymbolConfiguration?) -> Bool { fatalError("\(#function) not yet implemented") } } } /// An object that manages image data in your app. public class Image { private var WICBitmapDecoder: SwiftCOM.IWICBitmapDecoder? private var WICBitmapFrame: SwiftCOM.IWICBitmapFrameDecode? private var WICFormatConverter: SwiftCOM.IWICFormatConverter? internal var bitmap: SwiftCOM.IWICBitmapSource? { WICFormatConverter } // MARK - Creating and Initializing Image Objects /// Initializes and returns the image object with the contents of the /// specified file. public init?(contentsOfFile path: String) { guard let WICImagingFactory = WICImagingFactory else { return nil } do { self.WICBitmapDecoder = try WICImagingFactory.CreateDecoderFromFilename(path, nil, GENERIC_READ, WICDecodeMetadataCacheOnDemand) // TODO(compnerd) figure out how to handle multi-frame images let frames = try self.WICBitmapDecoder?.GetFrameCount() self.WICBitmapFrame = try self.WICBitmapDecoder?.GetFrame(frames! - 1) self.WICFormatConverter = try WICImagingFactory.CreateFormatConverter() try self.WICFormatConverter?.Initialize(WICBitmapFrame!, GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, nil, 0.0, WICBitmapPaletteTypeCustom) } catch { log.error("\(#function): \(error)") return nil } } // MARK - Getting the Image Size and Scale /// The scale factor of the image. public var scale: Float { 1.0 } /// The logical dimensions, in points, for the image. public var size: Size { guard let ImageSize: (UINT, UINT) = try? self.WICBitmapFrame?.GetSize() else { return .zero } return Size(width: Double(ImageSize.0), height: Double(ImageSize.1)) } }
31.929688
89
0.678493
908e805b889f0a6511c81d3480bc33f1a7d0f185
465
// // Linear.swift // Async // // Created by Kelly Bennett on 1/4/19. // import Foundation public struct Linear: ScoreFunctionElement { public static var typeKey = ScoreFunctionMap.linear // TODO: implement the rest of this public init() { } /// :nodoc: public func encode(to encoder: Encoder) throws {} /// :nodoc: public init(from decoder: Decoder) throws { //TODO: get from decoder } }
17.884615
55
0.595699
1182a6f6156a417e4cef722cc542ff89b7ea159f
463
// // AerialPlayerItem.swift // Aerial // // Created by Ethan Setnik on 11/22/17. // Copyright © 2017 John Coates. All rights reserved. // import AVFoundation import AVKit class AerialPlayerItem: AVPlayerItem { var video: AerialVideo? init(video: AerialVideo) { let videoURL = video.url let asset = cachedOrCachingAsset(videoURL) super.init(asset: asset, automaticallyLoadedAssetKeys: nil) self.video = video } }
22.047619
67
0.680346
218db666482581df0b5fa2c9823e4c8e5e3bc528
2,396
// // MediaRenderer1Device.swift // // Copyright (c) 2015 David Robles // // 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 @objcMembers public class MediaRenderer1Device: AbstractUPnPDevice { public var avTransportService: AVTransport1Service? { return service(forURN: "urn:schemas-upnp-org:service:AVTransport:1") as? AVTransport1Service } public var connectionManagerService: ConnectionManager1Service? { return service(forURN: "urn:schemas-upnp-org:service:ConnectionManager:1") as? ConnectionManager1Service } public var renderingControlService: RenderingControl1Service? { return service(forURN: "urn:schemas-upnp-org:service:RenderingControl:1") as? RenderingControl1Service } } /// for objective-c type checking extension AbstractUPnP { public func isMediaRenderer1Device() -> Bool { return self is MediaRenderer1Device } } /// overrides ExtendedPrintable protocol implementation extension MediaRenderer1Device { // var className: String { return "\(type(of: self))" } // override public var className: String { return "\(type(of: self))" } override public var description: String { let properties = PropertyPrinter() // properties.add(self.className, property: super.description) return properties.description } }
41.310345
112
0.740401
e5cb8b175d777f3b2ab7cc4515490007deb29153
4,024
import UIKit class VToast:UIView { private static let kHeight:CGFloat = 52 private weak var timer:Timer? private let kAnimationDuration:TimeInterval = 0.4 private let kTimeOut:TimeInterval = 3.5 private let kFontSize:CGFloat = 17 private let kLabelMargin:CGFloat = 15 class func messageOrange(message:String) { VToast.message(message:message, color:UIColor.gridOrange) } class func messageBlue(message:String) { VToast.message(message:message, color:UIColor.gridBlue) } private class func message(message:String, color:UIColor) { DispatchQueue.main.async { let toast:VToast = VToast( message:message, color:color) let rootView:UIView = UIApplication.shared.keyWindow!.rootViewController!.view rootView.addSubview(toast) let screenHeight:CGFloat = UIScreen.main.bounds.size.height let remain:CGFloat = screenHeight - kHeight let top:CGFloat = remain / 2.0 NSLayoutConstraint.topToTop( view:toast, toView:rootView, constant:top) NSLayoutConstraint.equalsHorizontal( view:toast, toView:rootView) NSLayoutConstraint.height( view:toast, constant:kHeight) rootView.layoutIfNeeded() toast.animate(open:true) } } private convenience init(message:String, color:UIColor) { self.init() clipsToBounds = true backgroundColor = color alpha = 0 translatesAutoresizingMaskIntoConstraints = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.bold(size:kFontSize) label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 label.backgroundColor = UIColor.clear label.text = message let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(label) addSubview(button) NSLayoutConstraint.equalsVertical( view:label, toView:self) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMargin) } func alertTimeOut(sender timer:Timer?) { timer?.invalidate() animate(open:false) } //MARK: actions func actionButton(sender button:UIButton) { button.isUserInteractionEnabled = false timer?.invalidate() alertTimeOut(sender:timer) } //MARK: private private func scheduleTimer() { self.timer = Timer.scheduledTimer( timeInterval:kTimeOut, target:self, selector:#selector(alertTimeOut(sender:)), userInfo:nil, repeats:false) } private func animate(open:Bool) { let alpha:CGFloat if open { alpha = 1 } else { alpha = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.alpha = alpha }) { [weak self] (done:Bool) in if open { self?.scheduleTimer() } else { self?.removeFromSuperview() } } } }
26.649007
90
0.546471
bfb5273d3dfe7688c109031fb3424159991d99ed
366
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T { func b( ) { class A : { func b( ) { let f = b<T f let a { func b< -> (n ( class { ( ( < ( : T T - { (( ( (i { ( ( extension { { { { ( = { { { func g - ( { { { ) { { { a { class { e = w
10.166667
87
0.54918
cca1dca99d275e08d161cf422550242fde48eb7b
8,228
// // main.swift // generate_keys // // Created by Kornel on 15/09/2018. // Copyright © 2018 Sparkle Project. All rights reserved. // import Foundation import Security private func commonKeychainItemAttributes() -> [String: Any] { /// Attributes used for both adding a new item and matching an existing one. return [ /// The type of the item (a generic password). kSecClass as String: kSecClassGenericPassword as String, /// The service string for the item (the Sparkle homepage URL). kSecAttrService as String: "https://sparkle-project.org", /// The account name for the item (in this case, the key type). kSecAttrAccount as String: "ed25519", /// The protocol used by the service (not actually used, so we claim SSH). kSecAttrProtocol as String: kSecAttrProtocolSSH as String, ] } private func failure(_ message: String) -> Never { /// Checking for both `TERM` and `isatty()` correctly detects Xcode. if ProcessInfo.processInfo.environment["TERM"] != nil && isatty(STDOUT_FILENO) != 0 { print("\u{001b}[1;91mERROR:\u{001b}[0m ", terminator: "") } else { print("ERROR: ", terminator: "") } print(message) exit(1) } func findPublicKey() -> Data? { var item: CFTypeRef? let res = SecItemCopyMatching(commonKeychainItemAttributes().merging([ /// Return a matched item's value as a CFData object. kSecReturnData as String: kCFBooleanTrue!, ], uniquingKeysWith: { $1 }) as CFDictionary, &item) switch res { case errSecSuccess: if let keys = (item as? Data).flatMap({ Data(base64Encoded: $0) }) { return keys[64...] } else { failure(""" Item found, but is corrupt or has been overwritten! Please delete the existing item from the keychain and try again. """) } case errSecItemNotFound: return nil case errSecAuthFailed: failure(""" Access denied. Can't check existing keys in the keychain. Go to Keychain Access.app, lock the login keychain, then unlock it again. """) case errSecUserCanceled: failure(""" User canceled the authorization request. To retry, run this tool again. """) case errSecInteractionNotAllowed: failure(""" The operating system has blocked access to the Keychain. You may be trying to run this command from a script over SSH, which is not supported. """) case let res: print(""" Unable to access an existing item in the Keychain due to an unknown error: \(res). You can look up this error at <https://osstatus.com/search/results?search=\(res)> """) // Note: Don't bother percent-encoding `res`, it's always an integer value and will not need escaping. } exit(1) } func generateKeyPair() -> Data { var seed = Array<UInt8>(repeating: 0, count: 32) var publicEdKey = Array<UInt8>(repeating: 0, count: 32) var privateEdKey = Array<UInt8>(repeating: 0, count: 64) guard ed25519_create_seed(&seed) == 0 else { failure("Unable to initialize random seed. Try restarting your computer.") } ed25519_create_keypair(&publicEdKey, &privateEdKey, seed) let query = commonKeychainItemAttributes().merging([ /// Mark the new item as sensitive (requires keychain password to export - e.g. a private key). kSecAttrIsSensitive as String: kCFBooleanTrue!, /// Mark the new item as permanent (supposedly, "stored in the keychain when created", but not actually /// used for generic passwords - we set it anyway for good measure). kSecAttrIsPermanent as String: kCFBooleanTrue!, /// The label of the new item (shown as its name/title in Keychain Access). kSecAttrLabel as String: "Private key for signing Sparkle updates", /// A comment regarding the item's content (can be viewed in Keychain Access; we give the public key here). kSecAttrComment as String: "Public key (SUPublicEDKey value) for this key is:\n\n\(Data(publicEdKey).base64EncodedString())", /// A short description of the item's contents (shown as "kind" in Keychain Access"). kSecAttrDescription as String: "private key", /// The actual data content of the new item. kSecValueData as String: Data(privateEdKey + publicEdKey).base64EncodedData() as CFData ], uniquingKeysWith: { $1 }) as CFDictionary switch SecItemAdd(query, nil) { case errSecSuccess: return Data(publicEdKey) case errSecDuplicateItem: failure("You already have a conflicting key in your Keychain which was not found during lookup.") case errSecAuthFailed: failure(""" System denied access to the Keychain. Unable to save the new key. Go to Keychain Access.app, lock the login keychain, then unlock it again. """) case let res: failure(""" The key could not be saved to the Keychain due to an unknown error: \(res). You can look up this error at <https://osstatus.com/search/results?search=\(res)> """) } exit(1) } /// Once it's safe to require Swift 5.3 and Xcode 12 for this code, rename this file to `generate_keys.swift` and /// replace this function with a class tagged with `@main`. func entryPoint() { let isLookupMode = (CommandLine.arguments.dropFirst().first.map({ $0 == "-p" }) ?? false) /// If not in lookup-only mode, give an intro blurb. if !isLookupMode { print(""" This tool uses the macOS Keychain to store a private key for signing app updates which will be distributed via Sparkle. The key will be associated with your user account. Note: You only need one signing key, no matter how many apps you embed Sparkle in. The keychain may ask permission for this tool to access an existing key, if one exists, or for permission to save the new key. You must allow access in order to successfully proceed. """) } switch (findPublicKey(), isLookupMode) { /// Existing key found, lookup mode - print just the pubkey and exit case (.some(let pubKey), true): print(pubKey.base64EncodedString()) /// Existing key found, normal mode - print instructions blurb and pubkey case (.some(let pubKey), false): print(""" A pre-existing signing key was found. This is how it should appear in your Info.plist: <key>SUPublicEDKey</key> <string>\(pubKey.base64EncodedString())</string> """) /// No existing key, lookup mode - error out case (.none, true): failure("No existing signing key found!") /// No existing key, normal mode - generate a new one case (.none, false): print("Generating a new signing key. This may take a moment, depending on your machine.") let pubKey = generateKeyPair() print(""" A key has been generated and saved in your keychain. Add the `SUPublicEDKey` key to the Info.plist of each app for which you intend to use Sparkle for distributing updates. It should appear like this: <key>SUPublicEDKey</key> <string>\(pubKey.base64EncodedString())</string> """) } } // Dispatch to a function because `@main` isn't stable yet at the time of this writing and top-level code is finicky. entryPoint()
41.14
137
0.59334
9b2075587da475f5327fa4db9c06ff0f886f74c6
1,950
import Basic import Foundation import TuistCore class SDKNode: GraphNode { let status: SDKStatus let type: Type init(name: String, platform: Platform, status: SDKStatus) throws { let sdk = AbsolutePath("/\(name)") guard let sdkExtension = sdk.extension, let type = Type(rawValue: sdkExtension) else { throw Error.unsupported(sdk: name) } self.status = status self.type = type let sdkRootPath = AbsolutePath(platform.xcodeSdkRootPath, relativeTo: AbsolutePath("/")) let path: AbsolutePath switch type { case .framework: path = sdkRootPath .appending(RelativePath("System/Library/Frameworks")) .appending(component: name) case .library: path = sdkRootPath .appending(RelativePath("usr/lib")) .appending(component: name) } super.init(path: path, name: String(name.split(separator: ".").first!)) } enum `Type`: String, CaseIterable { case framework case library = "tbd" static var supportedTypesDescription: String { let supportedTypes = allCases .map { ".\($0.rawValue)" } .joined(separator: ", ") return "[\(supportedTypes)]" } } enum Error: FatalError, Equatable { case unsupported(sdk: String) var description: String { switch self { case let .unsupported(sdk): let supportedTypes = Type.supportedTypesDescription return "The SDK type of \(sdk) is not currently supported - only \(supportedTypes) are supported." } } var type: ErrorType { switch self { case .unsupported: return .abort } } } }
27.857143
114
0.537436
5dcdc37d9e59f04fcff71d1a37d7be1c84d05347
4,085
import Combine @testable import CombineWamp import Foundation import XCTest // https://wamp-proto.org/_static/gen/wamp_latest.html#publishing-and-events final class PublisherTests: IntegrationTestBase { var connected: XCTestExpectation! var session: WampSession! let realm = URI("realm1")! var connection: AnyCancellable? override func setUp() { super.setUp() connected = expectation(description: "Connected") session = WampSession(transport: transport(), serialization: serialization, realm: realm, roles: .allClientRoles) connection = session.connect() .sink( receiveCompletion: { completion in switch completion { case let .failure(error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { [weak self] welcome in self?.connected.fulfill() } ) } func testPublishAndReceivePublished() throws { wait(for: [connected], timeout: 0.5) let publishedReceived = expectation(description: "Published should have been received") session .client .asPublisher! .publish(topic: URI("com.myapp.hello")!, positionalArguments: [.string("Hello World 42")]) .sink( receiveCompletion: { completion in switch completion { case let .failure(error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { published in XCTAssertTrue(published.publication.value > 0) publishedReceived.fulfill() } ).store(in: &cancellables) wait(for: [publishedReceived], timeout: 0.5) XCTAssertNotNil(connection) } func testPublishWithoutAck() throws { wait(for: [connected], timeout: 0.5) let publishedReceived = expectation(description: "Published should have been received") session .client .asPublisher! .publishWithoutAck(topic: URI("com.myapp.hello")!, positionalArguments: [.string("Hello World 42")]) .sink( receiveCompletion: { completion in switch completion { case let .failure(error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { _ in publishedReceived.fulfill() } ).store(in: &cancellables) wait(for: [publishedReceived], timeout: 0.5) XCTAssertNotNil(connection) } func testPublishAndReceiveError() throws { wait(for: [connected], timeout: 0.5) let errorReceived = expectation(description: "Error should have been received") session .client .asPublisher! .publish(topic: URI(unverified: ".myapp.hello..a"), positionalArguments: [.string("Hello World 42")]) .sink( receiveCompletion: { completion in switch completion { case let .failure(error): guard case let .commandError(commandError) = error else { return } XCTAssertEqual(commandError.error, WampError.invalidURI.uri) errorReceived.fulfill() case .finished: break } }, receiveValue: { published in XCTFail("Success was not expected") } ).store(in: &cancellables) wait(for: [errorReceived], timeout: 0.5) XCTAssertNotNil(connection) } }
35.521739
121
0.522889
ed1ed13c0ebd39b8fcc366e5e7400175f91e45d0
221
// // DeleteIDContainer.swift // APIErrorMiddleware // // Created by laijihua on 2018/7/15. // import Vapor import FluentPostgreSQL struct DeleteIDContainer<Model: PostgreSQLModel>: Content { var id: Model.ID }
14.733333
59
0.728507
2661669398ee982664392124eff74a4c55c7a8b2
3,458
// // SceneDelegate.swift // CoreDataProject // // Created by Matej Novotný on 21/10/2020. // import CoreData import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // this line of code ask core data to merge the objects based on their property context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
46.106667
147
0.715732
624ac39e874b3745e3f7e60e6db5bb9bdd99e7b9
2,782
// // TrackEvent+DataType.swift // ExponeaSDK // // Created by Dominik Hadl on 11/05/2018. // Copyright © 2018 Exponea. All rights reserved. // import Foundation extension TrackEvent { var dataTypes: [DataType] { var data: [DataType] = [] // Add project token. if let token = projectToken { data.append(.projectToken(token)) } // Convert all properties to key value items. if let properties = trackEventProperties as? Set<TrackEventProperty> { var props: [String: JSONValue] = [:] properties.forEach({ DatabaseManager.processProperty(key: $0.key, value: $0.value, into: &props) }) data.append(.properties(props)) } // Add event type. if let eventType = eventType { data.append(.eventType(eventType)) } // Add timestamp if we have it, otherwise none. data.append(.timestamp(timestamp == 0 ? nil : timestamp)) return data } } extension DatabaseManager { static func processProperty(key: String?, value: NSObject?, into dictionary: inout [String: JSONValue]) { guard let value = value else { Exponea.logger.log(.verbose, message: "Skipping empty value for property: \(key ?? "Empty")") return } switch value.self { case is NSString: guard let string = value as? NSString else { Exponea.logger.log(.error, message: "Failed to convert NSObject to NSString for: \(value).") break } dictionary[key!] = .string(string as String) case is NSNumber: guard let number = value as? NSNumber else { Exponea.logger.log(.error, message: "Failed to convert NSObject to NSNumber for: \(value).") break } // Switch based on number type switch CFNumberGetType(number) { case .charType: dictionary[key!] = .bool(number.boolValue) case .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type, .shortType, .intType, .longType, .longLongType, .cfIndexType, .nsIntegerType: dictionary[key!] = .int(number.intValue) case .float32Type, .float64Type, .floatType, .doubleType, .cgFloatType: dictionary[key!] = .double(number.doubleValue) } default: Exponea.logger.log(.verbose, message: "Skipping unsupported property value: \(value).") break } } }
34.345679
109
0.534148
03080c9049e692c0360a00dfbe0c40d68fb02964
1,609
// // SignedContainer.swift // Checkout // // Created by Brent Royal-Gordon on 11/5/17. // Copyright © 2017 Architechies. All rights reserved. // import Foundation public struct SignedContainer { private let pkcs7: _PKCS7 public init(data: Data) throws { pkcs7 = try _PKCS7(data: _BIO(data: data)) } private func verifiedContents(with certStore: _X509Store) throws -> Data { guard let signed = try pkcs7.signed() else { throw CheckoutError.missingSignature } do { try pkcs7.verify(with: certStore) } catch { throw CheckoutError.invalidSignature(underlying: error) } guard let contents = try signed.contents().data() else { throw CheckoutError.missingContents } return contents } public func verifiedContents(with certificates: [SigningCertificate] = [.apple]) throws -> Data { let store = _X509Store() for cert in certificates { try store.addCertificate(cert.x509) } return try verifiedContents(with: store) } } public struct SigningCertificate { public static let apple = try! SigningCertificate(contentsOf: Bundle(for: _X509.self).url(forResource: "Apple", withExtension: "cer")!) fileprivate let x509: _X509 public init(contentsOf url: URL) throws { let data = try Data(contentsOf: url) try self.init(data: data) } public init(data: Data) throws { x509 = try _X509(data: _BIO(data: data)) } }
26.816667
139
0.610317
dd665535d12c53fd55f3f6c41cf20cc600d1bf8b
14,864
// // CKRoomDirectCreatingViewController.swift // Riot // // Created by Sinbad Flyce on 1/21/19. // Copyright © 2019 matrix.org. All rights reserved. // import Foundation protocol CKRoomDirectCreatingViewControllerDelegate: class { func roomDirectCreating(withUserId userId: String, completion: ((_ success: Bool) -> Void)? ) } final class CKRoomDirectCreatingViewController: MXKViewController { // MARK: - OUTLET @IBOutlet weak var tableView: UITableView! // MARK: - ENUM private enum Section: Int { case search = 0 case action = 1 case suggested = 2 static func count() -> Int { return 3 } } // MARK: - PROPERTY /** delegate */ internal var delegate: CKRoomDirectCreatingViewControllerDelegate? /** data source */ private var suggestedDataSource = [MXKContact]() private let disposeBag = DisposeBag() // MARK: - OVERRIDE override func viewDidLoad() { super.viewDidLoad() // selection is enable self.tableView.allowsSelection = true // register cells self.tableView.register(CKRoomDirectCreatingSearchCell.nib, forCellReuseIdentifier: CKRoomDirectCreatingSearchCell.identifier) self.tableView.register(CKRoomDirectCreatingActionCell.nib, forCellReuseIdentifier: CKRoomDirectCreatingActionCell.identifier) self.tableView.register(CKRoomDirectCreatingSuggestedCell.nib, forCellReuseIdentifier: CKRoomDirectCreatingSuggestedCell.identifier) // Setup close button item let closeItemButton = UIBarButtonItem.init( image: UIImage(named: "back_button"), style: .plain, target: self, action: #selector(clickedOnBackButton(_:))) closeItemButton.theme.tintColor = themeService.attrStream { $0.navBarTintColor } // set nv items self.navigationItem.leftBarButtonItem = closeItemButton self.navigationItem.title = "New Conversation" self.navigationController?.navigationBar.tintColor = themeService.attrs.primaryTextColor self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow") // first reload ds self.reloadDataSource() bindingTheme() UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil) self.hideKeyboardWhenTappedAround() } // MARK: - ACTION @objc func clickedOnBackButton(_ sender: Any?) { self.dismiss(animated: true, completion: nil) } // MARK: - PRIVATE func bindingTheme() { // Binding navigation bar color themeService.attrsStream.subscribe(onNext: { [weak self] (theme) in self?.defaultBarTintColor = themeService.attrs.navBarBgColor self?.barTitleColor = themeService.attrs.navBarTintColor self?.tableView.reloadData() }).disposed(by: disposeBag) themeService.rx .bind({ $0.navBarBgColor }, to: view.rx.backgroundColor, tableView.rx.backgroundColor) .disposed(by: disposeBag) } /** Reload suggested data source */ private func reloadDataSource() { // reset self.suggestedDataSource.removeAll() // load them from ... let ds = MXKContactManager.shared().directMatrixContacts // loop in each for c in ds { // catch op if let c = c as? MXKContact { // add self.suggestedDataSource.append(c) } } // reload if suggestedDataSource.count > 0 { self.tableView.reloadSections( [Section.action.rawValue, Section.suggested.rawValue], with: .none) } } /** Action cell view */ private func cellForAction(atIndexPath indexPath: IndexPath) -> CKRoomDirectCreatingActionCell { // dequeue if let cell = tableView.dequeueReusableCell( withIdentifier: CKRoomDirectCreatingActionCell.identifier, for: indexPath) as? CKRoomDirectCreatingActionCell { // none style selection cell.selectionStyle = .none // action cell.newGroupHandler = { // is navigation ? if let nvc = self.navigationController { // init let vc = CKRoomCreatingViewController.instance() // import vc.importSession(self.mxSessions) // push vc nvc.pushViewController(vc, animated: true) } else { // init nvc let nvc = CKRoomCreatingViewController.instanceNavigation(completion: { (vc: MXKViewController) in // import vc.importSession(self.mxSessions) }) // present self.present(nvc, animated: true, completion: nil) } } // new a group calling cell.newCallHandler = { // init let vc = CKRoomCallCreatingViewController.instance() // import vc.importSession(self.mxSessions) // push vc self.navigationController?.pushViewController(vc, animated: true) } cell.theme.backgroundColor = themeService.attrStream{ $0.cellPrimaryBgColor } return cell } return CKRoomDirectCreatingActionCell() } /** Suggested cell view */ private func cellForSuggested(atIndexPath indexPath: IndexPath) -> CKRoomDirectCreatingSuggestedCell { // dequeue & confirm if let cell = tableView.dequeueReusableCell( withIdentifier: CKRoomDirectCreatingSuggestedCell.identifier, for: indexPath) as? CKRoomDirectCreatingSuggestedCell { // index of let contact = self.suggestedDataSource[indexPath.row] // display name cell.suggesteeLabel.text = contact.displayName cell.setAvatarUri( contact.matrixAvatarURL, identifyText: contact.displayName, session: self.mainSession) // status if let u = self.mainSession?.user( withUserId: (contact.matrixIdentifiers?.first as? String) ?? "") { cell.status = u.presence == MXPresenceOnline ? 1 : 0 } else { cell.status = 0 } cell.suggesteeLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor } cell.theme.backgroundColor = themeService.attrStream{ $0.cellPrimaryBgColor } return cell } return CKRoomDirectCreatingSuggestedCell() } /** Searching - cell view */ private func cellForSeaching(atIndexPath indexPath: IndexPath) -> CKRoomDirectCreatingSearchCell { // sure to make cell let cell = (self.tableView.dequeueReusableCell( withIdentifier: CKRoomDirectCreatingSearchCell.identifier, for: indexPath) as? CKRoomDirectCreatingSearchCell) ?? CKRoomDirectCreatingSearchCell() // handl serching cell.beginSearchingHandler = { text in // indicator self.startActivityIndicator() // try to seach text in hs self.mainSession.matrixRestClient.searchUsers(text, limit: 50, success: { (response: MXUserSearchResponse?) in // main asyn DispatchQueue.main.async { // text lenght if text.count > 0 { // seach self.finallySearchDirectoryUsers(byResponse: response) } else { // reload self.reloadDataSource() } self.stopActivityIndicator() } }, failure: { (_) in // main async DispatchQueue.main.async { self.reloadDataSource() self.stopActivityIndicator() } }) } cell.theme.backgroundColor = themeService.attrStream{ $0.cellPrimaryBgColor } return cell } /** Title for header */ private func titleForHeader(atSection section: Int) -> String { guard let s = Section(rawValue: section) else { return ""} switch s { case .search: return "" case .action: return "Probably you want" case .suggested: return "Suggested" } } /** Make a direct chat */ private func directChat(atIndexPath indexPath: IndexPath) { // in range if suggestedDataSource.count > indexPath.row { // index of let c = suggestedDataSource[indexPath.row] // first if let userId = c.matrixIdentifiers.first as? String { // progress start self.startActivityIndicator() // invoke delegate self.delegate?.roomDirectCreating(withUserId: userId, completion: { (success: Bool) in // progress stop self.stopActivityIndicator() // dismiss if success == true { self.clickedOnBackButton(nil)} }) } } } private func finallySearchDirectoryUsers(byResponse response: MXUserSearchResponse?) { // sure is value response if let results = response?.results, results.count > 0 { // reset self.suggestedDataSource.removeAll() // re-update for u in results { if let c = MXKContact(matrixContactWithDisplayName: u.displayname, andMatrixID: u.userId) { self.suggestedDataSource.append(c) } } // re-load self.tableView.reloadSections( [Section.action.rawValue, Section.suggested.rawValue], with: .none) } else { // no result self.suggestedDataSource.removeAll() self.tableView.reloadSections( [Section.action.rawValue, Section.suggested.rawValue], with: .none) } } } extension CKRoomDirectCreatingViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let s = Section(rawValue: indexPath.section) else { return 0} switch s { case .search: return CKLayoutSize.Table.row44px case .action: return UITableViewAutomaticDimension case .suggested: return CKLayoutSize.Table.row60px } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let view = CKRoomHeaderInSectionView.instance() { view.theme.backgroundColor = themeService.attrStream{ $0.primaryBgColor } view.descriptionLabel?.text = self.titleForHeader(atSection: section) view.descriptionLabel?.font = UIFont.systemFont(ofSize: 21) view.descriptionLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor } return view } return UIView() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let s = Section(rawValue: section) else { return 0} switch s { case .search: return CGFloat.leastNonzeroMagnitude case .action: return CKLayoutSize.Table.row43px case .suggested: return CKLayoutSize.Table.row43px } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNonzeroMagnitude } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let s = Section(rawValue: indexPath.section) else { return } tableView.deselectRow(at: indexPath, animated: false) switch s { case .search: return case .action: return case .suggested: self.directChat(atIndexPath: indexPath) break } } } extension CKRoomDirectCreatingViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Section.count() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let s = Section(rawValue: section) else { return 0} switch s { case .search: return 1 case .action: return 1 case .suggested: return self.suggestedDataSource.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let s = Section(rawValue: indexPath.section) else { return CKRoomCreatingBaseCell()} switch s { case .search: return cellForSeaching(atIndexPath: indexPath) case .action: return self.cellForAction(atIndexPath: indexPath) case .suggested: return self.cellForSuggested(atIndexPath: indexPath) } } } extension CKRoomDirectCreatingViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } }
32.812362
140
0.559002
de268f7953f52944894ecdddf2ffc86ea82b62ce
152
// // Comments.swift // iScoop // // Created by Taral Rathod on 18/02/22. // import Foundation struct Comments: Codable { var comments: Int? }
11.692308
40
0.644737
d9eb54f4027820a65d3978c221e5f16db152966b
2,598
/// Implementation details of `ValueReducer`. /// /// :nodoc: public protocol _ValueReducer { /// The type of fetched database values associatedtype Fetched /// The type of observed values associatedtype Value /// Returns whether the database region selected by the `fetch(_:)` method /// is constant. var _isSelectedRegionDeterministic: Bool { get } /// Fetches database values upon changes in an observed database region. /// /// ValueReducer semantics require that this method does not depend on /// the state of the reducer. func _fetch(_ db: Database) throws -> Fetched /// Transforms a fetched value into an eventual observed value. Returns nil /// when observer should not be notified. /// /// This method runs in some unspecified dispatch queue. /// /// ValueReducer semantics require that the first invocation of this /// method returns a non-nil value: /// /// let reducer = MyReducer() /// reducer._value(...) // MUST NOT be nil /// reducer._value(...) // MAY be nil /// reducer._value(...) // MAY be nil mutating func _value(_ fetched: Fetched) -> Value? } /// The `ValueReducer` protocol supports `ValueObservation`. public protocol ValueReducer: _ValueReducer { } extension ValueReducer { func fetch(_ db: Database, requiringWriteAccess: Bool) throws -> Fetched { if requiringWriteAccess { var fetchedValue: Fetched? try db.inSavepoint { fetchedValue = try _fetch(db) return .commit } return fetchedValue! } else { return try db.readOnly { try _fetch(db) } } } mutating func fetchAndReduce(_ db: Database, requiringWriteAccess: Bool) throws -> Value? { let fetchedValue = try fetch(db, requiringWriteAccess: requiringWriteAccess) return _value(fetchedValue) } } /// A namespace for types related to the `ValueReducer` protocol. public enum ValueReducers { // ValueReducers.Auto allows us to define ValueObservation factory methods. // // For example, ValueObservation.tracking(_:) is, practically, // ValueObservation<ValueReducers.Auto>.tracking(_:). /// :nodoc: public enum Auto: ValueReducer { public var _isSelectedRegionDeterministic: Bool { preconditionFailure() } public func _fetch(_ db: Database) throws -> Never { preconditionFailure() } public mutating func _value(_ fetched: Never) -> Never? { } } }
35.108108
95
0.640878
f933e679918e9c05d7feda572ef8f9792f61372f
1,045
// // SettingsViewController+TableView.swift // InstaTracker // // Created by Alex Morkovkin on 30.11.2020. // import Foundation import UIKit extension SettingsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ButtonAction.allCases.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SettingsViewController.cellIdentifier, for: indexPath) let menuItem = ButtonAction.init(rawValue: indexPath.row)! cell.textLabel?.text = menuItem.getTitle() cell.imageView?.image = menuItem.getImage() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let button = ButtonAction.init(rawValue: indexPath.row)! button.action(vc: self) tableView.deselectRow(at: indexPath, animated: true) } }
32.65625
119
0.711005
6aa8e63111ec54fc141f516d0affcb9dfa5d6ded
1,246
// // UIRefreshControlExntesionsTests.swift // SwifterSwift // // Created by ratul sharker on 7/24/18. // Copyright © 2018 SwifterSwift // #if os(iOS) import XCTest @testable import SwifterSwift final class UIRefreshControlExtensionTests: XCTestCase { func testBeginRefreshAsRefreshControlSubview() { let tableView = UITableView() XCTAssertEqual(tableView.contentOffset, .zero) let refreshControl = UIRefreshControl() tableView.addSubview(refreshControl) refreshControl.beginRefreshing(in: tableView, animated: true) XCTAssertTrue(refreshControl.isRefreshing) XCTAssertEqual(tableView.contentOffset.y, -refreshControl.frame.height) if #available(iOS 10.0, *) { let anotherTableview = UITableView() XCTAssertEqual(anotherTableview.contentOffset, .zero) anotherTableview.refreshControl = UIRefreshControl() anotherTableview.refreshControl?.beginRefreshing(in: anotherTableview, animated: true, sendAction: true) XCTAssertTrue(anotherTableview.refreshControl!.isRefreshing) XCTAssertEqual(anotherTableview.contentOffset.y, -anotherTableview.refreshControl!.frame.height) } } } #endif
31.15
116
0.718299
d6e0ab3dcb7f4eadc8c13b013ad2f9ce04519d3c
27,420
// // SwiftUI.swift // Pods // // Created by Denis Koryttsev on 02.03.2021. // import Foundation #if canImport(SwiftUI) && canImport(Combine) import SwiftUI import Combine public protocol SwiftUICompatibleTransition: Transition { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) func move<V>(_ state: Binding<Bool>, screenState: ContentScreenState<To.NestedScreen>, actionView: V, context: Context, completion: (() -> Void)?) -> AnyView where V: View } extension Win { @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) public struct SwiftUI<Root>: ScreenContainer where Root: Screen, Root.Content: View { let _root: Root public init(_ root: Root) { self._root = root } public subscript<T>(next path: KeyPath<Root.PathFrom, T>) -> T { _root[next: path] } public func index(of keyPath: PartialKeyPath<Root.PathFrom>) -> Int { _root.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<Root.PathFrom> { _root.keyPath(at: index) } public typealias Content = WindowGroup<Root.Content> public typealias Context = Root.Context public typealias NestedScreen = Root.NestedScreen public func makeContent(_ context: Root.Context, router: Router<Root.NestedScreen>) -> ContentResult<Win.SwiftUI<Root>> { let (content1, content0) = _root.makeContent(context, router: router) return (WindowGroup { content1 }, content0) } } } public protocol _TabsViewIdentity {} extension Tab { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) public struct SwiftUI<Root>: ContentScreen where Root: ScreenBuilder { public typealias NestedScreen = Self public typealias Content = TabsView public typealias Context = Root.Context let root: Root public subscript<T>(next path: KeyPath<Root.PathFrom, T>) -> T { root[next: path] } public func index(of keyPath: PartialKeyPath<Root.PathFrom>) -> Int { root.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<Root.PathFrom> { root.keyPath(at: index) } public func makeContent(_ context: Context, router: Router<NestedScreen>) -> ContentResult<Self> { let tabs = TabsView(router: router, content: root.makeContent(context, router: router), selectedIndex: 0) return (tabs, tabs) } public struct TabsView: View, _TabsViewIdentity { let router: Router<NestedScreen> let content: Root.Content @State var selectedIndex: Int public var body: some View { let _selected = _selectedIndex let _binding = _Binding( get: { _selected.wrappedValue }, set: { newValue in _selected.wrappedValue = newValue guard let state = router.state.childStates[router.keyPath(at: newValue)] else { return } router.state.next = state } ) router.state.selectedIndex_SwiftUI = _binding let binding = Binding(get: _binding.get, set: _binding.set) return TabView(selection: binding) { TupleView(content) } } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct SwiftUITransition<From, Too>: SwiftUICompatibleTransition where From: Screen, Too: Screen, From.Content: _TabsViewIdentity { public typealias To = Too let to: Too public subscript<T>(next path: KeyPath<To.PathFrom, T>) -> T { to[next: path] } public func index(of keyPath: PartialKeyPath<To.PathFrom>) -> Int { to.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<To.PathFrom> { to.keyPath(at: index) } public func move(from screen: From.Content, state: ContentScreenState<From.NestedScreen>, with context: Void, completion: (() -> Void)?) -> TransitionResult<From, To> { fatalError("unavailable") } public func move<V>(_ state: Binding<Bool>, screenState: ContentScreenState<Too.NestedScreen>, actionView: V, context: (), completion: (() -> Void)?) -> AnyView where V : View { fatalError("unavailable") } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) extension Tab.SwiftUI { public init(@ContentBuilder tabs builder: () -> Root) { self.init(root: builder()) } } extension Nav { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) public struct SwiftUI<Root>: ScreenContainer where Root: Screen, Root.Content: View { public typealias Context = Root.Context public typealias Content = NavigationView<Root.Content> public typealias NestedScreen = Root.NestedScreen let _root: Root public init(_ root: Root) { self._root = root } public subscript<T>(next path: KeyPath<Root.PathFrom, T>) -> T { _root[next: path] } public func index(of keyPath: PartialKeyPath<Root.PathFrom>) -> Int { _root.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<Root.PathFrom> { _root.keyPath(at: index) } public func makeContent(_ context: Root.Context, router: Router<Root.NestedScreen>) -> ContentResult<Nav.SwiftUI<Root>> { let (content1, content0) = _root.makeContent(context, router: router) return (NavigationView { content1 }, content0) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension Nav.Push { public struct SwiftUI<From, Too>: SwiftUICompatibleTransition where From: ContentScreen, Too: Screen, Too.Content: View { public typealias To = Too.NestedScreen let to: Too #if !os(macOS) let isDetail: Bool public init(_ to: Too, isDetail: Bool = true) { self.to = to self.isDetail = isDetail } #else public init(_ to: Too) { self.to = to } #endif public subscript<T>(next path: KeyPath<To.PathFrom, T>) -> T { to[next: path] } public func index(of keyPath: PartialKeyPath<To.PathFrom>) -> Int { to.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<To.PathFrom> { to.keyPath(at: index) } public func move(from surface: From.Content, state: ContentScreenState<From.NestedScreen>, with context: Too.Context, completion: (() -> Void)?) -> TransitionResult<From, To> { let state = TransitionState<From, To>() let (_, c0) = to.makeContent(context, router: Router(from: to, state: state)) return (state, (c0, c0)) } public func move<V>(_ state: Binding<Bool>, screenState: ContentScreenState<Too.NestedScreen>, actionView: V, context: Too.Context, completion: (() -> Void)?) -> AnyView where V : View { let link = NavigationLink( destination: to.makeContent(context, router: Router(from: to, state: screenState)).contentWrapper .onAppear(perform: completion), isActive: state.projectedValue, label: { actionView } ) #if os(iOS) return AnyView(link.isDetailLink(isDetail)) #else return AnyView(link) #endif } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension Presentation { public struct SwiftUI<From, Too>: SwiftUICompatibleTransition where From: ContentScreen, Too: Screen, Too.Content: View { public typealias To = Too.NestedScreen let to: Too public init(_ to: Too) { self.to = to } public subscript<T>(next path: KeyPath<To.PathFrom, T>) -> T { to[next: path] } public func index(of keyPath: PartialKeyPath<To.PathFrom>) -> Int { to.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<To.PathFrom> { to.keyPath(at: index) } public func move(from surface: From.Content, state: ContentScreenState<From.NestedScreen>, with context: Too.Context, completion: (() -> Void)?) -> TransitionResult<From, To> { let state = TransitionState<From, To>() let (_, c0) = to.makeContent(context, router: Router(from: to, state: state)) return (state, (c0, c0)) } public func move<V>(_ state: Binding<Bool>, screenState: ContentScreenState<Too.NestedScreen>, actionView: V, context: Too.Context, completion: (() -> Void)?) -> AnyView where V : View { AnyView(actionView.sheet(isPresented: state) { to.makeContent(context, router: Router(from: to, state: screenState)).contentWrapper .onAppear(perform: completion) }) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) extension Screen where Content: View { public func navigation() -> SwiftUI.Navigation<Self> { Nav.SwiftUI(self) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) extension Screen where Content: View { public func push<From>() -> SwiftUI.Push<From, Self> { Nav.Push.SwiftUI(self) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *) extension Screen where Content: View { public func present<From>() -> SwiftUI.Present<From, Self> { Presentation.SwiftUI(self) } } extension Router { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<T, ActionView>( _ path: KeyPath<From.PathFrom, T>, context: T.Context, @ViewBuilder action view: @escaping (Binding<Bool>) -> ActionView, completion: (() -> Void)? ) -> TransitionView<T, ActionView> where T: SwiftUICompatibleTransition, From == T.From, ActionView: View { let nextState = TransitionState<T.From.NestedScreen, T.To.NestedScreen>() nextState.previous = state state[child: path, T.To.NestedScreen.self] = nextState // replaced previous line return TransitionView<T, ActionView>( from[next: path], prevState: state, nextState: nextState, context: context, actionView: view, completion: completion ) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<T, ActionView>( _ path: KeyPath<From.PathFrom, Optional<T>>, context: T.Context, @ViewBuilder action view: @escaping (Binding<Bool>) -> ActionView, completion: (() -> Void)? ) -> TransitionView<T, ActionView>? where T: SwiftUICompatibleTransition, From == T.From, ActionView: View { guard let transition = from[next: path] else { return nil } let nextState = TransitionState<T.From.NestedScreen, T.To.NestedScreen>() nextState.previous = state state[child: path, T.To.NestedScreen.self] = nextState // replaced previous line return TransitionView<T, ActionView>( transition, prevState: state, nextState: nextState, context: context, actionView: view, completion: completion ) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<T, ActionLabel>(_ path: KeyPath<From.PathFrom, T>, context: T.Context, action label: ActionLabel, completion: (() -> Void)?) -> TransitionView<T, Button<ActionLabel>> where T: SwiftUICompatibleTransition, From == T.From, ActionLabel: View { move(path, context: context, action: { state in Button(action: { state.wrappedValue = true }, label: { label }) }, completion: completion) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<T, ActionLabel>(_ path: KeyPath<From.PathFrom, Optional<T>>, context: T.Context, action label: ActionLabel, completion: (() -> Void)?) -> TransitionView<T, Button<ActionLabel>>? where T: SwiftUICompatibleTransition, From == T.From, ActionLabel: View { move(path, context: context, action: { state in Button(action: { state.wrappedValue = true }, label: { label }) }, completion: completion) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct TransitionView<Transition, ActionView>: View where Transition: SwiftUICompatibleTransition, ActionView: View { let context: Transition.Context let transition: Transition let actionView: (Binding<Bool>) -> ActionView let completion: (() -> Void)? let prevState: ContentScreenState<Transition.From.NestedScreen> let state: ContentScreenState<Transition.To.NestedScreen> init(_ transition: Transition, prevState: ContentScreenState<Transition.From.NestedScreen>, nextState: ContentScreenState<Transition.To.NestedScreen>, context: Transition.Context, @ViewBuilder actionView: @escaping (Binding<Bool>) -> ActionView, completion: (() -> Void)?) { self.transition = transition self.context = context self.actionView = actionView self.completion = completion self.prevState = prevState self.state = nextState } @State var isActive: Bool = false public var body: some View { let _active = _isActive let _binding = _Binding( get: { _active.wrappedValue }, set: { [weak state, weak prevState] newValue in _active.wrappedValue = newValue prevState?.next = newValue ? state : nil } ) state.isActive_SwiftUI = _binding let binding = Binding(get: _binding.get, set: _binding.set) return transition.move(binding, screenState: state, actionView: actionView(binding), context: context, completion: completion) .onDisappear { [weak state] in state?.previous = nil } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public protocol ScreenPath_SwiftUI: PathProvider where PathFrom == T.PathFrom { associatedtype T: SwiftUICompatibleTransition func __move() -> AnyPublisher<ContentScreenState<T.To.NestedScreen>?, Never>? } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct StartPath_SwiftUI<T>: ScreenPath, ScreenPathPrivate, ScreenPath_SwiftUI where T: SwiftUICompatibleTransition { public typealias From = UnavailableContentScreen<Void> public typealias To = T.To let change: Change let keyPath: PartialKeyPath<T.From.PathFrom> let transition: T let state: ContentScreenState<T.From.NestedScreen>? var _state: AnyScreenState? { state } enum Change { case isActive case selectedIndex(Int) } public subscript<T>(next path: KeyPath<To.PathFrom, T>) -> T { transition[next: path] } public func index(of keyPath: PartialKeyPath<To.PathFrom>) -> Int { transition.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<To.PathFrom> { transition.keyPath(at: index) } public func __move() -> AnyPublisher<ContentScreenState<T.To.NestedScreen>?, Never>? { guard let _state = state?[child: keyPath, T.To.self] else { return nil } switch change { case .isActive: guard let swiftUI_state = _state.isActive_SwiftUI else { return nil } swiftUI_state.wrappedValue = true case .selectedIndex(let index): state?.selectedIndex_SwiftUI?.wrappedValue = index } return Future { promise in DispatchQueue.main.async { promise(.success(_state)) } }.eraseToAnyPublisher() } public func move(from surface: From.Content, completion: (() -> Void)?) -> Void { state?.next?._backFurther(completion: nil) var cancellable: AnyCancellable? cancellable = __move()?.sink(receiveValue: { (state) in cancellable?.cancel() cancellable = nil completion?() }) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public struct NextPath_SwiftUI<Prev, T>: ScreenPath, ScreenPathPrivate, ScreenPath_SwiftUI where Prev: ScreenPath & ScreenPath_SwiftUI, T: SwiftUICompatibleTransition, Prev.To.NestedScreen == T.From { public typealias From = Prev.From public typealias To = T.To let change: Change let keyPath: PartialKeyPath<Prev.T.PathFrom> let prev: Prev let transition: T let state: ContentScreenState<T.From.NestedScreen>? var _state: AnyScreenState? { state } enum Change { case isActive case selectedIndex(Int) } public subscript<T>(next path: KeyPath<To.PathFrom, T>) -> T { transition[next: path] } public func index(of keyPath: PartialKeyPath<To.PathFrom>) -> Int { transition.index(of: keyPath) } public func keyPath(at index: Int) -> PartialKeyPath<To.PathFrom> { transition.keyPath(at: index) } public func __move() -> AnyPublisher<ContentScreenState<T.To.NestedScreen>?, Never>? { guard let prevFuture = prev.__move() else { return nil } return prevFuture.flatMap { (prevState) -> Future<ContentScreenState<T.To.NestedScreen>?, Never> in guard let _state = prevState?[child: keyPath, T.To.self] else { return Future { $0(.success(nil)) } } switch change { case .isActive: guard let swiftUI_state = _state.isActive_SwiftUI else { return Future { $0(.success(nil)) } } swiftUI_state.wrappedValue = true case .selectedIndex(let index): prevState?.selectedIndex_SwiftUI?.wrappedValue = index } return Future { promise in DispatchQueue.main.async { promise(.success(_state)) } } }.eraseToAnyPublisher() } public func move(from surface: Prev.From.Content, completion: (() -> Void)?) -> Void { state?.next?._backFurther(completion: nil) var cancellable: AnyCancellable? cancellable = __move()?.sink(receiveValue: { (state) in cancellable?.cancel() cancellable = nil completion?() }) } } extension Router { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<T>(move path: KeyPath<PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From, T.To.Content: View { StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: self[next: path], state: state) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<T>(move path: KeyPath<PathFrom, Optional<T>>) -> StartPath_SwiftUI<T>? where T: SwiftUICompatibleTransition, T.From == From, T.To.Content: View { guard let transition = self[next: path] else { return nil } return StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: transition, state: state) } // @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) // public func move<T>(_ path: KeyPath<PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From, T.To.Content: View { // StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: self[next: path], state: state) // } // @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) // public func move<T>(_ path: KeyPath<PathFrom, Optional<T>>) -> StartPath_SwiftUI<T>? where T: SwiftUICompatibleTransition, T.From == From, T.To.Content: View { // guard let transition = self[next: path] else { return nil } // return StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: transition, state: state) // } } extension ScreenPath { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<U>(move path: KeyPath<To.PathFrom, U>) -> NextPath_SwiftUI<Self, U> where U: SwiftUICompatibleTransition, U.To.Content: View { let next = NextPath_SwiftUI<Self, U>(change: .isActive, keyPath: path, prev: self, transition: self[next: path], state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<U.From.NestedScreen>) return next } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<U>(move path: KeyPath<To.PathFrom, Optional<U>>) -> NextPath_SwiftUI<Self, U>? where U: SwiftUICompatibleTransition, U.To.Content: View { guard let transition = self[next: path] else { return nil } return NextPath_SwiftUI<Self, U>(change: .isActive, keyPath: path, prev: self, transition: transition, state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<U.From.NestedScreen>) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<U>(_ path: KeyPath<To.PathFrom, U>) -> NextPath_SwiftUI<Self, U> where U: SwiftUICompatibleTransition, U.To.Content: View { let next = NextPath_SwiftUI<Self, U>(change: .isActive, keyPath: path, prev: self, transition: self[next: path], state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<U.From.NestedScreen>) return next } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func move<U>(_ path: KeyPath<To.PathFrom, Optional<U>>) -> NextPath_SwiftUI<Self, U>? where U: SwiftUICompatibleTransition, U.To.Content: View { guard let transition = self[next: path] else { return nil } return NextPath_SwiftUI<Self, U>(change: .isActive, keyPath: path, prev: self, transition: transition, state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<U.From.NestedScreen>) } } extension Router where From.Content: _TabsViewIdentity { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<T>(select path: KeyPath<PathFrom, T>) -> StartPath_SwiftUI<Tab.SwiftUITransition<From, T>> { let screen = self[next: path] let transition = Tab.SwiftUITransition<From, T>(to: screen) return StartPath_SwiftUI<Tab.SwiftUITransition<From, T>>(change: .selectedIndex(index(of: path)), keyPath: path, transition: transition, state: state) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func select<T>(_ path: KeyPath<PathFrom, T>) -> StartPath_SwiftUI<Tab.SwiftUITransition<From, T>> { let screen = self[next: path] let transition = Tab.SwiftUITransition<From, T>(to: screen) return StartPath_SwiftUI<Tab.SwiftUITransition<From, T>>(change: .selectedIndex(index(of: path)), keyPath: path, transition: transition, state: state) } } extension ScreenPath where To.Content: _TabsViewIdentity { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public subscript<T>(select path: KeyPath<PathFrom, T>) -> NextPath_SwiftUI<Self, Tab.SwiftUITransition<To, T>> { let screen = self[next: path] let transition = Tab.SwiftUITransition<To, T>(to: screen) return NextPath_SwiftUI<Self, Tab.SwiftUITransition<To, T>>(change: .selectedIndex(index(of: path)), keyPath: path, prev: self, transition: transition, state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<To>) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public func select<T>(_ path: KeyPath<PathFrom, T>) -> NextPath_SwiftUI<Self, Tab.SwiftUITransition<To, T>> { let screen = self[next: path] let transition = Tab.SwiftUITransition<To, T>(to: screen) return NextPath_SwiftUI<Self, Tab.SwiftUITransition<To, T>>(change: .selectedIndex(index(of: path)), keyPath: path, prev: self, transition: transition, state: (self as! ScreenPathPrivate)._state?.next as? ContentScreenState<To>) } } /// ------------ @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension RootTransition: SwiftUICompatibleTransition where From.Root.Content: View { public func move<V>(_ state: Binding<Bool>, screenState: ContentScreenState<From.Root.NestedScreen>, actionView: V, context: From.Context, completion: (() -> Void)?) -> AnyView where V : View { AnyView(to.makeContent(context, router: Router(from: to, state: screenState)).contentWrapper) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension RootRouter where From.Root.Content: View { public subscript<T>(move path: KeyPath<From.Root.PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From.Root { StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: from[next: \.root][next: path], state: state.next as? ContentScreenState<From.Root.NestedScreen>) } public func move<T>(_ path: KeyPath<From.Root.PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From.Root { StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: from[next: \.root][next: path], state: state.next as? ContentScreenState<From.Root.NestedScreen>) } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension RootRouter where From.Root.Content: Scene { public subscript<T>(move path: KeyPath<From.Root.PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From.Root { StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: from[next: \.root][next: path], state: state.next as? ContentScreenState<From.Root.NestedScreen>) } public func move<T>(_ path: KeyPath<From.Root.PathFrom, T>) -> StartPath_SwiftUI<T> where T: SwiftUICompatibleTransition, T.From == From.Root { StartPath_SwiftUI<T>(change: .isActive, keyPath: path, transition: from[next: \.root][next: path], state: state.next as? ContentScreenState<From.Root.NestedScreen>) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension RootRouter where From.Root.NestedScreen.Content: _TabsViewIdentity { public subscript<S>(select path: KeyPath<From.Root.PathFrom, S>) -> StartPath_SwiftUI<Tab.SwiftUITransition<From.Root.NestedScreen, S>> { let root = from[next: \.root] let transition = Tab.SwiftUITransition<From.Root.NestedScreen, S>(to: root[next: path]) return StartPath_SwiftUI<Tab.SwiftUITransition<From.Root.NestedScreen, S>>(change: .selectedIndex(root.index(of: path)), keyPath: path, transition: transition, state: state.next as? ContentScreenState<From.Root.NestedScreen>) } public func select<S>(_ path: KeyPath<From.Root.PathFrom, S>) -> StartPath_SwiftUI<Tab.SwiftUITransition<From.Root.NestedScreen, S>> { let root = from[next: \.root] let transition = Tab.SwiftUITransition<From.Root.NestedScreen, S>(to: root[next: path]) return StartPath_SwiftUI<Tab.SwiftUITransition<From.Root.NestedScreen, S>>(change: .selectedIndex(root.index(of: path)), keyPath: path, transition: transition, state: state.next as? ContentScreenState<From.Root.NestedScreen>) } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension RootScreen where Root.Content: Scene { public func makeBody(_ context: Root.Context) -> some Scene { let nextState = TransitionState<Self, Root>() nextState.previous = state state.next = nextState return root.makeContent(context, router: Router(from: root, state: nextState)).contentWrapper } } #endif
51.735849
236
0.65671
64c51bbf7559e6b5cdf64ad33d5078c02adf4144
911
// // HomeRemoteTests.swift // HomeRemoteTests // // Created by Greg Statton on 5/19/15. // Copyright (c) 2015 Greg Statton. All rights reserved. // import UIKit import XCTest class HomeRemoteTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.621622
111
0.618002
56faed3e5ccd61ef75f74b46145355cd74c26de2
483
public final class TrieNode<T: Hashable> { public var value: T? public weak var parent: TrieNode? public var children: [T: TrieNode] = [:] public var isTerminating = false init() {} init(value: T, parent: TrieNode? = nil) { self.value = value self.parent = parent } } // MARK: - Insertion public extension TrieNode { func add(child: T) { guard children[child] == nil else { return } children[child] = TrieNode(value: child, parent: self) } }
21.954545
58
0.641822
75dd9038d2c4c8124b9dec477dc95f02b65e0f2f
20,883
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Rocket.Authorization { /** Refresh an account or profile level authorization token which is marked as refreshable. */ public enum RefreshToken { public static let service = APIService<Response>(id: "refreshToken", tag: "authorization", method: "POST", path: "/authorization/refresh", hasBody: true, securityRequirements: []) /** If you specify a cookie type then a content filter cookie will be returned along with the token(s). This is only really intended for web based clients which need to pass the cookies to a server to render a page based on the users content filters, e.g subscription code. If type `Session` the cookie will be session based. If type `Persistent` the cookie will have a medium term lifespan. If undefined no cookies will be set. */ public enum CookieType: String, Codable, Equatable, CaseIterable { case session = "Session" case persistent = "Persistent" } public final class Request: APIRequest<Response> { /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Body: APIModel { /** If you specify a cookie type then a content filter cookie will be returned along with the token(s). This is only really intended for web based clients which need to pass the cookies to a server to render a page based on the users content filters, e.g subscription code. If type `Session` the cookie will be session based. If type `Persistent` the cookie will have a medium term lifespan. If undefined no cookies will be set. */ public enum CookieType: String, Codable, Equatable, CaseIterable { case session = "Session" case persistent = "Persistent" } /** The token to refresh. */ public var token: String /** If you specify a cookie type then a content filter cookie will be returned along with the token(s). This is only really intended for web based clients which need to pass the cookies to a server to render a page based on the users content filters, e.g subscription code. If type `Session` the cookie will be session based. If type `Persistent` the cookie will have a medium term lifespan. If undefined no cookies will be set. */ public var cookieType: CookieType? public init(token: String, cookieType: CookieType? = nil) { self.token = token self.cookieType = cookieType } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) token = try container.decode("token") cookieType = try container.decodeIfPresent("cookieType") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(token, forKey: "token") try container.encodeIfPresent(cookieType, forKey: "cookieType") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Body else { return false } guard self.token == object.token else { return false } guard self.cookieType == object.cookieType else { return false } return true } public static func == (lhs: Body, rhs: Body) -> Bool { return lhs.isEqual(to: rhs) } } public var body: Body public init(body: Body, encoder: RequestEncoder? = nil) { self.body = body super.init(service: RefreshToken.service) { defaultEncoder in return try (encoder ?? defaultEncoder).encode(body) } } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status200: APIModel { /** The type of the token. */ public enum `Type`: String, Codable, Equatable, CaseIterable { case userAccount = "UserAccount" case userProfile = "UserProfile" } /** The token value used for authenticated requests. */ public var value: String /** True if this token can be refreshed, false if not. */ public var refreshable: Bool /** The timestamp this token expires. */ public var expirationDate: DateTime /** The type of the token. */ public var type: `Type` public init(value: String, refreshable: Bool, expirationDate: DateTime, type: `Type`) { self.value = value self.refreshable = refreshable self.expirationDate = expirationDate self.type = type } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) value = try container.decode("value") refreshable = try container.decode("refreshable") expirationDate = try container.decode("expirationDate") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(value, forKey: "value") try container.encode(refreshable, forKey: "refreshable") try container.encode(expirationDate, forKey: "expirationDate") try container.encode(type, forKey: "type") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status200 else { return false } guard self.value == object.value else { return false } guard self.refreshable == object.refreshable else { return false } guard self.expirationDate == object.expirationDate else { return false } guard self.type == object.type else { return false } return true } public static func == (lhs: Status200, rhs: Status200) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status400: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status400 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status400, rhs: Status400) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status401: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status401 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status401, rhs: Status401) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status403: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status403 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status403, rhs: Status403) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status404: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status404 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status404, rhs: Status404) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class Status500: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status500 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status500, rhs: Status500) -> Bool { return lhs.isEqual(to: rhs) } } /** Refresh an account or profile level authorization token which is marked as refreshable. */ public class DefaultResponse: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? DefaultResponse else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: DefaultResponse, rhs: DefaultResponse) -> Bool { return lhs.isEqual(to: rhs) } } public typealias SuccessType = Status200 /** OK */ case status200(Status200) /** Bad request. */ case status400(Status400) /** Invalid access token. */ case status401(Status401) /** Forbidden. */ case status403(Status403) /** Not found. */ case status404(Status404) /** Internal server error. */ case status500(Status500) /** Service error. */ case defaultResponse(statusCode: Int, DefaultResponse) public var success: Status200? { switch self { case .status200(let response): return response default: return nil } } public var response: Any { switch self { case .status200(let response): return response case .status400(let response): return response case .status401(let response): return response case .status403(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status400: return 400 case .status401: return 401 case .status403: return 403 case .status404: return 404 case .status500: return 500 case .defaultResponse(let statusCode, _): return statusCode } } public var successful: Bool { switch self { case .status200: return true case .status400: return false case .status401: return false case .status403: return false case .status404: return false case .status500: return false case .defaultResponse: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(Status200.self, from: data)) case 400: self = try .status400(decoder.decode(Status400.self, from: data)) case 401: self = try .status401(decoder.decode(Status401.self, from: data)) case 403: self = try .status403(decoder.decode(Status403.self, from: data)) case 404: self = try .status404(decoder.decode(Status404.self, from: data)) case 500: self = try .status500(decoder.decode(Status500.self, from: data)) default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(DefaultResponse.self, from: data)) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
42.273279
187
0.532826
c1161e6cb07c5310883fa33751a2560ec93e729c
4,486
import UIKit import SnapKit import ThemeKit import HUD import Chart import ComponentKit class MarketOverviewMetricsCell: UITableViewCell { static let cellHeight: CGFloat = 240 weak var viewController: UIViewController? private let totalMarketCapView: MarketMetricView private let volume24hView: MarketMetricView private let deFiCapView: MarketMetricView private let deFiTvlView: MarketMetricView init(chartConfiguration: ChartConfiguration) { totalMarketCapView = MarketMetricView(configuration: chartConfiguration) volume24hView = MarketMetricView(configuration: chartConfiguration) deFiCapView = MarketMetricView(configuration: chartConfiguration) deFiTvlView = MarketMetricView(configuration: chartConfiguration) super.init(style: .default, reuseIdentifier: nil) backgroundColor = .clear selectionStyle = .none contentView.addSubview(totalMarketCapView) totalMarketCapView.snp.makeConstraints { maker in maker.top.equalToSuperview().inset(CGFloat.margin12) maker.leading.equalToSuperview().inset(CGFloat.margin16) maker.height.equalTo(MarketMetricView.height) } contentView.addSubview(volume24hView) volume24hView.snp.makeConstraints { maker in maker.top.equalToSuperview().inset(CGFloat.margin12) maker.leading.equalTo(totalMarketCapView.snp.trailing).offset(CGFloat.margin8) maker.trailing.equalToSuperview().inset(CGFloat.margin16) maker.width.equalTo(totalMarketCapView.snp.width) maker.height.equalTo(MarketMetricView.height) } contentView.addSubview(deFiCapView) deFiCapView.snp.makeConstraints { maker in maker.top.equalTo(totalMarketCapView.snp.bottom).offset(CGFloat.margin8) maker.leading.equalToSuperview().inset(CGFloat.margin16) maker.height.equalTo(MarketMetricView.height) } contentView.addSubview(deFiTvlView) deFiTvlView.snp.makeConstraints { maker in maker.top.equalTo(volume24hView.snp.bottom).offset(CGFloat.margin8) maker.leading.equalTo(deFiCapView.snp.trailing).offset(CGFloat.margin8) maker.trailing.equalToSuperview().inset(CGFloat.margin16) maker.width.equalTo(deFiCapView.snp.width) maker.height.equalTo(MarketMetricView.height) } totalMarketCapView.onTap = { [weak self] in self?.onTap(metricType: .totalMarketCap) } volume24hView.onTap = { [weak self] in self?.onTap(metricType: .volume24h) } deFiCapView.onTap = { [weak self] in self?.onTap(metricType: .defiCap) } deFiTvlView.onTap = { [weak self] in self?.onTap(metricType: .tvlInDefi) } totalMarketCapView.title = "market.total_market_cap".localized volume24hView.title = "market.24h_volume".localized deFiCapView.title = "market.defi_cap".localized deFiTvlView.title = "market.defi_tvl".localized } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func onTap(metricType: MarketGlobalModule.MetricsType) { let viewController = MarketGlobalMetricModule.viewController(type: metricType) self.viewController?.present(viewController, animated: true) } } extension MarketOverviewMetricsCell { func set(viewItem: MarketOverviewViewModel.GlobalMarketViewItem) { totalMarketCapView.set( value: viewItem.totalMarketCap.value, diff: viewItem.totalMarketCap.diff, chartData: viewItem.totalMarketCap.chartData, trend: viewItem.totalMarketCap.chartTrend ) volume24hView.set( value: viewItem.volume24h.value, diff: viewItem.volume24h.diff, chartData: viewItem.volume24h.chartData, trend: viewItem.volume24h.chartTrend ) deFiCapView.set( value: viewItem.defiCap.value, diff: viewItem.defiCap.diff, chartData: viewItem.defiCap.chartData, trend: viewItem.defiCap.chartTrend ) deFiTvlView.set( value: viewItem.defiTvl.value, diff: viewItem.defiTvl.diff, chartData: viewItem.defiTvl.chartData, trend: viewItem.defiTvl.chartTrend ) } }
38.672414
94
0.679447
fe01bdbf003b058edd0ea018c6a582c020a8d759
1,947
// // CKContactListMatrixCell.swift // Riot // // Created by Sinbad Flyce on 1/28/19. // Copyright © 2019 matrix.org. All rights reserved. // import Foundation final class CKContactListMatrixCell: CKContactListBaseCell { // MARK: - OUTLET @IBOutlet weak var photoView: MXKImageView! @IBOutlet weak var displayNameLabel: UILabel! @IBOutlet weak var statusView: UIView! // MARK: - OVERRIDE override func awakeFromNib() { super.awakeFromNib() self.displayNameLabel.backgroundColor = UIColor.clear self.photoView.defaultBackgroundColor = .clear self.photoView.layer.cornerRadius = (self.photoView.bounds.height) / 2 self.photoView.clipsToBounds = true self.photoView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin] self.photoView.contentMode = .scaleAspectFill self.statusView.layer.cornerRadius = self.statusView.bounds.height / 2 self.statusView.layer.borderColor = UIColor.white.cgColor self.statusView.layer.borderWidth = 1 self.displayNameLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor } } // MARK: - PRIVATE public var status: Int { set { self.statusView.tag = newValue if newValue > 0 { self.statusView.backgroundColor = CKColor.Misc.onlineColor } else { self.statusView.backgroundColor = CKColor.Misc.offlineColor } } get { return self.statusView.tag } } // MARK: - OVERRIDE override func getMXKImageView() -> MXKImageView! { return self.photoView } override func prepareForReuse() { super.prepareForReuse() self.status = 0 } // MARK: - PUBLIC }
28.632353
161
0.630714
790508583c257d80a29e949c35d1849e8832ea39
639
// // IniCodingKey.swift // ParsINI // // Created by Florian Friedrich on 02.10.17. // Copyright © 2017 ser.soft GmbH. All rights reserved. // struct IniCodingKey: CodingKey { let intValue: Int? let stringValue: String init(stringValue: String) { self.stringValue = stringValue self.intValue = nil } init(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } } extension IniCodingKey { static let `super` = IniCodingKey(stringValue: "super") }
19.96875
59
0.619718
fc21d7579abe5157a9d310580b1323429ca1fd78
8,364
// Copyright 2019-2020 CoreOffice contributors // // 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. // // Created by Max Desiatov on 16/03/2019. // public struct Styles: Codable, Equatable { public let numberFormats: NumberFormats? public let fonts: Fonts? public let fills: Fills? public let borders: Borders? public let cellStyleFormats: CellStyleFormats? public let cellFormats: CellFormats? public let differentialFormats: DifferentialFormats? public let tableStyles: TableStyles? public let cellStyles: CellStyles? public let colors: Colors? enum CodingKeys: String, CodingKey { case numberFormats = "numFmts" case fonts case fills case borders case cellStyleFormats = "cellStyleXfs" case cellFormats = "cellXfs" case differentialFormats = "dxfs" case cellStyles case tableStyles case colors } } public struct Color: Codable, Equatable { public let indexed: Int? public let auto: Int? public let rgb: String? } public struct NumberFormats: Codable, Equatable { public let items: [NumberFormat] public let count: Int enum CodingKeys: String, CodingKey { case items = "numFmt" case count } } public struct NumberFormat: Codable, Equatable { public let id: Int public let formatCode: String enum CodingKeys: String, CodingKey { case id = "numFmtId" case formatCode } } public struct Fonts: Codable, Equatable { public let items: [Font] public let count: Int enum CodingKeys: String, CodingKey { case items = "font" case count } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) count = try container.decode(Int.self, forKey: .count) items = try container.decode([Font?].self, forKey: .items) .map { $0 ?? Font() } } init(items: [Font], count: Int) { self.items = items self.count = count } } public struct Font: Codable, Equatable { public struct Size: Codable, Equatable { public let value: Double enum CodingKeys: String, CodingKey { case value = "val" } } public struct Name: Codable, Equatable { public let value: String enum CodingKeys: String, CodingKey { case value = "val" } } public struct Bold: Codable, Equatable { public let value: Bool? enum CodingKeys: String, CodingKey { case value = "val" } } public struct Italic: Codable, Equatable { public let value: Bool? enum CodingKeys: String, CodingKey { case value = "val" } } public struct Strike: Codable, Equatable { public let value: Bool? enum CodingKeys: String, CodingKey { case value = "val" } } public let size: Size? public let color: Color? public let name: Name? public let bold: Bold? public let italic: Italic? public let strike: Strike? enum CodingKeys: String, CodingKey { case size = "sz" case color case name case bold = "b" case italic = "i" case strike } init( size: Size? = nil, color: Color? = nil, name: Name? = nil, bold: Bold? = nil, italic: Italic? = nil, strike: Strike? = nil ) { self.size = size self.color = color self.name = name self.bold = bold self.italic = italic self.strike = strike } } public struct Fills: Codable, Equatable { public let items: [Fill] public let count: Int enum CodingKeys: String, CodingKey { case items = "fill" case count } } public struct Fill: Codable, Equatable { public let patternFill: PatternFill } public struct PatternFill: Codable, Equatable { public let patternType: String public let foregroundColor: Color? public let backgroundColor: Color? enum CodingKeys: String, CodingKey { case foregroundColor = "fgColor" case backgroundColor = "bgColor" case patternType } } public struct Borders: Codable, Equatable { public let items: [Border] public let count: Int enum CodingKeys: String, CodingKey { case items = "border" case count } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) count = try container.decode(Int.self, forKey: .count) items = try container.decode([Border?].self, forKey: .items) .map { $0 ?? Border() } } } public struct Border: Codable, Equatable { public struct Value: Codable, Equatable { public let color: Color? public let style: String? } public let left: Value? public let right: Value? public let top: Value? public let bottom: Value? public let diagonal: Value? public let horizontal: Value? public let vertical: Value? init() { left = nil right = nil top = nil bottom = nil diagonal = nil horizontal = nil vertical = nil } } public struct CellStyleFormats: Codable, Equatable { public let items: [Format] public let count: Int enum CodingKeys: String, CodingKey { case items = "xf" case count } } public struct CellFormats: Codable, Equatable { public let items: [Format] public let count: Int enum CodingKeys: String, CodingKey { case items = "xf" case count } } /** Storage for cell formatting properties. More details are available at [datypic.com](http://www.datypic.com/sc/ooxml/t-ssml_CT_Xf.html) */ public struct Format: Codable, Equatable { public struct Alignment: Codable, Equatable { public let vertical: String? public let horizontal: String? public let wrapText: Bool? } public let numberFormatId: Int public let borderId: Int? public let fillId: Int? public let fontId: Int public let applyNumberFormat: Bool? public let applyFont: Bool? public let applyFill: Bool? public let applyBorder: Bool? public let applyAlignment: Bool? public let applyProtection: Bool? public let alignment: Alignment? enum CodingKeys: String, CodingKey { case numberFormatId = "numFmtId" case borderId case fillId case fontId case applyNumberFormat case applyFont case applyFill case applyBorder case applyAlignment case applyProtection case alignment } } public struct CellStyles: Codable, Equatable { public let items: [CellStyle] public let count: Int enum CodingKeys: String, CodingKey { case items = "cellStyle" case count } } public struct CellStyle: Codable, Equatable { public let name: String public let formatId: Int public let builtinId: Int enum CodingKeys: String, CodingKey { case formatId = "xfId" case name case builtinId } } /** Specifies a subset of formatting instead of applying formatting globally. More details are available at [officeopenxml.com](http://officeopenxml.com/SSstyles.php). */ public struct DifferentialFormats: Codable, Equatable { public let items: [Format] public let count: Int enum CodingKeys: String, CodingKey { case items = "dxf" case count } } public struct TableStyles: Codable, Equatable { public let count: Int public let items: [TableStyle] enum CodingKeys: String, CodingKey { case count case items = "tableStyle" } } public struct TableStyle: Codable, Equatable { public struct Element: Codable, Equatable { public let type: String } public let pivot: Bool public let name: String public let count: Int public let elements: [Element] enum CodingKeys: String, CodingKey { case pivot case count case name case elements = "tableStyleElement" } } public struct Colors: Codable, Equatable { public struct Indexed: Codable, Equatable { public let rgbColors: [Color] enum CodingKeys: String, CodingKey { case rgbColors = "rgbColor" } } public let indexed: Indexed enum CodingKeys: String, CodingKey { case indexed = "indexedColors" } }
22.666667
90
0.686155
1ec907c871d68e0275a8bba25f6b46ea97ccd6ad
47,607
/* Copyright 2018 JDCLOUD.COM 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. pipeline API OF Pipeline Create|Update|Read|Delete|Execute OpenAPI spec version: v1 Contact: NOTE: This class is auto generated by the jdcloud code generator program. */ import Foundation import JDCloudSDKCore import JDCloudSDKCommon /// 获取可选的源提供商 public class GetSourceProvidersRequest:JdCloudRequest { } public class GetOperationProvidersResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetOperationProvidersResult?; enum GetOperationProvidersResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetOperationProvidersResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetOperationProvidersResult?.self, forKey: .result) ?? nil } } public extension GetOperationProvidersResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetOperationProvidersResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 获取可选的源提供商 public class GetSourceProvidersResult:NSObject,JdCloudResult { /// 记录数 var totalCount:Int? /// 源提供商列表 var providers:[NameLabelPair?]? public override init(){ super.init() } enum GetSourceProvidersResultCodingKeys: String, CodingKey { case totalCount case providers } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetSourceProvidersResultCodingKeys.self) if decoderContainer.contains(.totalCount) { self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount) } if decoderContainer.contains(.providers) { self.providers = try decoderContainer.decode([NameLabelPair?]?.self, forKey: .providers) } } } public extension GetSourceProvidersResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetSourceProvidersResultCodingKeys.self) try encoderContainer.encode(totalCount, forKey: .totalCount) try encoderContainer.encode(providers, forKey: .providers) } } public class GetRegionsResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetRegionsResult?; enum GetRegionsResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetRegionsResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetRegionsResult?.self, forKey: .result) ?? nil } } public extension GetRegionsResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetRegionsResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 操作提供商 public class GetOperationProvidersResult:NSObject,JdCloudResult { /// 记录数 var totalCount:Int? /// 操作提供商列表 var providers:[NameLabelPair?]? public override init(){ super.init() } enum GetOperationProvidersResultCodingKeys: String, CodingKey { case totalCount case providers } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetOperationProvidersResultCodingKeys.self) if decoderContainer.contains(.totalCount) { self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount) } if decoderContainer.contains(.providers) { self.providers = try decoderContainer.decode([NameLabelPair?]?.self, forKey: .providers) } } } public extension GetOperationProvidersResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetOperationProvidersResultCodingKeys.self) try encoderContainer.encode(totalCount, forKey: .totalCount) try encoderContainer.encode(providers, forKey: .providers) } } /// 操作提供商 public class GetOperationProvidersRequest:JdCloudRequest { /// 源提供商类型 var type:String? enum GetOperationProvidersRequestRequestCodingKeys: String, CodingKey { case type } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetOperationProvidersRequestRequestCodingKeys.self) try encoderContainer.encode(type, forKey: .type) } } public class GetSourceProvidersResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetSourceProvidersResult?; enum GetSourceProvidersResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetSourceProvidersResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetSourceProvidersResult?.self, forKey: .result) ?? nil } } public extension GetSourceProvidersResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetSourceProvidersResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 可选地域 public class GetRegionsRequest:JdCloudRequest { /// 源提供商类型 var type:String? enum GetRegionsRequestRequestCodingKeys: String, CodingKey { case type } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetRegionsRequestRequestCodingKeys.self) try encoderContainer.encode(type, forKey: .type) } } /// 可选地域 public class GetRegionsResult:NSObject,JdCloudResult { /// 可选地域总数 var totalCount:Int? /// 可选地域列表 var regions:[NameLabelPair?]? public override init(){ super.init() } enum GetRegionsResultCodingKeys: String, CodingKey { case totalCount case regions } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetRegionsResultCodingKeys.self) if decoderContainer.contains(.totalCount) { self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount) } if decoderContainer.contains(.regions) { self.regions = try decoderContainer.decode([NameLabelPair?]?.self, forKey: .regions) } } } public extension GetRegionsResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetRegionsResultCodingKeys.self) try encoderContainer.encode(totalCount, forKey: .totalCount) try encoderContainer.encode(regions, forKey: .regions) } } /// 查询多个指定流水线执行及状态信息 /// /// public class ManualActionResult:NSObject,JdCloudResult { /// InstanceUuid var instanceUuid:String? /// ActionUuid var actionUuid:String? public override init(){ super.init() } enum ManualActionResultCodingKeys: String, CodingKey { case instanceUuid case actionUuid } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: ManualActionResultCodingKeys.self) if decoderContainer.contains(.instanceUuid) { self.instanceUuid = try decoderContainer.decode(String?.self, forKey: .instanceUuid) } if decoderContainer.contains(.actionUuid) { self.actionUuid = try decoderContainer.decode(String?.self, forKey: .actionUuid) } } } public extension ManualActionResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: ManualActionResultCodingKeys.self) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) try encoderContainer.encode(actionUuid, forKey: .actionUuid) } } /// 查询多个指定流水线执行及状态信息 /// /// public class ManualActionRequest:JdCloudRequest { /// 手动设置的状态,如SUCCESS,FAILED var status:String /// 流水线uuid var uuid:String /// 流水线实例uuid var instanceUuid:String /// 动作UUID var actionUuid:String public init(regionId: String,status:String,uuid:String,instanceUuid:String,actionUuid:String){ self.status = status self.uuid = uuid self.instanceUuid = instanceUuid self.actionUuid = actionUuid super.init(regionId: regionId) } enum ManualActionRequestRequestCodingKeys: String, CodingKey { case status case uuid case instanceUuid case actionUuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: ManualActionRequestRequestCodingKeys.self) try encoderContainer.encode(status, forKey: .status) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) try encoderContainer.encode(actionUuid, forKey: .actionUuid) } } public class ManualActionResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:ManualActionResult?; enum ManualActionResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: ManualActionResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(ManualActionResult?.self, forKey: .result) ?? nil } } public extension ManualActionResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: ManualActionResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 停止流水线的一次执行 public class StopPipelineInstanceResult:NSObject,JdCloudResult { /// InstanceUuid var instanceUuid:String? /// ActionUuid var actionUuid:String? public override init(){ super.init() } enum StopPipelineInstanceResultCodingKeys: String, CodingKey { case instanceUuid case actionUuid } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: StopPipelineInstanceResultCodingKeys.self) if decoderContainer.contains(.instanceUuid) { self.instanceUuid = try decoderContainer.decode(String?.self, forKey: .instanceUuid) } if decoderContainer.contains(.actionUuid) { self.actionUuid = try decoderContainer.decode(String?.self, forKey: .actionUuid) } } } public extension StopPipelineInstanceResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StopPipelineInstanceResultCodingKeys.self) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) try encoderContainer.encode(actionUuid, forKey: .actionUuid) } } public class GetPipelineInstanceResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetPipelineInstanceResult?; enum GetPipelineInstanceResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstanceResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetPipelineInstanceResult?.self, forKey: .result) ?? nil } } public extension GetPipelineInstanceResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstanceResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } public class GetPipelineInstancesByUuidsResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetPipelineInstancesByUuidsResult?; enum GetPipelineInstancesByUuidsResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstancesByUuidsResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetPipelineInstancesByUuidsResult?.self, forKey: .result) ?? nil } } public extension GetPipelineInstancesByUuidsResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesByUuidsResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } public class GetPipelineInstancesResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetPipelineInstancesResult?; enum GetPipelineInstancesResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstancesResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetPipelineInstancesResult?.self, forKey: .result) ?? nil } } public extension GetPipelineInstancesResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 根据条件查询流水线执行历史 /// /// public class GetPipelineInstancesByUuidsResult:NSObject,JdCloudResult { /// PipelineInstances var pipelineInstances:[PipelineInstance?]? public override init(){ super.init() } enum GetPipelineInstancesByUuidsResultCodingKeys: String, CodingKey { case pipelineInstances } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstancesByUuidsResultCodingKeys.self) if decoderContainer.contains(.pipelineInstances) { self.pipelineInstances = try decoderContainer.decode([PipelineInstance?]?.self, forKey: .pipelineInstances) } } } public extension GetPipelineInstancesByUuidsResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesByUuidsResultCodingKeys.self) try encoderContainer.encode(pipelineInstances, forKey: .pipelineInstances) } } /// 查询流水线执行结果及状态信息 public class GetPipelineInstanceRequest:JdCloudRequest { /// 流水线执行的状态,如果isSimple是true,只显示每个stage的状态, 而stage中的action状态将被忽略 var isSimple:Bool? /// 流水线uuid var uuid:String /// 流水线uuid执行历史记录的uuid, 也可以用 latest 字符串代替uuid, 来取得最近的状态 var instanceUuid:String public init(regionId: String,uuid:String,instanceUuid:String){ self.uuid = uuid self.instanceUuid = instanceUuid super.init(regionId: regionId) } enum GetPipelineInstanceRequestRequestCodingKeys: String, CodingKey { case isSimple case uuid case instanceUuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstanceRequestRequestCodingKeys.self) try encoderContainer.encode(isSimple, forKey: .isSimple) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) } } /// 查询流水线执行历史列表 public class GetPipelineInstancesResult:NSObject,JdCloudResult { /// TotalCount var totalCount:Int? /// Instances var instances:[PipelineInstance?]? public override init(){ super.init() } enum GetPipelineInstancesResultCodingKeys: String, CodingKey { case totalCount case instances } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstancesResultCodingKeys.self) if decoderContainer.contains(.totalCount) { self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount) } if decoderContainer.contains(.instances) { self.instances = try decoderContainer.decode([PipelineInstance?]?.self, forKey: .instances) } } } public extension GetPipelineInstancesResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesResultCodingKeys.self) try encoderContainer.encode(totalCount, forKey: .totalCount) try encoderContainer.encode(instances, forKey: .instances) } } /// 查询流水线执行结果及状态信息 public class GetPipelineInstanceResult:NSObject,JdCloudResult { /// PipelineInstance var pipelineInstance:PipelineInstance? public override init(){ super.init() } enum GetPipelineInstanceResultCodingKeys: String, CodingKey { case pipelineInstance } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineInstanceResultCodingKeys.self) if decoderContainer.contains(.pipelineInstance) { self.pipelineInstance = try decoderContainer.decode(PipelineInstance?.self, forKey: .pipelineInstance) } } } public extension GetPipelineInstanceResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstanceResultCodingKeys.self) try encoderContainer.encode(pipelineInstance, forKey: .pipelineInstance) } } public class StopPipelineInstanceResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:StopPipelineInstanceResult?; enum StopPipelineInstanceResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: StopPipelineInstanceResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(StopPipelineInstanceResult?.self, forKey: .result) ?? nil } } public extension StopPipelineInstanceResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StopPipelineInstanceResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 查询流水线执行历史列表 public class GetPipelineInstancesRequest:JdCloudRequest { /// 页码;默认为1 var pageNumber:Int? /// 分页大小;默认为10;取值范围[10, 100] var pageSize:Int? /// 流水线uuid var uuid:String public init(regionId: String,uuid:String){ self.uuid = uuid super.init(regionId: regionId) } enum GetPipelineInstancesRequestRequestCodingKeys: String, CodingKey { case pageNumber case pageSize case uuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesRequestRequestCodingKeys.self) try encoderContainer.encode(pageNumber, forKey: .pageNumber) try encoderContainer.encode(pageSize, forKey: .pageSize) try encoderContainer.encode(uuid, forKey: .uuid) } } /// 根据条件查询流水线执行历史 /// /// public class GetPipelineInstancesByUuidsRequest:JdCloudRequest { /// 流水线执行实例ID,多个ID用逗号分隔 var uuids:String /// 流水线执行的状态,如果isSimple是true,只显示每个stage的状态, 而stage中的action状态将被忽略 var isSimple:Bool? /// 页码;默认为1 var pageNumber:Int? /// 分页大小;默认为10;取值范围[10, 100] var pageSize:Int? /// Sorts var sorts:[Sort?]? /// 根据流水线名称查询 var filters:[Filter?]? public init(regionId: String,uuids:String){ self.uuids = uuids super.init(regionId: regionId) } enum GetPipelineInstancesByUuidsRequestRequestCodingKeys: String, CodingKey { case uuids case isSimple case pageNumber case pageSize case sorts case filters } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineInstancesByUuidsRequestRequestCodingKeys.self) try encoderContainer.encode(uuids, forKey: .uuids) try encoderContainer.encode(isSimple, forKey: .isSimple) try encoderContainer.encode(pageNumber, forKey: .pageNumber) try encoderContainer.encode(pageSize, forKey: .pageSize) try encoderContainer.encode(sorts, forKey: .sorts) try encoderContainer.encode(filters, forKey: .filters) } } /// 停止流水线的一次执行 public class StopPipelineInstanceRequest:JdCloudRequest { /// 流水线uuid var uuid:String /// 流水线执行的uuid var instanceUuid:String public init(regionId: String,uuid:String,instanceUuid:String){ self.uuid = uuid self.instanceUuid = instanceUuid super.init(regionId: regionId) } enum StopPipelineInstanceRequestRequestCodingKeys: String, CodingKey { case uuid case instanceUuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StopPipelineInstanceRequestRequestCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) } } public class ReadFileResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:ReadFileResult?; enum ReadFileResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: ReadFileResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(ReadFileResult?.self, forKey: .result) ?? nil } } public extension ReadFileResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: ReadFileResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 上传文件,返回文件内容 public class ReadFileRequest:JdCloudRequest { } /// 上传文件,返回文件内容 public class ReadFileResult:NSObject,JdCloudResult { /// Result var result:Bool? /// Contents var contents:String? public override init(){ super.init() } enum ReadFileResultCodingKeys: String, CodingKey { case result case contents } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: ReadFileResultCodingKeys.self) if decoderContainer.contains(.result) { self.result = try decoderContainer.decode(Bool?.self, forKey: .result) } if decoderContainer.contains(.contents) { self.contents = try decoderContainer.decode(String?.self, forKey: .contents) } } } public extension ReadFileResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: ReadFileResultCodingKeys.self) try encoderContainer.encode(result, forKey: .result) try encoderContainer.encode(contents, forKey: .contents) } } public class GetLimitsResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetLimitsResult?; enum GetLimitsResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetLimitsResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetLimitsResult?.self, forKey: .result) ?? nil } } public extension GetLimitsResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetLimitsResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 查询用户限制 public class GetLimitsRequest:JdCloudRequest { } /// 查询用户限制 public class GetLimitsResult:NSObject,JdCloudResult { /// 流水线数量限制 var numberLimit:Int? /// 是否可以创建 var canCreate:Bool? public override init(){ super.init() } enum GetLimitsResultCodingKeys: String, CodingKey { case numberLimit case canCreate } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetLimitsResultCodingKeys.self) if decoderContainer.contains(.numberLimit) { self.numberLimit = try decoderContainer.decode(Int?.self, forKey: .numberLimit) } if decoderContainer.contains(.canCreate) { self.canCreate = try decoderContainer.decode(Bool?.self, forKey: .canCreate) } } } public extension GetLimitsResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetLimitsResultCodingKeys.self) try encoderContainer.encode(numberLimit, forKey: .numberLimit) try encoderContainer.encode(canCreate, forKey: .canCreate) } } /// 删除一个流水线任务 public class DeletePipelineResult:NSObject,JdCloudResult { /// 流水线任务uuid var uuid:String? /// 删除成功则是true var result:Bool? public override init(){ super.init() } enum DeletePipelineResultCodingKeys: String, CodingKey { case uuid case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: DeletePipelineResultCodingKeys.self) if decoderContainer.contains(.uuid) { self.uuid = try decoderContainer.decode(String?.self, forKey: .uuid) } if decoderContainer.contains(.result) { self.result = try decoderContainer.decode(Bool?.self, forKey: .result) } } } public extension DeletePipelineResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: DeletePipelineResultCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(result, forKey: .result) } } /// 根据uuid启动一个流水线任务 public class StartPipelineRequest:JdCloudRequest { /// 流水线uuid var uuid:String public init(regionId: String,uuid:String){ self.uuid = uuid super.init(regionId: regionId) } enum StartPipelineRequestRequestCodingKeys: String, CodingKey { case uuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StartPipelineRequestRequestCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) } } public class StartPipelineResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:StartPipelineResult?; enum StartPipelineResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: StartPipelineResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(StartPipelineResult?.self, forKey: .result) ?? nil } } public extension StartPipelineResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StartPipelineResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 根据uuid获取流水线任务的配置信息 public class GetPipelineResult:NSObject,JdCloudResult { /// Pipeline var pipeline:Pipeline? public override init(){ super.init() } enum GetPipelineResultCodingKeys: String, CodingKey { case pipeline } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineResultCodingKeys.self) if decoderContainer.contains(.pipeline) { self.pipeline = try decoderContainer.decode(Pipeline?.self, forKey: .pipeline) } } } public extension GetPipelineResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineResultCodingKeys.self) try encoderContainer.encode(pipeline, forKey: .pipeline) } } /// 更新流水线任务 public class UpdatePipelineResult:NSObject,JdCloudResult { /// 流水线任务uuid var uuid:String? /// 更新成功则是true var result:Bool? public override init(){ super.init() } enum UpdatePipelineResultCodingKeys: String, CodingKey { case uuid case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: UpdatePipelineResultCodingKeys.self) if decoderContainer.contains(.uuid) { self.uuid = try decoderContainer.decode(String?.self, forKey: .uuid) } if decoderContainer.contains(.result) { self.result = try decoderContainer.decode(Bool?.self, forKey: .result) } } } public extension UpdatePipelineResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: UpdatePipelineResultCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(result, forKey: .result) } } /// 根据uuid启动一个流水线任务 public class StartPipelineResult:NSObject,JdCloudResult { /// 本次执行生成的实例的uuid var instanceUuid:String? /// 提交运行的流水线uuid var uuid:String? /// 提交任务是否成功 var result:Bool? public override init(){ super.init() } enum StartPipelineResultCodingKeys: String, CodingKey { case instanceUuid case uuid case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: StartPipelineResultCodingKeys.self) if decoderContainer.contains(.instanceUuid) { self.instanceUuid = try decoderContainer.decode(String?.self, forKey: .instanceUuid) } if decoderContainer.contains(.uuid) { self.uuid = try decoderContainer.decode(String?.self, forKey: .uuid) } if decoderContainer.contains(.result) { self.result = try decoderContainer.decode(Bool?.self, forKey: .result) } } } public extension StartPipelineResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: StartPipelineResultCodingKeys.self) try encoderContainer.encode(instanceUuid, forKey: .instanceUuid) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(result, forKey: .result) } } public class UpdatePipelineResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:UpdatePipelineResult?; enum UpdatePipelineResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: UpdatePipelineResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(UpdatePipelineResult?.self, forKey: .result) ?? nil } } public extension UpdatePipelineResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: UpdatePipelineResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } public class GetPipelinesResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetPipelinesResult?; enum GetPipelinesResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelinesResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetPipelinesResult?.self, forKey: .result) ?? nil } } public extension GetPipelinesResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelinesResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 查询获取流水线任务列表,并显示最后一次执行的状态或结果信息 /// /// /v1/regions/cn-south-1?sorts.1.name&#x3D;startedAt&amp;sorts.1.direction&#x3D;desc&amp;pageNumber&#x3D;1&amp;pageSize&#x3D;10&amp;filters.1.name&#x3D;name&amp;filters.1.values.1&#x3D;我的pipeline /// /// public class GetPipelinesResult:NSObject,JdCloudResult { /// TotalCount var totalCount:Int? /// Pipelines var pipelines:[SimplePipeline?]? public override init(){ super.init() } enum GetPipelinesResultCodingKeys: String, CodingKey { case totalCount case pipelines } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelinesResultCodingKeys.self) if decoderContainer.contains(.totalCount) { self.totalCount = try decoderContainer.decode(Int?.self, forKey: .totalCount) } if decoderContainer.contains(.pipelines) { self.pipelines = try decoderContainer.decode([SimplePipeline?]?.self, forKey: .pipelines) } } } public extension GetPipelinesResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelinesResultCodingKeys.self) try encoderContainer.encode(totalCount, forKey: .totalCount) try encoderContainer.encode(pipelines, forKey: .pipelines) } } public class DeletePipelineResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:DeletePipelineResult?; enum DeletePipelineResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: DeletePipelineResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(DeletePipelineResult?.self, forKey: .result) ?? nil } } public extension DeletePipelineResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: DeletePipelineResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 根据uuid获取流水线任务的配置信息 public class GetPipelineRequest:JdCloudRequest { /// 流水线 uuid var uuid:String public init(regionId: String,uuid:String){ self.uuid = uuid super.init(regionId: regionId) } enum GetPipelineRequestRequestCodingKeys: String, CodingKey { case uuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineRequestRequestCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) } } /// 新建流水线任务 public class CreatePipelineRequest:JdCloudRequest { /// Data var data:PipelineParams? enum CreatePipelineRequestRequestCodingKeys: String, CodingKey { case data } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: CreatePipelineRequestRequestCodingKeys.self) try encoderContainer.encode(data, forKey: .data) } } /// 删除一个流水线任务 public class DeletePipelineRequest:JdCloudRequest { /// 流水线任务uuid var uuid:String public init(regionId: String,uuid:String){ self.uuid = uuid super.init(regionId: regionId) } enum DeletePipelineRequestRequestCodingKeys: String, CodingKey { case uuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: DeletePipelineRequestRequestCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) } } public class CreatePipelineResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:CreatePipelineResult?; enum CreatePipelineResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: CreatePipelineResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(CreatePipelineResult?.self, forKey: .result) ?? nil } } public extension CreatePipelineResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: CreatePipelineResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } public class GetPipelineResponse:NSObject,Codable { var requestId:String?; var error:ServiceError?; var result:GetPipelineResult?; enum GetPipelineResponseCodingKeys: String, CodingKey { case requestId case error case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: GetPipelineResponseCodingKeys.self) self.requestId = try decoderContainer.decodeIfPresent(String?.self, forKey: .requestId) ?? nil self.error = try decoderContainer.decodeIfPresent(ServiceError?.self, forKey: .error) ?? nil self.result = try decoderContainer.decodeIfPresent(GetPipelineResult?.self, forKey: .result) ?? nil } } public extension GetPipelineResponse{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelineResponseCodingKeys.self) try encoderContainer.encode(requestId, forKey: .requestId) try encoderContainer.encode(error, forKey: .error) try encoderContainer.encode(result, forKey: .result) } } /// 更新流水线任务 public class UpdatePipelineRequest:JdCloudRequest { /// Data var data:PipelineParams? /// 流水线任务 uuid var uuid:String public init(regionId: String,uuid:String){ self.uuid = uuid super.init(regionId: regionId) } enum UpdatePipelineRequestRequestCodingKeys: String, CodingKey { case data case uuid } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: UpdatePipelineRequestRequestCodingKeys.self) try encoderContainer.encode(data, forKey: .data) try encoderContainer.encode(uuid, forKey: .uuid) } } /// 查询获取流水线任务列表,并显示最后一次执行的状态或结果信息 /// /// /v1/regions/cn-south-1?sorts.1.name&#x3D;startedAt&amp;sorts.1.direction&#x3D;desc&amp;pageNumber&#x3D;1&amp;pageSize&#x3D;10&amp;filters.1.name&#x3D;name&amp;filters.1.values.1&#x3D;我的pipeline /// /// public class GetPipelinesRequest:JdCloudRequest { /// 页码;默认为1 var pageNumber:Int? /// 分页大小;默认为10;取值范围[10, 100] var pageSize:Int? /// Sorts var sorts:[Sort?]? /// 根据流水线名称查询 var filters:[Filter?]? enum GetPipelinesRequestRequestCodingKeys: String, CodingKey { case pageNumber case pageSize case sorts case filters } public override func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: GetPipelinesRequestRequestCodingKeys.self) try encoderContainer.encode(pageNumber, forKey: .pageNumber) try encoderContainer.encode(pageSize, forKey: .pageSize) try encoderContainer.encode(sorts, forKey: .sorts) try encoderContainer.encode(filters, forKey: .filters) } } /// 新建流水线任务 public class CreatePipelineResult:NSObject,JdCloudResult { /// 流水线任务uuid var uuid:String? /// 创建成功则是true var result:Bool? public override init(){ super.init() } enum CreatePipelineResultCodingKeys: String, CodingKey { case uuid case result } required public init(from decoder: Decoder) throws { let decoderContainer = try decoder.container(keyedBy: CreatePipelineResultCodingKeys.self) if decoderContainer.contains(.uuid) { self.uuid = try decoderContainer.decode(String?.self, forKey: .uuid) } if decoderContainer.contains(.result) { self.result = try decoderContainer.decode(Bool?.self, forKey: .result) } } } public extension CreatePipelineResult{ func encode(to encoder: Encoder) throws { var encoderContainer = encoder.container(keyedBy: CreatePipelineResultCodingKeys.self) try encoderContainer.encode(uuid, forKey: .uuid) try encoderContainer.encode(result, forKey: .result) } }
30.913636
213
0.699897
62e9af32b00331aa8c1c8443101309123d0be0d3
1,082
// // CollectionPerformance.swift // VergeORM // // Created by muukii on 2019/12/21. // Copyright © 2019 muukii. All rights reserved. // import Foundation import XCTest class CollectionPerformance: XCTestCase { func testMakeCollection() { measure { _ = AnyCollection((0..<100000).map { $0 }) } } func testMakeLazySequence() { measure { _ = (0..<100000).lazy.map { $0 } } } func testMakeLazyCollection() { measure { _ = AnyCollection((0..<100000).lazy.map { $0 }) } } func testArrayCast() { let a = (0..<10000).map { Int($0) } measure { _ = a as [Any] } } func testDictionaryCast() { let a = (0..<10000).reduce(into: [Int : Int]()) { (d, n) in d[n] = n } measure { _ = a as [Int : Any] } } func testDictionaryCastFromAny() { let a = (0..<10000).reduce(into: [Int : Any]()) { (d, n) in d[n] = n } measure { _ = a as! [Int : Int] } } func testLoop() { } }
15.239437
63
0.492606
916a69ea3059c90df4eec03793ac5512cd1e3ac9
4,478
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftAWSLambdaRuntime open source project // // Copyright (c) 2017-2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// @testable import AWSLambdaEvents import XCTest class SNSTests: XCTestCase { static let eventBody = """ { "Records": [ { "EventSource": "aws:sns", "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5:6fabdb7f-b27e-456d-8e8a-14679db9e40c", "Sns": { "Type": "Notification", "MessageId": "bdb6900e-1ae9-5b4b-b7fc-c681fde222e3", "TopicArn": "arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5", "Subject": null, "Message": "{\\\"hello\\\": \\\"world\\\"}", "Timestamp": "2020-01-08T14:18:51.203Z", "SignatureVersion": "1", "Signature": "LJMF/xmMH7A1gNy2unLA3hmzyf6Be+zS/Yeiiz9tZbu6OG8fwvWZeNOcEZardhSiIStc0TF7h9I+4Qz3omCntaEfayzTGmWN8itGkn2mfn/hMFmPbGM8gEUz3+jp1n6p+iqP3XTx92R0LBIFrU3ylOxSo8+SCOjA015M93wfZzwj0WPtynji9iAvvtf15d8JxPUu1T05BRitpFd5s6ZXDHtVQ4x/mUoLUN8lOVp+rs281/ZdYNUG/V5CwlyUDTOERdryTkBJ/GO1NNPa+6m04ywJFa5d+BC8mDcUcHhhXXjpTEbt8AHBmswK3nudHrVMRO/G4zmssxU2P7ii5+gCfA==", "SigningCertUrl": "https://sns.eu-central-1.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem", "UnsubscribeUrl": "https://sns.eu-central-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5:6fabdb7f-b27e-456d-8e8a-14679db9e40c", "MessageAttributes": { "binary":{ "Type": "Binary", "Value": "YmFzZTY0" }, "string":{ "Type": "String", "Value": "abc123" } } } } ] } """ func testSimpleEventFromJSON() { let data = SNSTests.eventBody.data(using: .utf8)! var event: SNS.Event? XCTAssertNoThrow(event = try JSONDecoder().decode(SNS.Event.self, from: data)) guard let record = event?.records.first else { XCTFail("Expected to have one record") return } XCTAssertEqual(record.eventSource, "aws:sns") XCTAssertEqual(record.eventVersion, "1.0") XCTAssertEqual(record.eventSubscriptionArn, "arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5:6fabdb7f-b27e-456d-8e8a-14679db9e40c") XCTAssertEqual(record.sns.type, "Notification") XCTAssertEqual(record.sns.messageId, "bdb6900e-1ae9-5b4b-b7fc-c681fde222e3") XCTAssertEqual(record.sns.topicArn, "arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5") XCTAssertEqual(record.sns.message, "{\"hello\": \"world\"}") XCTAssertEqual(record.sns.timestamp, Date(timeIntervalSince1970: 1_578_493_131.203)) XCTAssertEqual(record.sns.signatureVersion, "1") XCTAssertEqual(record.sns.signature, "LJMF/xmMH7A1gNy2unLA3hmzyf6Be+zS/Yeiiz9tZbu6OG8fwvWZeNOcEZardhSiIStc0TF7h9I+4Qz3omCntaEfayzTGmWN8itGkn2mfn/hMFmPbGM8gEUz3+jp1n6p+iqP3XTx92R0LBIFrU3ylOxSo8+SCOjA015M93wfZzwj0WPtynji9iAvvtf15d8JxPUu1T05BRitpFd5s6ZXDHtVQ4x/mUoLUN8lOVp+rs281/ZdYNUG/V5CwlyUDTOERdryTkBJ/GO1NNPa+6m04ywJFa5d+BC8mDcUcHhhXXjpTEbt8AHBmswK3nudHrVMRO/G4zmssxU2P7ii5+gCfA==") XCTAssertEqual(record.sns.signingCertURL, "https://sns.eu-central-1.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem") XCTAssertEqual(record.sns.unsubscribeUrl, "https://sns.eu-central-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-central-1:079477498937:EventSources-SNSTopic-1NHENSE2MQKF5:6fabdb7f-b27e-456d-8e8a-14679db9e40c") XCTAssertEqual(record.sns.messageAttributes?.count, 2) XCTAssertEqual(record.sns.messageAttributes?["binary"], .binary([UInt8]("base64".utf8))) XCTAssertEqual(record.sns.messageAttributes?["string"], .string("abc123")) } }
53.951807
392
0.676865
d5fc88bb49bf46ff76b89b716f0793dca1440eec
1,476
// // tipperUITests.swift // tipperUITests // // Created by Joseph Fontana on 8/4/20. // Copyright © 2020 Joseph Fontana. All rights reserved. // import XCTest class tipperUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
33.545455
182
0.660569
331d7528297fda5ffb4b745e5ec972398eb97a59
8,212
// // LazyXMLParsingTests.swift // SWXMLHash // // Copyright (c) 2016 David Mohundro // // 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 SWXMLHash import XCTest // swiftlint:disable line_length class LazyXMLParsingTests: XCTestCase { let xmlToParse = """ <root> <header>header mixed content<title>Test Title Header</title>more mixed content</header> <catalog> <book id=\"bk101\"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id=\"bk102\"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id=\"bk103\"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book> </catalog> </root> """ var xml: XMLIndexer? override func setUp() { super.setUp() xml = SWXMLHash.config { config in config.shouldProcessLazily = true }.parse(xmlToParse) } func testShouldBeAbleToParseIndividualElements() { XCTAssertEqual(xml!["root"]["header"]["title"].element?.text, "Test Title Header") } func testShouldBeAbleToHandleSubsequentParseCalls() { XCTAssertEqual(xml!["root"]["header"]["title"].element?.text, "Test Title Header") XCTAssertEqual(xml!["root"]["catalog"]["book"][1]["author"].element?.text, "Ralls, Kim") } func testShouldBeAbleToParseElementGroups() { XCTAssertEqual(xml!["root"]["catalog"]["book"][1]["author"].element?.text, "Ralls, Kim") } func testShouldBeAbleToParseAttributes() { XCTAssertEqual(xml!["root"]["catalog"]["book"][1].element?.attribute(by: "id")?.text, "bk102") } func testShouldBeAbleToLookUpElementsByNameAndAttribute() { do { let value = try xml!["root"]["catalog"]["book"].withAttribute("id", "bk102")["author"].element?.text XCTAssertEqual(value, "Ralls, Kim") } catch { XCTFail("\(error)") } } func testShouldBeAbleToIterateElementGroups() { let result = xml!["root"]["catalog"]["book"].all.map({ $0["genre"].element!.text }).joined(separator: ", ") XCTAssertEqual(result, "Computer, Fantasy, Fantasy") } func testShouldBeAbleToIterateElementGroupsEvenIfOnlyOneElementIsFound() { XCTAssertEqual(xml!["root"]["header"]["title"].all.count, 1) } func testShouldBeAbleToIndexElementGroupsEvenIfOnlyOneElementIsFound() { XCTAssertEqual(xml!["root"]["header"]["title"][0].element?.text, "Test Title Header") } func testShouldBeAbleToIterateUsingForIn() { var count = 0 for _ in xml!["root"]["catalog"]["book"].all { count += 1 } XCTAssertEqual(count, 3) } func testShouldBeAbleToEnumerateChildren() { let result = xml!["root"]["catalog"]["book"][0].children.map({ $0.element!.name }).joined(separator: ", ") XCTAssertEqual(result, "author, title, genre, price, publish_date, description") } func testShouldBeAbleToHandleMixedContent() { XCTAssertEqual(xml!["root"]["header"].element?.text, "header mixed contentmore mixed content") } func testShouldHandleInterleavingXMLElements() { let interleavedXml = "<html><body><p>one</p><div>two</div><p>three</p><div>four</div></body></html>" let parsed = SWXMLHash.parse(interleavedXml) let result = parsed["html"]["body"].children.map({ $0.element!.text }).joined(separator: ", ") XCTAssertEqual(result, "one, two, three, four") } func testShouldBeAbleToProvideADescriptionForTheDocument() { let descriptionXml = "<root><foo><what id=\"myId\">puppies</what></foo></root>" let parsed = SWXMLHash.parse(descriptionXml) XCTAssertEqual(parsed.description, "<root><foo><what id=\"myId\">puppies</what></foo></root>") } func testShouldReturnNilWhenKeysDontMatch() { XCTAssertNil(xml!["root"]["what"]["header"]["foo"].element?.name) } func testShouldBeAbleToFilterOnIndexer() { let subIndexer = xml!["root"]["catalog"]["book"] .filterAll { elem, _ in elem.attribute(by: "id")!.text == "bk102" } .filterChildren { _, index in index >= 1 && index <= 3 } XCTAssertEqual(subIndexer.children[0].element?.name, "title") XCTAssertEqual(subIndexer.children[1].element?.name, "genre") XCTAssertEqual(subIndexer.children[2].element?.name, "price") XCTAssertEqual(subIndexer.children[0].element?.text, "Midnight Rain") XCTAssertEqual(subIndexer.children[1].element?.text, "Fantasy") XCTAssertEqual(subIndexer.children[2].element?.text, "5.95") } } extension LazyXMLParsingTests { static var allTests: [(String, (LazyXMLParsingTests) -> () throws -> Void)] { [ ("testShouldBeAbleToParseIndividualElements", testShouldBeAbleToParseIndividualElements), ("testShouldBeAbleToParseElementGroups", testShouldBeAbleToParseElementGroups), ("testShouldBeAbleToParseAttributes", testShouldBeAbleToParseAttributes), ("testShouldBeAbleToLookUpElementsByNameAndAttribute", testShouldBeAbleToLookUpElementsByNameAndAttribute), ("testShouldBeAbleToIterateElementGroups", testShouldBeAbleToIterateElementGroups), ("testShouldBeAbleToIterateElementGroupsEvenIfOnlyOneElementIsFound", testShouldBeAbleToIterateElementGroupsEvenIfOnlyOneElementIsFound), ("testShouldBeAbleToIndexElementGroupsEvenIfOnlyOneElementIsFound", testShouldBeAbleToIndexElementGroupsEvenIfOnlyOneElementIsFound), ("testShouldBeAbleToIterateUsingForIn", testShouldBeAbleToIterateUsingForIn), ("testShouldBeAbleToEnumerateChildren", testShouldBeAbleToEnumerateChildren), ("testShouldBeAbleToHandleMixedContent", testShouldBeAbleToHandleMixedContent), ("testShouldHandleInterleavingXMLElements", testShouldHandleInterleavingXMLElements), ("testShouldBeAbleToProvideADescriptionForTheDocument", testShouldBeAbleToProvideADescriptionForTheDocument), ("testShouldReturnNilWhenKeysDontMatch", testShouldReturnNilWhenKeysDontMatch), ("testShouldBeAbleToFilterOnIndexer", testShouldBeAbleToFilterOnIndexer) ] } }
45.370166
157
0.670604
50b814619ce3c275b87ec6504ce9ca37ba660c6e
719
// // NotificationExtension.swift // DemoApp // // Created by Galvin on 2020/2/26. // Copyright © 2020 GalvinLi. All rights reserved. // import Foundation extension NotificationObserver.Target { static let deviceEventTriggered = ObserverTarget<DeviceEvent>(name: "deviceEventTriggered") static let currentDeviceChanged = ObserverTarget<Nil>(name: "currentDeviceChanged") static let deviceListChanged = ObserverTarget<Nil>(name: "deviceListChanged") static let deviceConfigurationChanged = ObserverTarget<Nil>(name: "deviceConfigurationChanged") struct DistributedNotification { static let uiModeChanged = ObserverTarget<Nil>(name: "AppleInterfaceThemeChangedNotification") } }
35.95
102
0.764951
388a83975d2179413639640e3cc2c97ae84ce71d
758
// Copyright (c) 2018-2021 Brian Dewey. Covered by the Apache 2.0 license. import UIKit private let useSystemColors = false extension UIColor { static let grailTint = UIColor.systemOrange static let grailBackground = useSystemColors ? UIColor.systemBackground : UIColor(named: "grailBackground")! static let grailSecondaryBackground = useSystemColors ? UIColor.secondarySystemBackground : UIColor(named: "grailSecondaryBackground")! static let grailGroupedBackground = useSystemColors ? UIColor.systemGroupedBackground : UIColor(named: "grailSecondaryBackground")! static let grailSecondaryGroupedBackground = useSystemColors ? UIColor.secondarySystemGroupedBackground : UIColor(named: "grailBackground")! }
29.153846
75
0.774406
5dc7fcee9690dfe00ea4538fd92d1d9f9cb15e59
763
import UIKit import XCTest import UILocalizable class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.433333
111
0.606815
fc370dcb5e8a008958fa7ba9cf8517cf6fc002a5
4,255
// // Observables.swift // TiltUp // // Created by Michael Mattson on 9/23/19. // import Foundation @propertyWrapper public final class Observable<Observed> { public typealias Observer = (_ oldValue: Observed, _ newValue: Observed) -> Void private var observers: [UUID: (DispatchQueue, Observer)] = [:] public var wrappedValue: Observed { didSet { notifyObservers(oldValue: oldValue, newValue: wrappedValue) } } public var projectedValue: Observable<Observed> { self } public init(wrappedValue: Observed) { self.wrappedValue = wrappedValue } /** Adds an observer to be notified on the given queue when the receiver’s observed condition is met. Returns a `Disposable` that removes the observer upon deallocation. - parameter observingCurrentValue: If true, observe the value at the time `addObserver` is called. - parameter queue: The dispatch queue on which to notify the observer. Defaults to `DispatchQueue.main`. - parameter observer: The observer to be updated when the value changes. - returns: A `Disposable` that must be retained until you want to stop observing. Release the `Disposable` to remove the observer. */ public func addObserver(observingCurrentValue: Bool, on queue: DispatchQueue = .main, observer: @escaping Observer) -> Disposable { let uuid = UUID() observers[uuid] = (queue, observer) if observingCurrentValue { let observedValue = wrappedValue queue.async { observer(observedValue, observedValue) } } return Disposable { [weak self] in self?.observers[uuid] = nil } } /** Calls each of the receiver’s `observers` with `oldValue` and `newValue` as arguments. Each observer is called on the queue specified upon registration with `Observable.addObserver(on:observer:)`. - parameter oldValue: The observed old value of which to notify each observer. - parameter newValue: The observed new value of which to notify each observer. */ private func notifyObservers(oldValue: Observed, newValue: Observed) { observers.values.forEach { queue, observer in queue.async { observer(oldValue, newValue) } } } } extension Observable where Observed: ExpressibleByNilLiteral { public convenience init() { self.init(wrappedValue: nil) } } public final class ObserverList<Observed> { public typealias Observer = (Observed) -> Void fileprivate var observers: [UUID: (DispatchQueue, Observer)] = [:] /** Adds an observer to be notified on the given queue when the receiver’s observed condition is met. Returns a `Disposable` that removes the observer upon deallocation. - parameter queue: The dispatch queue on which to notify the observer. Defaults to `DispatchQueue.main`. - parameter observer: The observer to be notified when the observed condition is met. - returns: A `Disposable` that must be retained until you want to stop observing. Release the `Disposable` to remove the observer. */ public func addObserver(on queue: DispatchQueue = .main, observer: @escaping Observer) -> Disposable { let uuid = UUID() observers[uuid] = (queue, observer) return Disposable { [weak self] in self?.observers[uuid] = nil } } } public final class ObserverNotifier<Observed> { public let observerList = ObserverList<Observed>() public init() {} /** Calls each observer in the receiver’s `observerList` with `observed` as an argument. Each observer is called on the queue specified upon registration with `ObserverList.addObserver(on:observer:)`. - parameter observed: The observed value of which to notify each observer. */ public func notifyObservers(of observed: Observed) { observerList.observers.values.forEach { queue, observer in queue.async { observer(observed) } } } } public extension ObserverNotifier where Observed == Void { func notifyObservers() { notifyObservers(of: ()) } }
35.165289
135
0.66792
23752699c2d6235c0fd3e1563b2eb8f9789f7788
556
// // BaseAPIRequest.swift // EasyNetwork // // Created by ppsheep on 2017/4/28. // Copyright © 2017年 ppsheep. All rights reserved. // import Foundation protocol BaseAPIRequest { var api: String { get } var method: NetworkService.Method { get } var query: NetworkService.QueryType { get } var params: [String : Any]? { get } var headers: [String : String]? { get } } extension BaseAPIRequest { ///默认返回json func defaultJsonHeader() -> [String : String] { return ["Content-Type" : "application/json"] } }
20.592593
52
0.636691
50213b182f7a18821cab400a271a143d87970289
163
// // Blank.swift // Pushy // // This empty Swift file is necessary for // integrating the Pushy iOS SDK which is // written in Swift // import Foundation
14.818182
43
0.668712
2fc4bb2f4e0a95afd230ee9cf166b095b0b20a4f
1,150
// // GiveColleagueFeedbackWorkerSpec.swift // FeedbackAppTests // // Created by Ahmed Elassuty on 2/3/18. // Copyright © 2018 Challenges. All rights reserved. // import Quick import Nimble import FeedbackAppDomain @testable import FeedbackApp class GiveColleagueFeedbackWorkerSpec: QuickSpec { override func spec() { let request = GiveColleagueFeedbackRequest(userId: 1) let worker = GiveColleagueFeedbackWorker() describe("Worker") { var result: GiveColleagueFeedbackWorker.ResultType? afterEach { result = nil } it("should call the completion handler") { worker.giveColleagueFeedback(request: request) { workerResult in result = workerResult } expect(result).toEventuallyNot(beNil()) } it("should return error") { worker.giveColleagueFeedback(request: request) { workerResult in result = workerResult } expect(result?.error).toEventuallyNot(beNil()) } } } }
26.136364
80
0.588696
14fdaaee431776732e8a89da367e8bce810768a2
1,401
// // UABuilder.swift // NonWVApp-SWIFT // import Foundation import UIKit //eg. Darwin/16.3.0 func DarwinVersion() -> String { var sysinfo = utsname() uname(&sysinfo) let dv = String(bytes: Data(bytes: &sysinfo.release, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters) return "Darwin/\(dv)" } //eg. CFNetwork/808.3 func CFNetworkVersion() -> String { let dictionary = Bundle(identifier: "com.apple.CFNetwork")?.infoDictionary! let version = dictionary?["CFBundleShortVersionString"] as! String return "CFNetwork/\(version)" } //eg. iOS/10_1 func deviceVersion() -> String { let currentDevice = UIDevice.current return "\(currentDevice.systemName)/\(currentDevice.systemVersion)" } //eg. iPhone5,2 func deviceName() -> String { var sysinfo = utsname() uname(&sysinfo) return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters) } //eg. MyApp/1 func appNameAndVersion() -> String { let dictionary = Bundle.main.infoDictionary! let version = dictionary["CFBundleShortVersionString"] as! String let name = dictionary["CFBundleName"] as! String return "\(name)/\(version)" } func UAString() -> String { return "\(appNameAndVersion()) \(deviceName()) \(deviceVersion()) \(CFNetworkVersion()) \(DarwinVersion())" }
31.840909
145
0.698073
89b89ab375ac4c0bf46bf4880f32dc211e998173
1,138
// // UITableView+BIDequeCell.swift // MiaoleGB // // Created by ET|冰琳 on 16/2/24. // Copyright © 2016年 UOKO. All rights reserved. // import UIKit extension UITableView: ListView{ // in public func queueIn(cell: AnyClass){ self.queueIn(cell: cell, identifier: String(describing: cell)) } public func queueIn(cell: AnyClass, identifier: String){ let cellString = String(describing: cell) if let _ = Bundle.main.path(forResource: cellString, ofType: "nib") { self.register(UINib(nibName: cellString, bundle: nil), forCellReuseIdentifier: identifier) }else{ self.register(cell, forCellReuseIdentifier: identifier) } } // out public func queueOutCell<T>(identifier: String, for indexPath: IndexPath) -> T { return self.dequeueReusableCell(withIdentifier: identifier) as! T } public func queueOutCell<T: ReusableView>(for indexPath: IndexPath) -> T { print(String(describing: T.self)) return self.dequeueReusableCell(withIdentifier: String(describing: T.self)) as! T } }
29.179487
102
0.644991
c10e94dc9461248c00bf4238ec0142cb5451e545
3,905
// Copyright (c) 2019 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation /// Parses a LogManifest.plist file. /// That file has a list of the existing Xcode Logs inside a Derived Data's project directory public struct LogManifest { public func getWithLogOptions(_ logOptions: LogOptions) throws -> [LogManifestEntry] { let logFinder = LogFinder() let logManifestURL = try logFinder.findLogManifestWithLogOptions(logOptions) let logManifestDictionary = try getDictionaryFromURL(logManifestURL) return try parse(dictionary: logManifestDictionary, atPath: logManifestURL.path) } public func parse(dictionary: NSDictionary, atPath path: String) throws -> [LogManifestEntry] { guard let logs = dictionary["logs"] as? [String: [String: Any]] else { throw LogError.invalidLogManifest("The file at \(path) is not a valid " + "LogManifest file.") } return try logs.compactMap { entry -> LogManifestEntry? in guard let fileName = entry.value["fileName"] as? String, let title = entry.value["title"] as? String, let uniqueIdentifier = entry.value["uniqueIdentifier"] as? String, let scheme = entry.value["schemeIdentifier-schemeName"] as? String, let timeStartedRecording = entry.value["timeStartedRecording"] as? Double, let timeStoppedRecording = entry.value["timeStoppedRecording"] as? Double, let className = entry.value["className"] as? String, let type = LogManifestEntryType.buildFromClassName(className) else { throw LogError.invalidLogManifest("The file at \(path) is not a valid " + "LogManifest file.") } let startDate = Date(timeIntervalSinceReferenceDate: timeStartedRecording) let endDate = Date(timeIntervalSinceReferenceDate: timeStoppedRecording) let timestampStart = Int(startDate.timeIntervalSince1970.rounded()) let timestampEnd = Int(endDate.timeIntervalSince1970.rounded()) return LogManifestEntry(uniqueIdentifier: uniqueIdentifier, title: title, scheme: scheme, fileName: fileName, timestampStart: timestampStart, timestampEnd: timestampEnd, duration: timestampEnd - timestampStart, type: type) }.sorted(by: { lhs, rhs -> Bool in return lhs.timestampStart > rhs.timestampStart }) } private func getDictionaryFromURL(_ logManifestURL: URL) throws -> NSDictionary { guard let logContents = NSDictionary(contentsOfFile: logManifestURL.path) else { throw LogError.invalidLogManifest("The file at \(logManifestURL.path) is not a valid " + "LogManifest file.") } return logContents } }
50.064103
100
0.636364
0ef09f429a7111b5db5a31d4347be34fe948308e
5,497
// // ReactNativeLiveStreamView.swift // api.video-reactnative-live-stream // import Foundation import ApiVideoLiveStream import AVFoundation extension String { func toResolution() -> Resolution { switch self { case "240p": return Resolution.RESOLUTION_240 case "360p": return Resolution.RESOLUTION_360 case "480p": return Resolution.RESOLUTION_480 case "720p": return Resolution.RESOLUTION_720 case "1080p": return Resolution.RESOLUTION_1080 default: return Resolution.RESOLUTION_720 } } func toCaptureDevicePosition() -> AVCaptureDevice.Position { switch self { case "back": return AVCaptureDevice.Position.back case "front": return AVCaptureDevice.Position.front default: return AVCaptureDevice.Position.back } } } class ReactNativeLiveStreamView : UIView { private var liveStream: ApiVideoLiveStream? private var isStreaming: Bool = false override init(frame: CGRect) { super.init(frame: frame) // liveStream = ApiVideoLiveStream(preview: self) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func buildOrNull() -> ApiVideoLiveStream? { if let audioConfig = audioConfig, let videoConfig = videoConfig { do { let liveStream = try ApiVideoLiveStream(initialAudioConfig: audioConfig, initialVideoConfig: videoConfig, preview: self) liveStream.onConnectionSuccess = {() in self.onConnectionSuccess?([:]) } liveStream.onDisconnect = {() in self.isStreaming = false self.onDisconnect?([:]) } liveStream.onConnectionFailed = {(code) in self.isStreaming = false self.onConnectionFailed?([ "code": code ]) } return liveStream } catch { fatalError("build(): Can't create a live stream instance") } } return nil } private var videoBitrate: Int? { didSet { if let liveStream = liveStream { liveStream.videoBitrate = videoBitrate } } } private var audioConfig: AudioConfig? { didSet { if let liveStream = liveStream { liveStream.audioConfig = audioConfig! } else { liveStream = buildOrNull() } } } private var videoConfig: VideoConfig? { didSet { if let liveStream = liveStream { liveStream.videoConfig = videoConfig! } else { liveStream = buildOrNull() } } } @objc var audio: NSDictionary = [:] { didSet { audioConfig = AudioConfig(bitrate: audio["bitrate"] as! Int) } } @objc var video: NSDictionary = [:] { didSet { if (isStreaming) { videoBitrate = video["bitrate"] as! Int } else { videoConfig = VideoConfig(bitrate: video["bitrate"] as! Int, resolution: (video["resolution"] as! String).toResolution(), fps: video["fps"] as! Int) } } } @objc var camera: String = "back" { didSet { if let apiVideo = liveStream { let value = camera.toCaptureDevicePosition() if(value == apiVideo.camera){ return } apiVideo.camera = camera.toCaptureDevicePosition() } } } @objc var isMuted: Bool = false { didSet { if let apiVideo = liveStream { if(isMuted == apiVideo.isMuted){ return } apiVideo.isMuted = isMuted } } } @objc func startStreaming(requestId: Int, streamKey: String, url: String? = nil) { do { if let url = url { try liveStream!.startStreaming(streamKey: streamKey, url: url) } else { try liveStream!.startStreaming(streamKey: streamKey) } isStreaming = true self.onStartStreaming?([ "requestId": requestId, "result": true ]) } catch LiveStreamError.IllegalArgumentError(let message) { self.onStartStreaming?([ "requestId": requestId, "result": false, "error": message ]) } catch { self.onStartStreaming?([ "requestId": requestId, "result": false, "error": "Unknown error" ]) } } @objc func stopStreaming() { isStreaming = false liveStream!.stopStreaming() } @objc var onStartStreaming: RCTDirectEventBlock? = nil @objc var onConnectionSuccess: RCTDirectEventBlock? = nil @objc var onConnectionFailed: RCTDirectEventBlock? = nil @objc var onDisconnect: RCTDirectEventBlock? = nil @objc override func didMoveToWindow() { super.didMoveToWindow() } }
28.481865
136
0.520648
2274093092e1376a4ff055be459a60b15e1da454
1,363
// // VisualEffectView.swift // ReactantUI // // Created by Matous Hybl. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif public class VisualEffectView: Container { public override class var availableProperties: [PropertyDescription] { return Properties.visualEffectView.allProperties } public override var addSubviewMethod: String { return "contentView.addSubview" } public class override func runtimeType() -> String { return "UIVisualEffectView" } #if canImport(UIKit) public override func initialize(context: ReactantLiveUIWorker.Context) -> UIView { return UIVisualEffectView() } public override func add(subview: UIView, toInstanceOfSelf: UIView) { guard let visualEffectView = toInstanceOfSelf as? UIVisualEffectView else { return super.add(subview: subview, toInstanceOfSelf: toInstanceOfSelf) } visualEffectView.contentView.addSubview(subview) } #endif } public class VisualEffectViewProperties: ViewProperties { public let effect: AssignablePropertyDescription<VisualEffect> public required init(configuration: Configuration) { effect = configuration.property(name: "effect") super.init(configuration: configuration) } }
26.211538
86
0.710198
200f153d06dd41865b1c1e7ceea8edbbb862d56e
853
// // SearchMode.swift // NyrisSDK // // Created by MOSTEFAOUI Anas on 03/04/2018. // Copyright © 2018 nyris. All rights reserved. // import Foundation public struct XOptionHeader { public var exactMode:Bool = true public var similarityMode:Bool = true public var similarityLimit:UInt = 0 public var similarityThreshold:Float = -1 public var ocrMode:Bool = true public var group:Bool = true public var regroupThreshold:Float = -1 public var limit : Int = 20 init() { } public static var `default`:XOptionHeader { var xOption = XOptionHeader() xOption.exactMode = true xOption.ocrMode = true xOption.similarityMode = true xOption.limit = 20 return xOption } var header:String { return "" } }
20.309524
48
0.610785
d5eaf71055454775c3b6d2acaa889b4e36c4c49f
2,570
import Foundation class GamePresenter { private let model: Game.Model private weak var view: Game.View? private let navigator: GameUploadingNavigator private let action: GameUploadingCompletion? let primary = UIColor(red: 22.0 / 255.0, green: 197.0 / 255.0, blue: 217.0 / 255.0, alpha: 1.0) let validation = UIColor(red: 122.0 / 255.0, green: 204.0 / 255.0, blue: 82.0 / 255.0, alpha: 1.0) private enum Text: String { case skip = "SKIP" case done = "DONE" } init(model: Game.Model, view: Game.View, navigator: GameUploadingNavigator, action: GameUploadingCompletion?) { self.model = model self.view = view self.navigator = navigator self.action = action self.model.setProgressListener(with: self) } private func updateProgressView() { if model.newImageNeeded() { if let image = UIImage(named: "iconApp") { view?.updatePreview(image: image) } model.getCurrentImage { image in guard let image = image else { return } self.view?.updatePreview(image: image) } } view?.updateProgressView(value: model.getTotalProgress()) } private func checkUploadStatus() { if model.isUploadedOrFailed() { model.resetUploadIfNeeded() } updateAllUI() } } // MARK: - Game.Presenter extension GamePresenter: Game.Presenter { func onViewDidAppear() { model.resetUploadIfNeeded() view?.setButton(text: Text.skip.rawValue) view?.setProgress(color: primary) } func onStopButtonTapped() { if model.isUploadComplete() { navigator.showNextView(action: action) } else { navigator.showPreviousView() } } } extension GamePresenter: GameUploadingProgressListener { func onPhotoProgress(progress: Float, id: String) { model.updateProgress(id: id, progress: progress) _ = model.getProgress() DispatchQueue.main.async { self.checkUploadStatus() } } private func updateAllUI() { updateProgressView() updateProgressColor() updateText() } private func updateProgressColor() { let color = model.isUploadComplete() ? validation : primary view?.setProgress(color: color) } private func updateText() { let text = model.isUploadComplete() ? Text.done.rawValue : Text.skip.rawValue view?.setButton(text: text) } }
28.241758
115
0.611673
ddedbcfadd05276f3992041574493d1145e9f168
163
// // Methods.swift // NetworkKit // // Created by Leonir Alves Deolindo on 07/04/19. // import Foundation public enum Methods { case POST case GET }
11.642857
49
0.650307
16dfdfa03edca9e3ed8998902ba03d4c8b839bf5
299
// // RKPickerViewDataSource.swift // PickerView // // Created by Rayehe on 7/10/1397 AP. // Copyright © 1397 Rayehe. All rights reserved. // import Foundation import UIKit public protocol RKPickerViewDataSource : class { func buttonTitleFor(_ RKpickerView: RKPickerView) -> String }
18.6875
63
0.722408
75d618b37cea65f7b81cc63ab7e970831e8bcee1
3,158
// // HCILEWriteRfPathCompensation.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Write RF Path Compensation Command /// /// The command is used to indicate the RF path gain or loss between the RF transceiver and /// the antenna contributed by intermediate components. func lowEnergyWriteRfPathCompensation(rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue, rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue, timeout: HCICommandTimeout = .default) throws { let parameters = HCILEWriteRfPathCompensation(rfTxPathCompensationValue: rfTxPathCompensationValue, rfRxPathCompensationValue: rfRxPathCompensationValue) try deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Write RF Path Compensation Command /// /// The command is used to indicate the RF path gain or loss between the RF transceiver and /// the antenna contributed by intermediate components. A positive value means a net RF path gain /// and a negative value means a net RF path loss. The RF Tx Path Compensation Value parameter /// shall be used by the Controller to calculate radiative Tx Power Level used in the TxPower field /// in the Extended Header using the following equation: /// /// Radiative Tx Power Level = Tx Power Level at RF transceiver output + RF Tx Path Compensation Value /// /// For example, if the Tx Power Level is +4 (dBm) at RF transceiver output and the RF /// Path Compensation Value is -1.5 (dB), the radiative Tx Power Level is +4+(-1.5) = 2.5 (dBm). /// /// The RF Rx Path Compensation Value parameter shall be used by the Controller to calculate /// the RSSI value reported to the Host. public struct HCILEWriteRfPathCompensation: HCICommandParameter { public static let command = HCILowEnergyCommand.writeRFPathCompensation // 0x004D public var rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue public var rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue public init(rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue, rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue) { self.rfTxPathCompensationValue = rfTxPathCompensationValue self.rfRxPathCompensationValue = rfRxPathCompensationValue } public var data: Data { let rfTxPathCompensationValueBytes = UInt16.init(bitPattern: rfTxPathCompensationValue.rawValue).littleEndian.bytes let rfRxPathCompensationValueBytes = UInt16.init(bitPattern: rfRxPathCompensationValue.rawValue).littleEndian.bytes return Data([rfTxPathCompensationValueBytes.0, rfTxPathCompensationValueBytes.1, rfRxPathCompensationValueBytes.0, rfRxPathCompensationValueBytes.1]) } }
44.478873
123
0.715326
724e2896acb87ac64bfc29837b8a358c832feffe
2,402
// // ViewController.swift // EasterDate // // Created by Rufus Cable on 05/22/2016. // Copyright (c) 2016 Rufus Cable. All rights reserved. // import UIKit import EasterDate class ViewController: UIViewController { @IBOutlet var westernTitleLabel: UILabel! @IBOutlet var orthodoxTitleLabel: UILabel! @IBOutlet var westernEasterLabel: UILabel! @IBOutlet var orthodoxEasterLabel: UILabel! @IBOutlet var stepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() #if swift(>=3.0) let year = NSCalendar.current().components([.year], from: NSDate()).year #else let year = NSCalendar.currentCalendar().components([.Year], fromDate: NSDate()).year #endif stepper.minimumValue = Double(year - 10) stepper.maximumValue = Double(year + 10) stepper.value = Double(year) updateEasterDates() } func updateEasterDates() { let year = Int(stepper.value) let formatter = NSDateFormatter() #if swift(>=3.0) formatter.dateStyle = .mediumStyle formatter.timeStyle = .noStyle #else formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle #endif westernTitleLabel.text = "Western Easter \(year)" if let westernEaster = NSDate.westernEasterDateForYear(year) { #if swift(>=3.0) westernEasterLabel.text = formatter.string(from: westernEaster) #else westernEasterLabel.text = formatter.stringFromDate(westernEaster) #endif } else { westernEasterLabel.text = "unknown" } orthodoxTitleLabel.text = "Orthodox Easter \(year)" if let orthodoxEaster = NSDate.easternOrthodoxEasterDateForYear(year) { #if swift(>=3.0) orthodoxEasterLabel.text = formatter.string(from: orthodoxEaster) #else orthodoxEasterLabel.text = formatter.stringFromDate(orthodoxEaster) #endif } else { orthodoxEasterLabel.text = "unknown" } } #if swift(>=3.0) @IBAction func stepperValueChanged(sender: UIStepper) { updateEasterDates() } #else @IBAction func stepperValueChangedWithSender(sender: AnyObject) { updateEasterDates() } #endif }
28.258824
96
0.615321
d9edf37401fc2fb2c871ce8e1253014fa6164209
1,931
// // ITMainHeaderInfoView.swift // InTime // // Created by lisilong on 2019/10/19. // Copyright © 2019 BruceLi. All rights reserved. // import UIKit class ITMainHeaderInfoView: UIView { lazy var titleLabel: UILabel = { let label = UILabel() label.textAlignment = .left label.font = UIFont.boldSystemFont(ofSize: 15) label.textColor = UIColor.heightLightGrayColor return label }() lazy var addButton: UIButton = { let btn = UIButton() btn.addTarget(self, action: #selector(didAddButtonAction), for: .touchUpInside) return btn }() lazy var imageView: UIImageView = { let view = UIImageView() view.image = UIImage.init(named: "add") return view }() var didAddSeasonButtonBlock: (() -> ())? override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) addSubview(imageView) addSubview(addButton) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let height = self.frame.size.height let margin: CGFloat = 15.0 titleLabel.frame = CGRect.init(x: margin, y: 0.0, width: 200.0, height: height) let imageViewWH: CGFloat = 15.0; imageView.frame = CGRect.init(x: self.frame.size.width - imageViewWH - margin, y: (height - imageViewWH) * 0.5, width: imageViewWH, height: imageViewWH) let addButtonWidth: CGFloat = 50.0 addButton.frame = CGRect.init(x: self.frame.size.width - addButtonWidth - margin, y: 0.0, width: addButtonWidth, height: height) } // MARK: - Actions @objc func didAddButtonAction() { if let block = didAddSeasonButtonBlock { block() } } }
27.585714
160
0.598136
26770b7f9bed6ae58cef53027d7b706776949fd2
652
// // Theme.swift // NASAPhotos // // Created by Luke Van In on 2021/07/18. // import UIKit /// /// Defines an abstract interface for providing commonly used user interface attributes defined by the /// design system. The theme, together with the user interface objects, defines the catalog of components /// used to create user interfaces. /// protocol ThemeProtocol { func titleFont() -> UIFont? func subtitleFont() -> UIFont? func bodyFont() -> UIFont? } /// /// Global service locator that provides the theme used by all user interface elements. /// final class Theme { static var current: ThemeProtocol = StandardTheme() }
22.482759
105
0.707055
330c87fe2312764dbe482d20c70cb6466c2a5584
2,105
// // AddBookmarkParentViewController.swift // Hadith // // Created by Majid Khan on 3/08/2016. // Copyright © 2016 Muflihun.com. All rights reserved. // import Foundation import UIKit import JLToast class AddBookmarkParentViewController : CustomViewController { let bookmarkManager = BookmarkManager.sharedInstance() @IBOutlet weak var addBookmarkViewContainer: UIView! var refHadith : Hadith! override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "AddBookmarkEmbed") { let viewController = segue.destinationViewController as! AddBookmarkViewController viewController.parent = self } } func replaceWith(bookmark:Bookmark) { let title = bookmark.name bookmarkManager.remove([bookmark]) bookmarkManager.addBookmark(title, hadith: self.refHadith) Analytics.logEvent(.ReplaceBookmark, value: self.refHadith.availableRef) self.cancel() JLToast.makeText("Bookmark replaced").show() } @IBAction func cancel() { dismissViewControllerAnimated(true, completion: nil) navigationController?.popViewControllerAnimated(true) } @IBAction func add() { let alert = AlertViewWithCallback() alert.dismissWithClickedButtonIndex(1, animated: true) alert.title = "Enter bookmark name" alert.alertViewStyle = UIAlertViewStyle.PlainTextInput alert.addButtonWithTitle("Add") let textField = alert.textFieldAtIndex(0) textField?.placeholder = self.refHadith.availableRef alert.callback = { buttonIndex in if buttonIndex == 0 { self.bookmarkManager.addBookmark(alert.textFieldAtIndex(0)!.text!, hadith: self.refHadith) Analytics.logEvent(.AddBookmark, value: self.refHadith.availableRef) self.cancel() JLToast.makeText("Bookmark added").show() } } alert.addButtonWithTitle("Cancel") alert.show() } }
32.890625
106
0.658432
de6c54702c3af76d8000ea4393984b8dc0ef6cd8
6,623
// // GridSpec.swift // SudoChessFoundationTests // // Created by Daniel Panzer on 9/9/19. // Copyright © 2019 Daniel Panzer. All rights reserved. // import XCTest import Quick import Nimble @testable import SudoChess class GridSpec: QuickSpec { private var nullableSubject: Grid<Int?>! private var nonnullSubject: Grid<Int>! override func spec() { describe("an empty 3x3 nullable integer grid") { beforeEach { self.nullableSubject = Grid(rowSize: 3, columnSize: 3) } afterEach { self.nullableSubject = nil } it("reports nil for index 0,0") { expect(self.nullableSubject[0,0]).to(beNil()) } it("reports nil for index 1,1") { expect(self.nullableSubject[1,1]).to(beNil()) } it("reports an empty array when compactMapped") { expect(self.nullableSubject.compactMap({$0}).isEmpty) == true } context("when setting index 1,1 to 5") { beforeEach { self.nullableSubject[1,1] = 5 } it("continues to report nil for index 0,0") { expect(self.nullableSubject[0,0]).to(beNil()) } it("reports 5 for index 1,1") { expect(self.nullableSubject[1,1]) == 5 } it("reports an array with one element 5 when compactMapped") { expect(self.nullableSubject.compactMap({$0})) == [5] } } context("when setting index 0,0 to 2 and index 0,1 to 4") { beforeEach { self.nullableSubject[0,0] = 2 self.nullableSubject[0,1] = 4 } it("continues to report nil for index 1,1") { expect(self.nullableSubject[1,1]).to(beNil()) } it("reports 2 for index 0,0") { expect(self.nullableSubject[0,0]) == 2 } it("reports 4 for index 0,1") { expect(self.nullableSubject[0,1]) == 4 } it("reports an array of [2,4] when compactMapped") { expect(self.nullableSubject.compactMap({$0})) == [2, 4] } it("reports the expected array when mapped") { let expectedArray: [Int?] = [2, 4, nil, nil, nil, nil, nil, nil, nil] expect(self.nullableSubject.map({$0})) == expectedArray } } context("when setting index 0,0 to 3 and index 2,2 to 6") { beforeEach { self.nullableSubject[0,0] = 3 self.nullableSubject[2,2] = 6 } it("continues to report nil for index 1,1") { expect(self.nullableSubject[1,1]).to(beNil()) } it("reports 3 for index 0,0") { expect(self.nullableSubject[0,0]) == 3 } it("reports 6 for index 2,2") { expect(self.nullableSubject[2,2]) == 6 } it("reports an array of [3,6] when compactMapped") { expect(self.nullableSubject.compactMap({$0})) == [3, 6] } it("reports the expected array when mapped") { let expectedArray: [Int?] = [3, nil, nil, nil, nil, nil, nil, nil, 6] expect(self.nullableSubject.map({$0})) == expectedArray } } } describe("A 3x3 nullable integer grid initialized with an array") { let array = [nil, 2, 3, 4, 5, 6, 7, 8, 9] beforeEach { self.nullableSubject = Grid<Int?>(rowSize: 3, columnSize: 3, using: array) } afterEach { self.nullableSubject = nil } it("reports the expected value for 0,0") { expect(self.nullableSubject[0,0]).to(beNil()) } it("reports the expected value for 0,1") { expect(self.nullableSubject[0,1]) == 2 } it("reports the expected value for 1,0") { expect(self.nullableSubject[1,0]) == 4 } it("reports the expected value for 2,2") { expect(self.nullableSubject[2,2]) == 9 } it("reports the original array when mapped") { expect(self.nullableSubject.map({$0})) == array } it("reports the expected last element") { expect(self.nullableSubject.last) == 9 } it("reports the correct reverse map") { expect(self.nullableSubject.reversed()) == array.reversed() } } describe("A 3x3 nonnull integer grid initialized with an array") { beforeEach { self.nonnullSubject = Grid<Int>(rowSize: 3, columnSize: 3, using: [1, 2, 3, 4, 5, 6, 7, 8, 9]) } afterEach { self.nonnullSubject = nil } it("reports the expected value for 0,0") { expect(self.nonnullSubject[0,0]) == 1 } it("reports the expected value for 0,1") { expect(self.nonnullSubject[0,1]) == 2 } it("reports the expected value for 1,0") { expect(self.nonnullSubject[1,0]) == 4 } it("reports the expected value for 2,2") { expect(self.nonnullSubject[2,2]) == 9 } it("reports the original array when mapped") { let expectedArray: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9] expect(self.nonnullSubject.map({$0})) == expectedArray } } } }
33.790816
110
0.428205
87164a429db3db13ab1677c87e0529adf524bada
969
// // NotificationController.swift // handball referee companion WatchKit Extension // // Created by personal on 17.10.21. // import WatchKit import SwiftUI import UserNotifications class NotificationController: WKUserNotificationHostingController<NotificationView> { override var body: NotificationView { return NotificationView() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func didReceive(_ notification: UNNotification) { // This method is called when a notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification interface as quickly as possible. } }
28.5
90
0.712074
2fc5077a7c82b09dddb4588a2fbf44777fbdcf7e
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S<I:A protocol A{ protocol A typealias e:A typealias e
25.444444
87
0.772926
e487114b4b236544b14d1ee8ccc3d2e7d710421f
4,381
// // PoloniexExchange.swift // CoinTicker // // Created by Alec Ananian on 1/9/18. // Copyright © 2018 Alec Ananian. // // 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 Starscream import SwiftyJSON class PoloniexExchange: Exchange { private struct Constants { static let WebSocketURL = URL(string: "wss://api2.poloniex.com:443")! static let TickerAPIPath = "https://poloniex.com/public?command=returnTicker" static let TickerChannel = 1002 } init(delegate: ExchangeDelegate? = nil) { super.init(site: .poloniex, delegate: delegate) } override func load() { super.load(from: Constants.TickerAPIPath) { $0.json.compactMap { currencyJSON in let currencyCodes = currencyJSON.0.split(separator: "_") guard currencyCodes.count == 2, let baseCurrency = currencyCodes.last, let quoteCurrency = currencyCodes.first else { return nil } return CurrencyPair( baseCurrency: String(baseCurrency), quoteCurrency: String(quoteCurrency), customCode: currencyJSON.1["id"].stringValue ) } } } override internal func fetch() { requestAPI(Constants.TickerAPIPath).map { [weak self] result in if let strongSelf = self { for (_, result) in result.json { if let currencyPair = strongSelf.selectedCurrencyPair(withCustomCode: result["id"].stringValue) { strongSelf.setPrice(result["last"].doubleValue, for: currencyPair) } } if strongSelf.isUpdatingInRealTime { strongSelf.delegate?.exchangeDidUpdatePrices(strongSelf) } else { strongSelf.onFetchComplete() } } }.catch { error in print("Error fetching Poloniex ticker: \(error)") } if isUpdatingInRealTime { let socket = WebSocket(request: URLRequest(url: Constants.WebSocketURL)) socket.callbackQueue = socketResponseQueue socket.onEvent = { [weak self] event in switch event { case .connected(_): let jsonString = JSON([ "command": "subscribe", "channel": Constants.TickerChannel ]).rawString()! socket.write(string: jsonString) case .text(let text): if let strongSelf = self, let result = JSON(parseJSON: text).array, result.first?.int == Constants.TickerChannel, let data = result.last?.array, data.count >= 2 { if let productId = data.first?.stringValue, let currencyPair = strongSelf.selectedCurrencyPair(withCustomCode: productId) { strongSelf.setPrice(data[1].doubleValue, for: currencyPair) strongSelf.delegate?.exchangeDidUpdatePrices(strongSelf) } } default: break } } socket.connect() self.socket = socket } } }
39.827273
182
0.596896
33430d87738b86755404dae620995c2dba82469e
2,173
// // AppDelegate.swift // Struct // // Created by Tatsuya Tobioka on 2017/11/29. // Copyright © 2017 tnantoka. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.234043
285
0.755637
ebb070640781f2f616ce297b240f519de662bdb2
585
// // User.swift // SiberianViperExample // // Created by Sergey Petrachkov on 05/05/2018. // Copyright © 2018 West Coast IT. All rights reserved. // import Foundation struct User: Equatable { let id: String let firstname: String let lastname: String let description: String public static func ==(lhs: User, rhs: User) -> Bool { return lhs.id == rhs.id } } struct Profile: Account { let user: User var username: String { return "\(self.user.firstname) \(self.user.lastname)" } var description: String { return self.user.description } }
18.28125
57
0.663248
334fb2c51ad0defbbb53a4036f58cb9b7c761d9f
683
/* * Copyright (c) 2019 Zendesk. All rights reserved. * * By downloading or using the Zendesk Mobile SDK, You agree to the Zendesk Master * Subscription Agreement https://www.zendesk.com/company/customers-partners/master-subscription-agreement and Application Developer and API License * Agreement https://www.zendesk.com/company/customers-partners/application-developer-api-license-agreement and * acknowledge that such terms govern Your use of and access to the Mobile SDK. * */ import Foundation typealias SilentPushStrategyCompletion = (Bool) -> Void protocol SilentPushStrategy { func handleNotification(completion: @escaping SilentPushStrategyCompletion) }
37.944444
149
0.789165
390649d7978dbce2da7dcf911a8936cc0864ecde
932
// // Screen.swift // Core // // Created by Alexander Ivlev on 28/09/2019. // Copyright © 2019 ApostleLife. All rights reserved. // import Foundation import UIKit private /*static*/var associatedForRetainKey: UInt8 = 0 private /*static*/var associatedForRouterRetainKey: UInt8 = 0 public class Screen<View: UIViewController, Presenter: AnyObject> { public let view: View public let presenter: Presenter public init(view: View, presenter: Presenter) { self.view = view self.presenter = presenter // yes it's not good, but optimization all code objc_setAssociatedObject(view, &associatedForRetainKey, presenter, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public func setRouter(_ router: IRouter) { // yes it's not good, but optimization all code objc_setAssociatedObject(view, &associatedForRouterRetainKey, router, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } }
28.242424
113
0.717811
fbb8099009793d7f1bba3cdf0c0dc64bddd8672f
404
// // CollectionNoramlCell.swift // DouYuZB // // Created by mario on 2017/11/14. // Copyright © 2017年 mario. All rights reserved. // import UIKit class CollectionNoramlCell: CollectionBaseCell { @IBOutlet weak var roomLabel: UILabel! override var anchor : AnchorModel? { didSet { super.anchor = anchor roomLabel.text = anchor?.room_name } } }
18.363636
49
0.633663
e9e4c4ffdc579e1d00ea0c81067af3e21c195f9a
1,525
// Copyright 2020-2021 Tokamak contributors // // 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. // // Created by Carson Katri on 7/3/20. // import Foundation public struct _RotationEffect: GeometryEffect { public var angle: Angle public var anchor: UnitPoint public init(angle: Angle, anchor: UnitPoint = .center) { self.angle = angle self.anchor = anchor } public func effectValue(size: CGSize) -> ProjectionTransform { .init(CGAffineTransform.identity.rotated(by: CGFloat(angle.radians))) } public func body(content: Content) -> some View { content } public var animatableData: AnimatablePair<Angle.AnimatableData, UnitPoint.AnimatableData> { get { .init(angle.animatableData, anchor.animatableData) } set { (angle.animatableData, anchor.animatableData) = newValue[] } } } public extension View { func rotationEffect(_ angle: Angle, anchor: UnitPoint = .center) -> some View { modifier(_RotationEffect(angle: angle, anchor: anchor)) } }
29.326923
93
0.718689
e95d3839b64def981bbd82d0ab166f3149a2d017
3,435
// // PagingDelegateTests.swift // LithoUXComponents_Tests // // Created by Elliot Schrock on 10/9/19. // Copyright © 2019 CocoaPods. All rights reserved. // import XCTest import fuikit @testable import LUX @testable import FunNet class PagingDelegateTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } func testSecondPage() { var wasCalled = false let pageManager = MockPageManager({ wasCalled = true }) let delegate = FUITableViewDelegate() delegate.onWillDisplay = pageManager.willDisplayFunction() let tv = MockTableView() tv.numberOfRows = 20 tv.previousRow = 14 let cell = UITableViewCell() let indexPath = IndexPath.init(row: 15, section: 0) delegate.tableView(tv, willDisplay: cell, forRowAt: indexPath) XCTAssert(wasCalled) } func testNextPage() { var wasCalled = false let pageManager = MockPageManager({ wasCalled = true }) let delegate = FUITableViewDelegate() delegate.onWillDisplay = pageManager.willDisplayFunction() let tv = MockTableView() tv.numberOfRows = 40 tv.previousRow = 34 let cell = UITableViewCell() let indexPath = IndexPath.init(row: 35, section: 0) delegate.tableView(tv, willDisplay: cell, forRowAt: indexPath) XCTAssert(wasCalled) } func testNotNextPage() { var wasCalled = false let pageManager = MockPageManager({ wasCalled = true }) let delegate = FUITableViewDelegate() delegate.onWillDisplay = pageManager.willDisplayFunction() let tv = MockTableView() tv.numberOfRows = 40 tv.previousRow = 14 let cell = UITableViewCell() let indexPath = IndexPath.init(row: 15, section: 0) delegate.tableView(tv, willDisplay: cell, forRowAt: indexPath) XCTAssertFalse(wasCalled) } func testNotNextWhenPageSizeWrong() { var wasCalled = false let pageManager = MockPageManager({ wasCalled = true }) let delegate = FUITableViewDelegate() delegate.onWillDisplay = pageManager.willDisplayFunction() let tv = MockTableView() tv.numberOfRows = 42 tv.previousRow = 36 let cell = UITableViewCell() let indexPath = IndexPath.init(row: 37, section: 0) delegate.tableView(tv, willDisplay: cell, forRowAt: indexPath) XCTAssertFalse(wasCalled) } } class MockPageManager: LUXCallPager { var nextPageCalled: () -> Void init(_ nextPageCalled: @escaping () -> Void) { self.nextPageCalled = nextPageCalled super.init(CombineNetCall(configuration: ServerConfiguration(host: "lithobyte.co", apiRoute: "api/v1"), Endpoint())) } override func nextPage() { nextPageCalled() } } class MockTableView: UITableView { var previousRow: Int? var numberOfRows: Int? override var indexPathsForVisibleRows: [IndexPath]? { return [IndexPath(row: previousRow!, section: 0)] } override func numberOfRows(inSection section: Int) -> Int { return numberOfRows ?? 0 } }
28.865546
124
0.619505
5da52d656899367a4909645741fd6c96ef987ec8
2,917
// // Data.swift // QueryMall // // Created by Sudikoff Lab iMac on 11/18/15. // Copyright © 2015 QueryMall. All rights reserved. // import Foundation class DataManager{ //Singleton object static let sharedInstance = DataManager() //All objects come with a default public initializer in Swift //This prevents others from using the default '()' initializer for this class. private init(){ } //MARK: - Properties var dealList: [Deal] = [] /* var customerList: [Customer] = [] var orderList: [Order] = [] */ //--------------------------------- // MARK: - Communication with Server // TODO: - Requesting data from the server //--------------------------------- /** Retrieve deals data from the server and reload it to the table view */ func loadDeals() { // Alamofire.request(.GET, Constants.Server_Get_Deallist_URL, parameters: nil) // .responseJSON { response in // print("Alamofire request: \(response.request)") // original URL request // print("Alamofire response: \(response.response)") // URL response // print("Alamofire data: \(response.data)") // server data // print("Alamofire result: \(response.result)") // result of response serialization // // if let JSON = response.result.value { // print("JSON: \(JSON)") // } // } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){ Server.get(Constants.Server_Get_Deallist_URL, completionHandler: { (data) in print(data) self.dealList = data // //Reload table view data in the main thread // dispatch_async(dispatch_get_main_queue()) { // self.tableView.reloadData() // } }) } } func loadDealsMore() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){ Server.get(Constants.Server_Get_Deallist_URL, completionHandler: { (data) in print(data) for var i=0; i<2; i++ { self.dealList.append(data[i]) } // self.deals.addObjectsFromArray(data as NSArray as [AnyObject]) // //Reload table view data in the main thread // dispatch_async(dispatch_get_main_queue()) { // self.tableView.reloadData() // } }) } } }
30.705263
109
0.484745
e06c21c2cf5d9ab3059e614fabb881e6e70932a4
2,596
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import Amplify extension AWSGraphQLOperation: APIOperation { func getOperationId() -> UUID { return id } func cancelOperation() { cancel() } func updateProgress(_ data: Data, response: URLResponse?) { if isCancelled || isFinished { finish() return } let apiOperationResponse = APIOperationResponse(error: nil, response: response) do { try apiOperationResponse.validate() } catch let error as APIError { dispatch(result: .failure(error)) finish() return } catch { dispatch(result: .failure(APIError.unknown("", "", error))) finish() return } graphQLResponseDecoder.appendResponse(data) } func complete(with error: Error?, response: URLResponse?) { if isCancelled || isFinished { finish() return } let apiOperationResponse = APIOperationResponse(error: error, response: response) do { try apiOperationResponse.validate() } catch let error as APIError { dispatch(result: .failure(error)) finish() return } catch { dispatch(result: .failure(APIError.unknown("", "", error))) finish() return } do { let graphQLResponse = try graphQLResponseDecoder.decodeToGraphQLResponse() dispatch(result: .success(graphQLResponse)) finish() } catch let error as APIError { dispatch(result: .failure(error)) finish() } catch { let apiError = APIError.operationError("failed to process graphqlResponseData", "", error) dispatch(result: .failure(apiError)) finish() } } } class APIErrorHelper { static func getDefaultError(_ error: NSError) -> APIError { let errorMessage = """ Domain: [\(error.domain) Code: [\(error.code) LocalizedDescription: [\(error.localizedDescription) LocalizedFailureReason: [\(error.localizedFailureReason ?? "") LocalizedRecoverySuggestion: [\(error.localizedRecoverySuggestion ?? "") """ return APIError.unknown(errorMessage, "", error) } }
28.844444
102
0.548921
ef38e59d4e50d0fb7de7b5daa26d88daa3fef32c
917
// // QueueTests.swift // Signal // // Created by Khoa Pham on 1/2/16. // Copyright © 2016 Fantageek. All rights reserved. // import XCTest class QueueTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
25.472222
111
0.633588
5dcad14f8a6ea7a94d2c52b19d9daeba67b54c68
813
// // RestaurantDetailHeaderView.swift // FoodPin // // Created by Simon Ng on 8/9/2017. // Copyright © 2017 AppCoda. All rights reserved. // import UIKit class RestaurantDetailHeaderView: UIView { @IBOutlet var headerImageView: UIImageView! @IBOutlet var nameLabel: UILabel! { didSet { nameLabel.numberOfLines = 0 } } @IBOutlet var typeLabel: UILabel! { didSet { typeLabel.layer.cornerRadius = 5.0 typeLabel.layer.masksToBounds = true } } @IBOutlet var heartImageView: UIImageView! { didSet { heartImageView.image = UIImage(named: "heart-tick")?.withRenderingMode(.alwaysTemplate) heartImageView.tintColor = .white } } @IBOutlet var ratingImageView: UIImageView! }
24.636364
99
0.627306
1e08e6f3a49ad56e44273c316f9b2f6347638d24
2,853
// // DSFSparkline+Palette.swift // DSFSparklines // // Created by Darren Ford on 12/2/21. // Copyright © 2021 Darren Ford. All rights reserved. // // 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. // #if os(macOS) import Cocoa #else import UIKit #endif public extension DSFSparkline { /// The palette to use when drawing the pie. The first value in the datasource uses the first color, /// the second the second color etc. If there are more datapoints than colors (you shouldn't do this!) then /// the chart will start back at the start of the palette. /// /// These palettes can be safely shared between multiple pie views @objc(DSFSparklinePalette) class Palette: NSObject { /// The colors to be used when drawing segments @objc public let colors: [DSFColor] @objc public let cgColors: NSArray /// A default palette used when no palette is specified. @objc public static let shared = DSFSparkline.Palette([ DSFColor.systemRed, DSFColor.systemOrange, DSFColor.systemYellow, DSFColor.systemGreen, DSFColor.systemBlue, DSFColor.systemPurple, DSFColor.systemPink, ]) /// A default palette used when no palette is specified @objc public static let sharedGrays = DSFSparkline.Palette([ DSFColor(white: 0.9, alpha: 1), DSFColor(white: 0.7, alpha: 1), DSFColor(white: 0.5, alpha: 1), DSFColor(white: 0.3, alpha: 1), DSFColor(white: 0.1, alpha: 1), ]) @objc public init(_ colors: [DSFColor]) { self.colors = colors self.cgColors = NSArray(array: colors.map { $0.cgColor }) super.init() } @inlinable func colorAtOffset(_ offset: Int) -> DSFColor { return self.colors[offset % self.colors.count] } @inlinable func cgColorAtOffset(_ offset: Int) -> CGColor { return self.cgColors[offset % self.colors.count] as! CGColor } } }
37.539474
120
0.728707
ddfe5331258385f37a6a4c6750ca407bebb20a00
964
// // squashTests.swift // squashTests // // Created by Marc Risney on 9/23/16. // Copyright © 2016 Marc Risney. All rights reserved. // import XCTest @testable import squash class squashTests: 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.054054
111
0.629668
5df99368c80775337c8d960878ee24cc4b23e163
11,312
// // UpdatePinViewController.swift // breadwallet // // Created by Adrian Corscadden on 2017-02-16. // Copyright © 2017 breadwallet LLC. All rights reserved. // import UIKit import LocalAuthentication enum UpdatePinType { case creationNoPhrase case creationWithPhrase case update } class UpdatePinViewController : UIViewController, Subscriber { //MARK: - Public var setPinSuccess: ((String) -> Void)? var resetFromDisabledSuccess: (() -> Void)? var resetFromDisabledWillSucceed: (() -> Void)? init(store: Store, walletManager: WalletManager, type: UpdatePinType, showsBackButton: Bool = true, phrase: String? = nil) { self.store = store self.walletManager = walletManager self.phrase = phrase self.pinView = PinView(style: .create, length: store.state.pinLength) self.showsBackButton = showsBackButton self.faq = UIButton.buildFaqButton(store: store, articleId: ArticleIds.setPin) self.type = type super.init(nibName: nil, bundle: nil) } //MARK: - Private private let header = UILabel.wrapping(font: .customBold(size: 26.0), color: .darkText) private let instruction = UILabel.wrapping(font: .customBody(size: 14.0), color: .darkText) private let caption = UILabel.wrapping(font: .customBody(size: 13.0), color: .secondaryGrayText) private var pinView: PinView private let pinPad = PinPadViewController(style: .white, keyboardType: .pinPad, maxDigits: 0) private let spacer = UIView() private let store: Store private let walletManager: WalletManager private let faq: UIButton private var step: Step = .verify { didSet { switch step { case .verify: instruction.text = isCreatingPin ? S.UpdatePin.createInstruction : S.UpdatePin.enterCurrent caption.isHidden = true case .new: let instructionText = isCreatingPin ? S.UpdatePin.createInstruction : S.UpdatePin.enterNew if instruction.text != instructionText { instruction.pushNewText(instructionText) } header.text = S.UpdatePin.createTitle caption.isHidden = false case .confirmNew: caption.isHidden = true if isCreatingPin { header.text = S.UpdatePin.createTitleConfirm } else { instruction.pushNewText(S.UpdatePin.reEnterNew) } } } } private var currentPin: String? private var newPin: String? private var phrase: String? private let type: UpdatePinType private var isCreatingPin: Bool { return type != .update } private let newPinLength = 6 private let showsBackButton: Bool private enum Step { case verify case new case confirmNew } override func viewDidLoad() { addSubviews() addConstraints() setData() } private func addSubviews() { view.addSubview(header) view.addSubview(instruction) view.addSubview(caption) view.addSubview(pinView) view.addSubview(faq) view.addSubview(spacer) } private func addConstraints() { header.constrain([ header.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: C.padding[2]), header.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]), header.trailingAnchor.constraint(equalTo: faq.leadingAnchor, constant: -C.padding[1]) ]) instruction.constrain([ instruction.leadingAnchor.constraint(equalTo: header.leadingAnchor), instruction.topAnchor.constraint(equalTo: header.bottomAnchor, constant: C.padding[2]), instruction.trailingAnchor.constraint(equalTo: header.trailingAnchor) ]) pinView.constrain([ pinView.centerYAnchor.constraint(equalTo: spacer.centerYAnchor), pinView.centerXAnchor.constraint(equalTo: view.centerXAnchor), pinView.widthAnchor.constraint(equalToConstant: pinView.width), pinView.heightAnchor.constraint(equalToConstant: pinView.itemSize) ]) if E.isIPhoneX { addChildViewController(pinPad, layout: { pinPad.view.constrainBottomCorners(sidePadding: 0.0, bottomPadding: 0.0) pinPad.view.constrain([pinPad.view.heightAnchor.constraint(equalToConstant: pinPad.height), pinPad.view.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -C.padding[3])]) }) } else { addChildViewController(pinPad, layout: { pinPad.view.constrainBottomCorners(sidePadding: 0.0, bottomPadding: 0.0) pinPad.view.constrain([pinPad.view.heightAnchor.constraint(equalToConstant: pinPad.height)]) }) } spacer.constrain([ spacer.topAnchor.constraint(equalTo: instruction.bottomAnchor), spacer.bottomAnchor.constraint(equalTo: caption.topAnchor) ]) faq.constrain([ faq.topAnchor.constraint(equalTo: header.topAnchor), faq.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]), faq.constraint(.height, constant: 44.0), faq.constraint(.width, constant: 44.0)]) caption.constrain([ caption.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]), caption.bottomAnchor.constraint(equalTo: pinPad.view.topAnchor, constant: -C.padding[2]), caption.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]) ]) } private func setData() { caption.text = S.UpdatePin.caption view.backgroundColor = .whiteTint header.text = isCreatingPin ? S.UpdatePin.createTitle : S.UpdatePin.updateTitle instruction.text = isCreatingPin ? S.UpdatePin.createInstruction : S.UpdatePin.enterCurrent pinPad.ouputDidUpdate = { [weak self] text in guard let step = self?.step else { return } switch step { case .verify: self?.didUpdateForCurrent(pin: text) case .new : self?.didUpdateForNew(pin: text) case .confirmNew: self?.didUpdateForConfirmNew(pin: text) } } if isCreatingPin { step = .new caption.isHidden = false } else { caption.isHidden = true } if !showsBackButton { navigationItem.leftBarButtonItem = nil navigationItem.hidesBackButton = true } } private func didUpdateForCurrent(pin: String) { pinView.fill(pin.utf8.count) if pin.utf8.count == store.state.pinLength { if walletManager.authenticate(pin: pin) { pushNewStep(.new) currentPin = pin replacePinView() } else { if walletManager.walletDisabledUntil > 0 { dismiss(animated: true, completion: { self.store.perform(action: RequireLogin()) }) } else { clearAfterFailure() } } } } private func didUpdateForNew(pin: String) { pinView.fill(pin.utf8.count) if pin.utf8.count == newPinLength { newPin = pin pushNewStep(.confirmNew) } } private func didUpdateForConfirmNew(pin: String) { guard let newPin = newPin else { return } pinView.fill(pin.utf8.count) if pin.utf8.count == newPinLength { if pin == newPin { didSetNewPin() } else { clearAfterFailure() pushNewStep(.new) } } } private func clearAfterFailure() { pinPad.view.isUserInteractionEnabled = false pinView.shake { [weak self] in self?.pinPad.view.isUserInteractionEnabled = true self?.pinView.fill(0) } pinPad.clear() } private func replacePinView() { pinView.removeFromSuperview() pinView = PinView(style: .create, length: newPinLength) view.addSubview(pinView) pinView.constrain([ pinView.centerYAnchor.constraint(equalTo: spacer.centerYAnchor), pinView.centerXAnchor.constraint(equalTo: view.centerXAnchor), pinView.widthAnchor.constraint(equalToConstant: pinView.width), pinView.heightAnchor.constraint(equalToConstant: pinView.itemSize) ]) } private func pushNewStep(_ newStep: Step) { step = newStep pinPad.clear() DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.pinView.fill(0) } } private func didSetNewPin() { DispatchQueue.walletQueue.async { [weak self] in guard let newPin = self?.newPin else { return } var success: Bool? = false if let seedPhrase = self?.phrase { success = self?.walletManager.forceSetPin(newPin: newPin, seedPhrase: seedPhrase) } else if let currentPin = self?.currentPin { success = self?.walletManager.changePin(newPin: newPin, pin: currentPin) DispatchQueue.main.async { self?.store.trigger(name: .didUpgradePin) } } else if self?.type == .creationNoPhrase { success = self?.walletManager.forceSetPin(newPin: newPin) } DispatchQueue.main.async { if let success = success, success == true { if self?.resetFromDisabledSuccess != nil { self?.resetFromDisabledWillSucceed?() self?.store.perform(action: Alert.Show(.pinSet(callback: { [weak self] in self?.dismiss(animated: true, completion: { self?.resetFromDisabledSuccess?() }) }))) } else { self?.store.perform(action: Alert.Show(.pinSet(callback: { [weak self] in self?.setPinSuccess?(newPin) if self?.type != .creationNoPhrase { self?.parent?.dismiss(animated: true, completion: nil) } }))) } } else { let alert = UIAlertController(title: S.UpdatePin.updateTitle, message: S.UpdatePin.setPinError, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: { [weak self] _ in self?.clearAfterFailure() self?.pushNewStep(.new) })) self?.present(alert, animated: true, completion: nil) } } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
39.691228
139
0.588667
72e55356e3ffacf41e4b7348436a332b96ca8231
742
import Foundation import struct SwiftUI.LocalizedStringKey extension PasswordGeneratorView.ConfigurationView { enum PasswordType: CaseIterable, Hashable { case domainBased case serviceBased var title: LocalizedStringKey { switch self { case .domainBased: return Strings.PasswordGeneratorView.domainBased case .serviceBased: return Strings.PasswordGeneratorView.serviceBased } } } struct State: Equatable { var passwordType: PasswordType var domainState: PasswordGeneratorView.DomainView.State var serviceState: PasswordGeneratorView.ServiceView.State var isValid: Bool } }
23.1875
65
0.657682
ddd8f248ebb737ce6f795706ae0eab231dc1ef4d
64,861
/* * Copyright 2019 Google Inc. 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 UIKit import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_private_KeyboardWatcher_KeyboardWatcher import third_party_objective_c_material_components_ios_components_Snackbar_Snackbar protocol ExperimentCoordinatorViewControllerDelegate: class { /// Informs the delegate an experiment's archive state should be toggled. /// /// - Parameter experimentID: An experiment ID. func experimentViewControllerToggleArchiveStateForExperiment(withID experimentID: String) /// Informs the delegate the experiment should be deleted. /// /// - Parameter experiment: The experiment to delete. func experimentViewControllerDidRequestDeleteExperiment(_ experiment: Experiment) /// Informs the delegate the archive state of a trial should be toggled. /// /// - Parameter trialID: A trial ID. func experimentViewControllerToggleArchiveStateForTrial(withID trialID: String) /// Informs the delegate a trial should be shown. /// /// - Parameters: /// - trialID: A trial ID. /// - jumpToCaption: Whether to jump to the caption input when showing the trial. func experimentViewControllerShowTrial(withID trialID: String, jumpToCaption: Bool) /// Informs the delegate a note should be shown. /// /// - Parameters: /// - displayNote: The display note to show. /// - jumpToCaption: Whether to jump to the caption input when showing the trial. func experimentViewControllerShowNote(_ displayNote: DisplayNote, jumpToCaption: Bool) /// Informs the delegate a trial should be added to the current experiment. /// /// - Parameters: /// - trial: The trial to add. /// - isRecording: Whether the trial is recording. func experimentViewControllerAddTrial(_ trial: Trial, recording isRecording: Bool) /// Informs the delegate the deletion of a trial is complete, meaning it can no longer be undone. /// /// - Parameters: /// - trial: A trial. /// - experiment: The experiment the trial belonged to. func experimentViewControllerDeleteTrialCompleted(_ trial: Trial, fromExperiment experiment: Experiment) /// Informs the delegate that a trial finished recording. /// /// - Parameters: /// - trial: The trial. /// - experiment: The experiment the trial belongs to. func experimentViewControllerDidFinishRecordingTrial(_ trial: Trial, forExperiment experiment: Experiment) /// Informs the delegate the cover image for this experiment should be removed. /// /// - Parameter experiment: The experiment. /// - Returns: True if successful, otherwise false. func experimentViewControllerRemoveCoverImageForExperiment(_ experiment: Experiment) -> Bool /// Informs the delegate the experiment title changed. /// /// - Parameters: /// - title: The experiment title. /// - experiment: The experiment that changed. func experimentViewControllerDidSetTitle(_ title: String?, forExperiment experiment: Experiment) /// Informs the delegate the experiment cover image changed. /// /// - Parameters: /// - imageData: The cover image data. /// - metadata: The metadata associated with the image. /// - experiment: The experiment whose cover image was set. func experimentViewControllerDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperiment experiment: Experiment) /// Informs the delegate the experiment's recording trial changed. /// /// - Parameters: /// - recordingTrial: The recoring trial that changed. /// - experiment: The experiment that was changed. func experimentViewControllerDidChangeRecordingTrial(_ recordingTrial: Trial, experiment: Experiment) /// Informs the delegate an experiment picture note delete has completed. /// /// - Parameters: /// - pictureNote: The picture note. /// - experiment: The experiment the picture note belonged to. func experimentViewControllerDeletePictureNoteCompleted(_ pictureNote: PictureNote, forExperiment experiment: Experiment) } /// A coordinator view controller responsible for displaying the items in an experiment. class ExperimentCoordinatorViewController: MaterialHeaderViewController, DrawerPositionListener, EditExperimentViewControllerDelegate, ImageSelectorDelegate, NotesViewControllerDelegate, ObserveViewControllerDelegate, SensorSettingsDelegate, TriggerListDelegate, ExperimentItemsViewControllerDelegate, ExperimentUpdateListener, ExperimentStateListener { // MARK: - Properties /// The edit bar button. Exposed for testing. let editBarButton = MaterialBarButtonItem() /// The menu bar button. Exposed for testing. let menuBarButton = MaterialMenuBarButtonItem() /// A fixed space bar item. Exposed for testing. lazy var fixedSpaceBarItem: UIBarButtonItem = { let fixedSpace = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) fixedSpace.width = ViewConstants.iPadDrawerSidebarWidth + 16 fixedSpace.isEnabled = false return fixedSpace }() /// Interaction options for this experiment. var experimentInteractionOptions: ExperimentInteractionOptions /// The experiment. Exposed for testing. var experiment: Experiment weak var delegate: ExperimentCoordinatorViewControllerDelegate? weak var itemDelegate: ExperimentItemDelegate? private var dialogTransitionController: MDCDialogTransitionController? private let drawerVC: DrawerViewController? private let experimentDataParser: ExperimentDataParser private let experimentItemsViewController: ExperimentItemsViewController private let documentManager: DocumentManager private let metadataManager: MetadataManager private var renameDialog: RenameExperimentViewController? private var emptyViewTrailingConstraint: NSLayoutConstraint? private var drawerViewWidthConstraintSideBySide: NSLayoutConstraint? private var drawerViewLeadingConstraint: NSLayoutConstraint? private let emptyView = EmptyView(title: String.emptyExperiment, imageName: "empty_experiment_view") private var backMenuItem: MaterialBackBarButtonItem? private var drawerViewTopConstraint: NSLayoutConstraint? private let preferenceManager: PreferenceManager private let sensorController: SensorController private let sensorDataManager: SensorDataManager private let snackbarCategoryTriggersDisabled = "snackbarCategoryTriggersDisabled" private let snackbarCategoryDeletedRecording = "snackbarCategoryDeletedRecording" private let snackbarCategoryNoteDeleted = "snackbarCategoryNoteDeleted" private let snackbarCategoryExperimentArchivedState = "snackbarCategoryExperimentArchivedState" private let snackbarCategoryTrialArchivedState = "snackbarCategoryTrialArchivedState" private let snackbarCategoryCouldNotUpdateSensorSettings = "snackbarCategoryCouldNotUpdateSensorSettings" private let shouldAllowSharing: Bool // A dictionary of chart controllers, keyed by sensor ID. private var chartControllers = [String: ChartController]() private var statusBarHeight: CGFloat { return UIApplication.shared.statusBarFrame.size.height } override var trackedScrollView: UIScrollView? { return experimentItemsViewController.collectionView } /// Should the experiment require a name? Default is true. If false, user will not be asked to /// rename the experiment when leaving the VC if the title is not set. var requireExperimentTitle: Bool = true // MARK: - Public /// Designated initializer that takes an experiment. /// /// - Parameters: /// - experiment: The experiment. /// - experimentInteractionOptions: Experiment interaction options. /// - shouldAllowSharing: Should this experiment and its contents be shareable? /// - drawerViewController: A drawer view controller. /// - analyticsReporter: An AnalyticsReporter. /// - metadataManager: The metadata manager. /// - preferenceManager: The preference manager. /// - sensorController: The sensor controller. /// - sensorDataManager: The sensor data manager. /// - documentManager: The document manager. init(experiment: Experiment, experimentInteractionOptions: ExperimentInteractionOptions, shouldAllowSharing: Bool, drawerViewController: DrawerViewController?, analyticsReporter: AnalyticsReporter, metadataManager: MetadataManager, preferenceManager: PreferenceManager, sensorController: SensorController, sensorDataManager: SensorDataManager, documentManager: DocumentManager) { self.experiment = experiment self.experimentInteractionOptions = experimentInteractionOptions self.shouldAllowSharing = shouldAllowSharing self.drawerVC = drawerViewController self.metadataManager = metadataManager self.preferenceManager = preferenceManager self.sensorController = sensorController self.sensorDataManager = sensorDataManager self.documentManager = documentManager experimentDataParser = ExperimentDataParser(experimentID: experiment.ID, metadataManager: metadataManager, sensorController: sensorController) let isExperimentArchived = metadataManager.isExperimentArchived(withID: experiment.ID) experimentItemsViewController = ExperimentItemsViewController(experimentInteractionOptions: experimentInteractionOptions, metadataManager: metadataManager, shouldShowArchivedFlag: isExperimentArchived) super.init(analyticsReporter: analyticsReporter) experimentItemsViewController.delegate = self experimentItemsViewController.scrollDelegate = self // Set delegate for all drawer items. drawerVC?.observeViewController.delegate = self drawerVC?.cameraViewController.delegate = self drawerVC?.photoLibraryViewController.delegate = self drawerVC?.notesViewController.delegate = self // Configure observe. updateObserveWithExperimentTriggers() drawerVC?.observeViewController.setSensorLayouts(experiment.sensorLayouts, andAddListeners: experimentInteractionOptions.shouldShowDrawer) updateObserveWithAvailableSensors() // Register for trial stats update notifications. NotificationCenter.default.addObserver(self, selector: #selector(handleTrialStatsDidCompleteNotification(notification:)), name: SensorDataManager.TrialStatsCalculationDidComplete, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } deinit { drawerVC?.removeDrawerPositionListener(self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = MDCPalette.grey.tint200 updateExperimentTitle() // Experiment items view controller. This must be configured before the drawer or empty view, // because both rely on the experiment items count. experimentItemsViewController.view.translatesAutoresizingMaskIntoConstraints = false addChild(experimentItemsViewController) view.addSubview(experimentItemsViewController.view) experimentItemsViewController.view.pinToEdgesOfView(view) setCollectionViewInset() reloadExperimentItems() // Drawer. if let drawerVC = drawerVC { addChild(drawerVC) view.addSubview(drawerVC.drawerView) drawerVC.drawerView.translatesAutoresizingMaskIntoConstraints = false // TODO: This needs to be smart about in-call status bar changes. http://b/62135678 drawerViewTopConstraint = drawerVC.drawerView.topAnchor.constraint(equalTo: view.topAnchor, constant: statusBarHeight) drawerViewTopConstraint?.isActive = true drawerVC.drawerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true drawerVC.drawerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true drawerViewWidthConstraintSideBySide = drawerVC.drawerView.widthAnchor.constraint( equalToConstant: ViewConstants.iPadDrawerSidebarWidth) drawerViewLeadingConstraint = drawerVC.drawerView.leadingAnchor.constraint(equalTo: view.leadingAnchor) drawerVC.addDrawerPositionListener(self) updateDrawerForExperimentInteractionOptions(animated: false) } // Configure the empty view. emptyView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(emptyView) emptyView.topAnchor.constraint(equalTo: appBar.navigationBar.bottomAnchor).isActive = true emptyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true emptyViewTrailingConstraint = emptyView.trailingAnchor.constraint(equalTo: view.trailingAnchor) emptyViewTrailingConstraint?.isActive = true emptyView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true updateEmptyViewArchivedFlagInsets() updateEmptyView(animated: false) updateConstraints(forDisplayType: displayType, withSize: view.bounds.size) // Bar buttons. backMenuItem = MaterialBackBarButtonItem(target: self, action: #selector(backButtonPressed)) navigationItem.hidesBackButton = true navigationItem.leftBarButtonItem = backMenuItem editBarButton.button.addTarget(self, action: #selector(editButtonPressed), for: .touchUpInside) editBarButton.button.setImage(UIImage(named: "ic_edit"), for: .normal) editBarButton.button.accessibilityLabel = String.editExperimentBtnContentDescription editBarButton.button.accessibilityHint = String.editExperimentBtnContentDetails menuBarButton.button.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside) menuBarButton.button.setImage(UIImage(named: "ic_more_horiz"), for: .normal) updateRightBarButtonItems(for: displayType) // Reset the drawer since it is reused between experiments. drawerVC?.reset() if let drawerVC = drawerVC, drawerVC.isDisplayedAsSidebar { drawerVC.setPositionToFull(animated: false) } else if experimentItemsViewController.isEmpty { // If there is no content, display drawer at half height to encourage input. drawerVC?.setPositionToHalfOrPeeking(animated: false) } else { // Hide the drawer by default. drawerVC?.setPositionToPeeking(animated: false) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Bring the drawer to the front of the app bar view, which is brought to the front in // MaterialHeaderViewController. if let drawerVC = drawerVC { view.bringSubviewToFront(drawerVC.drawerView) } NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: .MDCKeyboardWatcherKeyboardWillChangeFrame, object: nil) setCollectionViewInset() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: .MDCKeyboardWatcherKeyboardWillChangeFrame, object: nil) // Dismiss snackbars presented by this view controller, but don't dismiss the delete experiment // undo snackbar. [snackbarCategoryTriggersDisabled, snackbarCategoryDeletedRecording, snackbarCategoryNoteDeleted, snackbarCategoryExperimentArchivedState, snackbarCategoryTrialArchivedState, snackbarCategoryCouldNotUpdateSensorSettings].forEach { MDCSnackbarManager.dismissAndCallCompletionBlocks(withCategory: $0) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (_) in let displayType = self.traitCollection.displayType(with: size) self.updateConstraints(forDisplayType: displayType, withSize: size) self.updateRightBarButtonItems(for: displayType) self.updateDrawerPosition(for: displayType, size: size) self.updateHeaderColor() self.updateEmptyViewArchivedFlagInsets() }) } /// Reloads the view with a new experiment. /// /// - Parameter experiment: An experiment. func reloadWithNewExperiment(_ experiment: Experiment) { self.experiment = experiment updateExperimentTitle() reloadExperimentItems() updateEmptyView(animated: true) } // Displays a detail view controller for the the display item, optionally jumping to the caption // field when it loads. private func displayDetailViewController(for displayItem: DisplayItem, jumpToCaption: Bool = false) { switch displayItem { case let displayTrial as DisplayTrial: delegate?.experimentViewControllerShowTrial(withID: displayTrial.ID, jumpToCaption: jumpToCaption) case let displayNote as DisplayNote: delegate?.experimentViewControllerShowNote(displayNote, jumpToCaption: jumpToCaption) default: return } } /// Cancels a recording if there was one in progress. func cancelRecordingIfNeeded() { guard RecordingState.isRecording else { return } drawerVC?.observeViewController.endRecording(isCancelled: true) } // MARK: - DrawerPositionListener func drawerViewController(_ drawerViewController: DrawerViewController, isPanningDrawerView drawerView: DrawerView) {} func drawerViewController(_ drawerViewController: DrawerViewController, willChangeDrawerPosition position: DrawerPosition) {} func drawerViewController(_ drawerViewController: DrawerViewController, didPanBeyondBounds panDistance: CGFloat) {} func drawerViewController(_ drawerViewController: DrawerViewController, didChangeDrawerPosition position: DrawerPosition) { setCollectionViewInset(onlyIfViewIsVisible: true) updateHeaderColor() } // MARK: - ExperimentItemsViewControllerDelegate func experimentItemsViewControllerDidSelectItem(_ displayItem: DisplayItem) { if RecordingState.isRecording { // Trial is recording, disable cell taps for detail views and taps on the recording indicator // cell should take you to a halfway-open drawer on the observe tab in portrait, open full // drawer in landscape. guard let displayTrial = displayItem as? DisplayTrial, displayTrial.status != .final else { return } drawerVC?.showContent() guard drawerVC?.currentViewController is ObserveViewController else { drawerVC?.selectObserve() return } } else { // No trial recording currently, cells tapped lead to detail views. displayDetailViewController(for: displayItem) } } func experimentItemsViewControllerMenuPressedForItem(_ displayItem: DisplayItem, button: MenuButton) { let popUpMenu = PopUpMenuViewController() // If the user is recording, we don't want them to enter any other VC like details, so remove // these menu items. if !RecordingState.isRecording { // View. func addViewAction() { popUpMenu.addAction(PopUpMenuAction( title: String.actionViewDetails, icon: UIImage(named: "ic_visibility")) { _ -> Void in self.displayDetailViewController(for: displayItem) }) } // Comment. func addCommentAction() { popUpMenu.addAction(PopUpMenuAction( title: String.actionAddCaption, icon: UIImage(named: "ic_comment")) { _ -> Void in self.displayDetailViewController(for: displayItem, jumpToCaption: true) }) } switch displayItem.itemType { case .textNote: // Edit. func showEditAction() { popUpMenu.addAction(PopUpMenuAction(title: String.actionEdit, icon: UIImage(named: "ic_edit")) { _ -> Void in self.displayDetailViewController(for: displayItem) }) } if experimentInteractionOptions.shouldAllowEdits { showEditAction() } else { addViewAction() } case .trial(_): addViewAction() case .snapshotNote(_), .pictureNote(_), .triggerNote(_): addViewAction() if experimentInteractionOptions.shouldAllowEdits { addCommentAction() } } } // Archive. func showArchiveAction(forTrial displayTrial: DisplayTrial) { let archiveTitle = displayTrial.isArchived ? String.actionUnarchive : String.actionArchive let archiveAccessibilityLabel = displayTrial.isArchived ? String.actionUnarchiveRecordingContentDescription : String.actionArchiveRecordingContentDescription let archiveImageName = displayTrial.isArchived ? "ic_unarchive" : "ic_archive" popUpMenu.addAction(PopUpMenuAction(title: archiveTitle, icon: UIImage(named: archiveImageName), accessibilityLabel: archiveAccessibilityLabel, handler: { (_) in self.delegate?.experimentViewControllerToggleArchiveStateForTrial(withID: displayTrial.ID) })) } if experimentInteractionOptions.shouldAllowEdits { switch displayItem.itemType { case .trial(let displayTrial): showArchiveAction(forTrial: displayTrial) default: break } } // Send a copy. if shouldAllowSharing, !RecordingState.isRecording, let displayPictureNote = displayItem as? DisplayPictureNote, displayPictureNote.imageFileExists, let imagePath = displayPictureNote.imagePath { popUpMenu.addAction(PopUpMenuAction.share(withFilePath: imagePath, presentingViewController: self, sourceView: button)) } // Delete. func showDeleteAction() { popUpMenu.addAction(PopUpMenuAction( title: String.actionDelete, icon: UIImage(named: "ic_delete"), accessibilityLabel: displayItem.itemType.deleteActionAccessibilityLabel) { _ -> Void in switch displayItem.itemType { case .trial(let trial): // Prompt the user to confirm deletion. let alertController = MDCAlertController(title: String.deleteRunDialogTitle, message: String.runReviewDeleteConfirm) let cancelAction = MDCAlertAction(title: String.btnDeleteObjectCancel) let deleteAction = MDCAlertAction(title: String.btnDeleteObjectConfirm) { (action) in // Delete the trial. self.itemDelegate?.trialDetailViewControllerDidRequestDeleteTrial(withID: trial.ID) } alertController.addAction(cancelAction) alertController.addAction(deleteAction) self.present(alertController, animated: true) default: if let displayNote = displayItem as? DisplayNote { self.itemDelegate?.detailViewControllerDidDeleteNote(displayNote) } } }) } if experimentInteractionOptions.shouldAllowDeletes { showDeleteAction() } popUpMenu.present(from: self, position: .sourceView(button)) } func experimentItemsViewControllerCommentPressedForItem(_ displayItem: DisplayItem) { displayDetailViewController(for: displayItem, jumpToCaption: true) } // MARK: - EditExperimentViewControllerDelegate func editExperimentViewControllerDidSetTitle(_ title: String?, forExperimentID experimentID: String) { delegate?.experimentViewControllerDidSetTitle(title, forExperiment: experiment) updateExperimentTitle() } func editExperimentViewControllerDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperimentID experimentID: String) { delegate?.experimentViewControllerDidSetCoverImageData(imageData, metadata: metadata, forExperiment: experiment) } // MARK: - ObserveViewControllerDelegate func observeViewControllerDidStartRecording(_ observeViewController: ObserveViewController) { experimentItemsViewController.collectionViewChangeScrollPosition = .bottom updateForRecording() } func observeViewControllerDidEndRecording(_ observeViewController: ObserveViewController) { experimentItemsViewController.collectionViewChangeScrollPosition = .top updateForRecording() } func observeViewController(_ observeViewController: ObserveViewController, didCreateSensorSnapshots sensorSnapshots: [SensorSnapshot]) { let snapshotNote = SnapshotNote(snapshots: sensorSnapshots) addNoteToExperimentOrTrial(snapshotNote) } func observeViewController(_ observeViewController: ObserveViewController, didReceiveNoteTrigger trigger: SensorTrigger, forSensor sensor: Sensor, atTimestamp timestamp: Int64) { let sensorSpec = SensorSpec(sensor: sensor) let triggerNote = TriggerNote(sensorSpec: sensorSpec, triggerInformation: trigger.triggerInformation, timestamp: timestamp) addNoteToExperimentOrTrial(triggerNote) } func observeViewController(_ observeViewController: ObserveViewController, didBeginTrial trial: Trial) { delegate?.experimentViewControllerAddTrial(trial, recording: true) } func observeViewController(_ observeViewController: ObserveViewController, didUpdateTrial trial: Trial, isFinishedRecording: Bool) { if isFinishedRecording { updateTrial(trial, didFinishRecording: isFinishedRecording) delegate?.experimentViewControllerDidFinishRecordingTrial(trial, forExperiment: experiment) UIAccessibility.post( notification: .announcement, argument: "\(String.runAddedContentDescription) \(String.toExperimentContentDescription)") } delegate?.experimentViewControllerDidChangeRecordingTrial(trial, experiment: experiment) } func observeViewController(_ observeViewController: ObserveViewController, didCancelTrial trial: Trial) { // Delete the trial and sensor data. experiment.removeTrial(withID: trial.ID) sensorDataManager.removeData(forTrialID: trial.ID) removeRecordingTrial() // Save the experiement. metadataManager.saveExperiment(experiment) // Now delete associated images. metadataManager.removeImagesAtPaths(trial.allImagePaths, experiment: experiment) // Update the UI. updateEmptyView(animated: true) } func observeViewController(_ observeViewController: ObserveViewController, didPressSetTriggersForSensor sensor: Sensor) { showTriggerListViewController(for: sensor) } func observeViewController(_ observeViewController: ObserveViewController, isSensorTriggerActive sensorTrigger: SensorTrigger) -> Bool { guard let index = experiment.sensorLayouts.index(where: { $0.sensorID == sensorTrigger.sensorID }) else { return false } return experiment.sensorLayouts[index].isTriggerActive(sensorTrigger.triggerID) } func observeViewController(_ observeViewController: ObserveViewController, didUpdateSensorLayouts sensorLayouts: [SensorLayout]) { // Only save the experiment if anything changed. if sensorLayouts != experiment.sensorLayouts { experiment.sensorLayouts = sensorLayouts metadataManager.saveExperimentWithoutDateChange(experiment) } } func observeViewControllerDidPressSensorSettings(_ observeViewController: ObserveViewController) { let vc = SensorSettingsViewController(enabledSensorIDs: experiment.availableSensorIDs, analyticsReporter: analyticsReporter, metadataManager: metadataManager, sensorController: sensorController) vc.delegate = self if UIDevice.current.userInterfaceIdiom == .pad { vc.modalPresentationStyle = .formSheet } present(vc, animated: true) } func observeViewController(_ observeViewController: ObserveViewController, didExceedTriggerFireLimitForSensor sensor: Sensor) { guard let sensorLayout = experiment.sensorLayoutForSensorID(sensor.sensorId) else { return } sensorLayout.activeSensorTriggerIDs.removeAll() metadataManager.saveExperimentWithoutDateChange(experiment) updateObserveWithExperimentTriggers() showSnackbar(withMessage: String.triggersDisabledMessage, category: snackbarCategoryTriggersDisabled, actionTitle: String.triggersDisabledActionTitle, actionHandler: { self.showTriggerListViewController(for: sensor) }) } // MARK: - ImageSelectorDelegate func imageSelectorDidCreateImageData(_ imageData: Data, metadata: NSDictionary?) { let pictureNote = PictureNote() let pictureFilePath = metadataManager.relativePicturePath(for: pictureNote.ID) guard metadataManager.saveImageData(imageData, atPicturePath: pictureFilePath, experimentID: experiment.ID, withMetadata: metadata) != nil else { return } pictureNote.filePath = pictureFilePath addNoteToExperimentOrTrial(pictureNote) } func imageSelectorDidCancel() {} // MARK: - ExperimentUpdateListener func experimentUpdateTrialNoteAdded(_ note: Note, toTrial trial: Trial) { if let displayNote = experimentDataParser.parseNote(note) { drawerVC?.observeViewController.addNoteToCharts(displayNote) } updateTrial(trial) } func experimentUpdateExperimentNoteAdded(_ note: Note, toExperiment experiment: Experiment) { addExperimentNote(note) } func experimentUpdateExperimentNoteDeleted(_ note: Note, experiment: Experiment, undoBlock: @escaping () -> Void) { removeNote(note) updateEmptyView(animated: true) var didUndo = false showUndoSnackbar( withMessage: String.snackbarNoteDeleted, category: snackbarCategoryNoteDeleted, undoBlock: { didUndo = true undoBlock() }, completion: { (_) in if !didUndo, let pictureNote = note as? PictureNote { self.delegate?.experimentViewControllerDeletePictureNoteCompleted( pictureNote, forExperiment: experiment) } }) } func experimentUpdateTrialNoteDeleted(_ note: Note, trial: Trial, experiment: Experiment, undoBlock: @escaping () -> Void) { updateTrial(trial) } func experimentUpdateNoteUpdated(_ note: Note, trial: Trial?, experiment: Experiment) { if let trial = trial { updateTrial(trial) } else { updateNote(note) } } func experimentUpdateTrialUpdated(_ trial: Trial, experiment: Experiment, updatedStats: Bool) { updateTrial(trial) } func experimentUpdateTrialAdded(_ trial: Trial, toExperiment experiment: Experiment, recording isRecording: Bool) { if isRecording { addRecordingTrial(trial) } else if !trial.isArchived || preferenceManager.shouldShowArchivedRecordings { addTrial(trial, sorted: true) } updateEmptyView(animated: true) } func experimentUpdateTrialDeleted(_ trial: Trial, fromExperiment experiment: Experiment, undoBlock: (() -> Void)?) { removeTrial(trial) updateEmptyView(animated: true) guard let undoBlock = undoBlock else { // If the snackbar is not showing, delete the associated sensor data. self.delegate?.experimentViewControllerDeleteTrialCompleted(trial, fromExperiment: experiment) return } var didUndo = false showUndoSnackbar(withMessage: String.deletedRecordingMessage, category: snackbarCategoryDeletedRecording, undoBlock: { didUndo = true undoBlock() }, completion: { (_) in // When the snackbar is finished showing, if undo was not performed, delete the associated // sensor data. if !didUndo { self.delegate?.experimentViewControllerDeleteTrialCompleted(trial, fromExperiment: experiment) } }) } func experimentUpdateTrialArchiveStateChanged(_ trial: Trial, experiment: Experiment, undoBlock: @escaping () -> Void) { updateTrial(trial) if trial.isArchived { // Only offer undo if the trial was archived. showUndoSnackbar(withMessage: String.archivedRunMessage, category: snackbarCategoryTrialArchivedState, undoBlock: undoBlock) } else { // If the user is unarchiving, hide any archived state undo snackbars. MDCSnackbarManager.dismissAndCallCompletionBlocks( withCategory: snackbarCategoryTrialArchivedState) } } // MARK: - ExperimentStateListener func experimentStateArchiveStateChanged(forExperiment experiment: Experiment, overview: ExperimentOverview, undoBlock: @escaping () -> Void) { if metadataManager.isExperimentArchived(withID: experiment.ID) { drawerVC?.observeViewController.removeAllSensorListeners() experimentInteractionOptions = .archived experimentItemsViewController.experimentInteractionOptions = experimentInteractionOptions experimentItemsViewController.shouldShowArchivedFlag = true // If the user just archived, show an undo snackbar. showUndoSnackbar(withMessage: String.archivedExperimentMessage, category: self.snackbarCategoryExperimentArchivedState, undoBlock: undoBlock) } else { // If the user is unarchiving, hide any archived state undo snackbars. MDCSnackbarManager.dismissAndCallCompletionBlocks( withCategory: self.snackbarCategoryExperimentArchivedState) drawerVC?.observeViewController.addListenersForAllSensorCards() experimentInteractionOptions = .normal experimentItemsViewController.experimentInteractionOptions = experimentInteractionOptions experimentItemsViewController.shouldShowArchivedFlag = false } updateDrawerForExperimentInteractionOptions() updateEmptyViewArchivedFlag() } func experimentStateDeleted(_ deletedExperiment: DeletedExperiment, undoBlock: (() -> Void)?) {} func experimentStateRestored(_ experiment: Experiment, overview: ExperimentOverview) {} // MARK: - NotesViewControllerDelegate func notesViewController(_ notesViewController: NotesViewController, didCreateTextForNote text: String) { let textNote = TextNote(text: text) addNoteToExperimentOrTrial(textNote) } // MARK: - TriggerListDelegate func triggerListViewController(_ triggerListViewController: TriggerListViewController, didUpdateTriggers sensorTriggers: [SensorTrigger], withActiveTriggerIDs activeTriggerIDs: [String], forSensor sensor: Sensor) { guard let sensorLayout = experiment.sensorLayoutForSensorID(sensor.sensorId) else { return } // Update sensor triggers. let updatedTriggerIds = sensorTriggers.map { $0.triggerID } let triggersForSensor = experiment.sensorTriggers.filter { $0.sensorID == sensor.sensorId } // If the updated trigger IDs do not contain the trigger's ID, remove it from the experiment. for trigger in triggersForSensor { if !updatedTriggerIds.contains(trigger.triggerID) { guard let index = experiment.sensorTriggers.index(where: { $0.triggerID == trigger.triggerID }) else { continue } experiment.sensorTriggers.remove(at: index) } } let experimentTriggerIDs = triggersForSensor.map { $0.triggerID } for trigger in sensorTriggers { if !experimentTriggerIDs.contains(trigger.triggerID) { // If the updated trigger contains a trigger ID not in the experiment's triggers, add it to // the experiment. experiment.sensorTriggers.append(trigger) } else { // If the experiment triggers contains the updated trigger, replace it. guard let index = experiment.sensorTriggers.index(where: { $0.triggerID == trigger.triggerID }) else { continue } experiment.sensorTriggers[index] = trigger } } // Update active sensor trigger IDs in the layout. sensorLayout.activeSensorTriggerIDs = activeTriggerIDs // Save the experiment. metadataManager.saveExperimentWithoutDateChange(experiment) // Update observe. updateObserveWithExperimentTriggers() } // MARK: - SensorSettingsDelegate func sensorSettingsViewController(_ sensorSettingsViewController: SensorSettingsViewController, didRequestCloseWithEnabledSensors enabledSensorIDs: [String]) { dismiss(animated: true) { guard !RecordingState.isRecording else { // Sensors should not be enabled or disabled during a recording. showSnackbar(withMessage: String.sensorSettingsCouldNotUpdateWhileRecording, category: self.snackbarCategoryCouldNotUpdateSensorSettings) return } var availableSensors = [SensorEntry]() for sensorID in enabledSensorIDs { if let sensor = self.sensorController.sensor(for: sensorID) { availableSensors.append(SensorEntry(sensor: sensor)) } } self.experiment.availableSensors = availableSensors self.metadataManager.saveExperimentWithoutDateChange(self.experiment) self.updateObserveWithAvailableSensors() } } // MARK: - UIGestureRecognizerDelegate override func interactivePopGestureShouldBegin() -> Bool { guard !RecordingState.isRecording else { return false } guard experiment.title == nil else { prepareToCloseObserve() return true } promptForTitleIfNecessary() return false } // MARK: - Private private func updateEmptyView(animated: Bool) { updateEmptyViewArchivedFlag() UIView.animate(withDuration: animated ? 0.5 : 0) { self.emptyView.alpha = self.experimentItemsViewController.isEmpty ? 1 : 0 } } private func updateEmptyViewArchivedFlag() { let isExperimentArchived = metadataManager.isExperimentArchived(withID: experiment.ID) emptyView.archivedFlag.isHidden = !isExperimentArchived } private func updateForRecording() { if let presentedViewController = presentedViewController as? PopUpMenuViewController { // If there's a popup menu presented, dismiss it first. presentedViewController.dismiss(animated: true) } let isRecording = RecordingState.isRecording navigationItem.leftBarButtonItem = isRecording ? nil : backMenuItem editBarButton.isEnabled = !isRecording menuBarButton.isEnabled = !isRecording let isCameraAllowed = CaptureSessionInterruptionObserver.shared.isCameraUseAllowed // Update the camera tab icon. drawerVC?.isCameraItemEnabled = isCameraAllowed if drawerVC?.currentViewController is CameraViewController { // Update the camera disabled view and start the capture session if the camera is currently // visible. drawerVC?.cameraViewController.photoCapturer.startCaptureSessionIfNecessary() drawerVC?.cameraViewController.updateDisabledView(forCameraUseAllowed: isCameraAllowed) } // Update the recording progress bar. if isRecording { drawerVC?.drawerView.recordingBar.startAnimating() } else { drawerVC?.drawerView.recordingBar.stopAnimating() } } /// Sets the collection view content inset for the drawer height. /// /// - Parameter onlyIfViewIsVisible: Whether or not to only set the collection view inset if the /// view is visible. private func setCollectionViewInset(onlyIfViewIsVisible: Bool = false) { guard !onlyIfViewIsVisible || experimentItemsViewController.isViewVisible else { // Calling this method while the experiment items collecion view is not visible can cause an // incorrect layout. It will be called again in viewWillAppear if the view is not currently // visible. return } var bottomInset = MDCKeyboardWatcher.shared().visibleKeyboardHeight var rightInset: CGFloat = 0 if experimentInteractionOptions.shouldShowDrawer, let drawerVC = drawerVC { if drawerVC.isDisplayedAsSidebar { rightInset = ViewConstants.iPadDrawerSidebarWidth } else { bottomInset = drawerVC.drawerView.visibleHeight } } experimentItemsViewController.setCollectionViewInsets(bottom: bottomInset, right: rightInset) } // If a trial is recording, adds the note to the trial, otherwise adds it to the experiment. func addNoteToExperimentOrTrial(_ note: Note) { itemDelegate?.detailViewControllerDidAddNote(note, forTrialID: drawerVC?.observeViewController.recordingTrial?.ID) var destination: String if drawerVC?.observeViewController.recordingTrial != nil { destination = String.toRunContentDescription } else { destination = String.toExperimentContentDescription } var announcementMessage: String switch note { case is TextNote: announcementMessage = String.textNoteAddedContentDescription case is PictureNote: announcementMessage = String.pictureNoteAddedContentDescription case is SnapshotNote: announcementMessage = String.snapshotNoteAddedContentDescription case is TriggerNote: announcementMessage = String.triggerNoteAddedContentDescription default: announcementMessage = String.noteAddedContentDescription } UIAccessibility.post(notification: .announcement, argument: "\(announcementMessage) \(destination)") } private func promptForTitleIfNecessary() { // If we aren't requiring an experiment to have a title, we're done. guard requireExperimentTitle == true else { dismissViewController() return } // If a user has set a title before, we're done. guard experiment.title == nil else { dismissViewController() return } // If the experiment is empty, delete it without prompting instead of forcing the user to rename // it and keeping it around. if experiment.isEmpty { prepareToCloseObserve() delegate?.experimentViewControllerDidRequestDeleteExperiment(experiment) return } let dialogController = MDCDialogTransitionController() let dialog = RenameExperimentViewController(analyticsReporter: analyticsReporter) dialog.textField.text = String.localizedUntitledExperiment dialog.textField.placeholder = String.experimentTitleHint dialog.okayButton.addTarget(self, action: #selector(renameExperimentOkayButtonPressed), for: .touchUpInside) dialog.modalPresentationStyle = .custom dialog.transitioningDelegate = dialogController dialog.mdc_dialogPresentationController?.dismissOnBackgroundTap = false present(dialog, animated: true) renameDialog = dialog dialogTransitionController = dialogController } private func dismissViewController() { prepareToCloseObserve() navigationController?.popViewController(animated: true) } // Sets observe's triggers from the experiment. private func updateObserveWithExperimentTriggers() { drawerVC?.observeViewController.sensorTriggers = experiment.sensorTriggers } // Sets observe's available sensors from the experiment. private func updateObserveWithAvailableSensors() { guard !experiment.availableSensors.isEmpty else { // Reset the available sensors to empty, since the drawer is re-used across experiments. drawerVC?.observeViewController.setAvailableSensorIDs([], andAddListeners: experimentInteractionOptions.shouldShowDrawer) return } // If no internal supported sensors are in the available sensors, make all sensors available by // setting the available sensors array to empty. let supportedInternalSensorIDs = sensorController.supportedInternalSensors.map { $0.sensorId } let supportedAvailableInternalSensorIDs = supportedInternalSensorIDs.filter { experiment.availableSensorIDs.contains($0) } if supportedAvailableInternalSensorIDs.isEmpty { experiment.availableSensors = [] } drawerVC?.observeViewController.setAvailableSensorIDs(experiment.availableSensorIDs, andAddListeners: experimentInteractionOptions.shouldShowDrawer) } private func prepareToCloseObserve() { drawerVC?.observeViewController.updateSensorLayouts() } private func updateHeaderColor(animated: Bool = true) { let isDark = drawerVC?.isOpenFull ?? false UIView.animate(withDuration: animated ? 0.2 : 0) { if let drawerVC = self.drawerVC, drawerVC.isDisplayedAsSidebar || !self.experimentInteractionOptions.shouldShowDrawer { self.appBar.headerViewController.headerView.backgroundColor = .appBarDefaultBackgroundColor } else { self.appBar.headerViewController.headerView.backgroundColor = isDark ? DrawerView.barBackgroundColor : .appBarDefaultBackgroundColor } } } private func updateConstraints(forDisplayType displayType: DisplayType, withSize size: CGSize) { drawerVC?.drawerView.setAvailableHeight(size.height - statusBarHeight) drawerViewTopConstraint?.constant = statusBarHeight drawerViewLeadingConstraint?.isActive = false drawerViewWidthConstraintSideBySide?.isActive = false let showAsSidebar = drawerVC != nil && experimentInteractionOptions.shouldShowDrawer && displayType == .regularWide drawerViewLeadingConstraint?.isActive = !showAsSidebar drawerViewWidthConstraintSideBySide?.isActive = showAsSidebar emptyViewTrailingConstraint?.constant = showAsSidebar ? -ViewConstants.iPadDrawerSidebarWidth : 0 drawerVC?.isDisplayedAsSidebar = showAsSidebar drawerVC?.cameraViewController.fullscreenButton.isHidden = showAsSidebar setCollectionViewInset(onlyIfViewIsVisible: true) } /// Updates the right bar button items for the display type. Exposed for testing. /// /// Parameter displayType: The display type of the view. func updateRightBarButtonItems(for displayType: DisplayType) { let showAsSidebar = drawerVC != nil && experimentInteractionOptions.shouldShowDrawer && displayType == .regularWide var buttons = [UIBarButtonItem]() if showAsSidebar { buttons.append(fixedSpaceBarItem) } buttons.append(menuBarButton) if experimentInteractionOptions.shouldAllowEdits { buttons.append(editBarButton) } navigationItem.rightBarButtonItems = buttons } private func updateDrawerPosition(for displayType: DisplayType, size: CGSize) { // Don't change drawer positions if it is not visible. Doing so can cause the keyboard to show // on iPad when the drawer is in landscape and notes is the selected item. guard let drawerVC = drawerVC, !drawerVC.drawerView.isHidden && drawerVC.drawerView.alpha == 1 else { return } switch displayType { case .compact, .compactWide: if size.isWiderThanTall && !drawerVC.isPeeking { // Open the drawer to full, as long as it wasn't peeking. Otherwise, pan to the current // position to retain the correct layout. drawerVC.setPositionToFull(animated: false) } else { drawerVC.drawerView.panToCurrentPosition(animated: false) } case .regular: drawerVC.setPositionToHalf(animated: false) case .regularWide: drawerVC.setPositionToFull(animated: false) } } /// Updates the drawer for the experiment interaction options. Exposed for testing. /// /// Parameter animated: Whether to animate the change. func updateDrawerForExperimentInteractionOptions(animated: Bool = true) { if experimentInteractionOptions.shouldShowDrawer { let showAsSidebar = displayType == .regularWide if showAsSidebar { drawerVC?.setPositionToFull(animated: false) } else if experimentItemsViewController.isEmpty { // If there is no content, display drawer at half height. drawerVC?.setPositionToHalf(animated: false) } else { // Hide the drawer by default. drawerVC?.setPositionToPeeking(animated: false) } } else { drawerVC?.drawerView.endEditing(true) } let duration = animated ? 0.3 : 0 UIView.animate(withDuration: duration, animations: { self.drawerVC?.drawerView.alpha = !self.experimentInteractionOptions.shouldShowDrawer ? 0 : 1 self.setCollectionViewInset(onlyIfViewIsVisible: true) self.updateConstraints(forDisplayType: self.displayType, withSize: self.view.bounds.size) self.view.layoutIfNeeded() }) { (_) in if !self.experimentInteractionOptions.shouldShowDrawer { self.drawerVC?.setPositionToPeeking(animated: false) } } updateRightBarButtonItems(for: displayType) } private func showTriggerListViewController(for sensor: Sensor) { guard let sensorLayout = experiment.sensorLayoutForSensorID(sensor.sensorId) else { return } let triggerListViewController = TriggerListViewController(sensorTriggers: experiment.triggersForSensor(sensor), activeTriggerIDs: sensorLayout.activeSensorTriggerIDs, sensor: sensor, delegate: self, analyticsReporter: analyticsReporter) let navigationController = UINavigationController(rootViewController: triggerListViewController) if UIDevice.current.userInterfaceIdiom == .pad { navigationController.modalPresentationStyle = .formSheet } present(navigationController, animated: true) } private func updateEmptyViewArchivedFlagInsets() { emptyView.archivedFlagInsets = experimentItemsViewController.cellInsets } private func reloadExperimentItems() { if let recordingTrial = drawerVC?.observeViewController.recordingTrial { addRecordingTrial(recordingTrial) } experimentItemsViewController.setExperimentItems(parseExperimentItems()) } /// Parses the experiment into a sorted array of display items. /// /// - Returns: A sorted array of display items (trials and notes). private func parseExperimentItems() -> [DisplayItem] { let includeArchivedRecordings = preferenceManager.shouldShowArchivedRecordings let trialsToInclude = experiment.trials.filter { !$0.isArchived || includeArchivedRecordings } var displayTrials = experimentDataParser.parsedTrials(trialsToInclude) // The recording trial will be handled separately, so remove it if there is one. let recordingTrial = drawerVC?.observeViewController.recordingTrial if let recordingIndex = displayTrials.firstIndex(where: { $0.ID == recordingTrial?.ID }) { displayTrials.remove(at: recordingIndex) } for (trialIndex, displayTrial) in displayTrials.enumerated() { for (sensorIndex, var displaySensor) in displayTrial.sensors.enumerated() { displaySensor.chartPresentationView = chartViewForSensor(displaySensor, trial: displayTrial) displayTrials[trialIndex].sensors[sensorIndex] = displaySensor } } var items: [DisplayItem] = displayTrials as [DisplayItem] items += experimentDataParser.parseNotes(experiment.notes) as [DisplayItem] items.sort { (data1, data2) -> Bool in // Sort oldest to newest. return data1.timestamp.milliseconds < data2.timestamp.milliseconds } return items } // Returns a chart view and adds its controller to the chart controllers array. private func chartViewForSensor(_ sensor: DisplaySensor, trial: DisplayTrial) -> ChartView { let chartController = ChartController(placementType: .previewReview, colorPalette: sensor.colorPalette, trialID: trial.ID, sensorID: sensor.ID, sensorStats: sensor.stats, cropRange: trial.cropRange, notes: trial.notes, sensorDataManager: sensorDataManager) chartControllers[trial.ID + sensor.ID] = chartController return chartController.chartView } /// Updates the title in the nav bar based on the current experiment. private func updateExperimentTitle() { title = experiment.title ?? String.localizedUntitledExperiment } // MARK: - Experiment Updates private func createDisplayTrial(fromTrial trial: Trial, isRecording: Bool) -> DisplayTrial { let maxNotes: Int? = isRecording ? nil : 2 var displayTrial = experimentDataParser.parseTrial(trial, maxNotes: maxNotes, isRecording: isRecording) // Update the chart controller. for (index, var displaySensor) in displayTrial.sensors.enumerated() { displaySensor.chartPresentationView = chartViewForSensor(displaySensor, trial: displayTrial) displayTrial.sensors[index] = displaySensor } return displayTrial } private func addRecordingTrial(_ trial: Trial) { let displayTrial = createDisplayTrial(fromTrial: trial, isRecording: true) experimentItemsViewController.addOrUpdateRecordingTrial(displayTrial) } /// Updates a trial. /// /// - Parameters: /// - trial: The trial to update. /// - didFinishRecording: True if the trial finished recording, and should be updated from a /// recording trial to a recorded trial. private func updateTrial(_ trial: Trial, didFinishRecording: Bool = false) { // If trial is archived, remove it if necessary. if trial.isArchived && !preferenceManager.shouldShowArchivedRecordings { experimentItemsViewController.removeTrial(withID: trial.ID) } else { // If trial is not archived, add or update it. let isRecording = drawerVC?.observeViewController.recordingTrial?.ID == trial.ID let displayTrial = self.createDisplayTrial(fromTrial: trial, isRecording: isRecording) if isRecording { experimentItemsViewController.addOrUpdateRecordingTrial(displayTrial) } else { experimentItemsViewController.addOrUpdateTrial(displayTrial, didFinishRecording: didFinishRecording) } } updateEmptyView(animated: true) } private func addTrial(_ trial: Trial, sorted isSorted: Bool) { let displayTrial = self.createDisplayTrial(fromTrial: trial, isRecording: false) experimentItemsViewController.addItem(displayTrial, sorted: isSorted) } @discardableResult private func removeTrial(_ trial: Trial) -> Int? { return experimentItemsViewController.removeTrial(withID: trial.ID) } private func removeRecordingTrial() { return experimentItemsViewController.removeRecordingTrial() } private func updateNote(_ note: Note) { guard let displayNote = experimentDataParser.parseNote(note) else { return } experimentItemsViewController.updateNote(displayNote) } private func addExperimentNote(_ note: Note) { guard let displayNote = experimentDataParser.parseNote(note) else { return } experimentItemsViewController.addItem(displayNote, sorted: true) updateEmptyView(animated: true) } private func removeNote(_ note: Note) { experimentItemsViewController.removeNote(withNoteID: note.ID) } // MARK: - User Actions @objc private func backButtonPressed() { promptForTitleIfNecessary() } @objc private func menuButtonPressed() { view.endEditing(true) let popUpMenu = PopUpMenuViewController() // Remove the cover image if one exists, and this is allowed. if experimentInteractionOptions.shouldAllowCoverRemoval && metadataManager.imagePathForExperiment(experiment) != nil { popUpMenu.addAction(PopUpMenuAction( title: String.removeCoverImage, accessibilityLabel: String.removeCoverImageContentDescription) { _ -> Void in let alertController = MDCAlertController(title: nil, message: String.removeCoverImageMessage) let cancelAction = MDCAlertAction(title: String.btnDeleteObjectCancel) let deleteAction = MDCAlertAction(title: String.btnDeleteObjectConfirm) { (action) in var snackbarMessage = String.removeCoverImageFailed if (self.delegate?.experimentViewControllerRemoveCoverImageForExperiment( self.experiment))! { snackbarMessage = String.removeCoverImageSuccessful } showSnackbar(withMessage: snackbarMessage) } alertController.addAction(cancelAction) alertController.addAction(deleteAction) self.present(alertController, animated: true) }) } // Show archived recordings? let archivedRecordingsIconName = preferenceManager.shouldShowArchivedRecordings ? "ic_check_box" : "ic_check_box_outline_blank" popUpMenu.addAction(PopUpMenuAction( title: String.includeArchivedTrials, icon: UIImage(named: archivedRecordingsIconName)) { _ -> Void in self.preferenceManager.shouldShowArchivedRecordings = !self.preferenceManager.shouldShowArchivedRecordings self.reloadExperimentItems() self.updateEmptyView(animated: true) }) // Archive experiment. func showArchiveAction() { let isExperimentArchived = metadataManager.isExperimentArchived(withID: experiment.ID) let archiveTitle = isExperimentArchived ? String.actionUnarchive : String.actionArchive let archiveAccessibilityLabel = isExperimentArchived ? String.actionUnarchiveExperimentContentDescription : String.actionArchiveExperimentContentDescription let iconName = isExperimentArchived ? "ic_unarchive" : "ic_archive" popUpMenu.addAction(PopUpMenuAction( title: archiveTitle, icon: UIImage(named: iconName), accessibilityLabel: archiveAccessibilityLabel) { _ -> Void in if RecordingState.isRecording { self.drawerVC?.observeViewController.endRecording(isCancelled: true) } self.drawerVC?.observeViewController.removeAllSensorListeners() self.delegate?.experimentViewControllerToggleArchiveStateForExperiment( withID: self.experiment.ID) }) } if experimentInteractionOptions.shouldAllowEdits { showArchiveAction() } // Send a copy. if shouldAllowSharing && !RecordingState.isRecording && !experiment.isEmpty { popUpMenu.addAction(PopUpMenuAction.exportExperiment(experiment, presentingViewController: self, sourceView: self.menuBarButton.button, documentManager: documentManager)) } // Delete. popUpMenu.addAction(PopUpMenuAction( title: String.actionDelete, icon: UIImage(named: "ic_delete"), accessibilityLabel: String.actionDeleteExperimentContentDescription) { a -> Void in // Prompt the user to confirm deletion. let alertController = MDCAlertController(title: String.deleteExperimentDialogTitle, message: String.deleteExperimentDialogMessage) let cancelAction = MDCAlertAction(title: String.btnDeleteObjectCancel) let deleteAction = MDCAlertAction(title: String.btnDeleteObjectConfirm) { (action) in if RecordingState.isRecording { self.drawerVC?.observeViewController.endRecording() } self.drawerVC?.observeViewController.removeAllSensorListeners() self.delegate?.experimentViewControllerDidRequestDeleteExperiment(self.experiment) } alertController.addAction(cancelAction) alertController.addAction(deleteAction) alertController.accessibilityViewIsModal = true self.present(alertController, animated: true) }) popUpMenu.present(from: self, position: .sourceView(menuBarButton.button)) } @objc private func editButtonPressed() { view.endEditing(true) let vc = EditExperimentViewController(experiment: experiment, analyticsReporter: analyticsReporter, metadataManager: metadataManager) vc.delegate = self if UIDevice.current.userInterfaceIdiom == .pad { vc.modalPresentationStyle = .formSheet } present(vc, animated: true) } @objc private func renameExperimentOkayButtonPressed() { guard let dialog = renameDialog else { return } var newTitle = dialog.textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) newTitle = newTitle == nil || newTitle == "" ? String.localizedUntitledExperiment : newTitle delegate?.experimentViewControllerDidSetTitle(newTitle, forExperiment: experiment) dialog.dismiss(animated: true) { self.dismissViewController() } renameDialog = nil dialogTransitionController = nil } // MARK: - Notifications @objc func handleKeyboardNotification(_ notification: Notification) { setCollectionViewInset(onlyIfViewIsVisible: true) } @objc private func handleTrialStatsDidCompleteNotification(notification: Notification) { guard let trialID = notification.userInfo?[SensorDataManager.TrialStatsDidCompleteTrialIDKey] as? String, let trial = experiment.trial(withID: trialID) else { return } updateTrial(trial) } }
42.365121
105
0.698155
e4ea51222c3d2bd1c89f54d1f7704d3f1ec17be2
576
// // GroupDetailTabTitleCell.swift // ConferenceAssociationApp // // Created by Coruscate on 29/11/18. // Copyright © 2018 CS-Mac-Mini. All rights reserved. // import UIKit class GroupDetailTabTitleCell: UICollectionViewCell { @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var viewLine: UIView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func setCellData(model : CellModel) { lblTitle.text = model.placeholder viewLine.isHidden = !model.isSelected } }
21.333333
54
0.663194
d7db3717cb840492c60c954866dbfd4f6bf64d10
1,760
// // AppCoordinator.swift // JDCoordinator // // Created by Jan Dammshäuser on 05/02/2017. // Copyright © 2017 Jan Dammshäuser. All rights reserved. // import Foundation /** Use the `AppCoordinator` only in a `UINavigationController` based application. The coordinator structure in your app can be seen as a tree. In this example the `AppCoordinator` is the root of every other coordinator. In order to prevent a coordinator from beeing deinitialized it has to have a strong reference somewhere. The `AppCoordinator` should be referenced by the `AppDelegate`. Every other `Coordinator` should be referenced by the `AppCoordinator` or one of its `Child`s. Use this class only once in your app. It should be the `Coordinator` where every navigation is started from. The `AppCoordinator` has to use the `UINavigationController` which the `AppDelegate` declares as `keyWindow`. */ open class AppCoordinator: Coordinating, RootNavigating, MutableParent, CoordinatorDelegate, ControllerDelegate, StartTestable { /// Initialize the `AppCoordinator` with a UINavigationController. /// - parameter navigationController: `UINavigationController` which is / will be `keyWindow.rootViewController` public init(with navigationController: UINavigationController) { self.navigationController = navigationController } // MARK: - Protocols public internal(set) var childCoordinators = ChildStorage() public let navigationController: UINavigationController open func start() { started() } open func presentedViewController(_: UIViewController, didMoveTo _: UIViewController?) {} open func presentedViewController(_: UIViewController, willMoveTo _: UIViewController?) {} var startedCount = 0 }
41.904762
138
0.761932
0a63bec026d013b5ed7c8aadadccc435f53d436c
231
// // Photo+CoreDataClass.swift // Photorama // // Created by Liyu Wang on 5/8/18. // Copyright © 2018 Oasis. All rights reserved. // // import Foundation import CoreData @objc(Photo) public class Photo: NSManagedObject { }
13.588235
48
0.692641
c18c8767423ce3143998e10109b7a687438f3226
3,014
// // BaseDetailCommentCell.swift // Quotely // // Created by Zheng-Yuan Yu on 2021/10/20. // import Foundation import UIKit protocol PostDetailCommentCellDelegate: AnyObject { func deleteCommentCell(_ cell: PostDetailCommentCell) func openOptionMenu(_ cell: PostDetailCommentCell) } class PostDetailCommentCell: UITableViewCell { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var editTextField: UITextField! @IBOutlet weak var doneEditingButton: UIButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var optionMenuButton: UIButton! weak var delegate: PostDetailCommentCellDelegate? var isEnableEdit = false { didSet { contentLabel.isHidden = isEnableEdit editTextField.isHidden = !isEnableEdit doneEditingButton.isHidden = !isEnableEdit } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear userImageView.clipsToBounds = true editButton.tintColor = .gray deleteButton.tintColor = .gray contentLabel.isHidden = isEnableEdit editTextField.isHidden = !isEnableEdit doneEditingButton.isHidden = !isEnableEdit } override func layoutSubviews() { super.layoutSubviews() userImageView.cornerRadius = userImageView.frame.width / 2 } func layoutCell( comment: Comment, userImageUrl: String?, userName: String, isAuthor: Bool ) { if let profileImageUrl = userImageUrl { userImageView.loadImage(profileImageUrl, placeHolder: nil) } else { userImageView.image = UIImage.asset(.logo) } nameLabel.text = userName timeLabel.text = Date.init(milliseconds: comment.createdTime).timeAgoDisplay() contentLabel.text = comment.content editButton.isHidden = !isAuthor deleteButton.isHidden = !isAuthor optionMenuButton.isHidden = isAuthor guard let editTime = comment.editTime else { return } timeLabel.text = "已編輯 \(Date.init(milliseconds: editTime).timeAgoDisplay())" } var editHandler: (String) -> Void = { _ in } @IBAction func tapEditButton(_ sender: UIButton) { isEnableEdit = true editTextField.text = contentLabel.text } @IBAction func doneEditing(_ sender: UIButton) { isEnableEdit = false guard let text = editTextField.text else { return } if text != contentLabel.text { editHandler(text) contentLabel.text = text } } @IBAction func deleteComment(_ sender: UIButton) { delegate?.deleteCommentCell(self) } @IBAction func tapOptionMenuButton(_ sender: UIButton) { delegate?.openOptionMenu(self) } }
27.907407
86
0.662906
67d8f3c9aea02693e402aeadc10cf06cfaaabcd6
207
public protocol LoginRepository { associatedtype UserCredentialsEntity func login(completion: (UserCredentialsEntity) -> Void) func logout() func register(user: UserCredentialsEntity) }
25.875
59
0.748792
e222d5af949025374fa3034d7c634fadbbc20a7b
5,241
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit /// Base class to support an avatar view /// Note: This class is made to be sublcassed class AvatarView: UIView, Themable { // MARK: - Properties // MARK: Outlets @IBOutlet weak var avatarImageView: MXKImageView! { didSet { self.setupAvatarImageView() } } // MARK: Private private(set) var theme: Theme? // MARK: Public override var isUserInteractionEnabled: Bool { get { return super.isUserInteractionEnabled } set { super.isUserInteractionEnabled = newValue self.updateAccessibilityTraits() } } /// Indicate highlighted state var isHighlighted: Bool = false { didSet { self.updateView() } } var action: (() -> Void)? // MARK: - Setup private func commonInit() { self.setupGestureRecognizer() self.updateAccessibilityTraits() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } // MARK: - Lifecycle override func layoutSubviews() { super.layoutSubviews() self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.height/2 } // MARK: - Public func fill(with viewData: AvatarViewDataProtocol) { self.updateAvatarImageView(with: viewData) self.setNeedsLayout() } func update(theme: Theme) { self.theme = theme } func updateAccessibilityTraits() { // Override in subclass } func setupAvatarImageView() { self.avatarImageView.defaultBackgroundColor = UIColor.clear self.avatarImageView.enableInMemoryCache = true self.avatarImageView.layer.masksToBounds = true } func updateAvatarImageView(with viewData: AvatarViewDataProtocol) { guard let avatarImageView = self.avatarImageView else { return } let defaultAvatarImage: UIImage? var defaultAvatarImageContentMode: UIView.ContentMode = .scaleAspectFill switch viewData.fallbackImage { case .matrixItem(let matrixItemId, let matrixItemDisplayName): defaultAvatarImage = AvatarGenerator.generateAvatar(forMatrixItem: matrixItemId, withDisplayName: matrixItemDisplayName) case .image(let image, let contentMode): defaultAvatarImage = image defaultAvatarImageContentMode = contentMode ?? .scaleAspectFill case .none: defaultAvatarImage = nil } if let avatarUrl = viewData.avatarUrl { avatarImageView.setImageURI(avatarUrl, withType: nil, andImageOrientation: .up, toFitViewSize: avatarImageView.frame.size, with: MXThumbnailingMethodScale, previewImage: defaultAvatarImage, mediaManager: viewData.mediaManager) avatarImageView.contentMode = .scaleAspectFill avatarImageView.imageView?.contentMode = .scaleAspectFill } else { avatarImageView.image = defaultAvatarImage avatarImageView.contentMode = defaultAvatarImageContentMode avatarImageView.imageView?.contentMode = defaultAvatarImageContentMode } } func updateView() { // Override in subclass if needed // TODO: Handle highlighted state } // MARK: - Private private func setupGestureRecognizer() { let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(buttonAction(_:))) gestureRecognizer.minimumPressDuration = 0 self.addGestureRecognizer(gestureRecognizer) } // MARK: - Actions @objc private func buttonAction(_ sender: UILongPressGestureRecognizer) { let isBackgroundViewTouched = sender.vc_isTouchingInside() switch sender.state { case .began, .changed: self.isHighlighted = isBackgroundViewTouched case .ended: self.isHighlighted = false if isBackgroundViewTouched { self.action?() } case .cancelled: self.isHighlighted = false default: break } } }
30.12069
132
0.60809
917b338bd711358c480f263a1e7157d0ae0d54b0
2,650
// // Array+Extension.swift // FaceAnimationTest // // Created by zhangerbing on 2021/8/13. // import Foundation extension Array { init?(unsafeData: Data) { guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil } #if swift(>=5.0) self = unsafeData.withUnsafeBytes({ .init($0.bindMemory(to: Element.self)) }) #else self = unsafeData.withUnsafeBytes({ .init(UnsafeBufferPointer<Element>(start: $0, count: unsafeData.count / MemoryLayout<Element>.stride)) }) #endif } } extension Array where Element: Comparable { func argsort() -> [Int] { var indices = [Int]() let sorted = self.sorted { $0 < $1 } sorted.forEach { element in guard let index = self.firstIndex(of: element) else { return } indices.append(index) } return indices } func clamp(to limits: ClosedRange<Element>) -> Self { map { $0.clamp(to: limits) } } } extension Array where Element == Float { @inlinable static func - (lhs:[Element], rhs: [Element]) -> [Element] { assert(lhs.count == rhs.count, "两数组个数必须相同") var array = lhs for (index, element) in lhs.enumerated() { array[index] = rhs[index] - element } return array } @inlinable static func * (lhs:[Element], rhs: [Element]) -> [Element] { assert(lhs.count == rhs.count, "两数组个数必须相同") var array = lhs for (index, element) in lhs.enumerated() { array[index] = rhs[index] * element } return array } } extension Array where Element == [Float] { @inlinable static func - (lhs:[Element], rhs: [Element]) -> [Element] { assert(lhs.count == rhs.count, "两数组个数必须相同") var array = lhs for (index, element) in lhs.enumerated() { array[index] = rhs[index] - element } return array } @inlinable static func * (lhs:[Element], rhs: [Element]) -> [Element] { assert(lhs.count == rhs.count, "两数组个数必须相同") var array = lhs for (index, element) in lhs.enumerated() { array[index] = rhs[index] * element } return array } } extension Array { /// 根据索引数组取子数组 subscript(indices: [Int]) -> Self { var array = [Element]() indices.forEach { index in guard index < count else { return } array.append(self[index]) } return array } }
25.238095
114
0.533208
754e7553768dd45b395619f58a4a5f4102d330b6
441
// // JJWebJSModule.swift // JJJSBridge // // Created by 李杰駿 on 2021/7/21. // import Foundation open class JJWebJSModule { public var name : String public var jsFunctions : [JJWebJSFunction] public var jsScripts : [String] public init(name : String, functions : [JJWebJSFunction] = [], jsScripts : [String] = []) { self.name = name self.jsFunctions = functions self.jsScripts = jsScripts } }
22.05
95
0.639456
1dde655c0be05570b1a43a09b8ddbe920547e516
12,148
// // FeatureViewController.swift // CFiOSExample // // Created by Dusan Juranovic on 14.1.21.. // import UIKit import ff_ios_client_sdk class FeatureViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var needHelpButton: UIButton! var enabledFeatures = [CDModule()] var availableFeatures: [FeatureCardRepresentable] = [CVModule(), CIModule(), CEModule(), CFModule()] var ceTrial: Int = 0 var cfTrial: Int = 0 var ciTrial: Int = 0 var cvTrial: Int = 0 var darkMode: Bool = false var topConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() setupNeedHelpButton() setupLayoutFlow() CfClient.sharedInstance.registerEventsListener() { (result) in switch result { case .failure(let error): print(error) case .success(let eventType): switch eventType { case .onPolling(let evaluations): print("Event: Received all evaluation flags") for eval in evaluations! { self.setupViewPreferences(evaluation: eval) } case .onEventListener(let evaluation): print("Event: Received an evaluation flag") guard let evaluation = evaluation else { return } self.setupViewPreferences(evaluation: evaluation) case .onComplete: print("Event: SSE stream has completed") case .onOpen: print("Event: SSE stream has been opened") case .onMessage(let messageObj): print(messageObj?.event ?? "Event: Message received") } } } } func setupLayoutFlow() { let minSpacing: CGFloat = 10 let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) layout.itemSize = CGSize(width: self.view.bounds.width / 2 - minSpacing, height: 220) layout.minimumInteritemSpacing = minSpacing layout.minimumLineSpacing = minSpacing collectionView.collectionViewLayout = layout } @IBAction func getById(_ sender: Any) { var id = "" let alert = UIAlertController(title: "Get by ID", message: nil, preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Enter EvaluationId" } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in id = alert.textFields![0].text! CfClient.sharedInstance.boolVariation(evaluationId: id) { (eval) in print(eval!) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func destroy(_ sender: Any) { CfClient.sharedInstance.destroy() self.navigationController?.popToRootViewController(animated: true) } func setupNeedHelpButton() { let helpButton = UIButton(frame: CGRect(x: 0, y: 0, width: 130, height: 50)) self.needHelpButton = helpButton self.needHelpButton.translatesAutoresizingMaskIntoConstraints = false self.needHelpButton.setAttributedTitle(NSAttributedString(string: "Need Help? ✋", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15, weight: .bold), NSAttributedString.Key.foregroundColor : UIColor.white]), for: .normal) self.needHelpButton.titleEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10) self.needHelpButton.backgroundColor = UIColor.systemGreen self.needHelpButton.layer.cornerRadius = 5 self.needHelpButton.transform = self.needHelpButton.transform.rotated(by: -CGFloat.pi / 2) self.view.addSubview(self.needHelpButton) self.topConstraint = NSLayoutConstraint(item: self.needHelpButton!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 210) NSLayoutConstraint.activate([NSLayoutConstraint(item: self.needHelpButton!, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 20), self.topConstraint, NSLayoutConstraint(item: self.needHelpButton!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50), NSLayoutConstraint(item: self.needHelpButton!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 130)]) } func setupViewPreferences(evaluation: Evaluation) { let flagType = FlagType(flag: evaluation.flag) let value = evaluation.value switch flagType { case .HarnessAppDemoCfRibbon: guard let enableRibbon = value.boolValue else {return} updateRibbon(.Features, ribbon: enableRibbon) case .HarnessAppDemoDarkMode: guard let darkMode = value.boolValue else {return} self.darkMode = darkMode if darkMode { self.view.backgroundColor = UIColor.black self.navigationController?.navigationBar.barStyle = .black self.navigationController?.navigationBar.tintColor = .white self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] } else { self.view.backgroundColor = UIColor(red: 248/255, green: 249/255, blue: 250/255, alpha: 1) self.navigationController?.navigationBar.barStyle = .default self.navigationController?.navigationBar.tintColor = .black self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black] } case .HarnessAppDemoCeTrialLimit: guard let int = value.intValue else {return} ceTrial = int updateTrial(.Efficiency, trial: int) case .HarnessAppDemoCfTrialLimit: guard let int = value.intValue else {return} cfTrial = int updateTrial(.Features, trial: int) case .HarnessAppDemoCiTrialLimit: guard let int = value.intValue else {return} ciTrial = int updateTrial(.Integration, trial: int) case .HarnessAppDemoCvTrialLimit: guard let int = value.intValue else {return} cvTrial = int updateTrial(.Verification, trial: int) case .HarnessAppDemoEnableCeModule: guard let enabled = value.boolValue else {return} let card = CEModule() card.featureTrialPeriod = ceTrial if enabled { self.insertCard(card) } else { self.removeCard(card) } case .HarnessAppDemoEnableCfModule: guard let enabled = value.boolValue else {return} let card = CFModule() card.featureTrialPeriod = cfTrial if enabled { self.insertCard(card) } else { self.removeCard(card) } case .HarnessAppDemoEnableCiModule: guard let enabled = value.boolValue else {return} let card = CIModule() card.featureTrialPeriod = ciTrial if enabled { self.insertCard(card) } else { self.removeCard(card) } case .HarnessAppDemoEnableCvModule: guard let enabled = value.boolValue else {return} let card = CVModule() card.featureTrialPeriod = cvTrial if enabled { self.insertCard(card) } else { self.removeCard(card) } case .HarnessAppDemoEnableGlobalHelp: guard let enable = value.boolValue else {return} self.needHelpButton.isHidden = !enable default: break } self.reloadCollection() } func insertCard(_ card: FeatureCardRepresentable) { for var c in availableFeatures { if c.featureName == card.featureName { c.available = true } } } func removeCard(_ card: FeatureCardRepresentable) { for var c in availableFeatures { if c.featureName == card.featureName { c.available = false } } } func updateTrial(_ card: FeatureName, trial:Int) { for var c in availableFeatures { if c.featureName == card { c.featureTrialPeriod = trial } } } func updateRibbon(_ card: FeatureName, ribbon:Bool) { for var c in availableFeatures { if c.featureName == card { c.hasRibbon = ribbon } } } private func reloadCollection() { self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.layoutSubviews() } enum FlagType { case HarnessAppDemoCfRibbon case HarnessAppDemoDarkMode case HarnessAppDemoCeTrialLimit case HarnessAppDemoCfTrialLimit case HarnessAppDemoCiTrialLimit case HarnessAppDemoCvTrialLimit case HarnessAppDemoEnableCeModule case HarnessAppDemoEnableCfModule case HarnessAppDemoEnableCiModule case HarnessAppDemoEnableCvModule case HarnessAppDemoEnableGlobalHelp case NoFlag init(flag: String) { switch flag { case "harnessappdemocfribbon": self = .HarnessAppDemoCfRibbon case "harnessappdemodarkmode": self = .HarnessAppDemoDarkMode case "harnessappdemocetriallimit": self = .HarnessAppDemoCeTrialLimit case "harnessappdemocftriallimit": self = .HarnessAppDemoCfTrialLimit case "harnessappdemocitriallimit": self = .HarnessAppDemoCiTrialLimit case "harnessappdemocvtriallimit": self = .HarnessAppDemoCvTrialLimit case "harnessappdemoenablecemodule": self = .HarnessAppDemoEnableCeModule case "harnessappdemoenablecfmodule": self = .HarnessAppDemoEnableCfModule case "harnessappdemoenablecimodule": self = .HarnessAppDemoEnableCiModule case "harnessappdemoenablecvmodule": self = .HarnessAppDemoEnableCvModule case "harnessappdemoenableglobalhelp": self = .HarnessAppDemoEnableGlobalHelp default: self = .NoFlag } } } enum FlagValue { case color(String) case bool(Bool) case int(Int) var colorValue: UIColor { switch self { case .color(let color): switch color.lowercased().replacingOccurrences(of: "\"", with: "") { case "red": return UIColor.red case "green": return UIColor.green case "blue": return UIColor.blue default: return UIColor.gray } case .bool(_): return UIColor.gray case .int(_): return UIColor.gray } } } } extension FeatureViewController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return enabledFeatures.count } return availableFeatures.filter{$0.available}.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "featureCell", for: indexPath) as! FeatureCell cell.darkMode = self.darkMode if indexPath.section == 0 { cell.configure(feature: enabledFeatures[indexPath.row]) } else { cell.configure(feature: availableFeatures.filter{$0.available}[indexPath.row]) } return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! CollectionHeaderView headerView.configureFor(self.darkMode) if indexPath.section == 0 { headerView.headerTitle.text = "Modules Enabled" } else { headerView.headerTitle.text = "Enable More Modules" } return headerView default: return UICollectionReusableView() } } } extension FeatureViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.section == 0 { self.topConstraint.isActive = false self.topConstraint = NSLayoutConstraint(item: self.needHelpButton!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: cell.center.y) NSLayoutConstraint.activate([topConstraint]) } } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // return CGSize(width: self.collectionView.frame.size.width/2 - 20, height: self.collectionView.frame.size.width/2 + 20) // } }
36.262687
183
0.726045
1cd76cf1847ba37d6931d83593847570f282c1c5
4,573
// // DexMarketPresenter.swift // WavesWallet-iOS // // Created by Pavel Gubin on 8/9/18. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxSwift import RxFeedback import RxCocoa import DomainLayer final class DexMarketPresenter: DexMarketPresenterProtocol { var interactor: DexMarketInteractorProtocol! weak var moduleOutput: DexMarketModuleOutput? private let disposeBag = DisposeBag() func system(feedbacks: [DexMarketPresenterProtocol.Feedback]) { var newFeedbacks = feedbacks newFeedbacks.append(modelsQuery()) newFeedbacks.append(searchModelsQuery()) Driver.system(initialState: DexMarket.State.initialState, reduce: { [weak self] state, event -> DexMarket.State in guard let self = self else { return state } return self.reduce(state: state, event: event) }, feedback: newFeedbacks) .drive() .disposed(by: disposeBag) } private func modelsQuery() -> Feedback { return react(request: { state -> DexMarket.State? in return state.isNeedLoadDefaultPairs ? state : nil }, effects: { [weak self] _ -> Signal<DexMarket.Event> in guard let self = self else { return Signal.empty() } return self.interactor.pairs().map { .setPairs($0) }.asSignal(onErrorSignalWith: Signal.empty()) }) } private func searchModelsQuery() -> Feedback { return react(request: { state -> DexMarket.State? in return state.isNeedSearching ? state : nil }, effects: { [weak self] state -> Signal<DexMarket.Event> in guard let self = self else { return Signal.empty() } return self.interactor.searchPairs(searchWord: state.searchKey) .map { .setPairs($0) }.asSignal(onErrorSignalWith: Signal.empty()) }) } private func reduce(state: DexMarket.State, event: DexMarket.Event) -> DexMarket.State { switch event { case .readyView: return state.changeAction(.none) case .setPairs(let pairs): return state.mutate { state in let items = pairs.map { DexMarket.ViewModel.Row.pair($0) } let section = DexMarket.ViewModel.Section(items: items) state.section = section state.isNeedSearching = false state.isNeedLoadDefaultPairs = false }.changeAction(.update) case .tapCheckMark(let index): if let pair = state.section.items[index].pair { interactor.checkMark(pair: pair) } return state.mutate { state in if let pair = state.section.items[index].pair { state.section.items[index] = DexMarket.ViewModel.Row.pair(pair.mutate {$0.isChecked = !$0.isChecked}) } }.changeAction(.update) case .tapInfoButton(let index): if let pair = state.section.items[index].pair { let infoPair = DexInfoPair.DTO.Pair(amountAsset: pair.amountAsset, priceAsset: pair.priceAsset, isGeneral: pair.isGeneral) moduleOutput?.showInfo(pair: infoPair) } return state.changeAction(.none) case .searchTextChange(let text): return state.mutate { $0.isNeedSearching = text.count > 0 $0.isNeedLoadDefaultPairs = text.count == 0 $0.searchKey = text }.changeAction(.none) } } } fileprivate extension DexMarket.ViewModel.Row { var pair: DomainLayer.DTO.Dex.SmartPair? { switch self { case .pair(let pair): return pair } } } fileprivate extension DexMarket.State { static var initialState: DexMarket.State { let section = DexMarket.ViewModel.Section(items: []) return DexMarket.State(action: .none, section: section, searchKey: "", isNeedSearching: false, isNeedLoadDefaultPairs: true) } func changeAction(_ action: DexMarket.State.Action) -> DexMarket.State { return mutate { state in state.action = action } } }
34.643939
138
0.565056
11e659cd4e654fbd750d50b3e32d679ca66c8a7a
290
// // Employee.swift // SwiftUIRestAPI // // Created by Angelos Staboulis on 5/9/21. // import Foundation struct Employee:Identifiable{ var id: Int var idRecord:Int var employee_name:String var employee_salary:Int var employee_age:Int var profile_image:String }
17.058824
43
0.706897
22d845a0d764e46c55f66c27db35c8d65a518660
1,085
// // Copyright © 2019 sroik. All rights reserved. // import SmartMachine import Surge import XCTest class NeuralNetworkTests: XCTestCase { func testEmptyNetCompilation() { NeuralNetwork().compile() } func testXORModel() { let input = Matrix([ [0, 0], [0, 1], [1, 0], [1, 1] ]) let prediction = NeuralNetwork.xor().predict(input) XCTAssert(prediction[0, 0] < 0) XCTAssert(prediction[1, 0] > 0) XCTAssert(prediction[2, 0] > 0) XCTAssert(prediction[3, 0] < 0) } } private extension NeuralNetwork { static func xor() -> NeuralNetwork { let nn = NeuralNetwork() nn.add(layer: .input(size: 2)) nn.add(layer: .fullyConnected(size: 2, activation: .tanh)) nn.add(layer: .fullyConnected(size: 1, activation: .tanh)) nn.layers[1].weights = Matrix([[4, -3], [4, -3]]) nn.layers[1].biases = [-2, 5] nn.layers[2].weights = Matrix([[5], [5]]) nn.layers[2].biases = [-5] return nn } }
24.659091
66
0.546544
79e4ea1b43355c918d03dd13373685b57a112aad
791
#if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif import OpenSSL public class TlsServer : ServerType { let server: ServerType let sslContext: SSLServerContext public init(server: ServerType,certificate: String, privateKey: String, certificateChain: String? = nil) throws { self.server = server sslContext = try SSLServerContext( certificate: certificate, privateKey: privateKey, certificateChain: certificateChain) } public func accept() throws -> HandledStream { let stream = try server.accept() return try HandledSSLServerStream(context: sslContext, rawStream: stream) } public func getSocket()->Int32 { return server.getSocket() } }
24.71875
118
0.651075
383af4972b0b2f34545ce275242ca9843c22087e
6,863
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore // MARK: Paginators extension ConfigService { /// Returns the details of one or more remediation exceptions. A detailed view of a remediation exception for a set of resources that includes an explanation of an exception and the time when the exception will be deleted. When you specify the limit and the next token, you receive a paginated response. AWS Config generates a remediation exception when a problem occurs executing a remediation action to a specific resource. Remediation exceptions blocks auto-remediation until the exception is cleared. When you specify the limit and the next token, you receive a paginated response. Limit and next token are not applicable if you request resources in batch. It is only applicable, when you request all resources. public func describeRemediationExceptionsPaginator( _ input: DescribeRemediationExceptionsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (DescribeRemediationExceptionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: describeRemediationExceptions, tokenKey: \DescribeRemediationExceptionsResponse.nextToken, on: eventLoop, onPage: onPage) } /// Provides a detailed view of a Remediation Execution for a set of resources including state, timestamps for when steps for the remediation execution occur, and any error messages for steps that have failed. When you specify the limit and the next token, you receive a paginated response. public func describeRemediationExecutionStatusPaginator( _ input: DescribeRemediationExecutionStatusRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (DescribeRemediationExecutionStatusResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: describeRemediationExecutionStatus, tokenKey: \DescribeRemediationExecutionStatusResponse.nextToken, on: eventLoop, onPage: onPage) } /// Returns a list of configuration items for the specified resource. The list contains details about each state of the resource during the specified time interval. If you specified a retention period to retain your ConfigurationItems between a minimum of 30 days and a maximum of 7 years (2557 days), AWS Config returns the ConfigurationItems for the specified retention period. The response is paginated. By default, AWS Config returns a limit of 10 configuration items per page. You can customize this number with the limit parameter. The response includes a nextToken string. To get the next page of results, run the request again and specify the string for the nextToken parameter. Each call to the API is limited to span a duration of seven days. It is likely that the number of records returned is smaller than the specified limit. In such cases, you can make another call, using the nextToken. public func getResourceConfigHistoryPaginator( _ input: GetResourceConfigHistoryRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (GetResourceConfigHistoryResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: getResourceConfigHistory, tokenKey: \GetResourceConfigHistoryResponse.nextToken, on: eventLoop, onPage: onPage) } /// Accepts a structured query language (SQL) SELECT command and an aggregator to query configuration state of AWS resources across multiple accounts and regions, performs the corresponding search, and returns resource configurations matching the properties. For more information about query components, see the Query Components section in the AWS Config Developer Guide. public func selectAggregateResourceConfigPaginator( _ input: SelectAggregateResourceConfigRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (SelectAggregateResourceConfigResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: selectAggregateResourceConfig, tokenKey: \SelectAggregateResourceConfigResponse.nextToken, on: eventLoop, onPage: onPage) } } extension ConfigService.DescribeRemediationExceptionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ConfigService.DescribeRemediationExceptionsRequest { return .init( configRuleName: self.configRuleName, limit: self.limit, nextToken: token, resourceKeys: self.resourceKeys ) } } extension ConfigService.DescribeRemediationExecutionStatusRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ConfigService.DescribeRemediationExecutionStatusRequest { return .init( configRuleName: self.configRuleName, limit: self.limit, nextToken: token, resourceKeys: self.resourceKeys ) } } extension ConfigService.GetResourceConfigHistoryRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ConfigService.GetResourceConfigHistoryRequest { return .init( chronologicalOrder: self.chronologicalOrder, earlierTime: self.earlierTime, laterTime: self.laterTime, limit: self.limit, nextToken: token, resourceId: self.resourceId, resourceType: self.resourceType ) } } extension ConfigService.SelectAggregateResourceConfigRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ConfigService.SelectAggregateResourceConfigRequest { return .init( configurationAggregatorName: self.configurationAggregatorName, expression: self.expression, limit: self.limit, maxResults: self.maxResults, nextToken: token ) } }
58.65812
909
0.732916
6946697c7de4f57a42ce7f3f9c999e0e104d8e5e
303
// // Wage.swift // window-shopper // // Created by Administrator on 8/12/20. // Copyright © 2020 Nyi Nyi Htun Lwin. All rights reserved. // import Foundation class Wage { class func getHours(forWage wage: Double, forPrice price: Double) -> Int{ return Int(ceil(price / wage)) } }
18.9375
77
0.653465
ababf8ba5f47d7d935e1a7098a5731234fa544fc
14,508
// // OTMClient.swift // On The Map // // Created by Jamie Nguyen on 12/5/17. // Copyright © 2017 Jamie Nguyen. All rights reserved. // import UIKit import Foundation class OTMClient : NSObject { // Shared Instance Singleton static let sharedInstance = OTMClient() // shared session var session = URLSession.shared // authentication state var sessionID : String? var username: String? var password: String? var myAccount = StudentInformation() func authenticateWithViewController(_ viewController: UIViewController,_ parameters: [String:AnyObject], completionHandlerForAuth: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { print("starting authenticating") var request = URLRequest(url: URL(string: "https://www.udacity.com/api/session")!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = "{\"udacity\": {\"username\": \"\(username!)\", \"password\": \"\(password!)\"}}".data(using: .utf8) let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { completionHandlerForAuth(false, error?.localizedDescription) return } let range = Range(5..<data!.count) let newData = data?.subdata(in: range) /* subset response data! */ let parsedResult: [String:AnyObject]! do { parsedResult = try JSONSerialization.jsonObject(with: newData!, options: .allowFragments) as! [String:AnyObject] } catch { completionHandlerForAuth(false, "Could not parse the data as JSON: '\(newData.debugDescription)'") return } if let _ = parsedResult["status"], let errorMessage = parsedResult["error"] { completionHandlerForAuth(false, "\(errorMessage)") return } let thissession = parsedResult["session"] as! [String: String] self.sessionID = thissession["id"] let thisaccount = parsedResult["account"] as! [String: AnyObject] let key = thisaccount["key"] self.myAccount.uniqueKey = key as? String completionHandlerForAuth(true,nil) } task.resume() return task } // MARK: POSTING NEW LOCATION func postStudentLocation(parameters: [String: AnyObject],completionHandlerForPin: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!) request.httpMethod = "POST" request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = "{\"uniqueKey\": \"\(self.myAccount.uniqueKey!)\", \"firstName\": \"\(self.myAccount.firstName!)\", \"lastName\": \"\(self.myAccount.lastName!)\",\"mapString\": \"\(parameters[OTMClient.JSONResponseKeys.MapString]!)\", \"mediaURL\": \"\(parameters[OTMClient.JSONResponseKeys.MediaURL]!)\",\"latitude\": \(parameters[OTMClient.JSONResponseKeys.Latitute]!), \"longitude\": \(parameters[OTMClient.JSONResponseKeys.Longitude]!)}".data(using: .utf8) let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { print(error!) completionHandlerForPin(false, "Pin Failed") return } let parsedResult: [String:AnyObject]! do { parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject] } catch { completionHandlerForPin(false, "Could not parse the data as JSON: '\(data.debugDescription)'") return } self.myAccount.createdAt = parsedResult["createdAt"] as? String self.myAccount.objectId = parsedResult["objectId"] as? String self.myAccount.mediaURL = parameters["mediaURL"] as? String completionHandlerForPin(true, nil) } task.resume() return task } // MARK: GET USER INFO func getStudentLocations(completionHandlerForGetStudentLocations: @escaping (_ locations: [StudentInformation]?, _ errorString: String?) -> Void) -> URLSessionDataTask { var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation?order=-updatedAt&limit=100")!) request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { print(error!) completionHandlerForGetStudentLocations(nil, "Get Students Location Failed") return } let parsedResult: [String:AnyObject]! do { parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject] } catch { completionHandlerForGetStudentLocations(nil, "Could not parse the data as JSON: '\(data.debugDescription)'") return } if let results = parsedResult?["results"] as? [[String:AnyObject]] { let studentInformations = StudentInformation.studentInformationsFromResults(results) completionHandlerForGetStudentLocations(studentInformations, nil) } else { completionHandlerForGetStudentLocations(nil,"Cannot parse GetStudentLocations") return } } task.resume() return task } // MARK: GET PUBLIC USER DATA func getPublicUserData (completionHandlerForGetPublicUserData: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { let request = URLRequest(url: URL(string: "https://www.udacity.com/api/users/\(self.myAccount.uniqueKey!)")!) let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { print(error!) completionHandlerForGetPublicUserData(false, "Get Public User Data failed") return } let range = Range(5..<data!.count) let newData = data?.subdata(in: range) /* subset response data! */ let parsedResult: [String:AnyObject]! do { parsedResult = try JSONSerialization.jsonObject(with: newData!, options: .allowFragments) as! [String:AnyObject] } catch { completionHandlerForGetPublicUserData(false, "Could not parse the data as JSON: '\(newData.debugDescription)'") return } let thisuser = parsedResult["user"] self.myAccount.firstName = thisuser!["first_name"] as? String self.myAccount.lastName = thisuser!["last_name"] as? String completionHandlerForGetPublicUserData(true, nil) } task.resume() return task } // MARK: PUTTING A STUDENT LOCATION func puttingStudentLocation(_ parameters: [String: AnyObject], completionHandlerForPutStudentLocation: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { let urlString = "https://parse.udacity.com/parse/classes/StudentLocation/\(self.myAccount.objectId!)" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "PUT" request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = "{\"uniqueKey\": \"\(self.myAccount.uniqueKey!)\", \"firstName\": \"\(self.myAccount.firstName!)\", \"lastName\": \"\(self.myAccount.lastName!)\",\"mapString\": \"\(self.myAccount.mapString!)\", \"mediaURL\": \"\(parameters["mediaURL"]!)\",\"latitude\": \(parameters["latitude"]!), \"longitude\": \(parameters["longitude"]!)}".data(using: .utf8) print("{\"uniqueKey\": \"\(self.myAccount.uniqueKey!)\", \"firstName\": \"\(self.myAccount.firstName!)\", \"lastName\": \"\(self.myAccount.lastName!)\",\"mapString\": \"\(self.myAccount.mapString!)\", \"mediaURL\": \"\(parameters["mediaURL"]!)\",\"latitude\": \(parameters["latitude"]!), \"longitude\": \(parameters["longitude"]!)}") let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { // Handle error… print("Posting new location failed") completionHandlerForPutStudentLocation(false, error?.localizedDescription) return } let parsedResult: [String:AnyObject]! do { parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject] } catch { completionHandlerForPutStudentLocation(false, "Could not parse the data as JSON: '\(data.debugDescription)'") return } print("PARSED RESULT AT PUT NEW LOCATION", parsedResult) self.myAccount.updatedAt = parsedResult[OTMClient.JSONResponseKeys.UpdatedAt] as? String self.myAccount.mediaURL = parameters["mediaURL"] as? String self.myAccount.mapString = parameters["mapString"] as? String completionHandlerForPutStudentLocation(true, nil) } task.resume() return task } // MARK: GET A STUDENT LOCATION func getAStudentLocation(completionHandlerForGetAStudentLocation: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { let txtAppend = String(self.myAccount.uniqueKey!).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let urlString = "https://parse.udacity.com/parse/classes/StudentLocation?where={\"uniqueKey\":\"\(txtAppend!)\"}" let url = NSURL(string: (urlString as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!) var request = URLRequest(url: url! as URL) request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { completionHandlerForGetAStudentLocation(false, "Getting student information failed") return } let parsedResult: [String:AnyObject] do { parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject] print("GET A STUDENT LOCATION PARSEDRESULT", parsedResult) } catch { completionHandlerForGetAStudentLocation(false, "Could not parse the data as JSON: '\(data.debugDescription)'") return } //UPDATE LOCATION, CREATED AT let results = parsedResult["results"] as! [[String: AnyObject]] if results.count > 0 { self.myAccount = StudentInformation(dictionary: results[0]) completionHandlerForGetAStudentLocation(true, nil) } else { completionHandlerForGetAStudentLocation(true, "No past location posted") } } task.resume() return task } // MARK: DELETE A SESSION func deleteSession(_ completionHandlerForDeleteSession: @escaping (_ success: Bool, _ errorString: String?) -> Void) -> URLSessionDataTask { var request = URLRequest(url: URL(string: "https://www.udacity.com/api/session")!) request.httpMethod = "DELETE" var xsrfCookie: HTTPCookie? = nil let sharedCookieStorage = HTTPCookieStorage.shared for cookie in sharedCookieStorage.cookies! { if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie } } if let xsrfCookie = xsrfCookie { request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN") } let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if error != nil { completionHandlerForDeleteSession(false, "Log out failed") return } let range = Range(5..<data!.count) let newData = data?.subdata(in: range) /* subset response data! */ print(String(data: newData!, encoding: .utf8)!) } task.resume() return task } // MARK: SHOW ALERT MESSAGE func showAlertMessage(title: String, message: String, viewController: UIViewController, shouldPop: Bool) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Dismiss", comment: "Default action"), style: .default, handler: { _ in if shouldPop { viewController.navigationController?.popViewController(animated: true) } })) viewController.present(alert, animated: true, completion: nil) } }
52.756364
471
0.624414
9cacc8a950b69a94e296e179c0529b5d3c43d69e
274
import Combine var subscriptions = Set<AnyCancellable>() let items = [1, 2, 3, 5, 7, 11, 13] items.publisher .print() .count() // count won´t finish until finish event is sent .sink(receiveValue: { print("Num. items: \($0)") }) .store(in: &subscriptions)
22.833333
61
0.635036
6418e6a38854ca4e1f5c064f3c81ca9d654cbab4
600
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension String { func f: d = Swift.Type func b<1 { struct c<T>()).C) -> { class d) -> Int { } return b() { self.c == j> T> ((({ extension String { var b { } } } case b { class c { } class B { class func f(bytes: Array) -> Void>() -> { } } } } } var f == { class A { } }) } protocol d { self.b.Generator.dynamicType.Generator.Element == { } func g: b = a typealias B : BooleanType, f
15
87
0.631667
9b1ee228dbb5b5c5e0de13c95b522f7592b380ef
468
// // Copyright © 2020 Jesús Alfredo Hernández Alarcón. All rights reserved. // import Foundation public struct ImageComment: Equatable { public let id: UUID public let message: String public let createdAt: Date public let username: String public init(id: UUID, message: String, createdAt: Date, username: String) { self.id = id self.message = message self.createdAt = createdAt self.username = username } }
23.4
79
0.668803
6131b15dd5446e3d7102c604cc4dc341227ab6ec
9,931
// // MyShopViewController.swift // AdForMerchant // // Created by Kuma on 2/25/16. // Copyright © 2016 Windward. All rights reserved. // import UIKit import ObjectMapper class MyShopViewController: BaseViewController { @IBOutlet fileprivate weak var tableView: UITableView! var storeInfo: StoreInfo! = StoreInfo() var payPasswd: String = "" var addressCount = 0 override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "我的店铺" if let storeInfo = UserManager.sharedInstance.userInfo?.storeInfo { self.storeInfo = storeInfo } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) requestStoreInfo() requestAddressList() } 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?) { if segue.identifier == "ShopCreate@MerchantCenter" { guard let desVC = segue.destination as? ShopCreateViewController else {return} desVC.storeInfo = storeInfo } } // MARK: - Http request func requestStoreInfo() { kApp.requestUserInfoWithCompleteBlock({ if let storeInfo = UserManager.sharedInstance.userInfo?.storeInfo { self.storeInfo = storeInfo } self.tableView.reloadData() }) } func showPayCodeView() { let payCodeVC = PayCodeVerificationViewController() payCodeVC.modalPresentationStyle = .custom payCodeVC.confirmBlock = {payPassword in self.payPasswd = payPassword self.requestCheckPayCode() } present(payCodeVC, animated: true, completion: nil) } // MARK: - Http request func requestCheckPayCode() { let parameters: [String: Any] = [ "pay_password": payPasswd ] let aesKey = AFMRequest.randomStringWithLength16() let aesIV = AFMRequest.randomStringWithLength16() Utility.showMBProgressHUDWithTxt() RequestManager.request(AFMRequest.merchantCheckPaypassword(parameters, aesKey, aesIV), aesKeyAndIv: (aesKey, aesIV)) { (_, _, object, error, _) -> Void in if (object) != nil { Utility.hideMBProgressHUD() AOLinkedStoryboardSegue.performWithIdentifier("MyShopAssistantViewController@MerchantCenter", source: self, sender: nil) } else { if let userInfo = error?.userInfo, let msg = userInfo["message"] as? String { Utility.showMBProgressHUDToastWithTxt(msg) } else { Utility.hideMBProgressHUD() } } } } func requestAddressList() { let aesKey = AFMRequest.randomStringWithLength16() let aesIV = AFMRequest.randomStringWithLength16() Utility.showMBProgressHUDWithTxt() RequestManager.request(AFMRequest.storeAddressList(aesKey, aesIV), aesKeyAndIv: (aesKey, aesIV)) { (_, _, object, _, _) -> Void in if (object) != nil { guard let result = object as? [String: Any] else {return} if let addressList = result["address_list"] as? [[String: Any]] { self.addressCount = addressList.count Utility.hideMBProgressHUD() self.tableView.reloadData() } } else { Utility.hideMBProgressHUD() } } } } extension MyShopViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 6 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { default: return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch (indexPath.section, indexPath.row) { case (0, _): let cell = tableView.dequeueReusableCell(withIdentifier: "MyShopHeaderTableViewCell", for: indexPath) return cell default: guard let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCellId") else { return UITableViewCell(style: .value1, reuseIdentifier: "DefaultCellId") } return cell } } } extension MyShopViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.selectionStyle = .none if indexPath.section >= 1 && indexPath.section <= 5 { cell.textLabel?.textColor = UIColor.colorWithHex("#393939") cell.textLabel?.font = UIFont.systemFont(ofSize: 15) cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } switch (indexPath.section, indexPath.row) { case (0, 0): guard let _cell = cell as? MyShopHeaderTableViewCell else {return} _cell.shopBgImgView.sd_setImage(with: URL(string: storeInfo.cover)) _cell.shopAvatarImgView.sd_setImage(with: URL(string: storeInfo.logo), placeholderImage: UIImage(named: "PlaceHolderHeadportrait")) if storeInfo.name.isEmpty { _cell.shopNameLbl.text = "店铺名称设置" } else { _cell.shopNameLbl.text = storeInfo.name } _cell.shopRatingLbl.text = "评分:" + storeInfo.score case (1, 0): cell.imageView?.image = UIImage(named: "MyShopIconCategory") cell.textLabel?.text = "店铺分类" case (2, 0): cell.imageView?.image = UIImage(named: "btn_Item_management") cell.textLabel?.text = "货号管理" case (3, 0): cell.imageView?.image = UIImage(named: "btn_commodity_setting") cell.textLabel?.text = "商品设置" case (4, 0): cell.imageView?.image = UIImage(named: "btn_my_shop_assistant") cell.textLabel?.text = "我的店员" case (5, 0): cell.imageView?.image = UIImage(named: "MyShopIconAddress") cell.detailTextLabel?.text = "\(addressCount)" cell.detailTextLabel?.textColor = UIColor.colorWithHex("#393939") cell.textLabel?.text = "店铺地址" default: break } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 10.0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: return 130 default: return 45 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0, 0): AOLinkedStoryboardSegue.performWithIdentifier("ShopCreate@MerchantCenter", source: self, sender: nil) case (1, 0): if !kApp.pleaseAttestationAction(showAlert: true, type: .shopsCategory) { return } AOLinkedStoryboardSegue.performWithIdentifier("ShopCategoryManage@MerchantCenter", source: self, sender: nil) case(2, 0): if !kApp.pleaseAttestationAction(showAlert: true, type: .itemManageCategory) { return } AOLinkedStoryboardSegue.performWithIdentifier("ItemManageViewController@MerchantCenter", source: self, sender: nil) case (3, 0): let destVC = GoodsSetViewController() navigationController?.pushViewController(destVC, animated: true) case (4, 0): let statsu = UserManager.sharedInstance.userInfo?.status ?? .unverified // 未认证:没有设置支付密码 if statsu == .unverified { if !kApp.pleaseAttestationAction(showAlert: true, type: .myShopAssistanManage) { return } } guard let vc = UIStoryboard(name: "VerifyPayPass", bundle: nil).instantiateInitialViewController() as? VerifypasswordViewController else {return} vc.type = .verify vc.modalPresentationStyle = .custom vc.resultHandle = { (result, data) in switch result { case .passed: self.dim(.out, coverNavigationBar: true) vc.dismiss(animated: true, completion: nil) AOLinkedStoryboardSegue.performWithIdentifier("MyShopAssistantViewController@MerchantCenter", source: self, sender: nil) case .failed: break case .canceled: self.dim(.out, coverNavigationBar: true) vc.dismiss(animated: true, completion: nil) } } self.dim(.in, coverNavigationBar: true) self.present(vc, animated: true, completion: nil) case (5, 0): if !kApp.pleaseAttestationAction(showAlert: true, type: .shopAdressManage) { return } AOLinkedStoryboardSegue.performWithIdentifier("ShopAddressManage@MerchantCenter", source: self, sender: nil) default: break } } }
37.617424
162
0.596113
0976a3736e5090c3333424fee6766908247a6079
7,142
#if os(iOS) || os(OSX) @testable import EventflitSwift import XCTest func setUpDefaultMockResponses(eventflitClient: Eventflit, deviceClientId: String) { let jsonData = "{\"id\":\"\(deviceClientId)\"}".data(using: String.Encoding.utf8, allowLossyConversion: false)! let url = URL(string: "https://nativepushclient-cluster1.eventflit.com/client_api/v1/clients")! let urlResponse = HTTPURLResponse(url: url, statusCode: 201, httpVersion: nil, headerFields: nil) MockSession.addMockResponse(for: url, httpMethod: "POST", data: jsonData, urlResponse: urlResponse, error: nil) let emptyJsonData = "".data(using: String.Encoding.utf8)! let subscriptionModificationUrl = URL(string: "https://nativepushclient-cluster1.eventflit.com/client_api/v1/clients/\(deviceClientId)/interests/donuts")! let susbcriptionModificationResponse = HTTPURLResponse(url: subscriptionModificationUrl, statusCode: 204, httpVersion: nil, headerFields: nil) let httpMethodForSubscribe = "POST" MockSession.addMockResponse(for: subscriptionModificationUrl, httpMethod: httpMethodForSubscribe, data: emptyJsonData, urlResponse: susbcriptionModificationResponse, error: nil) let httpMethodForUnsubscribe = "DELETE" MockSession.addMockResponse(for: subscriptionModificationUrl, httpMethod: httpMethodForUnsubscribe, data: emptyJsonData, urlResponse: susbcriptionModificationResponse, error: nil) eventflitClient.nativeEventflit.URLSession = MockSession.shared } class NativeEventflitTests: XCTestCase { public class DummyDelegate: EventflitDelegate { public var testClientId: String? = nil public var registerEx: XCTestExpectation? = nil public var subscribeEx: XCTestExpectation? = nil public var unsubscribeEx: XCTestExpectation? = nil public var registerFailEx: XCTestExpectation? = nil public var interestName: String? = nil public func subscribedToInterest(name: String) { if interestName == name { subscribeEx!.fulfill() } } public func unsubscribedFromInterest(name: String) { if interestName == name { unsubscribeEx!.fulfill() } } public func registeredForPushNotifications(clientId: String) { XCTAssertEqual(clientId, testClientId) registerEx!.fulfill() } public func failedToRegisterForPushNotifications(response: URLResponse, responseBody: String?) { registerFailEx!.fulfill() } } var key: String! var eventflit: Eventflit! var socket: MockWebSocket! var dummyDelegate: DummyDelegate! var testClientId: String! override func setUp() { super.setUp() key = "testKey123" testClientId = "your_client_id" let options = EventflitClientOptions( authMethod: AuthMethod.inline(secret: "secret"), autoReconnect: false ) eventflit = Eventflit(key: key, options: options) socket = MockWebSocket() socket.delegate = eventflit.connection eventflit.connection.socket = socket dummyDelegate = DummyDelegate() eventflit.delegate = dummyDelegate } func testReceivingAClientIdAfterRegisterIsCalled() { setUpDefaultMockResponses(eventflitClient: eventflit, deviceClientId: testClientId) let ex = expectation(description: "the clientId should be received when registration succeeds") dummyDelegate.testClientId = testClientId dummyDelegate.registerEx = ex eventflit.nativeEventflit.register(deviceToken: "SOME_DEVICE_TOKEN".data(using: String.Encoding.utf8)!) waitForExpectations(timeout: 0.5) } func testSubscribingToAnInterest() { setUpDefaultMockResponses(eventflitClient: eventflit, deviceClientId: testClientId) let registerEx = expectation(description: "the clientId should be received when registration succeeds") let subscribeEx = expectation(description: "the client should successfully subscribe to an interest") dummyDelegate.testClientId = testClientId dummyDelegate.interestName = "donuts" dummyDelegate.registerEx = registerEx dummyDelegate.subscribeEx = subscribeEx eventflit.nativeEventflit.subscribe(interestName: "donuts") eventflit.nativeEventflit.register(deviceToken: "SOME_DEVICE_TOKEN".data(using: String.Encoding.utf8)!) waitForExpectations(timeout: 0.5) } func testUnsubscribingFromAnInterest() { setUpDefaultMockResponses(eventflitClient: eventflit, deviceClientId: testClientId) let registerEx = expectation(description: "the clientId should be received when registration succeeds") let subscribeEx = expectation(description: "the client should successfully subscribe to an interest") let unsubscribeEx = expectation(description: "the client should successfully unsubscribe from an interest") dummyDelegate.testClientId = testClientId dummyDelegate.interestName = "donuts" dummyDelegate.registerEx = registerEx dummyDelegate.subscribeEx = subscribeEx dummyDelegate.unsubscribeEx = unsubscribeEx eventflit.nativeEventflit.subscribe(interestName: "donuts") eventflit.nativeEventflit.register(deviceToken: "SOME_DEVICE_TOKEN".data(using: String.Encoding.utf8)!) eventflit.nativeEventflit.unsubscribe(interestName: "donuts") waitForExpectations(timeout: 0.5) } func testSubscribingWhenClientIdIsNotSetQueuesSubscriptionModificationRequest() { eventflit.nativeEventflit.clientId = nil XCTAssertEqual(eventflit.nativeEventflit.requestQueue.count, 0, "the nativeEventflit request queue should be empty") eventflit.nativeEventflit.subscribe(interestName: "donuts") Thread.sleep(forTimeInterval: 0.5) XCTAssertEqual(eventflit.nativeEventflit.requestQueue.count, 1, "the nativeEventflit request queue should contain the subscribe request") XCTAssertEqual(eventflit.nativeEventflit.requestQueue.paused, true, "the nativeEventflit request queue should be paused") } func testFailingToRegisterWithEventflitForPushNotificationsCallsTheAppropriateDelegateFunction() { let jsonData = "".data(using: String.Encoding.utf8, allowLossyConversion: false)! let url = URL(string: "https://nativepushclient-cluster1.eventflit.com/client_api/v1/clients")! let urlResponse = HTTPURLResponse(url: url, statusCode: 500, httpVersion: nil, headerFields: nil) MockSession.addMockResponse(for: url, httpMethod: "POST", data: jsonData, urlResponse: urlResponse, error: nil) eventflit.nativeEventflit.URLSession = MockSession.shared let registerFailEx = expectation(description: "the appropriate delegate should be called when registration fails") dummyDelegate.registerFailEx = registerFailEx eventflit.nativeEventflit.register(deviceToken: "SOME_DEVICE_TOKEN".data(using: String.Encoding.utf8)!) waitForExpectations(timeout: 0.5) } } #endif
46.376623
183
0.729067
de6ab44845c3e8dbf02bbe05fd15051adb881b69
4,914
// // LoginSMSView.swift // StoryIDDemo // // Created by Sergey Ryazanov on 27.04.2020. // Copyright © 2020 breffi. All rights reserved. // import UIKit protocol LoginSMSViewDelegate: AnyObject { func loginSmsView(_ view: LoginSMSView, didEnterCode code: String?) } final class LoginSMSView: BaseView { weak var delegate: LoginSMSViewDelegate? private let titleLabel = UILabel() let textField = SMSTextField() let separatorView = UIView() let tapGesture = UITapGestureRecognizer() let tapResendGesture = UITapGestureRecognizer() let resendLabel = UILabel() override func setup() { super.setup() self.addGestureRecognizer(tapGesture) self.backgroundColor = UIColor.idWhite self.titleLabel.backgroundColor = UIColor.clear self.titleLabel.numberOfLines = 1 self.titleLabel.textColor = UIColor.idBlack self.titleLabel.textAlignment = NSTextAlignment.left self.titleLabel.font = UIFont.systemFont(ofSize: 34.0, weight: UIFont.Weight.bold) self.titleLabel.text = "login_sms_title".loco self.addSubview(self.titleLabel) self.textField.backgroundColor = UIColor.clear self.textField.textAlignment = NSTextAlignment.center self.textField.placeholder = "login_sms_placeholder".loco self.textField.keyboardType = UIKeyboardType.numberPad self.textField.autocapitalizationType = UITextAutocapitalizationType.none self.textField.updateValidState = {[unowned self] sms, isValid in if isValid { self.delegate?.loginSmsView(self, didEnterCode: sms) } } self.textField.isWrongInput = true _ = self.textField.checkValidation() self.addSubview(self.textField) self.separatorView.backgroundColor = UIColor.idBlack self.separatorView.alpha = 0.5 self.addSubview(self.separatorView) self.resendLabel.isUserInteractionEnabled = true self.resendLabel.numberOfLines = 0 self.addSubview(self.resendLabel) self.resendLabel.addGestureRecognizer(tapResendGesture) self.titleLabel.translatesAutoresizingMaskIntoConstraints = false self.textField.translatesAutoresizingMaskIntoConstraints = false self.separatorView.translatesAutoresizingMaskIntoConstraints = false self.resendLabel.translatesAutoresizingMaskIntoConstraints = false self.setupConstraints() } func updateResend(text: String?, isEnabled: Bool) { self.tapResendGesture.isEnabled = isEnabled guard let text = text else { self.resendLabel.text = "" return } var color = UIColor.idBlack if isEnabled == false { color = UIColor.gray } let resendText = AttributedStringBuilder(font: UIFont.systemFont(ofSize: 11.0, weight: UIFont.Weight.semibold), color: color, alignment: NSTextAlignment.center, kern: 0.0) .add(text) .changeParagraphStyle(minimumLineHeight: 13.0) .result() self.resendLabel.attributedText = resendText } // MARK: - Constraints private func setupConstraints() { NSLayoutConstraint.activate([ self.titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: UIViewController.idSafeAreaInsets.top + 22.0), self.titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16.0), self.titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16.0), self.resendLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor), self.resendLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 64.0), self.resendLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -64.0), self.resendLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 40.0), self.separatorView.bottomAnchor.constraint(equalTo: self.resendLabel.topAnchor, constant: -55), self.separatorView.heightAnchor.constraint(equalToConstant: 1.0), self.separatorView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16.0), self.separatorView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16.0), self.textField.bottomAnchor.constraint(equalTo: self.separatorView.topAnchor, constant: -5.0), self.textField.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20.0), self.textField.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20.0), self.textField.heightAnchor.constraint(equalToConstant: 20.0), ]) } }
39.629032
130
0.676842
67d56b9d117cffe8a59e30d816f62e58e63d6fe5
2,096
/** * Copyright (c) 2021 Dustin Collins (Strega's Gate) * All Rights Reserved. * Licensed under Apache License v2.0 * * Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate */ import WinSDK /// Describes the subresources from a 3D texture to use in a render-target view. public struct D3DTexture3DRenderTargetView { public typealias RawValue = WinSDK.D3D12_TEX3D_RTV internal var rawValue: RawValue /// The index of the mipmap level to use. public var mipIndex: UInt32 { get { return rawValue.MipSlice } set { rawValue.MipSlice = newValue } } /// First depth level to use. public var depthIndex: UInt32 { get { return rawValue.FirstWSlice } set { rawValue.FirstWSlice = newValue } } /// Number of depth levels to use in the render-target view, starting from FirstWSlice. A value of -1 indicates all of the slices along the w axis, starting from FirstWSlice. public var depthCount: UInt32 { get { return rawValue.WSize } set { rawValue.WSize = newValue } } /** Describes the subresources from a 3D texture to use in a render-target view. - parameter mipIndex: The index of the mipmap level to use mip slice. - parameter depthIndex: First depth level to use. - parameter depthCount: Number of depth levels to use in the render-target view, starting from FirstWSlice. A value of -1 indicates all of the slices along the w axis, starting from FirstWSlice. */ public init(mipIndex: UInt32, depthIndex: UInt32, depthCount: UInt32) { self.rawValue = RawValue(MipSlice: mipIndex, FirstWSlice: depthIndex, WSize: depthCount) } internal init(_ rawValue: RawValue) { self.rawValue = rawValue } } //MARK: - Original Style API #if !Direct3D12ExcludeOriginalStyleAPI @available(*, deprecated, renamed: "D3DTexture3DRenderTargetView") public typealias D3D12_TEX3D_RTV = D3DTexture3DRenderTargetView #endif
31.283582
198
0.66937