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
1c8303af275d7da3d1079516c4432dc0937986b3
5,365
// // FilesViewController.swift // AudioRecording // // Created by Кирилл Володин on 09.03.2018. // Copyright © 2018 Кирилл Володин. All rights reserved. // import UIKit import BubbleTransition protocol FilesViewControllerDelegate: class { func recordDidSelected(_ record: RecordViewModel) } final class FilesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var microphoneButton: UIButton! @IBOutlet weak var bottomView: UIView! var isFromMessage = false weak var delegate: FilesViewControllerDelegate? private var rootAssembly: RootAssembly private var model: FilesPresentationModel private let cellIdentifier = "\(AudioRecordCell.self)" private let cellHeight: CGFloat = 60 private var playingRow: Int = -1 let transition = BubbleTransition() init(rootAssembly: RootAssembly, model: FilesPresentationModel) { self.model = model self.rootAssembly = rootAssembly super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() setupUI() bindEvents() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) model.obtainAudioRecords() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } private func setupUI() { if isFromMessage { addBackButton() } title = "Аудиозаписи" setupTableView() setupMicrophoneButton() } private func bindEvents() { model.changeStateHandler = { [unowned self] status in switch status { case .loading: break case .rich: self.tableView.reloadData() case .error(let message): print(message) } } } private func setupTableView() { tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() tableView.register(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier) } private func setupMicrophoneButton() { bottomView.layer.masksToBounds = false bottomView.layer.shadowColor = UIColor.lightGray.cgColor bottomView.layer.shadowOffset = CGSize(width: 0, height: -2.5) bottomView.layer.shadowOpacity = 0.3 bottomView.layer.shadowRadius = 2 microphoneButton.layer.masksToBounds = false microphoneButton.layer.shadowColor = UIColor.red.cgColor microphoneButton.layer.shadowOffset = CGSize(width: 0, height: 3) microphoneButton.layer.shadowOpacity = 0.5 microphoneButton.layer.shadowRadius = 4 } @IBAction func record(_ sender: UIButton) { if playingRow != -1 { model.stopRecord(item: playingRow) playingRow = -1 // tableView.reloadData() } guard let viewcontroller = rootAssembly.recordingAssembly.recordingViewController() else { return } viewcontroller.transitioningDelegate = self viewcontroller.modalPresentationStyle = .custom present(viewcontroller, animated: true, completion: nil) } } extension FilesViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model.audioRecords.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AudioRecordCell else { return UITableViewCell() } cell.row = indexPath.item cell.delegate = self cell.configure(viewModel: model.audioRecords[indexPath.item]) if indexPath.item == playingRow { cell.play() } else { cell.stop() } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { model.deleteRecord(item: indexPath.item) tableView.deleteRows(at: [indexPath], with: .fade) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let record = model.audioRecords[indexPath.item] delegate?.recordDidSelected(record) navigationController?.popViewController(animated: true) } } extension FilesViewController: AudioRecordCellDelegate { func buttonPressed(row: Int) { if playingRow == row { model.stopRecord(item: row) } else { model.playRecord(item: row) } playingRow = row tableView.reloadData() } } extension FilesViewController: FilesPresentationModelDelegate { func playingFinished() { playingRow = -1 tableView.reloadData() } }
30.310734
156
0.643057
ac096df647ce6217eea6b94e84b2574c059d8cc3
542
// // FeaturedArticleMod.swift // SportsNews // // Created by Craig Clayton on 7/28/20. // import Foundation struct FeaturedArticleMod: Decodable { let id: String let title: String let subtitle: String let article: FeaturedArticle enum CodingKeys: String, CodingKey { case id case title case subtitle = "sub_title" case article = "featured_article" } static let `default` = Self(id: "123", title: "Featured", subtitle: "Article", article: FeaturedArticle.default) }
20.846154
116
0.647601
efbe30e5d29679254a68188320af6286917b8d71
673
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // /// Sentiment Analysis result for Predictions category public struct Sentiment { public let predominantSentiment: SentimentType public let sentimentScores: [SentimentType: Double]? public init(predominantSentiment: SentimentType, sentimentScores: [SentimentType: Double]?) { self.predominantSentiment = predominantSentiment self.sentimentScores = sentimentScores } } public enum SentimentType: String { case unknown case positive case negative case neutral case mixed }
24.035714
60
0.713224
6a9d22ed309cf2a924b4d7c49bca698ae3512e5d
1,087
// // DetailViewController.swift // Blog Reader // // Created by Jason Shultz on 12/5/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var webView: UIWebView! var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let postWebView = self.webView { postWebView.loadHTMLString(detail.valueForKey("content")!.description, baseURL: NSURL(string:"https://googleblog.blogspot.com/")) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.645833
145
0.614535
698998fd74a5655a4365a7b752e282c8da1b4ef0
5,924
// // TabBarView.swift // // // Created by Ling Zhan on 2020/6/10. // import SwiftUI @available(iOS 13.0, *) public struct TabBarItemView: View { @Binding var selectedTag: Int let tag: Int let iconType: TabBarIconType let item: TabBarItem public var body: some View { VStack { if selectedTag == tag { if iconType == .system { if item.selectedWidth != nil && item.selectedHeight != nil { Image(systemName: item.selectedIcon) .resizable() .modifier(ImageSizeModifier(width: item.selectedWidth, height: item.selectedHeight)) .modifier(ImageColorModifier(color: item.selectedColor)) }else { Image(systemName: item.selectedIcon) .modifier(ImageColorModifier(color: item.selectedColor)) } }else { if item.selectedWidth != nil && item.selectedHeight != nil { if item.selectedColor != nil { Image(item.selectedIcon) .resizable() .renderingMode(.template) .modifier(ImageSizeModifier(width: item.selectedWidth, height: item.selectedHeight)) .modifier(ImageColorModifier(color: item.selectedColor)) }else { Image(item.selectedIcon) .resizable() .modifier(ImageSizeModifier(width: item.selectedWidth, height: item.selectedHeight)) } }else { if item.selectedColor != nil { Image(item.selectedIcon) .renderingMode(.template) .modifier(ImageColorModifier(color: item.selectedColor)) }else { Image(item.selectedIcon) } } } } else { if iconType == .system { if item.width != nil && item.height != nil { Image(systemName: item.icon) .resizable() .modifier(ImageSizeModifier(width: item.width, height: item.height)) .modifier(ImageColorModifier(color: item.color)) }else { Image(systemName: item.icon) .modifier(ImageColorModifier(color: item.color)) } }else { if item.width != nil && item.height != nil { if item.color != nil { Image(item.icon) .resizable() .renderingMode(.template) .modifier(ImageSizeModifier(width: item.width, height: item.height)) .modifier(ImageColorModifier(color: item.color)) }else { Image(item.icon) .resizable() .modifier(ImageSizeModifier(width: item.width, height: item.height)) } }else { if item.color != nil { Image(item.icon) .renderingMode(.template) .modifier(ImageColorModifier(color: item.color)) }else { Image(item.icon) } } } } } } private struct ImageSizeModifier: ViewModifier { let width, height: CGFloat? func body(content: Content) -> some View { return content .frame(width: width, height: height, alignment: .center) } } private struct ImageColorModifier: ViewModifier { let color: Color? func body(content: Content) -> some View { return content .foregroundColor(color) } } } @available(iOS 13.0, *) public struct TabBarView: View { @Binding public var selectedIndex: Int public let items: [TabBarItem] public var iconType: TabBarIconType public let iconAlignment: Alignment public var height: CGFloat public init(selectedIndex: Binding<Int>, items: [TabBarItem], iconType: TabBarIconType = .system, iconAlignment: Alignment = .center, height: CGFloat = 49 ) { self._selectedIndex = selectedIndex self.items = items self.iconType = iconType self.iconAlignment = iconAlignment self.height = height } public var body: some View { GeometryReader { geometry in HStack(alignment: .bottom, spacing: 0) { ForEach(0..<self.items.count) { index in TabBarItemView(selectedTag: self.$selectedIndex, tag: index, iconType: self.iconType, item: self.items[index]) .onTapGesture(perform: { self.selectedIndex = index }) .frame( width: geometry.size.width / CGFloat(self.items.count), height: self.height, alignment: self.iconAlignment) } } }.frame(height: self.height) } }
40.855172
116
0.445307
89349344ab048c9f18464e545f851da1f7f98781
734
// // Parser.swift // // Created by Marcel Tesch on 2021-05-20. // Think different. // /// A parser encapsulates the logic required to retrieve structured information from unstructured inputs /// and affords the facilities to define said logic in terms of elementary building blocks. public struct Parser<Value> { private let block: (Substring) throws -> (Value, Substring)? public init(_ block: @escaping (Substring) throws -> (Value, Substring)?) { self.block = block } } public extension Parser { func parse(_ input: Substring) throws -> (Value, Substring)? { try block(input) } func parse(_ input: String) throws -> (Value, Substring)? { try parse(input.substring) } }
22.9375
104
0.668937
bbeecf6bdffa907acb28bc3afd131d799ba2f893
815
// // AppDelegate.swift // Example // // Created by Robin Enhorn on 2019-09-23. // Copyright © 2019 iZettle. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { } }
32.6
179
0.769325
bba0802510d7043b44a2259c1e1613e027348d98
10,769
// // TableView.swift // Pods // // Created by Hamza Ghazouani on 20/07/2017. // // import UIKit /// The delegate of a TableView/CollectionView object must adopt the PlaceholderDelegate protocol. the method of the protocol allow the delegate to perform placeholders action. public protocol PlaceholderDelegate: class { /// Performs the action to the delegate of the table or collection view /// /// - Parameters: /// - view: the table view or the collection /// - placeholder: The placeholder source of the action func view(_ view: Any, actionButtonTappedFor placeholder: Placeholder) } /// A table view that allows to show easily placeholders like no results, no internet connection, etc open class HGTableView: UITableView { // MARK: - Public properties /// The placeholdersProvider property is responsible for the placeholders views and data final public var placeholdersProvider = PlaceholdersProvider.default { willSet { /// before changing the placeholders data, we should be sure that the tableview is in the default configuration. Otherwise If the dataSource and the delegate are in placeholder configuration, and we set the new data, the old one will be released and we will lose the defaultDataSource and defaultDelegate (they will be set to nil) showDefault() } } /** * The object that acts as the delegate of the table view placeholders. * The delegate must adopt the PlaceholderDelegate protocol. The delegate is not retained. */ public weak var placeholderDelegate: PlaceholderDelegate? /** * The object that acts as the data source of the table view. * The data source must adopt the UITableViewDataSource protocol. The data source is not retained. */ weak open override var dataSource: UITableViewDataSource? { didSet { /* we save only the initial data source (and not a placeholder datasource) to allow to go back to the initial data */ if dataSource is PlaceholderDataSourceDelegate { return } defaultDataSource = dataSource } } /** * The object that acts as the delegate of the table view. * The delegate must adopt the UITableViewDelegate protocol. The delegate is not retained. */ open override weak var delegate: UITableViewDelegate? { didSet { /* we save only the initial delegate (and not the placeholder delegate) to allow to go back to the initial one */ if delegate is PlaceholderDataSourceDelegate { return } defaultDelegate = delegate } } /** * Returns an accessory view that is displayed above the table. * The default value is nil. The table header view is different from a section header. */ open override var tableHeaderView: UIView? { didSet { if tableHeaderView == nil { return } defaultTableHeaderView = tableHeaderView } } /** * Returns an accessory view that is displayed below the table. * The default value is nil. The table footer view is different from a section footer. */ open override var tableFooterView: UIView? { didSet { if tableFooterView == nil { return } defaultTableFooterView = tableFooterView } } /** * Keeps user seperatorStyle instead of overriding with system default * The default value is UITableViewCellSeparatorStyle.singleLine */ open override var separatorStyle: UITableViewCell.SeparatorStyle { didSet { defaultSeparatorStyle = separatorStyle } } /** * A Boolean value that determines whether bouncing always occurs when the placeholder is shown. * The default value is false */ open var placeholdersAlwaysBounceVertical = false // MARK: - Private properties /// The defaultDataSource is used to allow to go back to the initial data source of the table view after switching to a placeholder data source internal weak var defaultDataSource: UITableViewDataSource? /// The defaultDelegate is used to allow to go back to the initial delegate of the table view after switching to a placeholder delegate internal weak var defaultDelegate: UITableViewDelegate? /// The defaultSeparatorStyle is used to save the tableview separator style, because, when you switch to a placeholder, is changed to `.none` fileprivate var defaultSeparatorStyle: UITableViewCell.SeparatorStyle! /// The defaultAlwaysBounceVertical is used to save the tableview bouncing setup, because, when you switch to a placeholder, the vertical bounce is disabled fileprivate var defaultAlwaysBounceVertical: Bool! /// The defaultTableViewHeader is used to save the tableview header when you switch to placeholders fileprivate var defaultTableHeaderView: UIView? /// The defaultTableViewFooter is used to save the tableview footer when you switch to placeholders fileprivate var defaultTableFooterView: UIView? // MARK: - init methods /** Returns an table view initialized from data in a given unarchiver. - parameter aDecoder: An unarchiver object. - returns: self, initialized using the data in decoder. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } /** Initializes and returns a table view object having the given frame and style. Returns an initialized TableView object, or nil if the object could not be successfully initialized. - parameter frame: A rectangle specifying the initial location and size of the table view in its superview’€™s coordinates. The frame of the table view changes as table cells are added and deleted. - parameter style: A constant that specifies the style of the table view. See Table View Style for descriptions of valid constants. - returns: Returns an initialized TableView object, or nil if the object could not be successfully initialized. */ override public init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) setup() } /** * Config the table view to be able to show placeholders */ private func setup() { // register the placeholder view cell register(cellType: PlaceholderTableViewCell.self) defaultSeparatorStyle = separatorStyle defaultAlwaysBounceVertical = alwaysBounceVertical defaultTableHeaderView = tableHeaderView defaultTableFooterView = tableFooterView customSetup() } /// Implement this method of you want to add new default placeholdersProvider, new default cell, etc open func customSetup() {} // MARK: - Manage table view data and placeholders /** Switch to different data sources and delegate of the table view (placeholders and initial data source & delegate) - parameter theSource: the selected data source - parameter theDelegate: the selected delegate */ internal func switchTo(dataSource theDataSource: UITableViewDataSource?, delegate theDelegate: UITableViewDelegate? = nil) { // if the data source and delegate are already set, no need to switch if dataSource === theDataSource && delegate === theDelegate { return } if let placeholderDataSource = theDataSource as? PlaceholderDataSourceDelegate { // placeholder configuration super.separatorStyle = .none alwaysBounceVertical = placeholdersAlwaysBounceVertical let style = placeholderDataSource.placeholder.style if style?.shouldShowTableViewHeader != true { // style = nil or shouldShowTableViewHeader == false tableHeaderView = nil } if style?.shouldShowTableViewFooter != true { tableFooterView = nil } } else { // default configuration separatorStyle = defaultSeparatorStyle alwaysBounceVertical = defaultAlwaysBounceVertical tableHeaderView = defaultTableHeaderView tableFooterView = defaultTableFooterView } dataSource = theDataSource delegate = theDelegate super.reloadData() } /// The total number of rows in all sections of the tableView private func numberOfRowsInAllSections() -> Int { let numberOfSections = defaultDataSource?.numberOfSections?(in: self) ?? 1 var rows = 0 for i in 0 ..< numberOfSections { rows += defaultDataSource?.tableView(self, numberOfRowsInSection: i) ?? 0 } return rows } /** Reloads the rows and sections of the table view. If the number of rows == 0 it shows no results placeholder */ open override func reloadData() { // if the tableview is empty we switch automatically to no data placeholder if numberOfRowsInAllSections() == 0 { showNoResultsPlaceholder() return } // if the data source is in no data placeholder, and the user tries to reload data, we will switch automatically to default if dataSource is PlaceholderDataSourceDelegate { showDefault() return } super.reloadData() } /** Called when the adjusted content insets of the scroll view change. */ open override func adjustedContentInsetDidChange() { if dataSource is PlaceholderDataSourceDelegate { // Force table view to recalculate the cell height, because the method tableView:heightForRowAt: is called before adjusting the content of the scroll view guard let indexPaths = indexPathsForVisibleRows else { return } reloadRows(at: indexPaths, with: .automatic) } } } extension UITableView { /** Register a NIB-Based `UITableViewCell` subclass (conforming to `Reusable` & `NibLoadable`) - parameter cellType: the `UITableViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register - seealso: `register(_:,forCellReuseIdentifier:)` */ final func register<T: UITableViewCell>(cellType: T.Type) where T: Reusable & NibLoadable { self.register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier) } }
39.446886
342
0.66515
115abbecee1b04c63a9bd3609d482dfa1fcde33e
5,201
// // ImagesView.swift // mvp // // Created by Alberto Penas Amor on 19/4/21. // import UIKit import SwiftUI //TODO: snackBar multiple errors with animations, when hidden after timeout we can not see it //TODO: end page + loading -> nextPage class ImagesView: UIView { private let presenter: ImagesPresenter private let flowLayout = UICollectionViewFlowLayout() private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) private let activityIndicatorView: UIActivityIndicatorView = .init(style: .large) private let snackBarView: SnackBarView = .init(frame: .zero) private let numColumns: Int = 2 private var images: [Image] = .init() init(presenter: ImagesPresenter) { self.presenter = presenter super.init(frame: .zero) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func didLoad() { presenter.fetch() } } private extension ImagesView { func setup() { translatesAutoresizingMaskIntoConstraints = false collectionView.translatesAutoresizingMaskIntoConstraints = false activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false snackBarView.translatesAutoresizingMaskIntoConstraints = false collectionView.dataSource = self collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: ImageCollectionViewCell.identifier) collectionView.flowLayout.numberOfColumns(numColumns, heightRatio: 1.5) collectionView.backgroundColor = .white activityIndicatorView.color = .gray activityIndicatorView.hidesWhenStopped = true snackBarView.button.addTarget(self, action: #selector(retry), for: .touchUpInside) addSubview(collectionView) addSubview(activityIndicatorView) addSubview(snackBarView) NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: topAnchor), collectionView.trailingAnchor.constraint(equalTo: trailingAnchor), collectionView.bottomAnchor.constraint(equalTo: bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: leadingAnchor), activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor), activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor), snackBarView.leadingAnchor.constraint(equalTo: leadingAnchor), snackBarView.trailingAnchor.constraint(equalTo: trailingAnchor), snackBarView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor), ]) } @objc func retry() { presenter.retry() } } extension ImagesView: ImagesPresenterOutput { func new(state: ImagesState) { switch state { case .loading: activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() case let .error(message): activityIndicatorView.isHidden = true snackBarView.show(message: message, buttonText: "Retry") case let .data(imgs): activityIndicatorView.isHidden = true images = imgs collectionView.reloadData() } } } extension ImagesView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCollectionViewCell.identifier, for: indexPath) as! ImageCollectionViewCell cell.imageView.kf.setImage(with: images[indexPath.row].url, options: [.transition(.fade(0.3)), .cacheOriginalImage]) return cell } } /* typealias ImageModel = Image @available(iOS 13, *) struct ImagesView_Previews: PreviewProvider { static var previews: some View { Group { UIViewPreview { let view = ImagesView(presenter: ) let items: [ImageModel] = [ .init(id: 1, url: URL(string: "https://nrs.harvard.edu/urn-3:HUAM:COIN09238_dlvr")!) ] view.new(state: .data(items)) return view } .frame(width: 375, height: 875) .previewLayout(.sizeThatFits) .previewDisplayName("Data") } Group { UIViewPreview { let view = ImagesView() view.new(state: .loading) return view } .frame(width: 375, height: 875) .previewLayout(.sizeThatFits) .previewDisplayName("Loading") } Group { UIViewPreview { let view = ImagesView() view.new(state: .error("Something went wrong, try again")) return view } .frame(width: 375, height: 875) .previewLayout(.sizeThatFits) .previewDisplayName("Error") } } }*/
36.370629
154
0.653913
e8f602f43c18caeb232f50948ef83c1e02a7c94c
732
import Foundation /// List of Italian regions. public enum Region { /// Regione Lazio. case lazio /// Regione Puglia. case puglia(Puglia) /// Regione Friuli-Venezia Giulia case friuliVeneziaGiulia /// Regione Lombardia case lombardia(Lombardia) /// Regione Trentino-Alto Adige case trentinoAltoAdige(TrentinoAltoAdige) } /// Local health units of Regione Puglia. public enum Puglia { /// ASL Taranto. case taranto } /// Local health units of Regione Lombardia. public enum Lombardia { /// ASST Valtellina e Alto Lario case valtellinaEAltoLario } /// Local health units of Regione Trentino-Alto Adige. public enum TrentinoAltoAdige { /// APSS Trento case trento }
20.914286
54
0.695355
5b3b6f1ada8b323fedab1f992b861129ebaa0731
1,442
// // MSGInputSeparatorView.swift // MessengerKit // // Created by Stephen Radford on 08/06/2018. // Copyright © 2018 Cocoon Development Ltd. All rights reserved. // import UIKit /// The separator between the `MSGPlaceholderTextView` and the send button. /// /// This is used because we had some issues drawing the line manually. class MSGInputSeparatorView: UIView { var barColor: UIColor? = .lightGray { didSet { bar.backgroundColor = barColor } } private lazy var bar: UIView = { let view = UIView() view.backgroundColor = self.barColor return view }() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } convenience init() { self.init(frame: .zero) setup() } func setup() { bar.translatesAutoresizingMaskIntoConstraints = false addSubview(bar) bar.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true bar.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true bar.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true bar.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true } }
26.703704
78
0.603329
f7febfdd424706207e0707093008a3b5fe23806d
5,954
// Copyright 2019 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. // // AWSClientDelegate+addAWSClientQueryOperationBody.swift // SmokeAWSModelGenerate // import Foundation import ServiceModelCodeGeneration import ServiceModelEntities internal extension AWSClientDelegate { internal func addAWSClientQueryOperationBody( name: String, fileBuilder: FileBuilder, codeGenerator: ServiceModelCodeGenerator, function: AWSClientFunction, http: (verb: String, url: String), invokeType: InvokeType, signAllHeaders: Bool) { fileBuilder.incIndent() let typeName = function.name.getNormalizedTypeName(forModel: codeGenerator.model) let wrappedTypeDeclaration: String if function.inputType != nil { wrappedTypeDeclaration = "\(typeName)OperationHTTPRequestInput(encodable: input)" } else { wrappedTypeDeclaration = "NoHTTPRequestInput(encodable: input)" } fileBuilder.appendLine(""" let handlerDelegate = AWSClientChannelInboundHandlerDelegate( credentialsProvider: credentialsProvider, awsRegion: awsRegion, service: service, """) if signAllHeaders { fileBuilder.appendLine(""" target: target, signAllHeaders: true) """) } else { fileBuilder.appendLine(""" target: target) """) } fileBuilder.appendLine(""" let wrappedInput = \(wrappedTypeDeclaration) let requestInput = QueryWrapperHTTPRequestInput( wrappedInput: wrappedInput, action: \(baseName)ModelOperations.\(function.name).rawValue, version: apiVersion) """) fileBuilder.appendEmptyLine() let httpClientName = getHttpClientForOperation(name: name, httpClientConfiguration: codeGenerator.customizations.httpClientConfiguration) let returnStatement = getQueryOperationReturnStatement( functionOutputType: function.outputType, invokeType: invokeType, httpClientName: httpClientName, http: http) fileBuilder.appendLine(returnStatement) fileBuilder.appendLine("}", preDec: true) } private func getQueryOperationNoOutputReturnStatement( invokeType: InvokeType, httpClientName: String, http: (verb: String, url: String)) -> String { switch invokeType { case .sync: return """ return try \(httpClientName).executeSyncRetriableWithOutput( endpointPath: "\(http.url)", httpMethod: .\(http.verb), input: requestInput, handlerDelegate: handlerDelegate, retryConfiguration: retryConfiguration, retryOnError: retryOnErrorProvider) """ case .async: return """ _ = try \(httpClientName).executeAsyncRetriableWithOutput( endpointPath: "\(http.url)", httpMethod: .\(http.verb), input: requestInput, completion: completion, handlerDelegate: handlerDelegate, retryConfiguration: retryConfiguration, retryOnError: retryOnErrorProvider) """ } } private func getQueryOperationWithOutputReturnStatement( invokeType: InvokeType, httpClientName: String, http: (verb: String, url: String)) -> String { switch invokeType { case .sync: return """ try \(httpClientName).executeSyncRetriableWithoutOutput( endpointPath: "\(http.url)", httpMethod: .\(http.verb), input: requestInput, handlerDelegate: handlerDelegate, retryConfiguration: retryConfiguration, retryOnError: retryOnErrorProvider) """ case .async: return """ _ = try \(httpClientName).executeAsyncRetriableWithoutOutput( endpointPath: "\(http.url)", httpMethod: .\(http.verb), input: requestInput, completion: completion, handlerDelegate: handlerDelegate, retryConfiguration: retryConfiguration, retryOnError: retryOnErrorProvider) """ } } private func getQueryOperationReturnStatement( functionOutputType: String?, invokeType: InvokeType, httpClientName: String, http: (verb: String, url: String)) -> String { if functionOutputType != nil { return getQueryOperationNoOutputReturnStatement( invokeType: invokeType, httpClientName: httpClientName, http: http) } else { return getQueryOperationWithOutputReturnStatement( invokeType: invokeType, httpClientName: httpClientName, http: http) } } }
37.446541
133
0.577091
f84c91fdfd5c6fe9ecf64203fb2e8a8cb9f9e718
1,131
import XCTest class HeapTests: XCTestCase { var iheap: PriorityQueue<Int>.ArrayHeap! override func setUp() { super.setUp() iheap = PriorityQueue.ArrayHeap() } func testTopElementWhenSingle() { iheap.add(42) XCTAssertEqual(iheap.removeTop(), 42) } func testTopElementWhenEmpty() { XCTAssertNil(iheap.removeTop()) } func testTopElementWhenTwoInOrder() { iheap.add(2) iheap.add(4) XCTAssertEqual(iheap.removeTop(), 2) } func testTopElementWhenTwoNotInOrder() { iheap.add(4) iheap.add(2) XCTAssertEqual(iheap.removeTop(), 2) } func testRandomCheck() { continueAfterFailure = false for n in 1..<100 { var items:[Int] = [] for _ in 0..<n { let x = Int(arc4random_uniform(100)) - 50 items.append(x) iheap.add(x) } for x in items.sorted() { XCTAssertEqual(iheap.removeTop(), x, "\(items)") } } } }
19.842105
64
0.512821
db897100e26068cb87ee3827f36cc64815e51605
3,514
// // BaseMobileConnectServiceSpec.swift // MobileConnectSDK // // Created by Mircea Grecu on 26/08/2016. // Copyright © 2016 GSMA. All rights reserved. // import Foundation import Quick import Nimble import UIKit @testable import MobileConnectSDK private let kURLString = "https://reference.io/mobileconnect/index.php/auth?acr_values=2&client_id=x-ZWRhNjU3OWI3MGIwYTRh&client_name=test1&context=the%20context&login_hint=ENCR_MSISDN%d&nonce=A8EA1FC33DE443F8A40ED83FFD9E7740&redirect_uri=http%3A//complete/&response_type=code&scope=openid%20mc_identity_phonenumber%20phone%20openid%20mc_authz%20openid%20mc_authn&state=872DA020D1E1479F972090C793C04362" let kReferenceRedirect : NSURL = NSURL(string: "http://www.gooelg.com")! class BaseMobileConnectServiceSpec : BaseServiceSpec { override func spec() { super.spec() describe("Check base mobile connect extension") { self.checkKeyValueFromString() self.callBaseMobileServiceWithParameter([:]) } describe("Check base mobile connect functions") { self.checkParametersAreValid() self.presentWebControllerCheck() BaseMobileConnectService().didReceiveResponseFromController(nil, withRedirectModel: nil, error: nil) self.startInHandlerFunction() } } func checkKeyValueFromString() { context("check key-value from string") { let dictionary = BaseMobileConnectService.keyValuesFromString(kURLString) it("dictionary should not be nil", closure: { expect(dictionary).notTo(beNil()) }) let redirectURLIsValid = BaseMobileConnectService().isValidRedirectURL(kReferenceRedirect, inController: self.webControllerMock, redirect:kReferenceRedirect) it("check redirectURL", closure: { expect(redirectURLIsValid).notTo(beTrue()) }) } } func checkParametersAreValid() { waitUntil { (done:() -> Void) in BaseMobileConnectService().parametersAreValid([(nil,MCErrorCode.Unknown)], completionHandler: { (error) in it("should have error", closure: { expect(error).notTo(beNil()) }) done() }) } } func presentWebControllerCheck() { waitUntil { (done:() -> Void) in BaseMobileConnectService().presentWebControllerWithRequest(nil, inController: UIViewController(), errorHandler: { (error) in it("should have error", closure: { expect(error).notTo(beNil()) }) done() }) } } func startInHandlerFunction() { waitUntil { (done:() -> Void) in BaseMobileConnectService().startInHandler({ }, withParameters: [(nil, MCErrorCode.Unknown)], completionHandler: { (error) in it("should have error", closure: { expect(error).notTo(beNil()) }) done() }) } } func callBaseMobileServiceWithParameter(parameters : [String:String]) { BaseMobileConnectService().didReceiveResponseWithParameters([:], fromController: self.webControllerMock) BaseMobileConnectService().webController(self.webControllerMock, failedLoadingRequestWithError: nil) } }
37.382979
403
0.621514
7ab187e39590bd3051e9dd185c6bd7295b825bda
236
// // Constants.swift // AuctionApp // import UIKit let Device = UIDevice.current private let iosVersion = NSString(string: Device.systemVersion).doubleValue let iOS8 = iosVersion >= 8 let iOS7 = iosVersion >= 7 && iosVersion < 8
16.857143
75
0.720339
d7cdd919e112702513d355bc02c473bcd18005b1
384
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "MentionmeSwift", products: [ .library( name: "MentionmeSwift", targets: [ "MentionmeSwift" ] ) ], targets: [ .target( name: "MentionmeSwift", path: "MentionmeSwift" ) ] )
17.454545
35
0.471354
1801bcc62c2ba002cad17c983777dc9719ef477a
281
// // DTODefinitions.swift // // // Created by Janusz Czornik on 08/06/2021. // import Foundation /// Domain object for decoding server responses public protocol DecodableDTO: Decodable { } /// Domain object for encoding server requests protocol EncodableDTO: Encodable { }
16.529412
47
0.733096
ff07593440a248b775a73774a31eae3e25763d0c
256
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing map :{ if{ class C{ class c{enum S<T where g:a{{} class A{{} let h=B class B<a class B
18.285714
87
0.722656
91867bdb8bb61bafd3e0b9a8792c313bd2e876cc
3,316
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @testable import _StringProcessing extension PEG.VM where Input == String { typealias MEProg = MEProgram func transpile() throws -> MEProg { typealias Builder = MEProg.Builder var builder = MEProg.Builder() // Address token info // // TODO: Could builder provide a generalized mapping table? typealias TokenEntry = (Builder.AddressToken, use: InstructionAddress, target: InstructionAddress) var addressTokens = Array<TokenEntry>() for idx in instructions.indices { if let address = instructions[idx].pc { addressTokens.append( (builder.makeAddress(), use: idx, target: address)) } } var nextTokenIdx = addressTokens.startIndex func nextToken() -> Builder.AddressToken { defer { addressTokens.formIndex(after: &nextTokenIdx) } return addressTokens[nextTokenIdx].0 } for idx in instructions.indices { defer { // TODO: Linear is probably fine... for (tok, _, _) in addressTokens.lazy.filter({ $0.target == idx }) { builder.resolve(tok) } } switch instructions[idx] { case .nop: builder.buildNop() case .comment(let s): builder.buildNop(s) case .consume(let n): builder.buildAdvance(Distance(n)) case .branch(_): builder.buildBranch(to: nextToken()) case .condBranch(let condition, _): // TODO: Need to map our registers over... _ = condition fatalError()//builder.buildCondBranch(condition, to: nextToken()) case .save(_): builder.buildSave(nextToken()) case .clear: builder.buildClear() case .restore: builder.buildRestore() case .push(_): fatalError() case .pop: fatalError() case .call(_): builder.buildCall(nextToken()) case .ret: builder.buildRet() case .assert(_,_): fatalError()//builder.buildAssert(e, r) case .assertPredicate(_, _): fatalError()//builder.buildAssertPredicate(p, r) case .match(let e): builder.buildMatch(e) case .matchPredicate(let p): builder.buildConsume { input, bounds in p(input[bounds.lowerBound]) ? input.index(after: bounds.lowerBound) : nil } case .matchHook(_): fatalError()//builder.buildMatchHook(h) case .assertHook(_, _): fatalError()//builder.buildAssertHook(h, r) case .accept: builder.buildAccept() case .fail: builder.buildFail() case .abort(let s): builder.buildAbort(s) } } return try builder.assemble() } } extension PEG.Program where Element == Character { public func transpile( ) throws -> Engine<String> { try Engine(compile(for: String.self).vm.transpile()) } }
27.865546
81
0.584138
f4993d6f5e17d5762dbefe63390ce05da1259b9a
2,364
// // ZAAppDelegateConnectorNetworkProtocol.swift // ZappPlugins // // Created by Alex Zchut on 20/05/2019. // import Foundation @objc public protocol ZAAppDelegateConnectorNetworkProtocol { @objc @discardableResult func requestJsonObject(forRequest request:URLRequest, completion: ((Bool, Any?, Error?, Int) -> Void)?) -> URLSessionTask? @objc @discardableResult func requestJsonObject(forRequest request:URLRequest, queue: DispatchQueue?, completion: ((Bool, Any?, Error?, Int) -> Void)?) -> URLSessionTask? @objc func requestJsonObject(forUrlString urlString:String, method: String, parameters:[String: Any]?, completion: ((Bool, Any?, Error?, Int) -> Void)?) @objc @discardableResult func requestJsonObject(forUrlString urlString:String, method: String, parameters:[String: Any]?, queue: DispatchQueue?, completion: ((Bool, Any?, Error?, Int) -> Void)?) -> URLSessionTask? @objc @discardableResult func requestJsonObject(forUrlString urlString:String, method: String, parameters:[String: Any]?, queue: DispatchQueue?, headers: [String: String]?, completion: ((Bool, Any?, Error?, Int) -> Void)?) -> URLSessionTask? @objc func requestDataObject(forUrlString urlString:String, method: String, parameters:[String: Any]?, completion: ((Bool, Data?, Error?, Int, String?) -> Void)?) @objc @discardableResult func requestDataObject(forRequest request:URLRequest, completion: ((Bool, Data?, Error?, Int) -> Void)?) -> URLSessionTask? }
49.25
135
0.45643
f8340d96d3c309b21dd00afdacc2853098d20295
263
import XCTest import GEOSwift final class MultiPointTests: XCTestCase { func testInitWithPoints() { let points = makePoints(withCount: 3) let multiPoint = MultiPoint(points: points) XCTAssertEqual(multiPoint.points, points) } }
20.230769
51
0.695817
8f663b82c30c47a26837b1deb2b815393bb1442d
4,142
/* Copyright (c) 2019, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation /// An `OCKCarePlan` represents a set of tasks, including both interventions and assesments, that a patient is supposed to complete as part of his /// or her treatment for a specific condition. For example, a care plan for obesity may include tasks requiring the patient to exercise, record their /// weight, and log meals. As the care plan evolves with the patient's progress, the care provider may modify the exercises and include notes each /// time about why the changes were made. public struct OCKCarePlan: Codable, Equatable, OCKVersionSettable, OCKObjectCompatible, OCKCarePlanConvertible, OCKCarePlanInitializable { /// A title describing this care plan. public var title: String /// The version identifier in the local database of the patient to whom this care plan belongs. public var patientID: OCKLocalVersionID? // MARK: OCKIdentifiable public let identifier: String // MARK: OCKVersionable public internal(set) var localDatabaseID: OCKLocalVersionID? public internal(set) var nextVersionID: OCKLocalVersionID? public internal(set) var previousVersionID: OCKLocalVersionID? // MARK: OCKObjectCompatible public var createdAt: Date? public var updatedAt: Date? public var deletedAt: Date? public var groupIdentifier: String? public var tags: [String]? public var externalID: String? public var userInfo: [String: String]? public var source: String? public var asset: String? public var notes: [OCKNote]? /// Initialize a care plan with a title, identifier, and optional patient version. /// /// - Parameters: /// - identifier: A user-defined identifier for the care plane. /// - title: A title for the care plan. /// - patientID: The version identifier in the local database of the patient to whom this care plan belongs. public init(identifier: String, title: String, patientID: OCKLocalVersionID?) { self.title = title self.identifier = identifier self.patientID = patientID } /// Initialize a new care plan from an `OCKCarePlan` /// /// - Parameter value: The care plan to copy. /// - Note: This simply creates a copy of the provided care plan. public init(value: OCKCarePlan) { self = value } /// Convert an `OCKCarePlan` to an `OCKCarePlan`. This method just returns `self` unmodified. public func convert() -> OCKCarePlan { return self } }
46.022222
149
0.739739
87c4eab3537aa702c32ace77852fc5202a39dbef
1,195
// // ColorProvider.swift // FunFacts // // Created by Steve Wall on 2/3/20. // Copyright © 2020 Stephen Wall. All rights reserved. // import UIKit import GameKit struct ColorProvider { let colors = [ UIColor(red: 244.0 / 255.0, green: 67.0 / 255.0, blue: 54.0 / 255.0, alpha: 1.0), UIColor(red: 236.0 / 255.0, green: 64.0 / 255.0, blue: 122.0 / 255.0, alpha: 1.0), UIColor(red: 156.0 / 255.0, green: 39.0 / 255.0, blue: 176.0 / 255.0, alpha: 1.0), UIColor(red: 33.0 / 255.0, green: 150.0 / 255.0, blue: 243.0 / 255.0, alpha: 1.0), UIColor(red: 0.0 / 255.0, green: 188.0 / 255.0, blue: 54.0 / 255.0, alpha: 1.0), UIColor(red: 102.0 / 255.0, green: 187.0 / 255.0, blue: 106.0 / 255.0, alpha: 1.0), UIColor(red: 251.0 / 255.0, green: 192 / 255.0, blue: 45 / 255.0, alpha: 1.0), UIColor(red: 255.0 / 255.0, green: 152.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0), UIColor(red: 158.0 / 255.0, green: 158.0 / 255.0, blue: 158.0 / 255.0, alpha: 1.0) ] func getRandomColor() -> UIColor { let index = GKRandomSource.sharedRandom().nextInt(upperBound: colors.count) return colors[index] } }
39.833333
91
0.572385
bf2ae33e08c5ab3f47941240ee247f107b79e746
2,906
import UIKit class LoginView: UIView { let stackView = UIStackView() let usernameTextField = UITextField() let passwordTextField = UITextField() let dividerView = UIView() override init(frame: CGRect) { super.init(frame: frame) style() layout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not beem implemented") } /// intrinsicContentSize: The default size a controls wants to be // override var intrinsicContentSize: CGSize { // return CGSize(width: 200, height: 200) // } } extension LoginView { func style() { translatesAutoresizingMaskIntoConstraints = false backgroundColor = .secondarySystemBackground stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 8 usernameTextField.translatesAutoresizingMaskIntoConstraints = false usernameTextField.placeholder = "Username" usernameTextField.delegate = self dividerView.translatesAutoresizingMaskIntoConstraints = false dividerView.backgroundColor = .secondarySystemFill passwordTextField.translatesAutoresizingMaskIntoConstraints = false passwordTextField.placeholder = "Password" passwordTextField.isSecureTextEntry = true passwordTextField.delegate = self passwordTextField.clearsOnInsertion = false passwordTextField.clearsOnBeginEditing = false passwordTextField.enablePasswordToggle() } func layout() { stackView.addArrangedSubview(usernameTextField) stackView.addArrangedSubview(dividerView) stackView.addArrangedSubview(passwordTextField) addSubview(stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalToSystemSpacingBelow: topAnchor, multiplier: 1), stackView.leadingAnchor.constraint(equalToSystemSpacingAfter: leadingAnchor, multiplier: 1), trailingAnchor.constraint(equalToSystemSpacingAfter: stackView.trailingAnchor, multiplier: 1), bottomAnchor.constraint(equalToSystemSpacingBelow: stackView.bottomAnchor, multiplier: 1) ]) dividerView.heightAnchor.constraint(equalToConstant: 1).isActive = true layer.cornerRadius = 5 clipsToBounds = true } } extension LoginView: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { usernameTextField.endEditing(true) passwordTextField.endEditing(true) return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } func textFieldDidEndEditing(_ textField: UITextField) { } }
31.247312
106
0.672402
5da69bd6cdbb7060442f39fab4adc21c9d4bbd57
14,698
// // MainPageView.swift // // Created by Kevin Kha on 3/10/21. // import SwiftUI struct MainPageView: View { @State var round: Int = 0 @State var totalMoney: Int = 500 @State var dice0: Int = 1 @State var dice1: Int = 1 @State var dice2: Int = 1 @State var dice3: Int = 1 @State private var resetAlert = false @State private var loseAlert = false @State private var bet = 50.0 @Environment(\.horizontalSizeClass) var layoutMode var playerSum: Int { get { return self.dice0 + self.dice1 } } var compSum: Int { get { return self.dice2 + self.dice3 } } var alert: Alert { Alert(title: Text("Game Reset!"), message: Text("Total money and round numbers have been reset.")) } var alert2: Alert { Alert(title: Text("Game Over!"), message: Text("You have run out of money! The game will reset.")) } var body: some View { NavigationView { VStack { if layoutMode == .compact { HStack { Image("Dices") Text("Simple Dice Game") .bold() .font(.title) .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/) .frame(width:250, height:30, alignment: .center) NavigationLink(destination: RulesView()) { Image(systemName: "info.circle") .foregroundColor(Color.blue) } } HStack { Text("Round: \(round)") .padding() .frame(width: 150, height: 30, alignment: .trailing) Text("Total Money: \(totalMoney)") .frame(width: 170, height: 30, alignment: .leading) .frame(width: 200, height: 50) } .foregroundColor(.black) .background(Color.green) .padding() HStack { VStack { Text("Player") .bold() .padding() Image("Dice\(dice0)") .padding() Image("Dice\(dice1)") Text("\(playerSum)") .font(.title) .fontWeight(.heavy) .frame(width: 100, height: 100) }.background(Color.blue) //.padding() VStack{ Text("Computer") .bold() .padding() Image("Dice\(dice2)") .padding() Image("Dice\(dice3)") Text("\(compSum)") .font(.title) .fontWeight(.heavy) .frame(width: 100, height: 100) }.background(Color.red) } Slider(value: $bet, in: 0...100, step: 5) .padding(.leading, 50) .padding(.trailing, 50) HStack { Text("Amount to bet: ") .padding(.bottom, 20) Text("\(Int(bet))") .foregroundColor(.red) .padding(.bottom, 20) } HStack { Button(action: { self.round = self.round + 1 self.dice0 = Int.random(in: 1...6) self.dice1 = Int.random(in: 1...6) self.dice2 = Int.random(in: 1...6) self.dice3 = Int.random(in: 1...6) if (playerSum > compSum){ self.totalMoney = self.totalMoney + Int(bet) } else if (playerSum < compSum) { self.totalMoney = self.totalMoney - Int(bet) } if (self.totalMoney <= 0) { loseAlert = true self.round = 0 self.totalMoney = 500 self.dice0 = 1 self.dice1 = 1 self.dice2 = 1 self.dice3 = 1 self.bet = 50.0 } }, label: { HStack { Image("Roll") Text("Roll") .bold() } .frame(width:120, height: 30, alignment: .center) .background(Color.green) .foregroundColor(.white) .cornerRadius(20) .padding(.trailing, 10) }).alert(isPresented: $loseAlert, content: { self.alert2 }) Button(action: { self.round = 0 self.totalMoney = 500 self.dice0 = 1 self.dice1 = 1 self.dice2 = 1 self.dice3 = 1 self.bet = 50.0 resetAlert = true }, label: { Text("Reset") .bold() .frame(width:120, height: 30, alignment: .center) .background(Color.orange) .foregroundColor(.white) .cornerRadius(20) .padding(.leading, 10) }).alert(isPresented: $resetAlert, content: { self.alert }) } Spacer() } else { HStack { Spacer() VStack { Text("Player") .bold() .padding() Image("Dice\(dice0)") .padding() Image("Dice\(dice1)") Text("\(playerSum)") .font(.title) .fontWeight(.heavy) .frame(width: 100, height: 80) } .padding(.top, -10) .padding(.bottom, -10) .background(Color.blue) VStack { HStack { Image("Dices") Text("Simple Dice Game") .bold() .font(.title) .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/) .frame(width:250, height:30, alignment: .center) NavigationLink(destination: RulesView()) { Image(systemName: "info.circle") .foregroundColor(Color.blue) } } HStack { Text("Round: \(round)") .padding() .frame(width: 150, height: 30, alignment: .trailing) Text("Total Money: \(totalMoney)") .frame(width: 170, height: 30, alignment: .leading) .frame(width: 200, height: 50) } .foregroundColor(.black) .background(Color.green) Spacer() Slider(value: $bet, in: 0...100, step: 5) .padding(.leading, 50) .padding(.trailing, 50) HStack { Text("Amount to bet: ") .padding(.bottom, 20) Text("\(Int(bet))") .foregroundColor(.red) .padding(.bottom, 20) } HStack { Button(action: { self.round = self.round + 1 self.dice0 = Int.random(in: 1...6) self.dice1 = Int.random(in: 1...6) self.dice2 = Int.random(in: 1...6) self.dice3 = Int.random(in: 1...6) if (playerSum > compSum){ self.totalMoney = self.totalMoney + Int(bet) } else if (playerSum < compSum) { self.totalMoney = self.totalMoney - Int(bet) } if (self.totalMoney <= 0) { loseAlert = true self.round = 0 self.totalMoney = 500 self.dice0 = 1 self.dice1 = 1 self.dice2 = 1 self.dice3 = 1 self.bet = 50.0 } }, label: { HStack { Image("Roll") Text("Roll") .bold() } .frame(width:120, height: 30, alignment: .center) .background(Color.green) .foregroundColor(.white) .cornerRadius(20) .padding(.trailing, 10) }).alert(isPresented: $loseAlert, content: { self.alert2 }) Button(action: { self.round = 0 self.totalMoney = 500 self.dice0 = 1 self.dice1 = 1 self.dice2 = 1 self.dice3 = 1 self.bet = 50.0 resetAlert = true }, label: { Text("Reset") .bold() .frame(width:120, height: 30, alignment: .center) .background(Color.orange) .foregroundColor(.white) .cornerRadius(20) .padding(.leading, 10) }).alert(isPresented: $resetAlert, content: { self.alert }) } //.frame(width: 200, height: 50) Spacer() } .padding() VStack{ Text("Computer") .bold() .padding() Image("Dice\(dice2)") .padding() Image("Dice\(dice3)") Text("\(compSum)") .font(.title) .fontWeight(.heavy) .frame(width: 100, height: 80) } .padding(.top, -10) .padding(.bottom, -10) .background(Color.red) Spacer() } } }.background(Color.yellow.edgesIgnoringSafeArea(.all)) //.navigationBarTitle("Main Game") .navigationBarHidden(true) //.background(SwiftUI.Color.yellow.edgesIgnoringSafeArea(.all)) //WelcomeView() } .phoneOnlyStackNavigationView() } } extension View { func phoneOnlyStackNavigationView() -> some View { if UIDevice.current.userInterfaceIdiom == .phone { return AnyView(self.navigationViewStyle(StackNavigationViewStyle())) } else { return AnyView(self) } } } struct MainGameView_Previews: PreviewProvider { static var previews: some View { MainPageView() } }
43.485207
101
0.300313
08f6b2248efce67ec34b4d2f61e21f6cf300a485
954
// // KeyboardButton.swift // Paperboard // // Created by Igor Zapletnev on 13.12.2020. // Copyright © 2020 Exyte. All rights reserved. // import UIKit class KeyboardButton: UIButton { var isPressed: Bool = false var defaultBackgroundColor: UIColor = .white var highlightBackgroundColor: UIColor = .lightGray override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override func layoutSubviews() { super.layoutSubviews() backgroundColor = isHighlighted || isPressed ? highlightBackgroundColor : defaultBackgroundColor } func commonInit() { layer.cornerRadius = 5.0 layer.masksToBounds = false layer.shadowOffset = CGSize(width: 0, height: 1.0) layer.shadowRadius = 0.0 layer.shadowOpacity = 0.35 } }
24.461538
102
0.641509
8928d9b3923590c5183a53eceb8f3cb25560b1df
3,159
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // PurchaserInfoStrings.swift // // Created by Tina Nguyen on 12/11/20. // import Foundation // swiftlint:disable identifier_name enum PurchaserInfoStrings { case checking_intro_eligibility_locally_error(error: Error) case checking_intro_eligibility_locally_result(productIdentifiers: [String: NSNumber]) case checking_intro_eligibility_locally case invalidating_purchaserinfo_cache case no_cached_purchaserinfo case purchaserinfo_stale_updating_in_background case purchaserinfo_stale_updating_in_foreground case purchaserinfo_updated_from_network case purchaserinfo_updated_from_network_error(error: Error) case sending_latest_purchaserinfo_to_delegate case sending_updated_purchaserinfo_to_delegate case vending_cache case error_getting_data_from_purchaserinfo_json(error: Error) case invalid_json } extension PurchaserInfoStrings: CustomStringConvertible { var description: String { switch self { case .checking_intro_eligibility_locally_error(let error): return "Couldn't check intro eligibility locally, error: \(error.localizedDescription)" case .checking_intro_eligibility_locally_result(let productIdentifiers): return "Local intro eligibility computed locally. Result: \(productIdentifiers)" case .checking_intro_eligibility_locally: return "Attempting to check intro eligibility locally" case .invalidating_purchaserinfo_cache: return "Invalidating PurchaserInfo cache." case .no_cached_purchaserinfo: return "No cached PurchaserInfo, fetching from network." case .purchaserinfo_stale_updating_in_background: return "PurchaserInfo cache is stale, " + "updating from network in background." case .purchaserinfo_stale_updating_in_foreground: return "PurchaserInfo cache is stale, " + "updating from network in foreground." case .purchaserinfo_updated_from_network: return "PurchaserInfo updated from network." case .purchaserinfo_updated_from_network_error(let error): return "Attempt to update PurchaserInfo from network failed.\n\(error.localizedDescription)" case .sending_latest_purchaserinfo_to_delegate: return "Sending latest PurchaserInfo to delegate." case .sending_updated_purchaserinfo_to_delegate: return "Sending updated PurchaserInfo to delegate." case .vending_cache: return "Vending PurchaserInfo from cache." case .error_getting_data_from_purchaserinfo_json(let error): return "Couldn't get data from purchaserInfo.jsonObject\n\(error.localizedDescription)" case .invalid_json: return "Invalid JSON returned from purchaserInfo.jsonObject" } } }
34.714286
104
0.731561
28e3a80adab4646ecaa57ca68055896dba9934d0
2,706
// // FinanceKit // Copyright © 2021 Christian Mitteldorf. All rights reserved. // MIT license, see LICENSE file for details. // import FinanceKit import XCTest class CurrencyConverterTests: XCTestCase { func testConvertAmountFromCurrencyToCurrencyAtRate() { let amount: Decimal = 100 let sut = CurrencyConverter() let converted = sut.convert(amount, from: .danishKroner, to: .australianDollars, at: 0.225) XCTAssertEqual(converted, 22.50) } func testConvertAmountFromCurrencyToCurrencyAtOneToOneRate() { let amount: Decimal = 100 let sut = CurrencyConverter() let converted = sut.convert(amount, from: .danishKroner, to: .australianDollars, at: 1.0) XCTAssertEqual(converted, 100) } func testConvertAmountFromCurrencyToCurrencyWithCurrencyPairs() { let amount: Decimal = 100 let pairs = [ CurrencyPair(baseCurrency: .australianDollars, secondaryCurrency: .danishKroner, rate: 4.5813) ] let sut = CurrencyConverter() let converted = sut.convert(amount, from: .australianDollars, to: .danishKroner, with: pairs) XCTAssertEqual(converted, 458.13, accuracy: 0.01) } func testConvertAmountFromCurrencyToCurrencyWithCurrencyPairsIfInverted() { let amount: Decimal = 100 let pairs = [ CurrencyPair(baseCurrency: .danishKroner, secondaryCurrency: .australianDollars, rate: 0.2182) ] let sut = CurrencyConverter() let converted = sut.convert(amount, from: .australianDollars, to: .danishKroner, with: pairs) XCTAssertEqual(converted, 458.29, accuracy: 0.01) } func testConvertAmountWithCurrencyPairAtRate() { let amount: Decimal = 100 let pair = CurrencyPair(baseCurrency: .danishKroner, secondaryCurrency: .australianDollars, rate: 0.225) let sut = CurrencyConverter() let converted = sut.convert(amount, with: pair) XCTAssertEqual(converted, 22.50) } func testConvertMoneyWithCurrencyToCurrencyAtRate() { let money = Money(100, in: .danishKroner) let sut = CurrencyConverter() let converted: Money = sut.convert(money, to: .australianDollars, at: 0.225) XCTAssertEqual(converted, 22.50) XCTAssertEqual(converted.currency?.code, .australianDollar) } func testConvertMoneyWithoutCurrencyToCurrencyAtRate() { let amount = Money(100) let sut = CurrencyConverter() let converted: Money = sut.convert(amount, to: .australianDollars, at: 0.225) XCTAssertEqual(converted, 100) XCTAssertEqual(converted.currency?.code, .australianDollar) } }
35.142857
112
0.68071
ef6127ec55b0bea46d457b220a99eea04b7fe2ea
450
// // UIImage+Math.swift // Watsons // // Created by Daniele Salvioni on 31/03/19. // Copyright © 2019 daniele salvioni. All rights reserved. // import UIKit extension UIImage { var aspectRatio: CGFloat { get { if self.size.height != 0 { return self.size.width/self.size.height } else { return 0 } } } }
16.071429
59
0.471111
de9cdd735de14e2fab2cff9ae435406ca10b8cad
4,212
// // RegexTests.swift // // This file is part of Regex - https://github.com/ddddxxx/Regex // Copyright (C) 2019 Xander Deng. Licensed under the MIT License. // import XCTest import Foundation @testable import Regex class RegexTests: XCTestCase { func testInit() { let pattern = "(foo|bar)" XCTAssertNoThrow(try Regex(pattern)) let badPattern = "(" XCTAssertThrowsError(try Regex(badPattern)) } func testMatches() { let source = "foo" let regex = Regex("f.o") XCTAssertTrue(regex.isMatch(source)) XCTAssertTrue(regex ~= source) switch source { case regex: break default: XCTFail() } } func testReplace() { let source = "123 foo fo0 bar" let regex = Regex("(foo|bar)") let result = source.replacingMatches(of: regex, with: "$1baz") XCTAssertEqual(result, "123 foobaz fo0 barbaz") } func testCaptureGroup() { let source = "123 foo bar baz" let regex = Regex(#"(\d+)(boo)? (foo) bar"#) let match = regex.firstMatch(in: source)! XCTAssertEqual(match.string, "123 foo bar") XCTAssertEqual(match.captures.count, 4) XCTAssertEqual(match[0]?.string, "123 foo bar") XCTAssertEqual(match[1]?.string, "123") XCTAssertNil(match[2]) XCTAssertEqual(match[3]?.string, "foo") } func testExtendedGraphemeClusters() { let source = "cafe\u{301}" // café let cafe = Regex("caf.").firstMatch(in: source)! XCTAssertEqual(cafe.string, "cafe") XCTAssertEqual(cafe.content, "cafe") let accent = Regex(".$").firstMatch(in: source)! XCTAssertEqual(accent.string, "\u{301}") XCTAssertEqual(accent.content, "\u{301}") } func testPatternMatch() { let regex = Regex("(foo|bar)") XCTAssert(regex ~= "foo") switch "bar" { case regex: break default: XCTFail() } switch "baz" { case regex: XCTFail() default: break } } func testAsciiNativeStringPerformance() { let string = TestResources.dullBoy().makeNative() let pattern = Regex(#"[A-Z][a-z]+"#) measure { let matchs = pattern.matches(in: string) XCTAssertEqual(matchs.count, 2000) for match in matchs { _ = match.content } } } func testAsciiCocoaStringPerformance() { let string = TestResources.dullBoy().makeCocoa() let pattern = Regex(#"[A-Z][a-z]+"#) measure { let matchs = pattern.matches(in: string as String) XCTAssertEqual(matchs.count, 2000) for match in matchs { _ = match.content } } } func testNonAsciiNativeStringPerformance() { let string = TestResources.shijing().makeNative() let pattern = Regex(#"(?<=[,。?!\s])([\u4E00-\u9FFF]+?)?"#) measure { let matchs = pattern.matches(in: string) XCTAssertEqual(matchs.count, 330) for match in matchs { _ = match.content } } } func testNonAsciiCocoaStringPerformance() { let string = TestResources.shijing().makeCocoa() let pattern = Regex(#"(?<=[,。?!\s])([\u4E00-\u9FFF]+?)?"#) measure { let matchs = pattern.matches(in: string as String) XCTAssertEqual(matchs.count, 330) for match in matchs { _ = match.content } } } } enum TestResources { static func shijing() -> String { let resources = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("Resources") let url = resources.appendingPathComponent("shijing").appendingPathExtension("txt") return try! String(contentsOf: url) } static func dullBoy() -> String { return String(repeating: "All work and no play makes Jack a dull boy\n", count: 1000) } }
29.25
115
0.549145
cc55677882c4381543386904e9a9d06afa77ed9d
2,082
// // ViewController.swift // Magic Hours // // Created by Quentin Cornu on 28/10/2018. // Copyright © 2018 Quentin. All rights reserved. // import UIKit import RealmSwift class HomeViewController: UIViewController { private let homeView: HomeView = { let view = HomeView() view.dataButton.addTarget(self, action: #selector(handleDataTap), for: .touchUpInside) view.statButton.addTarget(self, action: #selector(handleStatTap), for: .touchUpInside) view.validateButton.addTarget(self, action: #selector(addNotes), for: .touchUpInside) return view }() override func viewDidLoad() { super.viewDidLoad() view = homeView } // MARK: - Actions @objc private func handleDataTap() { print("Data button tapped") } @objc private func handleStatTap() { let statViewController = StatViewController() present(statViewController, animated: true, completion: nil) } @objc private func addNotes() { let realm = try! Realm() print(Realm.Configuration.defaultConfiguration.fileURL!) let notes = homeView.getNotes() print("Adding notes : E(\(notes.energy)) F(\(notes.focus)) M(\(notes.motivation))") let newEnergyPoint = DataPoint() newEnergyPoint.date = Date() newEnergyPoint.criteria = String(Criteria.energy.rawValue) newEnergyPoint.note = notes.energy let newFocusPoint = DataPoint() newFocusPoint.date = Date() newFocusPoint.criteria = String(Criteria.focus.rawValue) newFocusPoint.note = notes.focus let newMotivationPoint = DataPoint() newMotivationPoint.date = Date() newMotivationPoint.criteria = String(Criteria.motivation.rawValue) newMotivationPoint.note = notes.motivation try! realm.write { realm.add(newEnergyPoint) realm.add(newFocusPoint) realm.add(newMotivationPoint) } } }
28.916667
94
0.6244
8f417fcacb8d44292e58d7f1107af050942def16
2,100
/// Copyright (c) 2022 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 SwiftUI extension Color { static let colors: [Color] = [ .green, .red, .blue, .gray, .yellow, .pink, .orange, .purple ] static func random() -> Color { colors.randomElement() ?? .black } }
50
97
0.741429
4a64c2ce3d2572d6e8ea75cd73f793c3470b991b
517
// // ViewController.swift // ParseChat // // Created by Joe Antongiovanni on 2/25/18. // Copyright © 2018 Joe Antongiovanni. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.884615
80
0.675048
bf0cab5c400a0baaf956dfa9ae9a57415d2bdd9d
2,681
// // MainTabBarController.swift // Moop // // Created by Chang Woo Son on 2019/06/19. // Copyright © 2019 kor45cw. All rights reserved. // import UIKit protocol ScrollToTopDelegate: class { var canScrollToTop: Bool { get set } func scrollToTop() } class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.viewControllers = [movieViewController(), alarmViewController(), settingViewController()] } private func movieViewController() -> UINavigationController { let currentNavigationController = UINavigationController(rootViewController: MovieView.instance()) currentNavigationController.navigationBar.prefersLargeTitles = true let currentTabBarItem = UITabBarItem(title: "영화".localized, image: UIImage(named: "movie"), tag: 0) currentTabBarItem.selectedImage = UIImage(named: "movie_selected") currentNavigationController.tabBarItem = currentTabBarItem return currentNavigationController } private func alarmViewController() -> UINavigationController { let alarmNavigationController = UINavigationController(rootViewController: AlarmView.instance()) alarmNavigationController.navigationBar.prefersLargeTitles = true let alarmTabBarItem = UITabBarItem(title: "알림".localized, image: UIImage(systemName: "bell"), tag: 1) alarmTabBarItem.selectedImage = UIImage(systemName: "bell.fill") alarmNavigationController.tabBarItem = alarmTabBarItem return alarmNavigationController } private func settingViewController() -> UINavigationController { let settingNavigationController = UINavigationController(rootViewController: SettingView.instance()) settingNavigationController.navigationBar.prefersLargeTitles = true let settingTabBarItem = UITabBarItem(title: "설정".localized, image: UIImage(named: "setting"), tag: 2) settingTabBarItem.selectedImage = UIImage(named: "setting_selected") settingNavigationController.tabBarItem = settingTabBarItem return settingNavigationController } } extension MainTabBarController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { guard let navi = viewController as? UINavigationController else { return } if let viewController = navi.viewControllers.first as? ScrollToTopDelegate, viewController.canScrollToTop { viewController.scrollToTop() } } }
42.555556
115
0.721373
0edde6475a58e5f8db4a45483dca08d5dc782d5d
795
// // JABGlobalVariables.swift // JABSwiftCore // // Created by Jeremy Bannister on 4/11/15. // Copyright (c) 2015 Jeremy Bannister. All rights reserved. // import UIKit public var heightOfStatusBar = UIApplication.shared.statusBarFrame.size.height public var staticOnScreenView: UIView? public let partialSlideFraction = CGFloat(0.3) public let thresholdDragDistance = CGFloat(90.0) public let backPanTouchThreshold = CGFloat(25.0) public let globalStopwatch = JABStopwatch() public var currentDebugView = UIView() public var rootViewController = UIViewController() public func max<T: Comparable> (of value1: T, _ value2: T) -> T { return value1 > value2 ? value1 : value2 } public func min<T: Comparable> (of value1: T, _ value2: T) -> T { return value1 < value2 ? value1 : value2 }
31.8
108
0.750943
def7214fa56555790480cedfb96e5a17163bd5e5
4,786
import UIKit open class ToastView: UIView { // MARK: Properties open var text: String? { get { return self.textLabel.text } set { self.textLabel.text = newValue } } // MARK: Appearance /// The background view's color. override open dynamic var backgroundColor: UIColor? { get { return self.backgroundView.backgroundColor } set { self.backgroundView.backgroundColor = newValue } } /// The background view's corner radius. @objc open dynamic var cornerRadius: CGFloat { get { return self.backgroundView.layer.cornerRadius } set { self.backgroundView.layer.cornerRadius = newValue } } /// The inset of the text label. @objc open dynamic var textInsets = UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10) /// The color of the text label's text. @objc open dynamic var textColor: UIColor? { get { return self.textLabel.textColor } set { self.textLabel.textColor = newValue } } /// The font of the text label. @objc open dynamic var font: UIFont? { get { return self.textLabel.font } set { self.textLabel.font = newValue } } /// The bottom offset from the screen's bottom in portrait mode. @objc open dynamic var bottomOffsetPortrait: CGFloat = { switch UIDevice.current.userInterfaceIdiom { case .unspecified: return 30 case .phone: return 30 case .pad: return 60 case .tv: return 90 case .carPlay: return 30 default: return 30 } }() /// The bottom offset from the screen's bottom in landscape mode. @objc open dynamic var bottomOffsetLandscape: CGFloat = { switch UIDevice.current.userInterfaceIdiom { case .unspecified: return 20 case .phone: return 20 case .pad: return 40 case .tv: return 60 case .carPlay: return 20 default: return 20 } }() // MARK: UI private let backgroundView: UIView = { let `self` = UIView() self.backgroundColor = UIColor(white: 0, alpha: 0.7) self.layer.cornerRadius = 5 self.clipsToBounds = true return self }() private let textLabel: UILabel = { let `self` = UILabel() self.textColor = .white self.backgroundColor = .clear self.font = { switch UIDevice.current.userInterfaceIdiom { case .unspecified: return .systemFont(ofSize: 12) case .phone: return .systemFont(ofSize: 12) case .pad: return .systemFont(ofSize: 16) case .tv: return .systemFont(ofSize: 20) case .carPlay: return .systemFont(ofSize: 12) default: return .systemFont(ofSize: 12) } }() self.numberOfLines = 0 self.textAlignment = .center return self }() // MARK: Initializing public init() { super.init(frame: .zero) self.isUserInteractionEnabled = false self.addSubview(self.backgroundView) self.addSubview(self.textLabel) } required convenience public init?(coder aDecoder: NSCoder) { self.init() } // MARK: Layout override open func layoutSubviews() { super.layoutSubviews() let containerSize = ToastWindow.shared.frame.size let constraintSize = CGSize( width: containerSize.width * (280.0 / 320.0), height: CGFloat.greatestFiniteMagnitude ) let textLabelSize = self.textLabel.sizeThatFits(constraintSize) self.textLabel.frame = CGRect( x: self.textInsets.left, y: self.textInsets.top, width: textLabelSize.width, height: textLabelSize.height ) self.backgroundView.frame = CGRect( x: 0, y: 0, width: self.textLabel.frame.size.width + self.textInsets.left + self.textInsets.right, height: self.textLabel.frame.size.height + self.textInsets.top + self.textInsets.bottom ) var x: CGFloat var y: CGFloat var width: CGFloat var height: CGFloat let orientation = UIApplication.shared.statusBarOrientation if orientation.isPortrait || !ToastWindow.shared.shouldRotateManually { width = containerSize.width height = containerSize.height y = self.bottomOffsetPortrait } else { width = containerSize.height height = containerSize.width y = self.bottomOffsetLandscape } let backgroundViewSize = self.backgroundView.frame.size x = (width - backgroundViewSize.width) * 0.5 y = height - (backgroundViewSize.height + y) self.frame = CGRect( x: x, y: y, width: backgroundViewSize.width, height: backgroundViewSize.height ) } override open func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? { if let superview = self.superview { let pointInWindow = self.convert(point, to: superview) let contains = self.frame.contains(pointInWindow) if contains && self.isUserInteractionEnabled { return self } } return nil } }
27.825581
93
0.669453
5078ae275f012e0cb0a6c0815dc24b63433b681c
3,333
// // RequestTaskMap.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A type that maintains a two way, one to on map of `URLSessionTask`s to `Request`s. struct RequestTaskMap { private var requests: [URLSessionTask: Request] private var tasks: [Request: URLSessionTask] init(requests: [URLSessionTask: Request] = [:], tasks: [Request: URLSessionTask] = [:]) { self.requests = requests self.tasks = tasks } // TODO: Investigate whether we could make stronger guarantees. Would likely need to abandon subscripts. subscript(_ request: Request) -> URLSessionTask? { get { return tasks[request] } set { guard let newValue = newValue else { guard let task = tasks[request] else { fatalError("RequestTaskMap consistency error: no task corresponding to request found.") } tasks.removeValue(forKey: request) requests.removeValue(forKey: task) return } tasks[request] = newValue requests[newValue] = request } } subscript(_ task: URLSessionTask) -> Request? { get { return requests[task] } set { guard let newValue = newValue else { guard let request = requests[task] else { fatalError("RequestTaskMap consistency error: no request corresponding to task found.") } requests.removeValue(forKey: task) tasks.removeValue(forKey: request) return } requests[task] = newValue tasks[newValue] = task } } var count: Int { precondition(requests.count == tasks.count, "RequestTaskMap.count invalid, requests.count: \(requests.count) != tasks.count: \(tasks.count)") return requests.count } var isEmpty: Bool { precondition(requests.isEmpty == tasks.isEmpty, "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(requests.isEmpty) != tasks.isEmpty: \(tasks.isEmpty)") return requests.isEmpty } }
37.033333
128
0.642064
892809676abd795417d220d09cdb50b6281ea641
10,880
// Copyright SIX DAY LLC. All rights reserved. // Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit enum RestartReason { case walletChange case changeLocalization case serverChange } protocol SettingsCoordinatorDelegate: class, CanOpenURL { func didRestart(with account: Wallet, in coordinator: SettingsCoordinator, reason: RestartReason) func didUpdateAccounts(in coordinator: SettingsCoordinator) func didCancel(in coordinator: SettingsCoordinator) func didPressShowWallet(in coordinator: SettingsCoordinator) func assetDefinitionsOverrideViewController(for: SettingsCoordinator) -> UIViewController? func showConsole(in coordinator: SettingsCoordinator) func delete(account: Wallet, in coordinator: SettingsCoordinator) } class SettingsCoordinator: Coordinator { private let keystore: Keystore private var config: Config private let sessions: ServerDictionary<WalletSession> private let promptBackupCoordinator: PromptBackupCoordinator private let analyticsCoordinator: AnalyticsCoordinator private let walletConnectCoordinator: WalletConnectCoordinator private var account: Wallet { return sessions.anyValue.account } let navigationController: UINavigationController weak var delegate: SettingsCoordinatorDelegate? var coordinators: [Coordinator] = [] lazy var rootViewController: SettingsViewController = { let controller = SettingsViewController(config: config, keystore: keystore, account: account, analyticsCoordinator: analyticsCoordinator) controller.delegate = self controller.modalPresentationStyle = .pageSheet return controller }() lazy var advancedSettingsViewController: AdvancedSettingsViewController = { let controller = AdvancedSettingsViewController() controller.delegate = self controller.hidesBottomBarWhenPushed = true return controller }() init( navigationController: UINavigationController = UINavigationController(), keystore: Keystore, config: Config, sessions: ServerDictionary<WalletSession>, promptBackupCoordinator: PromptBackupCoordinator, analyticsCoordinator: AnalyticsCoordinator, walletConnectCoordinator: WalletConnectCoordinator ) { self.navigationController = navigationController self.navigationController.modalPresentationStyle = .formSheet self.keystore = keystore self.config = config self.sessions = sessions self.promptBackupCoordinator = promptBackupCoordinator self.analyticsCoordinator = analyticsCoordinator self.walletConnectCoordinator = walletConnectCoordinator promptBackupCoordinator.subtlePromptDelegate = self } func start() { navigationController.viewControllers = [rootViewController] } func restart(for wallet: Wallet, reason: RestartReason) { delegate?.didRestart(with: wallet, in: self, reason: reason) } } extension SettingsCoordinator: SupportViewControllerDelegate { } extension SettingsCoordinator: SettingsViewControllerDelegate { func settingsViewControllerWalletConnectSelected(in controller: SettingsViewController) { walletConnectCoordinator.showSessions() } func settingsViewControllerShowSeedPhraseSelected(in controller: SettingsViewController) { switch account.type { case .real(let account): let coordinator = ShowSeedPhraseCoordinator(navigationController: navigationController, keystore: keystore, account: account) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) case .watch: break } } func settingsViewControllerHelpSelected(in controller: SettingsViewController) { let viewController = SupportViewController() viewController.delegate = self viewController.navigationItem.largeTitleDisplayMode = .never viewController.hidesBottomBarWhenPushed = true navigationController.pushViewController(viewController, animated: true) } func settingsViewControllerChangeWalletSelected(in controller: SettingsViewController) { let coordinator = AccountsCoordinator( config: config, navigationController: navigationController, keystore: keystore, promptBackupCoordinator: promptBackupCoordinator, analyticsCoordinator: analyticsCoordinator ) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) } func settingsViewControllerMyWalletAddressSelected(in controller: SettingsViewController) { delegate?.didPressShowWallet(in: self) } func settingsViewControllerBackupWalletSelected(in controller: SettingsViewController) { switch account.type { case .real(let account): let coordinator = BackupCoordinator( navigationController: navigationController, keystore: keystore, account: account, analyticsCoordinator: analyticsCoordinator ) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) case .watch: break } } func settingsViewControllerActiveNetworksSelected(in controller: SettingsViewController) { let coordinator = EnabledServersCoordinator(navigationController: navigationController, selectedServers: config.enabledServers) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) } func settingsViewControllerAdvancedSettingsSelected(in controller: SettingsViewController) { navigationController.pushViewController(advancedSettingsViewController, animated: true) } } extension SettingsCoordinator: ShowSeedPhraseCoordinatorDelegate { func didCancel(in coordinator: ShowSeedPhraseCoordinator) { removeCoordinator(coordinator) } } extension SettingsCoordinator: CanOpenURL { func didPressViewContractWebPage(forContract contract: AlphaWallet.Address, server: RPCServer, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(forContract: contract, server: server, in: viewController) } func didPressViewContractWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(url, in: viewController) } func didPressOpenWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressOpenWebPage(url, in: viewController) } } extension SettingsCoordinator: AccountsCoordinatorDelegate { func didAddAccount(account: Wallet, in coordinator: AccountsCoordinator) { delegate?.didUpdateAccounts(in: self) } func didDeleteAccount(account: Wallet, in coordinator: AccountsCoordinator) { delegate?.delete(account: account, in: self) for each in sessions.values { TransactionsTracker(sessionID: each.sessionID).fetchingState = .initial } delegate?.didUpdateAccounts(in: self) guard !coordinator.accountsViewController.hasWallets else { return } coordinator.navigationController.popViewController(animated: true) delegate?.didCancel(in: self) } func didCancel(in coordinator: AccountsCoordinator) { coordinator.navigationController.popViewController(animated: true) removeCoordinator(coordinator) } func didSelectAccount(account: Wallet, in coordinator: AccountsCoordinator) { coordinator.navigationController.popViewController(animated: true) removeCoordinator(coordinator) restart(for: account, reason: .walletChange) } } extension SettingsCoordinator: LocalesCoordinatorDelegate { func didSelect(locale: AppLocale, in coordinator: LocalesCoordinator) { coordinator.localesViewController.navigationController?.popViewController(animated: true) removeCoordinator(coordinator) restart(for: account, reason: .changeLocalization) } } extension SettingsCoordinator: EnabledServersCoordinatorDelegate { func didSelectServers(servers: [RPCServer], in coordinator: EnabledServersCoordinator) { //Defensive. Shouldn't allow no server to be selected guard !servers.isEmpty else { return } let unchanged = config.enabledServers.sorted(by: { $0.chainID < $1.chainID }) == servers.sorted(by: { $0.chainID < $1.chainID }) if unchanged { coordinator.stop() removeCoordinator(coordinator) } else { config.enabledServers = servers restart(for: account, reason: .serverChange) } } func didSelectDismiss(in coordinator: EnabledServersCoordinator) { coordinator.stop() removeCoordinator(coordinator) } } extension SettingsCoordinator: PromptBackupCoordinatorSubtlePromptDelegate { var viewControllerToShowBackupLaterAlert: UIViewController { return rootViewController } func updatePrompt(inCoordinator coordinator: PromptBackupCoordinator) { rootViewController.promptBackupWalletView = coordinator.subtlePromptView } } extension SettingsCoordinator: BackupCoordinatorDelegate { func didCancel(coordinator: BackupCoordinator) { removeCoordinator(coordinator) } func didFinish(account: AlphaWallet.Address, in coordinator: BackupCoordinator) { promptBackupCoordinator.markBackupDone() promptBackupCoordinator.showHideCurrentPrompt() removeCoordinator(coordinator) } } extension SettingsCoordinator: AdvancedSettingsViewControllerDelegate { func advancedSettingsViewControllerConsoleSelected(in controller: AdvancedSettingsViewController) { delegate?.showConsole(in: self) } func advancedSettingsViewControllerClearBrowserCacheSelected(in controller: AdvancedSettingsViewController) { let coordinator = ClearDappBrowserCacheCoordinator(inViewController: rootViewController) coordinator.start() addCoordinator(coordinator) } func advancedSettingsViewControllerTokenScriptSelected(in controller: AdvancedSettingsViewController) { guard let controller = delegate?.assetDefinitionsOverrideViewController(for: self) else { return } controller.navigationItem.largeTitleDisplayMode = .never navigationController.pushViewController(controller, animated: true) } func advancedSettingsViewControllerChangeLanguageSelected(in controller: AdvancedSettingsViewController) { let coordinator = LocalesCoordinator() coordinator.delegate = self coordinator.start() addCoordinator(coordinator) coordinator.localesViewController.navigationItem.largeTitleDisplayMode = .never navigationController.pushViewController(coordinator.localesViewController, animated: true) } func advancedSettingsViewControllerChangeCurrencySelected(in controller: AdvancedSettingsViewController) { } func advancedSettingsViewControllerAnalyticsSelected(in controller: AdvancedSettingsViewController) { } }
37.133106
139
0.766085
50132f465878e090a7205c675eaea7fb220a55bf
427
extension CommandConfig { /// Adds Fluent's commands to the `CommandConfig`. Currently add migration commands. /// /// var commandConfig = CommandConfig.default() /// commandConfig.useFluentCommands() /// services.register(commandConfig) /// public mutating func useFluentCommands() { use(RevertCommand.self, as: "revert") use(MigrateCommand.self, as: "migrate") } }
32.846154
88
0.64637
0a8a8906c4c00c31baf179304bae6dcb54f9f936
72,910
/* * Copyright 2019 Google LLC. 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. */ // swiftlint:disable file_length import UIKit import MaterialComponents.MaterialCollections import MaterialComponents.MaterialDialogs import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialSnackbar import third_party_sciencejournal_ios_ScienceJournalProtos protocol ObserveViewControllerDelegate: class { /// Tells the delegate recording started. func observeViewController(_ observeViewController: ObserveViewController, didStartRecordingFromUserInteraction userInteraction: Bool) /// Tells the delegate recording stopped. func observeViewController(_ observeViewController: ObserveViewController, didEndRecordingFromUserInteraction userInteraction: Bool) /// Tells the delegate sensor snapshots were created. func observeViewController(_ observeViewController: ObserveViewController, didCreateSensorSnapshots sensorSnapshots: [SensorSnapshot]) /// Tells the delegate a trigger note was received. func observeViewController(_ observeViewController: ObserveViewController, didReceiveNoteTrigger trigger: SensorTrigger, forSensor sensor: Sensor, atTimestamp timestamp: Int64) /// Tells the delegate a trial began recording. func observeViewController(_ observeViewController: ObserveViewController, didBeginTrial trial: Trial) /// Tells the delegate a trial was updated. func observeViewController(_ observeViewController: ObserveViewController, didUpdateTrial trial: Trial, isFinishedRecording: Bool) /// Tells the delegate a trial recording was cancelled. func observeViewController(_ observeViewController: ObserveViewController, didCancelTrial trial: Trial) /// Tells the delegate set triggers was pressed for a sensor. func observeViewController(_ observeViewController: ObserveViewController, didPressSetTriggersForSensor sensor: Sensor) /// Asks the delegate if a sensor trigger is active. func observeViewController(_ observeViewController: ObserveViewController, isSensorTriggerActive sensorTrigger: SensorTrigger) -> Bool /// Tells the delegate sensor layouts were updated. func observeViewController(_ observeViewController: ObserveViewController, didUpdateSensorLayouts sensorLayouts: [SensorLayout]) /// Tells the delegate sensor settings was pressed for a sensor. func observeViewControllerDidPressSensorSettings(_ observeViewController: ObserveViewController) /// Tells the delegate a sensor exceeded the maximum allowed trigger fire limit. func observeViewController(_ observeViewController: ObserveViewController, didExceedTriggerFireLimitForSensor sensor: Sensor) } // swiftlint:disable type_body_length // TODO: Consider breaking into multiple files for each delegate. /// Manages the view that displays sensor data, both for observing and recording. open class ObserveViewController: ScienceJournalCollectionViewController, ChartControllerDelegate, DrawerItemViewController, DrawerPositionListener, ObserveDataSourceDelegate, ObserveFooterCellDelegate, SensorCardCellDelegate, TimeAxisControllerDelegate, RecordingManagerDelegate { enum Error: Swift.Error { case recordingManagerIsNotReady case recordingIsMissingData } // MARK: - Constants let cellGap: CGFloat = 10.0 let jumpToNowTrailingConstantHidden: CGFloat = 65 let jumpToNowTrailingConstantVisible: CGFloat = -14 let jumpToNowAnimationDuration: TimeInterval = 0.8 let SensorCellIdentifier = "SensorCell" let FooterCellIdentifier = "FooterCell" var chartTimeAxisInsets: UIEdgeInsets { let sideInset = cellHorizontalInset / 2 let chartYAxisInset = ChartView.yLabelWidth return UIEdgeInsets(top: 0, left: sideInset + chartYAxisInset, bottom: 0, right: sideInset) } /// Record button view. let recordButtonView = RecordButtonView(frame: .zero) let recordingTimerView = TimerView() // MARK: - Properties let observeDataSource: ObserveDataSource let timeAxisController = TimeAxisController(style: .observe) let recordingManager: RecordingManager var recordingTrial: Trial? let sensorController: SensorController @objc private(set) lazy var scrollViewContentObserver = ScrollViewContentObserver(scrollView: collectionView) // TODO: Refactor this out by more logically enabling/disabling the brightness listener. // http://b/64401602 /// Is there a brightness listener in use? private var brightnessListenerExists: Bool = false /// The delegate. weak var delegate: ObserveViewControllerDelegate? /// Sensor triggers for the experiment. var sensorTriggers = [SensorTrigger]() { didSet { recordingManager.removeAllTriggers() for trigger in activeSensorTriggers { if let sensor = sensorController.sensor(for: trigger.sensorID) { recordingManager.add(trigger: trigger, forSensor: sensor) } } // Update sensor cards for whether or not they need a visual trigger view, and if a change is // made to visible cells, invalidate the collection view layout and layout the view. if updateSensorCardsForVisualTriggers(whileRecording: recordingManager.isRecording) { invalidateCollectionView(andLayoutIfNeeded: true) } } } /// The sensor triggers that are currently active for the experiment. var activeSensorTriggers: [SensorTrigger] { guard let delegate = self.delegate else { return [] } return sensorTriggers.filter { delegate.observeViewController(self, isSensorTriggerActive: $0) } } /// Are we recording? var isRecording: Bool { return recordingManager.isRecording } private var drawerPanner: DrawerPanner? private var backgroundRecordingTaskID: UIBackgroundTaskIdentifier? private var backgroundRecordingTimer: Timer? private var recordingSaveTimer: Timer? private var shouldNotifyUserIfBackgroundRecordingWillEnd = false private let jumpToNowButton = JumpToNowButton() private var jumpToNowTrailingConstraint: NSLayoutConstraint? private let recordButtonViewWrapper = UIView() private var recordButtonViewWrapperHeightConstraint: NSLayoutConstraint? private let preferenceManager: PreferenceManager /// The interval in which recorded data is saved while recoridng, in seconds. private let saveInterval: TimeInterval = 5 // The audio and brightness sensor background message alert, stored so that it can be dismissed if // it is still on screen when a recording stopped alert shows in `applicationWillResignActive()`. private var audioAndBrightnessSensorBackgroundMessageAlert: MDCAlertController? /// Sensor layouts used for the setup of the sensor cards. private var sensorLayouts: [SensorLayout] { return observeDataSource.items.compactMap { $0.sensorLayout } } /// The available sensors for the current experiment. private var availableSensorIDs: [String] { return self.observeDataSource.availableSensorIDs } // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - analyticsReporter: An AnalyticsReporter. /// - preferenceManager: The preference manager. /// - sensorController: The sensor controller. /// - sensorDataManager: The sensor data manager. public init(analyticsReporter: AnalyticsReporter, preferenceManager: PreferenceManager, sensorController: SensorController, sensorDataManager: SensorDataManager) { self.preferenceManager = preferenceManager self.sensorController = sensorController self.recordingManager = RecordingManager(sensorDataManager: sensorDataManager) observeDataSource = ObserveDataSource(sensorController: sensorController) observeDataSource.shouldShowFooterAddButton = FeatureFlags.isActionAreaEnabled == false let flowLayout = MDCCollectionViewFlowLayout() flowLayout.minimumLineSpacing = SensorCardCell.cardInsets.bottom super.init(collectionViewLayout: flowLayout, analyticsReporter: analyticsReporter) observeDataSource.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(localNotificationManagerDidReceiveStopRecordingAction), name: LocalNotificationManager.DidReceiveStopRecordingAction, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(accessibilityVoiceOverStatusChanged), name: UIAccessibility.voiceOverStatusDidChangeNotification, object: nil) // If a user will be signed out, this notification will be fired. NotificationCenter.default.addObserver(self, selector: #selector(forceEndRecordingForSignOut), name: .userWillBeSignedOut, object: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } /// Adds the note to all recording charts. /// /// - Parameter note: A display note. func addNoteToCharts(_ note: DisplayNote) { guard recordingTrial != nil else { return } observeDataSource.enumerateChartControllers { $0.addNote(note) } timeAxisController.addNoteDotAtTimestamp(note.timestamp.milliseconds) } /// This should be called when observe will no longer be used by an experiment for input. To /// enable observing again either call `addListenersForAllSensorCards()` or set new sensor /// layouts with listeners. func prepareForReuse() { removeAllSensorListeners() } // MARK: - View lifecycle override open func viewDidLoad() { super.viewDidLoad() // Always register collection view cells early to avoid a reload occurring first. collectionView?.register(SensorCardCell.self, forCellWithReuseIdentifier: SensorCellIdentifier) collectionView?.register(ObserveFooterCell.self, forCellWithReuseIdentifier: FooterCellIdentifier) recordingManager.delegate = self styler.cellStyle = .default MDCAlertColorThemer.apply(ViewConstants.alertColorScheme) collectionView?.backgroundColor = ArduinoColorPalette.containerBackgroundColor if FeatureFlags.isActionAreaEnabled { collectionView?.contentInsetAdjustmentBehavior = .automatic } else { collectionView?.contentInsetAdjustmentBehavior = .never } collectionView?.panGestureRecognizer.addTarget( self, action: #selector(handleCollectionViewPanGesture(_:))) timeAxisController.delegate = self timeAxisController.listener = { [weak self] visibleXAxis, dataXAxis, sourceChartController in guard let strongSelf = self else { return } strongSelf.observeDataSource.enumerateChartControllers { // Only update chart controller if `chartController` not equal the current controller. // This prevents interaction loops when the change is initiated by one of the enumerated // chart controllers. if sourceChartController != $0 { $0.setXAxis(visibleXAxis: visibleXAxis, dataXAxis: dataXAxis) } // Let chart know whether it is pinned or not. $0.chartOptions.isPinnedToNow = strongSelf.timeAxisController.isPinnedToNow } } // Record button view. recordButtonView.snapshotButton.addTarget(self, action: #selector(snapshotButtonPressed), for: .touchUpInside) recordButtonView.recordButton.addTarget(self, action: #selector(recordButtonPressed), for: .touchUpInside) recordButtonView.translatesAutoresizingMaskIntoConstraints = false recordButtonViewWrapper.addSubview(recordButtonView) recordButtonView.topAnchor.constraint( equalTo: recordButtonViewWrapper.topAnchor).isActive = true recordButtonView.leadingAnchor.constraint( equalTo: recordButtonViewWrapper.leadingAnchor).isActive = true recordButtonView.trailingAnchor.constraint( equalTo: recordButtonViewWrapper.trailingAnchor).isActive = true recordButtonViewWrapper.backgroundColor = DrawerView.actionBarBackgroundColor?.withAlphaComponent(0.8) recordButtonViewWrapper.translatesAutoresizingMaskIntoConstraints = false view.addSubview(recordButtonViewWrapper) recordButtonViewWrapper.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true recordButtonViewWrapper.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true recordButtonViewWrapper.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true recordButtonViewWrapperHeightConstraint = recordButtonViewWrapper.heightAnchor.constraint(equalTo: recordButtonView.heightAnchor) recordButtonViewWrapperHeightConstraint?.isActive = true // TODO: Just hiding this so it will still work w/o the AA flag, but should probably be removed // at the time of The Big Delete of the old UI. recordButtonViewWrapper.isHidden = FeatureFlags.isActionAreaEnabled // Time axis view. addChild(timeAxisController) let axisView = timeAxisController.timeAxisView axisView.alpha = 0 // Initially, the axis view is hidden. axisView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(axisView) axisView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true axisView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true if FeatureFlags.isActionAreaEnabled { axisView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true } else { axisView.bottomAnchor.constraint(equalTo: recordButtonViewWrapper.topAnchor).isActive = true } // Jump to now button jumpToNowButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(jumpToNowButton) let trailingConstraint = jumpToNowButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: jumpToNowTrailingConstantHidden) trailingConstraint.isActive = true jumpToNowTrailingConstraint = trailingConstraint jumpToNowButton.bottomAnchor.constraint(equalTo: axisView.topAnchor, constant: -14).isActive = true jumpToNowButton.addTarget(self, action: #selector(jumpToNowButtonPressed), for: .touchUpInside) updateNavigationItems() // Adjust the content insets of the view based on action bar and time axis. adjustContentInsets() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Update sensors for any cells showing the sensor picker as available sensors may have changed. updateSensorPickersIfNeeded() // This is the earliest point the chart axis report the correct value. timeAxisController.chartTimeAxisInsets = chartTimeAxisInsets // Reset data and time axis for all charts if not recording. if !recordingManager.isRecording { observeDataSource.enumerateChartControllers { $0.resetData() } timeAxisController.resetAxisToDefault() timeAxisController.isPinnedToNow = true } updateCollectionViewScrollEnabled() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateBrightnessSensorListenerIfNecessary(viewVisible: true) } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateBrightnessSensorListenerIfNecessary(viewVisible: false) } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil, completion: { (_) in self.timeAxisController.chartTimeAxisInsets = self.chartTimeAxisInsets }) } override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override open func viewSafeAreaInsetsDidChange() { recordButtonViewWrapperHeightConstraint?.constant = view.safeAreaInsetsOrZero.bottom adjustContentInsets() } // Updates the listener for a brightness sensor if one exists and we're not in record mode. This // allows the brightness sensor to be paused when not recording, which means the camera can be // used to take images. private func updateBrightnessSensorListenerIfNecessary(viewVisible: Bool) { guard !isRecording else { return } observeDataSource.items.forEach { card in guard card.sensor is BrightnessSensor else { return } if viewVisible && !brightnessListenerExists { addListener(forSensorCard: card) } else if !viewVisible { removeListener(forSensorCard: card) } } } // MARK: - Alerts /// Presents an alert controller with a message. /// /// - Parameters: /// - title: The title of the alert. Optional. /// - message: The message to show. /// - dismissTitle: Optional alternative title for the dismiss button, "OK" if not set. @discardableResult private func showAlert(withTitle title: String?, message: String, dismissTitle: String? = nil) -> MDCAlertController { let alert = MDCAlertController(title: title, message: message) let cancelAction = MDCAlertAction(title: dismissTitle ?? String.actionCancel) alert.addAction(cancelAction) present(alert, animated: true) return alert } // MARK: - User actions @objc func snapshotButtonPressed() { func createSnapshots() { let sensorSnapshots = recordingManager.sensorSnapshots guard sensorSnapshots.count == self.observeDataSource.items.count else { // Not all sensors provided a snapshot, show a toast alert. let message = MDCSnackbarMessage() message.text = String.snapshotFailedDisconnected MDCSnackbarManager.default.setButtonTitleColor( ArduinoColorPalette.yellowPalette.tint200, for: .normal) MDCSnackbarManager.default.show(message) return } self.delegate?.observeViewController(self, didCreateSensorSnapshots: sensorSnapshots) } // If the drawer will be animating, create the snapshots after the animation completes. if let drawerViewController = drawerViewController { drawerViewController.minimizeFromFull(completion: { createSnapshots() }) } else { createSnapshots() } } @objc func recordButtonPressed() throws { if !recordingManager.isRecording { guard recordingManager.isReady else { throw Error.recordingManagerIsNotReady } startRecording(fromUserInteraction: true) timeAxisController.isPinnedToNow = true drawerViewController?.setPositionToFull() } else { // If data is missing from at least one sensor, throw the error guard !recordingManager.isRecordingMissingData else { throw Error.recordingIsMissingData } endRecording(fromUserInteraction: true) drawerViewController?.minimizeFromFull() // Increment the successful recording count. RatingsPromptManager.shared.incrementSuccessfulRecordingCount() } } /// Creates a trial and begins recording sensor data. func startRecording(fromUserInteraction: Bool = false) { // Cannot start recording a trial if one is already in progress. guard recordingTrial == nil else { return } for card in observeDataSource.items where card.sensor is BrightnessSensor { CaptureSessionInterruptionObserver.shared.isBrightnessSensorInUse = true break } beginBackgroundRecordingTask() // Show the time axis view. showTimeAxisView(true) // Create a trial. let trial = Trial() recordingTrial = trial // Remove the add sensor card button if it is being shown (if all sensors have cards, it // wouldn't be shown). if let footerIndexPath = observeDataSource.footerIndexPath { observeDataSource.shouldShowFooterAddButton = false collectionView?.deleteSections(IndexSet(integer: footerIndexPath.section)) } resetCalculators() recordingManager.startRecording(trialID: trial.ID) recordingSaveTimer = Timer.scheduledTimer(timeInterval: saveInterval, target: self, selector: #selector(recordingSaveTimerFired), userInfo: nil, repeats: true) delegate?.observeViewController(self, didStartRecordingFromUserInteraction: fromUserInteraction) trial.recordingRange.min = recordingManager.recordingStartDate! // Do an initial update so that if the app terminates before the recording save timer fires, the // trial has semi-valid data. updateRecordingTrial(isFinishedRecording: false) delegate?.observeViewController(self, didBeginTrial: trial) for sensorCard in observeDataSource.items { sensorCard.chartController.recordingStartTime = recordingManager.recordingStartDate if let sensorLayout = sensorCard.sensorLayout, sensorLayout.shouldShowStatsOverlay { sensorCard.chartController.shouldShowStats = true } if (sensorCard.sensor is AudioSensor || sensorCard.sensor is BrightnessSensor) && !preferenceManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage { audioAndBrightnessSensorBackgroundMessageAlert = showAlert(withTitle: String.sensorTypeBackgroundIssueDialogTitle, message: String.sensorTypeAudioAndBrightnessBackgroundMessage, dismissTitle: String.actionConfirmCasual) preferenceManager.hasUserSeenAudioAndBrightnessSensorBackgroundMessage = true } } timeAxisController.recordingStartTime = recordingManager.recordingStartDate recordButtonView.recordButton.isSelected = true updateCellsToRecord(true) updateNavigationItems() } /// Ends a recording, which will stop writing data to the database and create a completed trial /// with layouts and stats if appropriate. /// /// - Parameters: /// - isCancelled: True if the recording was cancelled, otherwise false. Default is false. /// - removeCancelledData: True if data from a cancelled recording should be removed, otherwise /// false (data is left in the database). Only has impact if /// `isCancelled` is true. Default is true. func endRecording(isCancelled: Bool = false, removeCancelledData: Bool = true, fromUserInteraction: Bool = false) { guard recordingTrial != nil else { print("[ObserveViewController] Recording ended with no valid recording trial.") return } CaptureSessionInterruptionObserver.shared.isBrightnessSensorInUse = false updateCellsToRecord(false) // Hide the time axis view. showTimeAxisView(false) // Stop the recorder. recordingManager.endRecording(isCancelled: isCancelled, removeCancelledData: removeCancelledData) recordingSaveTimer?.invalidate() recordingSaveTimer = nil delegate?.observeViewController(self, didEndRecordingFromUserInteraction: fromUserInteraction) // Show the add sensor card button if it should be (if all sensors have cards, it shouldn't be // shown). observeDataSource.shouldShowFooterAddButton = FeatureFlags.isActionAreaEnabled == false if let footerIndexPath = observeDataSource.footerIndexPath { collectionView?.insertSections(IndexSet(integer: footerIndexPath.section)) } // If the recording was not cancelled, configure the new trial. If it was cancelled and we // need to remove data, do that now instead. if !isCancelled { updateRecordingTrial(isFinishedRecording: true) } else if removeCancelledData { cancelAndRemoveRecordingTrial() } observeDataSource.enumerateChartControllers { (chartController) in chartController.recordingStartTime = nil chartController.shouldShowStats = false chartController.removeAllNotes() } timeAxisController.recordingStartTime = nil timeAxisController.removeAllNoteDots() recordButtonView.recordButton.isSelected = false recordButtonView.timerLabel.text = nil updateNavigationItems() endBackgroundRecordingTask() } @objc private func jumpToNowButtonPressed() { timeAxisController.isPinnedToNow = true } // MARK: - Changing sensors in cells // Loops through visible cells and updates their sensor pickers, if they're showing. This is // useful when first loading this VC or for when a user comes back from a modal that might change // available sensors. private func updateSensorPickersIfNeeded() { if let visibleCells = collectionView?.visibleCells { visibleCells.forEach { (cell) in guard let indexPath = collectionView?.indexPath(for: cell), let cell = cell as? SensorCardCell, observeDataSource.item( at: indexPath.item).cellState.options.contains(.sensorPickerVisible) else { return } cell.updateSensorPicker() } } } func removeListener(forSensorCard sensorCard: SensorCard) { let sensor = sensorCard.sensor do { try recordingManager.removeListener(for: sensor) if sensor is BrightnessSensor { brightnessListenerExists = false } } catch { print("Error removing listener \(error.localizedDescription)") } } func addListener(forSensorCard sensorCard: SensorCard) { let sensor = sensorCard.sensor if sensor is BrightnessSensor && !isViewVisible { // The brightness sensor should only have a listener added if the view is visible. This is // necessary for the camera to take pictures. The brightness sensor will have a listener // added in viewDidAppear. return } sensorCard.chartController.resetData() recordingManager.addListener( forSensor: sensor, triggers: activeSensorTriggers.filter { $0.sensorID == sensor.sensorId }, using: { [weak self] (dataPoint) in var sensorCardCell: SensorCardCell? if let indexPath = self?.observeDataSource.indexPathForItem(sensorCard) { sensorCardCell = self?.collectionView?.cellForItem(at: indexPath) as? SensorCardCell } sensorCard.chartController.addDataPointToEnd(dataPoint) let visibleYAxis = sensorCard.chartController.visibleYAxis if let cell = sensorCardCell { cell.currentValueView.textLabel.text = sensor.string(for: dataPoint.y, withUnits: true) cell.currentValueView.setAnimatingIconValue(dataPoint.y, minValue: visibleYAxis.min, maxValue: visibleYAxis.max) } sensorCard.toneGenerator.setToneFrequency(for: dataPoint.y, valueMin: visibleYAxis.min, valueMax: visibleYAxis.max, atTimestamp: dataPoint.x) // Only add a value to the calculator if a trial is recording. if let recordingManager = self?.recordingManager, recordingManager.isRecording { sensorCard.statCalculator.addDataPoint(dataPoint) if let min = sensorCard.statCalculator.minimum, let max = sensorCard.statCalculator.maximum, let average = sensorCard.statCalculator.average { sensorCard.chartController.setStats(min: min, max: max, average: average) if let cell = sensorCardCell { cell.statsView.setMin(sensor.string(for: min), average: sensor.string(for: average), max: sensor.string(for: max)) } } } }) if sensor is BrightnessSensor { brightnessListenerExists = true } } /// Removes all sensor listeners. func removeAllSensorListeners() { for sensorCard in observeDataSource.items { sensorCard.toneGenerator.stop() removeListener(forSensorCard: sensorCard) observeDataSource.endUsingSensor(sensorCard.sensor) } } /// Adds listeners for all sensor cards. func addListenersForAllSensorCards() { // Track the previous footer path, if it existed. let previousFooterIndexPath = observeDataSource.footerIndexPath for sensorCard in observeDataSource.items { observeDataSource.beginUsingSensor(sensorCard.sensor) addListener(forSensorCard: sensorCard) if let sensorLayout = sensorCard.sensorLayout, sensorLayout.isAudioEnabled { sensorCard.toneGenerator.start() } } // If the footer was showing, is still showing, and should no longer show, remove it. if collectionView?.numberOfSections == 2 && observeDataSource.footerIndexPath == nil, let previousFooterIndexPath = previousFooterIndexPath { collectionView?.deleteSections(IndexSet(integer: previousFooterIndexPath.section)) } } // MARK: - Helpers private func removeSensorCardFromDataSource(_ sensorCard: SensorCard) { observeDataSource.removeItem(sensorCard) removeSensorLayoutForSensorCard(sensorCard) removeListener(forSensorCard: sensorCard) observeDataSource.endUsingSensor(sensorCard.sensor) sensorCard.toneGenerator.stop() } private func updateSensorCard(_ sensorCard: SensorCard, with sensor: Sensor) { guard sensorCard.sensor.sensorId == sensor.sensorId else { return } // Stop listening to previous sensor removeListener(forSensorCard: sensorCard) observeDataSource.endUsingSensor(sensorCard.sensor) // Start listening to new sensor sensorCard.sensor = sensor observeDataSource.beginUsingSensor(sensorCard.sensor) addListener(forSensorCard: sensorCard) } private func removeSensorCardCell(_ cell: SensorCardCell) { guard let indexPath = collectionView?.indexPath(for: cell) else { return } let previousFooterPath = observeDataSource.footerIndexPath // Update the dataSource. let sensorCard = observeDataSource.item(at: indexPath.item) removeSensorCardFromDataSource(sensorCard) collectionView?.performBatchUpdates({ // Delete the cell. self.collectionView?.deleteItems(at: [indexPath]) if previousFooterPath == nil { if let newFooterPath = self.observeDataSource.footerIndexPath { // Footer was not visible before but is now, insert it. self.collectionView?.insertSections(IndexSet(integer: newFooterPath.section)) } } }, completion: { (_) in self.updateSensorPickersIfNeeded() // TODO: Show/Enable the "Add Sensor" button if needed }) } func addNewSensorCardCell() { // Track the previous footer path, if it existed. let previousFooterIndexPath = observeDataSource.footerIndexPath guard let newSensorCard = observeDataSource.sensorCardWithNextSensor() else { return } configureSensorCard(newSensorCard, andAddListener: true) addSensorLayoutForSensorCard(newSensorCard) let newItemIndexPath = observeDataSource.lastCardIndexPath let indexPathsOfSensorPickersToHide = [Int](0..<newItemIndexPath.item).map { IndexPath(item: $0, section: 0) } collectionView?.performBatchUpdates({ self.hideSensorPickers(at: indexPathsOfSensorPickersToHide) self.collectionView?.insertItems(at: [newItemIndexPath]) // If the footer should no longer show, remove it. if self.observeDataSource.footerIndexPath == nil, let previousFooterIndexPath = previousFooterIndexPath { self.collectionView?.deleteSections(IndexSet(integer: previousFooterIndexPath.section)) } }, completion: { (_) in // TODO: Hide/Disable the "Add Sensor" button. }) collectionView?.scrollToItem(at: IndexPath(item: newItemIndexPath.item, section: 0), at: .top, animated: true) } /// Hides the sensor picker for sensor cards at index paths. /// /// - Parameter indexPaths: The index paths of cells at which to hide the sensor picker. func hideSensorPickers(at indexPaths: [IndexPath]) { for indexPath in indexPaths { let cellData = observeDataSource.item(at: indexPath.item) cellData.cellState.options.remove(.sensorPickerVisible) if let sensorCell = collectionView?.cellForItem(at: indexPath) as? SensorCardCell { sensorCell.setStateOptions(cellData.cellState.options, animated: true) } } } // Called when starting and stopping recording, tells all items in the data source to change to // or from record mode and updates cells on screen animated. private func updateCellsToRecord(_ recording: Bool) { for (index, sensorCard) in observeDataSource.items.enumerated() { if recording { sensorCard.cellState.options.remove(.sensorPickerVisible) sensorCard.cellState.options.insert(.statsViewVisible) } else { sensorCard.cellState.options.remove(.statsViewVisible) if index == observeDataSource.items.endIndex - 1 { sensorCard.cellState.options.insert(.sensorPickerVisible) } } let indexPath = IndexPath(item: index, section: 0) if let sensorCell = collectionView?.cellForItem(at: indexPath) as? SensorCardCell { sensorCell.setStateOptions(sensorCard.cellState.options, animated: true) } } updateSensorCardsForVisualTriggers(whileRecording: recording) invalidateCollectionView() } func configureSensorCard(_ sensorCard: SensorCard, withSensorLayout sensorLayout: SensorLayout? = nil, andAddListener shouldAddListener: Bool) { if shouldAddListener { observeDataSource.beginUsingSensor(sensorCard.sensor) addListener(forSensorCard: sensorCard) } sensorCard.chartController.setXAxis(visibleXAxis: timeAxisController.visibleXAxis, dataXAxis: timeAxisController.dataXAxis) sensorCard.chartController.delegate = self // If the sensor card has a layout, configure the sensor card to match it. Otherwise, create a // layout for the card. if let sensorLayout = sensorLayout { if shouldAddListener && sensorLayout.isAudioEnabled { sensorCard.toneGenerator.start() } sensorCard.chartController.shouldShowStats = sensorLayout.shouldShowStatsOverlay sensorCard.sensorLayout = SensorLayout(proto: sensorLayout.proto) } else { addSensorLayoutForSensorCard(sensorCard) } } // Adjust collection view insets for the record button view and time axis view. func adjustContentInsets() { if FeatureFlags.isActionAreaEnabled { let topInset = timeAxisController.timeAxisView.alpha > 0 ? timeAxisController.timeAxisView.systemLayoutSizeFitting( UIView.layoutFittingCompressedSize).height : 0 collectionView?.contentInset.top = topInset collectionView?.scrollIndicatorInsets.top = topInset if FeatureFlags.isActionAreaEnabled, collectionView?.contentOffset.y == 0 { // Adjusts the offset so the timeAxisView doesn't obscure the top-most card collectionView?.contentOffset.y = -topInset } } else { var bottomInset = recordButtonViewWrapper.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height if timeAxisController.timeAxisView.alpha > 0 { bottomInset += timeAxisController.timeAxisView.systemLayoutSizeFitting( UIView.layoutFittingCompressedSize).height } collectionView?.contentInset.bottom = bottomInset collectionView?.scrollIndicatorInsets.bottom = bottomInset } } // Animates the display of the time axis view. func showTimeAxisView(_ isVisible: Bool) { if FeatureFlags.isActionAreaEnabled { self.transitionCoordinator?.animate(alongsideTransition: { _ in self.timeAxisController.timeAxisView.alpha = isVisible ? 1 : 0 self.adjustContentInsets() }) } else { UIView.animate(withDuration: 0.4) { self.timeAxisController.timeAxisView.alpha = isVisible ? 1 : 0 self.adjustContentInsets() } } } // Resets all sensor card calculators. func resetCalculators() { for sensorCard in observeDataSource.items { sensorCard.statCalculator.reset() } } @objc private func setCollectionViewContentOffsetToZero() { collectionView?.setContentOffset(.zero, animated: true) } private func updateSensorsForAvailableSensorIDs(andAddListener shouldAddListener: Bool) { let observeItems = observeDataSource.items for sensorCard in observeItems { if !availableSensorIDs.contains(sensorCard.sensor.sensorId) { removeSensorCardFromDataSource(sensorCard) } else if let sensor = sensorController.sensor(for: sensorCard.sensor.sensorId), sensorCard.sensor != sensor { updateSensorCard(sensorCard, with: sensor) } } addInitialSensorCardIfNeeded(andAddListener: shouldAddListener) collectionView?.reloadData() } // If there are no observe data source items, add an initial sensor card. Exposed for testing. func addInitialSensorCardIfNeeded(andAddListener shouldAddListener: Bool) { if observeDataSource.items.isEmpty, let firstSensorCard = observeDataSource.sensorCardWithNextSensor() { configureSensorCard(firstSensorCard, andAddListener: shouldAddListener) } } @objc private func recordingSaveTimerFired() { recordingManager.save() updateRecordingTrial(isFinishedRecording: false) } private func updateRecordingTrial(isFinishedRecording: Bool) { guard let recordingTrial = recordingTrial else { return } // Set the recording end timestamp. recordingTrial.recordingRange.max = Date().millisecondsSince1970 // Remove previous stats and sensor appearances. recordingTrial.trialStats.removeAll() recordingTrial.removeAllSensorAppearances() for sensor in recordingManager.recordingSensors { // Assemble trial stats. let sensorTrialStats = TrialStats(sensorID: sensor.sensorId) // Add trial stats from the sensorCard.statCalculator if let sensorCard = observeDataSource.sensorCard(for: sensor) { sensorTrialStats.addStatsFromStatCalculator(sensorCard.statCalculator) } // Add trial stats from the zoom recorder. if let recorder = recordingManager.recorder(forSensorID: sensor.sensorId) { sensorTrialStats.zoomPresenterTierCount = recorder.zoomTierCount sensorTrialStats.zoomLevelBetweenTiers = Recorder.zoomLevelBetweenTiers } recordingTrial.trialStats.append(sensorTrialStats) recordingTrial.addSensorAppearance(BasicSensorAppearance(sensor: sensor), for: sensor.sensorId) } recordingTrial.sensorLayouts = sensorLayouts // Clear recording trial before notifying delegate since the existence of the recording trial // can indicate a recording is in progress. if isFinishedRecording { self.recordingTrial = nil } delegate?.observeViewController(self, didUpdateTrial: recordingTrial, isFinishedRecording: isFinishedRecording) } private func cancelAndRemoveRecordingTrial() { guard let recordingTrial = recordingTrial else { return } self.recordingTrial = nil delegate?.observeViewController(self, didCancelTrial: recordingTrial) } private func updateCollectionViewScrollEnabled() { // The collection view scrolling should be disabled when in a drawer, unless voiceover mode is // running or the drawer is open full. var shouldEnableScroll: Bool { guard let drawerViewController = drawerViewController else { return true } return drawerViewController.isOpenFull || UIAccessibility.isVoiceOverRunning } collectionView?.isScrollEnabled = shouldEnableScroll } /// Sets the densor layouts used for the setup of the sensor cards. func setSensorLayouts(_ sensorLayouts: [SensorLayout], andAddListeners: Bool) { observeDataSource.removeAllItems() for sensorLayout in sensorLayouts { var cellStateOptions: SensorCardCell.State.Options = sensorLayout.sensorID == sensorLayouts.last?.sensorID ? .showingSensorPicker : .normal guard let sensor = sensorController.sensor(for: sensorLayout.sensorID), sensor.isSupported else { continue } if sensorHasVisualTriggers(sensor, forRecording: recordingManager.isRecording) { cellStateOptions.insert(.visualTriggersVisible) } let sensorCard = observeDataSource.sensorCardWithSensor(sensor, cardColorPalette: sensorLayout.colorPalette, cellStateOptions: cellStateOptions) configureSensorCard(sensorCard, withSensorLayout: sensorLayout, andAddListener: andAddListeners) } addInitialSensorCardIfNeeded(andAddListener: andAddListeners) collectionView?.reloadData() } /// Sets the available sensors for the current experiment. func setAvailableSensorIDs(_ availableSensorIDs: [String], andAddListeners: Bool) { if availableSensorIDs != self.availableSensorIDs { self.observeDataSource.availableSensorIDs = availableSensorIDs } // Even if sensor IDs didn't change, sensors could (e.g. configuration // changed), so let's update them. updateSensorsForAvailableSensorIDs(andAddListener: andAddListeners) } /// The visual triggers to show for a sensor. /// /// - Parameters: /// - sensor: The sensor. /// - recording: Whether or not the sensor is being recorded. Used to filter triggers that /// should fire only when recording. /// - Returns: The visual triggers to show. func visualTriggers(_ sensor: Sensor, forRecording isRecording: Bool) -> [SensorTrigger] { return activeSensorTriggers.filter { $0.sensorID == sensor.sensorId && $0.isVisualTrigger && (isRecording || !isRecording && !$0.triggerInformation.triggerOnlyWhenRecording) } } /// Whether or not a sensor has visual triggers to show. /// /// - Parameters: /// - sensor: The sensor. /// - recording: Whether or not the sensor is being recorded. Used to filter triggers that /// should fire only when recording. /// - Returns: Whether or not the sensor has visual triggers to show. func sensorHasVisualTriggers(_ sensor: Sensor, forRecording isRecording: Bool) -> Bool { return !visualTriggers(sensor, forRecording: isRecording).isEmpty } // Invalidates the collection view layout and optionally lays it out if needed. private func invalidateCollectionView(andLayoutIfNeeded layoutIfNeeded: Bool = false) { collectionView?.collectionViewLayout.invalidateLayout() if layoutIfNeeded { UIView.animate(withDuration: SensorCardCell.stateOptionsChangeAnimationDuration, delay: 0, options: SensorCardCell.stateOptionsChangeAnimationOptions, animations: { self.collectionView?.layoutIfNeeded() }) } } /// Updates sensor cards and visible cells for whether or not they should show a visual trigger /// view. /// /// - Parameter isRecording: Whether or not sensors are being recorded. Filters out triggers that /// should fire only while recording if needed. /// - Returns: Whether or not the collection view needs a layout update. @discardableResult func updateSensorCardsForVisualTriggers( whileRecording isRecording: Bool) -> Bool { var shouldLayoutCollectionView = false // Sets the cell's state options if it is visible, and marks `shouldLayoutCollectionView` as // true. func setStateOptionsAndLayoutIfNeeded(for sensorCard: SensorCard) { if let indexPath = observeDataSource.indexPathForItem(sensorCard), let cell = collectionView?.cellForItem(at: indexPath) as? SensorCardCell { cell.setStateOptions(sensorCard.cellState.options, animated: true) shouldLayoutCollectionView = true } } for sensorCard in observeDataSource.items { if sensorHasVisualTriggers(sensorCard.sensor, forRecording: isRecording) { if !sensorCard.cellState.options.contains(.visualTriggersVisible) { // If there should be a visual trigger view, but then sensor card doesn't have one, add // it. The collection view should be layed out. sensorCard.cellState.options.insert(.visualTriggersVisible) setStateOptionsAndLayoutIfNeeded(for: sensorCard) } // If the cell is on screen, give it the updated triggers. if let indexPath = observeDataSource.indexPathForItem(sensorCard), let cell = collectionView?.cellForItem(at: indexPath) as? SensorCardCell { let visualTriggersForSensor = visualTriggers(sensorCard.sensor, forRecording: recordingManager.isRecording) cell.visualTriggerView.setTriggers(visualTriggersForSensor, forSensor: sensorCard.sensor) } } else if !sensorHasVisualTriggers(sensorCard.sensor, forRecording: isRecording) && sensorCard.cellState.options.contains(.visualTriggersVisible) { // If there should not be a visual trigger view and there is one, remove it. The collection // view should be layed out. sensorCard.cellState.options.remove(.visualTriggersVisible) setStateOptionsAndLayoutIfNeeded(for: sensorCard) } } return shouldLayoutCollectionView } private func showJumpToNowButton() { jumpToNowTrailingConstraint?.constant = jumpToNowTrailingConstantVisible let distance = jumpToNowTrailingConstantVisible - jumpToNowTrailingConstantHidden jumpToNowButton.animateRollRotationTransform(forDistance: distance, duration: jumpToNowAnimationDuration) } private func hideJumpToNowButton() { jumpToNowTrailingConstraint?.constant = jumpToNowTrailingConstantHidden let distance = jumpToNowTrailingConstantHidden - jumpToNowTrailingConstantVisible jumpToNowButton.animateRollRotationTransform(forDistance: distance, duration: jumpToNowAnimationDuration) } private func updateNavigationItems() { guard FeatureFlags.isActionAreaEnabled else { return } if isRecording { // Reset to 0 since we reuse the view and otherwise previous value lingers in UI momentarily. recordingTimerView.updateTimerLabel(with: 0) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: recordingTimerView) title = String.actionAreaTitleRecording } else { // Settings button. let settingsButton = UIBarButtonItem(image: UIImage(named: "ic_settings"), style: .plain, target: self, action: #selector(settingsButtonPressed)) settingsButton.accessibilityLabel = String.titleActivitySensorSettings navigationItem.rightBarButtonItem = settingsButton title = String.actionAreaTitleAddSensorNote } } @objc private func settingsButtonPressed() { showSettings() } private func updateTimerLabel(with duration: Int64) { if FeatureFlags.isActionAreaEnabled { recordingTimerView.updateTimerLabel(with: duration) } else { recordButtonView.updateTimerLabel(with: duration) } } private func showSettings() { delegate?.observeViewControllerDidPressSensorSettings(self) } // MARK: - Sensor layouts private func addSensorLayoutForSensorCard(_ sensorCard: SensorCard) { let sensorLayout = SensorLayout(sensorID: sensorCard.sensor.sensorId, colorPalette: sensorCard.colorPalette) sensorLayout.isAudioEnabled = sensorCard.toneGenerator.isPlayingTone sensorCard.sensorLayout = sensorLayout delegate?.observeViewController(self, didUpdateSensorLayouts: sensorLayouts) } func updateSensorLayouts() { for sensorCard in observeDataSource.items { guard let sensorLayout = sensorCard.sensorLayout else { continue } sensorLayout.isAudioEnabled = sensorCard.toneGenerator.isPlayingTone sensorLayout.sensorID = sensorCard.sensor.sensorId sensorLayout.shouldShowStatsOverlay = sensorCard.chartController.shouldShowStats } delegate?.observeViewController(self, didUpdateSensorLayouts: sensorLayouts) } private func removeSensorLayoutForSensorCard(_ sensorCard: SensorCard) { sensorCard.sensorLayout = nil delegate?.observeViewController(self, didUpdateSensorLayouts: sensorLayouts) } // MARK: - Background recording private func beginBackgroundRecordingTask() { backgroundRecordingTaskID = UIApplication.shared.beginBackgroundTask { // If background recording ends because it ran out of time, cancel the recording-will-end // notification and present a recording ended notification. Then end recording. LocalNotificationManager.shared.cancelRecordingWillEndNotification() LocalNotificationManager.shared.presentRecordingEndedNotification() // `endRecording()` calls `endBackgroundRecordingTask()`, which ends the background task. self.endRecording() } startBackgroundRecordingTimer() } private func endBackgroundRecordingTask() { if let backgroundRecordingTaskID = self.backgroundRecordingTaskID, backgroundRecordingTaskID != .invalid { UIApplication.shared.endBackgroundTask(backgroundRecordingTaskID) } self.backgroundRecordingTaskID = .invalid stopBackgroundRecordingTimer() } private func startBackgroundRecordingTimer() { guard backgroundRecordingTimer == nil else { return } backgroundRecordingTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(backgroundRecordingTimerFired), userInfo: nil, repeats: true) // Allows the timer to fire while scroll views are tracking. RunLoop.main.add(backgroundRecordingTimer!, forMode: .common) } private func stopBackgroundRecordingTimer() { backgroundRecordingTimer?.invalidate() backgroundRecordingTimer = nil } @objc private func backgroundRecordingTimerFired() { if UIApplication.shared.backgroundTimeRemaining < 60 { notifyUserBackgroundRecordingWillEnd() } else { shouldNotifyUserIfBackgroundRecordingWillEnd = true } } private func notifyUserBackgroundRecordingWillEnd() { guard shouldNotifyUserIfBackgroundRecordingWillEnd else { return } shouldNotifyUserIfBackgroundRecordingWillEnd = false LocalNotificationManager.shared.presentRecordingWillEndNotification() } // MARK: - UICollectionViewDataSource override open func numberOfSections(in collectionView: UICollectionView) -> Int { return observeDataSource.numberOfSections } override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return observeDataSource.numberOfItemsInSection(section) } override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == observeDataSource.footerIndexPath?.section && observeDataSource.footerIndexPath != nil && observeDataSource.footerIndexPath == indexPath { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FooterCellIdentifier, for: indexPath) if let cell = cell as? ObserveFooterCell { cell.delegate = self } return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SensorCellIdentifier, for: indexPath) if let cell = cell as? SensorCardCell { let sensorCard = observeDataSource.item(at: indexPath.item) let visualTriggersForSensor = visualTriggers(sensorCard.sensor, forRecording: recordingManager.isRecording) cell.configureWithSensor(sensorCard.sensor, delegate: self, stateOptions: sensorCard.cellState.options, colorPalette: sensorCard.colorPalette, chartView: sensorCard.chartController.chartView, visualTriggers: visualTriggersForSensor) sensorCard.toneGenerator.setPlayingStateUpdateBlock { (isPlayingTone) in cell.headerView.setShowAudioIcon(isPlayingTone) } } return cell } } // MARK: - UICollectionViewDelegate override open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let sensorCell = cell as? SensorCardCell, let sensor = sensorCell.sensor, let sensorCard = observeDataSource.item(withSensorID: sensor.sensorId) else { return } // Mark chart as visible so it will know to draw its data. sensorCard.chartController.isObserveVisible = true } override open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let sensorCell = cell as? SensorCardCell, let sensor = sensorCell.sensor, let sensorCard = observeDataSource.item(withSensorID: sensor.sensorId) else { return } // Mark chart as not visible so it won't keep drawing data. sensorCard.chartController.isObserveVisible = false } // MARK: - UICollectionViewDelegateFlowLayout private var cellHorizontalInset: CGFloat { var inset = SensorCardCell.cardInsets.left + SensorCardCell.cardInsets.right if let drawerViewController = drawerViewController, !drawerViewController.drawerView.isDisplayedAsSidebar, traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular { inset = 300 } return inset + view.safeAreaInsetsOrZero.left + view.safeAreaInsetsOrZero.right } override open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.bounds.size.width - cellHorizontalInset if indexPath.section == observeDataSource.footerIndexPath?.section && observeDataSource.footerIndexPath != nil && observeDataSource.footerIndexPath == indexPath { return CGSize(width: width, height: ObserveFooterCell.cellHeight) } return CGSize(width: width, height: observeDataSource.item(at: indexPath.item).cellState.height) } override open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: SensorCardCell.cardInsets.top, left: cellHorizontalInset / 2, bottom: SensorCardCell.cardInsets.bottom, right: cellHorizontalInset / 2) } // MARK: - ObserveFooterCellDelegate func observeFooterAddButtonPressed() { addNewSensorCardCell() } // MARK: - TimeAxisControllerDelegate func timeAxisController(_ timeAxisController: TimeAxisController, didChangePinnedToNow isPinnedToNow: Bool) { if isPinnedToNow { hideJumpToNowButton() } else { showJumpToNowButton() } } // MARK: - SensorCardCellDelegate func sensorCardCellExpandButtonPressed(_ sensorCardCell: SensorCardCell) { guard let indexPath = collectionView?.indexPath(for: sensorCardCell) else { return } // Update the datasource. let sensorCard = observeDataSource.item(at: indexPath.item) if sensorCard.cellState.options.contains(.sensorPickerVisible) { sensorCard.cellState.options.remove(.sensorPickerVisible) } else { let indexPathsOfSensorPickersToHide = observeDataSource.indexPathsForCardsShowingSensorPicker() hideSensorPickers(at: indexPathsOfSensorPickersToHide) sensorCard.cellState.options.insert(.sensorPickerVisible) } sensorCardCell.setStateOptions(sensorCard.cellState.options, animated: true) invalidateCollectionView(andLayoutIfNeeded: true) } func sensorCardCell(_ sensorCardCell: SensorCardCell, didSelectSensor sensor: Sensor) { guard let indexPath = collectionView?.indexPath(for: sensorCardCell) else { return } let sensorCard = observeDataSource.item(at: indexPath.item) // If this is the same sensor already being displayed, return. guard sensorCard.sensor != sensor else { return } // Stop listening to previous sensor removeListener(forSensorCard: sensorCard) observeDataSource.endUsingSensor(sensorCard.sensor) removeSensorLayoutForSensorCard(sensorCard) // Start listening to new sensor sensorCard.sensor = sensor // Clear the current value so it does not persist between sensors when the new sensor takes // a moment to return a value. sensorCardCell.currentValueView.textLabel.text = sensorCard.sensor.unitDescription observeDataSource.beginUsingSensor(sensorCard.sensor) addListener(forSensorCard: sensorCard) addSensorLayoutForSensorCard(sensorCard) sensorCardCell.updateSensor(sensor, chartView: sensorCard.chartController.chartView) } func sensorCardAvailableSensors(_ sensorCardCell: SensorCardCell, withSelectedSensor selectedSensor: Sensor?) -> [Sensor] { return observeDataSource.availableSensors(withSelectedSensor: selectedSensor) } func sensorCardCell(_ sensorCardCell: SensorCardCell, menuButtonPressed menuButton: MenuButton) { guard let indexPath = collectionView?.indexPath(for: sensorCardCell) else { return } let sensorCard = observeDataSource.item(at: indexPath.item) let popUpMenu = PopUpMenuViewController() // Enable/disable audio. (based on whether or not audio is playing). if sensorCard.toneGenerator.isPlayingTone { popUpMenu.addAction(PopUpMenuAction(title: String.graphOptionsAudioFeedbackDisable, icon: UIImage(named: "ic_volume_mute")) { (_) in sensorCard.toneGenerator.stop() sensorCard.sensorLayout?.isAudioEnabled = false }) } else { popUpMenu.addAction(PopUpMenuAction(title: String.graphOptionsAudioFeedbackEnable, icon: UIImage(named: "ic_volume_up")) { (_) in sensorCard.toneGenerator.start() sensorCard.sensorLayout?.isAudioEnabled = true }) } // Audio settings. popUpMenu.addAction(PopUpMenuAction(title: String.menuItemAudioSettings, icon: UIImage(named: "ic_audio_settings")) { (_) in // TODO: Create a full modal VC for audio settings. http://b/63319780 let audioSettingsActionSheetController = UIAlertController(title: String.menuItemAudioSettings, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: String.actionCancel, style: .cancel) audioSettingsActionSheetController.addAction(cancelAction) for soundType in SoundTypeManager.sharedInstance.allSoundTypes { let action = UIAlertAction(title: soundType.name, style: .default) { (_) in sensorCard.toneGenerator.soundType = soundType } audioSettingsActionSheetController.addAction(action) } if UIDevice.current.userInterfaceIdiom == .pad { audioSettingsActionSheetController.modalPresentationStyle = .popover audioSettingsActionSheetController.popoverPresentationController?.sourceView = menuButton audioSettingsActionSheetController.popoverPresentationController?.sourceRect = menuButton.bounds } self.present(audioSettingsActionSheetController, animated: true) }) if !isRecording { // Triggers create/edit. let triggerActionTitle = sensorTriggers.filter { $0.sensorID == sensorCard.sensor.sensorId }.isEmpty ? String.menuItemSetTriggers : String.menuItemEditTriggers popUpMenu.addAction(PopUpMenuAction(title: triggerActionTitle, icon: UIImage(named: "ic_trigger")) { (_) in self.delegate?.observeViewController(self, didPressSetTriggersForSensor: sensorCard.sensor) }) // If there is more than one card, add a close card option. if observeDataSource.shouldAllowCardDeletion { popUpMenu.addAction(PopUpMenuAction(title: String.btnSensorCardClose, icon: UIImage(named: "ic_close")) { (_) in self.removeSensorCardCell(sensorCardCell) }) } } popUpMenu.present(from: self, position: .sourceView(menuButton)) } func sensorCardCellInfoButtonPressed(_ sensorCardCell: SensorCardCell) { guard let indexPath = collectionView?.indexPath(for: sensorCardCell) else { return } let sensorCard = observeDataSource.item(at: indexPath.item) let vc = LearnMoreViewController(sensor: sensorCard.sensor, analyticsReporter: analyticsReporter) if UIDevice.current.userInterfaceIdiom == .pad { vc.modalPresentationStyle = .formSheet } present(vc, animated: true) } func sensorCardCellSensorSettingsButtonPressed(_ cell: SensorCardCell) { showSettings() } func sensorCardCellDidTapStats(_ sensorCardCell: SensorCardCell) { guard let indexPath = collectionView?.indexPath(for: sensorCardCell) else { return } // Toggle display of stats and save state to sensor layout. let sensorCard = observeDataSource.item(at: indexPath.item) let shouldShowStats = !sensorCard.chartController.shouldShowStats sensorCard.chartController.shouldShowStats = shouldShowStats sensorCard.sensorLayout?.shouldShowStatsOverlay = shouldShowStats } // MARK: - ChartControllerDelegate func chartController(_ chartController: ChartController, didUpdateVisibleXAxis visibleAxis: ChartAxis<Int64>) { timeAxisController.visibleAxisChanged(visibleAxis, by: chartController) } func chartController(_ chartController: ChartController, scrollStateChanged isUserScrolling: Bool) { timeAxisController.isUserScrolling = isUserScrolling } func chartControllerDidFinishLoadingData(_ chartController: ChartController) {} func chartController(_ chartController: ChartController, shouldPinToNow: Bool) { timeAxisController.isPinnedToNow = shouldPinToNow } // MARK: - DrawerItemViewController public func setUpDrawerPanner(with drawerViewController: DrawerViewController) { if let collectionView = collectionView { drawerPanner = DrawerPanner(drawerViewController: drawerViewController, scrollView: collectionView) } } public func reset() { collectionView?.scrollToTop() } // MARK: - DrawerPositionListener public func drawerViewController(_ drawerViewController: DrawerViewController, willChangeDrawerPosition position: DrawerPosition) { // If the content offset of the scroll view is within the first cell, scroll to the top when the // drawer position changes to anything but open full. if let collectionView = collectionView, let firstSensorCard = observeDataSource.firstItem { let firstCellHeight = firstSensorCard.cellState.height let isContentOffsetWithinFirstCell = collectionView.contentOffset.y < firstCellHeight if isContentOffsetWithinFirstCell && !drawerViewController.isPositionOpenFull(position) { perform(#selector(setCollectionViewContentOffsetToZero), with: nil, afterDelay: 0.01) } } } public func drawerViewController(_ drawerViewController: DrawerViewController, didChangeDrawerPosition position: DrawerPosition) { updateCollectionViewScrollEnabled() } public func drawerViewController(_ drawerViewController: DrawerViewController, isPanningDrawerView drawerView: DrawerView) {} public func drawerViewController(_ drawerViewController: DrawerViewController, didPanBeyondBounds panDistance: CGFloat) { collectionView?.contentOffset = CGPoint(x: 0, y: panDistance) } // MARK: - RecordingManagerDelegate func recordingManager(_ recordingManager: RecordingManager, didFireVisualTrigger trigger: SensorTrigger, forSensor sensor: Sensor) { guard let indexPath = observeDataSource.indexPath(ofSensor: sensor) else { return } let cell = collectionView?.cellForItem(at: indexPath) as? SensorCardCell cell?.visualTriggerView.triggerFired() } func recordingManager(_ recordingManager: RecordingManager, didFireStartRecordingTrigger trigger: SensorTrigger) { startRecording() } func recordingManager(_ recordingManager: RecordingManager, didFireStopRecordingTrigger trigger: SensorTrigger) { endRecording() } func recordingManager(_ recordingManager: RecordingManager, didFireNoteTrigger trigger: SensorTrigger, forSensor sensor: Sensor, atTimestamp timestamp: Int64) { if observeDataSource.sensorCard(for: sensor) != nil { // TODO: Add note to chart (requires new chart controller method). delegate?.observeViewController(self, didReceiveNoteTrigger: trigger, forSensor: sensor, atTimestamp: timestamp) } } func recordingManager(_ recordingManager: RecordingManager, hasRecordedForDuration duration: Int64) { updateTimerLabel(with: duration) } func recordingManager(_ recordingManager: RecordingManager, didExceedTriggerFireLimitForSensor sensor: Sensor) { delegate?.observeViewController(self, didExceedTriggerFireLimitForSensor: sensor) } // MARK: - ObserveDataSourceDelegate func observeDataSource(_ observeDataSource: ObserveDataSource, sensorStateDidChangeForCard sensorCard: SensorCard) { // This delegate method can be called on a non-main thread. guard Thread.isMainThread else { DispatchQueue.main.async { self.observeDataSource(observeDataSource, sensorStateDidChangeForCard: sensorCard) } return } guard let visibleCells = collectionView?.visibleCells else { return } for case let cell as SensorCardCell in visibleCells { guard let sensor = cell.sensor else { continue } if sensor.sensorId == sensorCard.sensor.sensorId { cell.updateSensorLoadingState() break } } } // MARK: - UIScrollViewDelegate override open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { drawerPanner?.scrollViewWillBeginDragging(scrollView) } override open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { drawerPanner?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } // MARK: - Gesture recognizer @objc func handleCollectionViewPanGesture(_ panGestureRecognizer: UIPanGestureRecognizer) { drawerPanner?.handlePanGesture(panGestureRecognizer) } // MARK: - Notifications @objc func applicationWillResignActive() { updateSensorLayouts() // If there are no sensors recording besides audio and brightness, end recording and prepare an // alert. if recordingManager.isRecording { let otherSensors = observeDataSource.items.filter({ !($0.sensor is AudioSensor || $0.sensor is BrightnessSensor) }) if otherSensors.isEmpty { audioAndBrightnessSensorBackgroundMessageAlert?.dismiss(animated: false) endRecording() showAlert(withTitle: String.recordingStopped, message: String.sensorTypeAudioAndBrightnessRecordingStoppedMessage) } } updateBrightnessSensorListenerIfNecessary(viewVisible: false) for sensorCard in observeDataSource.items { sensorCard.sensor.prepareForBackground() } } @objc func applicationDidBecomeActive() { let isViewOnScreen = view.superview != nil if isViewOnScreen { updateBrightnessSensorListenerIfNecessary(viewVisible: true) } for sensorCard in observeDataSource.items { sensorCard.sensor.prepareForForeground() } } @objc private func applicationWillTerminate() { // If the app is about to terminate, end recording so it will save. if recordingManager.isRecording { endRecording() } } @objc private func localNotificationManagerDidReceiveStopRecordingAction() { endRecording() } @objc private func accessibilityVoiceOverStatusChanged() { updateCollectionViewScrollEnabled() } @objc private func forceEndRecordingForSignOut() { if recordingManager.isRecording { // When a user is forced to sign out, their DB is completely removed along with all of their // data. We need to make sure the recording manager does not also attempt to remove data // asynchronously. endRecording(isCancelled: true, removeCancelledData: false) } } } // swiftlint:enable file_length, type_body_length
41.54416
117
0.702455
de96c55d0dd92e8b33c3c7ddd7b99c4df7d3247c
704
// // ItemListRepository.swift // DataStore // // Created by Tomosuke Okada on 2021/01/30. // import Foundation public enum ItemListRepositoryProvider { public static func provide() -> ItemListRepository { return ItemListRepositoryImpl(apiDataStore: PokeAPIDataStoreProvider.provide()) } } public protocol ItemListRepository { func get(completion: @escaping ((Result<ItemListResponse, Error>) -> Void)) } private struct ItemListRepositoryImpl: ItemListRepository { let apiDataStore: PokeAPIDataStore func get(completion: @escaping ((Result<ItemListResponse, Error>) -> Void)) { self.apiDataStore.request(ItemListAPIRequest(), completion: completion) } }
24.275862
87
0.734375
14b4338577b2968bd9257894a64fd4171f61dab6
8,938
// // AnimationFactory.swift // ThesisApp // // Created by Erik Kümmerling on 16.02.19. // Copyright © 2019 Erik Kümmerling. All rights reserved. // import UIKit import Lottie public enum Direction { case top, right, bottom, left } public class AnimationFactory { public static func fadeOut() -> MagicAnimation { return FadeOutAnimation() } public static func fadeIn() -> MagicAnimation { return FadeInAnimation() } public static func zoomOut() -> MagicAnimation { return ZoomOutAnimation() } public static func zoomIn() -> MagicAnimation { return ZoomInAnimation() } public static func slideOut(to direction: Direction) -> MagicAnimation { switch direction { case .top: return SlideOutToTop() case .right: return SlideOutToRight() case .bottom: return SlideOutToBottom() case .left: return SlideOutToLeft() } } public static func slideIn(from direction: Direction) -> MagicAnimation { switch direction { case .top: return SlideInFromTop() case .right: return SlideInFromRight() case .bottom: return SlideInFromBottom() case .left: return SlideInFromLeft() } } public static func popUp() -> MagicAnimation { return PopUp() } public static func popUpReversed() -> MagicAnimation { return PopUpReversed() } public static func valueUp() -> MagicAnimation { return ValueUpAnimation() } public static func valueDown() -> MagicAnimation { return ValueDownAnimation() } public static func lottie() -> MagicAnimation { return LottieAnimation() } } private class LottieAnimation: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return {} } func customAnimation(view: UIView, duration: Double) { if let lottie = view as? AnimationView { let speed = lottie.animation!.duration / duration lottie.animationSpeed = CGFloat(speed) lottie.play() } } } private class ValueUpAnimation: MagicAnimation { var label: UILabel? var interactive: Bool = false var start: Double = 0 var end: Double = 0 var animationDuration: Double? let animationStartDate = Date() func prepareBeforeAnimation(view: UIView) { if let label = view as? UILabel { self.end = Double(label.text!) ?? 0 label.text = String(start) } } func animation(view: UIView) -> (() -> Void) { return {} } func customAnimation(view: UIView, duration: Double) { animationDuration = Double(duration) if let label = view as? UILabel { self.label = label let displayLink = CADisplayLink(target: self, selector: #selector(handleUpdate)) displayLink.add(to: .main, forMode: .default) } } func updateCustomAnimation(view: UIView, percentComplete: CGFloat) { interactive = true if let label = view as? UILabel { let value = 100 * Double(percentComplete) print("value: \(value), end: \(end), percent: \(percentComplete)") print(value) label.text = "\(Int(value))" } } @objc func handleUpdate() { if !interactive { let now = Date() let elipsedTime = now.timeIntervalSince(animationStartDate) if elipsedTime > animationDuration! { self.label!.text = "\(Int(end))" } else { let percentage = elipsedTime / animationDuration! let value = start + percentage * (end - start) self.label!.text = "\(Int(value))" } } } func animationCompletion(view: UIView) {} } private class ValueDownAnimation: MagicAnimation { var label: UILabel? var start: Double = 0 var end: Double = 0 var animationDuration: Double? let animationStartDate = Date() func animation(view: UIView) -> (() -> Void) { return {} } func customAnimation(view: UIView, duration: Double) { animationDuration = Double(duration) if let label = view as? UILabel, let start = Double(label.text!){ self.label = label self.start = start let displayLink = CADisplayLink(target: self, selector: #selector(handleUpdate)) displayLink.add(to: .main, forMode: .default) } } @objc func handleUpdate() { let now = Date() let elipsedTime = now.timeIntervalSince(animationStartDate) if elipsedTime > animationDuration! { self.label!.text = "\(Int(end))" } else { let percentage = elipsedTime / animationDuration! let value = start - (start * percentage) self.label!.text = "\(Int(value))" } } } private class FadeOutAnimation: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.alpha = 0.0 } } } private class FadeInAnimation: MagicAnimation { func prepareBeforeAnimation(view: UIView) { view.alpha = 0.0 } func animation(view: UIView) -> (() -> Void) { return { view.alpha = 1.0 } } } private class ZoomOutAnimation: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.transform = CGAffineTransform(scaleX: 2.0, y: 2.0) } } } private class ZoomInAnimation: MagicAnimation { func prepareBeforeAnimation(view: UIView) { view.transform = CGAffineTransform(scaleX: 2.0, y: 2.0) } func animation(view: UIView) -> (() -> Void) { return { view.transform = .identity } } } private class SlideOutToTop: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y = -view.frame.height } } } private class SlideOutToRight: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.x = UIScreen.main.bounds.size.width } } } private class SlideOutToBottom: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y = UIScreen.main.bounds.size.height } } } private class SlideOutToLeft: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.x = -view.frame.width } } } private class SlideInFromTop: MagicAnimation { var initialY: CGFloat? func prepareBeforeAnimation(view: UIView) { initialY = view.frame.origin.y view.frame.origin.y = -((view.frame.origin.y >= 0 ? view.frame.origin.y : 0.0) + view.frame.height) } func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y = self.initialY! } } } private class SlideInFromRight: MagicAnimation { var initialX: CGFloat? func prepareBeforeAnimation(view: UIView) { initialX = view.frame.origin.x view.frame.origin.x = UIScreen.main.bounds.size.width } func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.x = self.initialX! } } } private class SlideInFromBottom: MagicAnimation { var initialY: CGFloat? func prepareBeforeAnimation(view: UIView) { initialY = view.frame.origin.y view.frame.origin.y = UIScreen.main.bounds.size.height } func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y = self.initialY! } } } private class SlideInFromLeft: MagicAnimation { var initialX: CGFloat? func prepareBeforeAnimation(view: UIView) { initialX = view.frame.origin.x view.frame.origin.x = -((view.frame.origin.x >= 0 ? view.frame.origin.x : 0.0) + view.frame.width) } func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.x = self.initialX! } } } private class PopUp: MagicAnimation { var initialY: CGFloat? var initialAlpha: CGFloat? func prepareBeforeAnimation(view: UIView) { initialAlpha = view.alpha view.frame.origin.y += 20 view.alpha = 0.0 } func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y -= 20 view.alpha = self.initialAlpha! } } } private class PopUpReversed: MagicAnimation { func animation(view: UIView) -> (() -> Void) { return { view.frame.origin.y += 20 view.alpha = 0.0 } } }
26.443787
107
0.577982
fbb13afbe60bb047f14c1b84c9f2586b7b262f82
1,997
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation /// No-op implementation of the SpanBuilder class PropagatedSpanBuilder: SpanBuilder { private var tracer: Tracer private var isRootSpan: Bool = false private var spanContext: SpanContext? init(tracer: Tracer, spanName: String) { self.tracer = tracer } @discardableResult public func startSpan() -> Span { if spanContext == nil, !isRootSpan { spanContext = OpenTelemetry.instance.contextProvider.activeSpan?.context } return PropagatedSpan(context: spanContext ?? SpanContext.create(traceId: TraceId.random(), spanId: SpanId.random(), traceFlags: TraceFlags(), traceState: TraceState())) } @discardableResult public func setParent(_ parent: Span) -> Self { spanContext = parent.context return self } @discardableResult public func setParent(_ parent: SpanContext) -> Self { spanContext = parent return self } @discardableResult public func setNoParent() -> Self { isRootSpan = true return self } @discardableResult public func addLink(spanContext: SpanContext) -> Self { return self } @discardableResult public func addLink(spanContext: SpanContext, attributes: [String: AttributeValue]) -> Self { return self } @discardableResult public func setSpanKind(spanKind: SpanKind) -> Self { return self } @discardableResult public func setStartTime(time: Date) -> Self { return self } public func setAttribute(key: String, value: AttributeValue) -> Self { return self } func setActive(_ active: Bool) -> Self { return self } }
29.367647
116
0.589384
76802009728c7b520611004590f1a571752d9226
5,262
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ // This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/ import AVFoundation /// Based on the Pink Trombone algorithm by Neil Thapen, this implements a physical /// model of the vocal tract glottal pulse wave. The tract model is based on the /// classic Kelly-Lochbaum /// segmented cylindrical 1d waveguide model, and the glottal pulse wave is a /// LF glottal pulse model. /// /// NOTE: This node is CPU intensitve and will drop packet if your buffer size is /// too short. It requires at least 64 samples on an iPhone X, for example. public class VocalTract: Node, AudioUnitContainer, Tappable, Toggleable { /// Unique four-letter identifier "vocw" public static let ComponentDescription = AudioComponentDescription(generator: "vocw") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Specification details for frequency public static let frequencyDef = NodeParameterDef( identifier: "frequency", name: "Glottal frequency.", address: akGetParameterAddress("VocalTractParameterFrequency"), range: 0.0 ... 22_050.0, unit: .hertz, flags: .default) /// Glottal frequency. @Parameter public var frequency: AUValue /// Specification details for tonguePosition public static let tonguePositionDef = NodeParameterDef( identifier: "tonguePosition", name: "Tongue position (0-1)", address: akGetParameterAddress("VocalTractParameterTonguePosition"), range: 0.0 ... 1.0, unit: .generic, flags: .default) /// Tongue position (0-1) @Parameter public var tonguePosition: AUValue /// Specification details for tongueDiameter public static let tongueDiameterDef = NodeParameterDef( identifier: "tongueDiameter", name: "Tongue diameter (0-1)", address: akGetParameterAddress("VocalTractParameterTongueDiameter"), range: 0.0 ... 1.0, unit: .generic, flags: .default) /// Tongue diameter (0-1) @Parameter public var tongueDiameter: AUValue /// Specification details for tenseness public static let tensenessDef = NodeParameterDef( identifier: "tenseness", name: "Vocal tenseness. 0 = all breath. 1=fully saturated.", address: akGetParameterAddress("VocalTractParameterTenseness"), range: 0.0 ... 1.0, unit: .generic, flags: .default) /// Vocal tenseness. 0 = all breath. 1=fully saturated. @Parameter public var tenseness: AUValue /// Specification details for nasality public static let nasalityDef = NodeParameterDef( identifier: "nasality", name: "Sets the velum size. Larger values of this creates more nasally sounds.", address: akGetParameterAddress("VocalTractParameterNasality"), range: 0.0 ... 1.0, unit: .generic, flags: .default) /// Sets the velum size. Larger values of this creates more nasally sounds. @Parameter public var nasality: AUValue // MARK: - Audio Unit /// Internal Audio Unit for VocalTract public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { [VocalTract.frequencyDef, VocalTract.tonguePositionDef, VocalTract.tongueDiameterDef, VocalTract.tensenessDef, VocalTract.nasalityDef] } /// Create the DSP Refence for this node /// - Returns: DSP Reference public override func createDSP() -> DSPRef { akCreateDSP("VocalTractDSP") } } // MARK: - Initialization /// Initialize this vocal tract node /// /// - Parameters: /// - frequency: Glottal frequency. /// - tonguePosition: Tongue position (0-1) /// - tongueDiameter: Tongue diameter (0-1) /// - tenseness: Vocal tenseness. 0 = all breath. 1=fully saturated. /// - nasality: Sets the velum size. Larger values of this creates more nasally sounds. /// public init( frequency: AUValue = 160.0, tonguePosition: AUValue = 0.5, tongueDiameter: AUValue = 1.0, tenseness: AUValue = 0.6, nasality: AUValue = 0.0 ) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit guard let audioUnit = avAudioUnit.auAudioUnit as? AudioUnitType else { fatalError("Couldn't create audio unit") } self.internalAU = audioUnit self.stop() self.frequency = frequency self.tonguePosition = tonguePosition self.tongueDiameter = tongueDiameter self.tenseness = tenseness self.nasality = nasality } } }
35.795918
108
0.651653
e4b1be8ce84a2b52ed8ce1dedf6ef0327d0a8a94
3,372
import UIKit import Cartography class ChannelMembersCell: UICollectionViewCell { private var data = Data() private struct Data { var members: [[String: Any]] = [] var highlightedIndex: Int = -1 } private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) view.dataSource = self view.delegate = self view.backgroundColor = .white view.alwaysBounceHorizontal = true view.allowsSelection = false view.register(ChannelMemberCell.self, forCellWithReuseIdentifier: String(describing: ChannelMemberCell.self)) return view }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(collectionView) constrain(contentView, collectionView) { (view, collectionView) in collectionView.edges == view.edges } } required convenience init?(coder aDecoder: NSCoder) { self.init(frame: CGRect.zero) } func setData(members: [[String: Any]], highlightedIndex: Int) { data.members = members data.highlightedIndex = highlightedIndex UIView.performWithoutAnimation { collectionView.reloadSections(IndexSet(integer: 0)) } guard 0 ..< members.count ~= highlightedIndex else { return } guard let cell = collectionView.cellForItem(at: IndexPath(item: highlightedIndex, section: 0)) else { return } collectionView.scrollRectToVisible(cell.frame, animated: true) } } extension ChannelMembersCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.members.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: ChannelMemberCell.self), for: indexPath) if let cell = cell as? ChannelMemberCell { cell.setData(member: data.members[indexPath.item]) cell.isSelected = indexPath.item == data.highlightedIndex } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 60, height: collectionView.bounds.size.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets.zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 8 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 8 } }
39.209302
175
0.709668
5da86e07b3ef6807b6670bd8ab29893b5f5f3462
232
// // LandmarksApp.swift // Landmarks // // Created by Muhammad Afkar on 13/08/21. // import SwiftUI @main struct LandmarksApp: App { var body: some Scene { WindowGroup { ContentView() } } }
12.888889
42
0.568966
d562a314a03f9056b9f98528143654601c2391c1
1,231
// // tipcalculatorTests.swift // tipcalculatorTests // // Created by 孙建芬 on 2022/1/12. // import XCTest @testable import tipcalculator class tipcalculatorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } 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 { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
33.27027
130
0.687246
67c0b5dcf3ff6430de28b382316e18f2a43a02b4
331
// // DeviceEvent.swift // QminderAPI // // Created by Kristaps Grinbergs on 13/06/2018. // Copyright © 2018 Kristaps Grinbergs. All rights reserved. // import Foundation /// Device events public enum DeviceWebsocketEvent: String { /// Overview monitor changed case overviewMonitorChange = "OVERVIEW_MONITOR_CHANGE" }
19.470588
61
0.734139
87c72c3cc5b7a9f0024d4621163146057b0e2e7b
692
#if os(iOS) import UIKit extension UIView { func g_addShadow() { layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: 0, height: 1) layer.shadowRadius = 1 } func g_addRoundBorder() { layer.borderWidth = 1 layer.borderColor = Config.Grid.FrameView.borderColor.cgColor layer.cornerRadius = 3 clipsToBounds = true } func g_quickFade(visible: Bool = true) { UIView.animate(withDuration: 0.1, animations: { self.alpha = visible ? 1 : 0 }) } func g_fade(visible: Bool) { UIView.animate(withDuration: 0.25, animations: { self.alpha = visible ? 1 : 0 }) } } #endif
19.771429
65
0.648844
d734ef473a73fed4c0b539f7eb6d6e3e66eb3fa4
5,308
// // Copyright (c) Vatsal Manot // #if os(iOS) || os(macOS) || targetEnvironment(macCatalyst) #if targetEnvironment(macCatalyst) import AppKit #endif import ObjectiveC import Swift import SwiftUI #if canImport(UIKit) import UIKit #endif /// A toolbar item. public struct OldToolbarItem { public enum Content { #if os(iOS) || targetEnvironment(macCatalyst) case systemSymbol(SFSymbolName) case systemItem(UIBarButtonItem.SystemItem) #endif #if os(macOS) case view(AnyView) case cocoaImage(NSImage) case cocoaView(NSView) #endif case none } private(set) var itemIdentifier: String private(set) var content: Content private(set) var action: () -> () = { } private(set) var label: String? private(set) var title: String? private(set) var isBordered: Bool = false public init( itemIdentifier: String, content: Content = .none ) { self.itemIdentifier = itemIdentifier self.content = content } #if os(macOS) public init<Content: View>( itemIdentifier: String, @ViewBuilder content: () -> Content ) { self.itemIdentifier = itemIdentifier self.content = .view(content().eraseToAnyView()) } #endif } extension OldToolbarItem { static var targetAssociationKey: Void = () #if os(macOS) || targetEnvironment(macCatalyst) func toNSToolbarItem() -> NSToolbarItem { var result = NSToolbarItem(itemIdentifier: .init(rawValue: itemIdentifier)) let target = NSToolbarItem._ActionTarget(action: action) switch content { #if os(macOS) case let .view(view): result.view = NSHostingView(rootView: view) case let .cocoaImage(image): result.image = image case let .cocoaView(view): result.view = view #endif #if targetEnvironment(macCatalyst) case let .systemSymbol(name): result.image = AppKitOrUIKitImage(systemName: name.rawValue) case let .systemItem(item): do { result = NSToolbarItem( itemIdentifier: .init(rawValue: itemIdentifier), barButtonItem: UIBarButtonItem( barButtonSystemItem: item, target: target, action: #selector(NSToolbarItem._ActionTarget.performAction) ) ) } #endif case .none: break } objc_setAssociatedObject(result, &OldToolbarItem.targetAssociationKey, target, .OBJC_ASSOCIATION_RETAIN) result.action = #selector(NSToolbarItem._ActionTarget.performAction) result.isEnabled = true result.target = target if let label = label { result.label = label } if let title = title { result.title = title } return result } #endif } // MARK: - Protocol Conformances - extension OldToolbarItem: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.itemIdentifier == rhs.itemIdentifier } } // MARK: - API - extension OldToolbarItem { public func content(_ content: Content) -> Self { var result = self result.content = content return result } public func action(_ action: @escaping () -> ()) -> Self { var result = self result.action = action return result } public func label(_ label: String) -> Self { var result = self result.label = label return result } public func title(_ title: String) -> Self { var result = self result.title = title return result } public func bordered(_ isBordered: Bool) -> Self { var result = self result.isBordered = isBordered return result } } extension View { #if os(macOS) public func toolbarItem(withIdentifier identifier: String) -> OldToolbarItem { .init(itemIdentifier: identifier, content: .view(.init(self))) } #endif public func toolbarItems(_ toolbarItems: OldToolbarItem...) -> some View { preference(key: OldToolbarViewItemsPreferenceKey.self, value: toolbarItems) } } // MARK: - Auxiliary Implementation - public struct OldToolbarViewItemsPreferenceKey: PreferenceKey { public typealias Value = [OldToolbarItem] public static var defaultValue: Value { [] } public static func reduce(value: inout Value, nextValue: () -> Value) { } } #if os(macOS) || targetEnvironment(macCatalyst) extension NSToolbarItem { class _ActionTarget: NSObject { private let action: () -> () init(action: @escaping () -> ()) { self.action = action } @objc(performAction) func performAction() { action() } } } #endif #endif
24.348624
112
0.564431
7935ff0d1edc096a1885a08db39b52bee2f4ed7c
1,598
import Foundation func expandTheNumber(_ number: Int) -> [Int] { // To be honest I found alot of help for this one, and it is very pretty, but, taking these concepts, I wanted to see what I could come up with on my own. var numberArray: [Int] = [] let ones = number % 10 let tens = (number - ones) % 100 let hundreds = (number - tens - ones) % 1000 let thousands = (number - hundreds - tens - ones) % 10000 let tenThousands = (number - hundreds - tens - ones) % 100000 if number > 9999 { numberArray.append(tenThousands) } if number > 999 { numberArray.append(thousands) } if number > 99 { numberArray.append(hundreds) } if number > 9 { numberArray.append(tens) } numberArray.append(ones) // And this is the ugly and ucompleted version of what I could conjure up. Almost there. if number > 9 { let newNumber = number % 10 numberArray.append(newNumber) } if number > 99 { let newNumber = (number - (number % 10)) % 100 numberArray.append(newNumber) } if number > 999 { let newNumber = ((number - (number % 100)) - (number % 10)) % 1000 numberArray.append(newNumber) } return numberArray.reversed() } expandTheNumber(199) // [100, 90, 9] expandTheNumber(100) // [100, 0, 0] expandTheNumber(0) // [0] expandTheNumber(562) // [500, 60, 2] expandTheNumber(5280) // [5000, 200, 80, 0] expandTheNumber(560) // [500, 60, 0]
30.150943
158
0.575094
9c760fd884a27ed02f477469619633836dc27705
17,591
// // FeedWranglerAccountDelegate.swift // Account // // Created by Jonathan Bennett on 2019-08-29. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Articles import RSCore import RSParser import RSWeb import SyncDatabase import os.log final class FeedWranglerAccountDelegate: AccountDelegate { var behaviors: AccountBehaviors = [] var isOPMLImportInProgress = false var server: String? = FeedWranglerConfig.clientPath var credentials: Credentials? { didSet { caller.credentials = credentials } } var accountMetadata: AccountMetadata? var refreshProgress = DownloadProgress(numberOfTasks: 0) private let caller: FeedWranglerAPICaller private let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Feed Wrangler") private let database: SyncDatabase init(dataFolder: String, transport: Transport?) { if let transport = transport { caller = FeedWranglerAPICaller(transport: transport) } else { let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData sessionConfiguration.timeoutIntervalForRequest = 60.0 sessionConfiguration.httpShouldSetCookies = false sessionConfiguration.httpCookieAcceptPolicy = .never sessionConfiguration.httpMaximumConnectionsPerHost = 1 sessionConfiguration.httpCookieStorage = nil sessionConfiguration.urlCache = nil if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } let session = URLSession(configuration: sessionConfiguration) caller = FeedWranglerAPICaller(transport: session) } database = SyncDatabase(databaseFilePath: dataFolder.appending("/DB.sqlite3")) } func accountWillBeDeleted(_ account: Account) { caller.logout() { _ in } } func refreshAll(for account: Account, completion: @escaping (Result<Void, Error>) -> Void) { refreshProgress.addToNumberOfTasksAndRemaining(6) self.refreshCredentials(for: account) { self.refreshProgress.completeTask() self.refreshSubscriptions(for: account) { result in self.refreshProgress.completeTask() switch result { case .success: self.sendArticleStatus(for: account) { result in self.refreshProgress.completeTask() switch result { case .success: self.refreshArticleStatus(for: account) { result in self.refreshProgress.completeTask() switch result { case .success: self.refreshArticles(for: account) { result in self.refreshProgress.completeTask() switch result { case .success: self.refreshMissingArticles(for: account) { result in self.refreshProgress.completeTask() switch result { case .success: DispatchQueue.main.async { completion(.success(())) } case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } } } func refreshCredentials(for account: Account, completion: @escaping (() -> Void)) { os_log(.debug, log: log, "Refreshing credentials...") // MARK: TODO credentials = try? account.retrieveCredentials(type: .feedWranglerToken) completion() } func refreshSubscriptions(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) { os_log(.debug, log: log, "Refreshing subscriptions...") caller.retrieveSubscriptions { result in switch result { case .success(let subscriptions): self.syncFeeds(account, subscriptions) completion(.success(())) case .failure(let error): os_log(.debug, log: self.log, "Failed to refresh subscriptions: %@", error.localizedDescription) completion(.failure(error)) } } } func refreshArticles(for account: Account, page: Int = 0, completion: @escaping ((Result<Void, Error>) -> Void)) { os_log(.debug, log: log, "Refreshing articles, page: %d...", page) caller.retrieveFeedItems(page: page) { result in switch result { case .success(let items): self.syncFeedItems(account, items) { if items.count == 0 { completion(.success(())) } else { self.refreshArticles(for: account, page: (page + 1), completion: completion) } } case .failure(let error): completion(.failure(error)) } } } func refreshMissingArticles(for account: Account, completion: @escaping ((Result<Void, Error>)-> Void)) { account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { articleIDsResult in func process(_ fetchedArticleIDs: Set<String>) { os_log(.debug, log: self.log, "Refreshing missing articles...") let group = DispatchGroup() let articleIDs = Array(fetchedArticleIDs) let chunkedArticleIDs = articleIDs.chunked(into: 100) for chunk in chunkedArticleIDs { group.enter() self.caller.retrieveEntries(articleIDs: chunk) { result in switch result { case .success(let entries): self.syncFeedItems(account, entries) { group.leave() } case .failure(let error): os_log(.error, log: self.log, "Refresh missing articles failed: %@", error.localizedDescription) group.leave() } } } group.notify(queue: DispatchQueue.main) { self.refreshProgress.completeTask() os_log(.debug, log: self.log, "Done refreshing missing articles.") completion(.success(())) } } switch articleIDsResult { case .success(let articleIDs): process(articleIDs) case .failure(let databaseError): self.refreshProgress.completeTask() completion(.failure(databaseError)) } } } func sendArticleStatus(for account: Account, completion: @escaping VoidResultCompletionBlock) { os_log(.debug, log: log, "Sending article status...") database.selectForProcessing { result in func processStatuses(_ syncStatuses: [SyncStatus]) { let articleStatuses = Dictionary(grouping: syncStatuses, by: { $0.articleID }) let group = DispatchGroup() articleStatuses.forEach { articleID, statuses in group.enter() self.caller.updateArticleStatus(articleID, statuses) { group.leave() } } group.notify(queue: DispatchQueue.main) { os_log(.debug, log: self.log, "Done sending article statuses.") completion(.success(())) } } switch result { case .success(let syncStatuses): processStatuses(syncStatuses) case .failure(let databaseError): completion(.failure(databaseError)) } } } func refreshArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) { os_log(.debug, log: log, "Refreshing article status...") let group = DispatchGroup() group.enter() caller.retrieveAllUnreadFeedItems { result in switch result { case .success(let items): self.syncArticleReadState(account, items) group.leave() case .failure(let error): os_log(.info, log: self.log, "Retrieving unread entries failed: %@.", error.localizedDescription) group.leave() } } // starred group.enter() caller.retrieveAllStarredFeedItems { result in switch result { case .success(let items): self.syncArticleStarredState(account, items) group.leave() case .failure(let error): os_log(.info, log: self.log, "Retrieving starred entries failed: %@.", error.localizedDescription) group.leave() } } group.notify(queue: DispatchQueue.main) { os_log(.debug, log: self.log, "Done refreshing article statuses.") completion(.success(())) } } func importOPML(for account: Account, opmlFile: URL, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func addFolder(for account: Account, name: String, completion: @escaping (Result<Folder, Error>) -> Void) { fatalError() } func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func createWebFeed(for account: Account, url: String, name: String?, container: Container, completion: @escaping (Result<WebFeed, Error>) -> Void) { refreshProgress.addToNumberOfTasksAndRemaining(2) self.refreshCredentials(for: account) { self.refreshProgress.completeTask() self.caller.addSubscription(url: url) { result in self.refreshProgress.completeTask() switch result { case .success(let subscription): self.addFeedWranglerSubscription(account: account, subscription: subscription, name: name, container: container, completion: completion) case .failure(let error): DispatchQueue.main.async { completion(.failure(error)) } } } } } private func addFeedWranglerSubscription(account: Account, subscription sub: FeedWranglerSubscription, name: String?, container: Container, completion: @escaping (Result<WebFeed, Error>) -> Void) { DispatchQueue.main.async { let feed = account.createWebFeed(with: sub.title, url: sub.feedURL, webFeedID: String(sub.feedID), homePageURL: sub.siteURL) account.addWebFeed(feed, to: container) { result in switch result { case .success: if let name = name { account.renameWebFeed(feed, to: name) { result in switch result { case .success: self.initialFeedDownload(account: account, feed: feed, completion: completion) case .failure(let error): completion(.failure(error)) } } } else { self.initialFeedDownload(account: account, feed: feed, completion: completion) } case .failure(let error): completion(.failure(error)) } } } } private func initialFeedDownload(account: Account, feed: WebFeed, completion: @escaping (Result<WebFeed, Error>) -> Void) { self.caller.retrieveFeedItems(page: 0, feed: feed) { results in switch results { case .success(let entries): self.syncFeedItems(account, entries) { DispatchQueue.main.async { completion(.success(feed)) } } case .failure(let error): DispatchQueue.main.async { completion(.failure(error)) } } } } func renameWebFeed(for account: Account, with feed: WebFeed, to name: String, completion: @escaping (Result<Void, Error>) -> Void) { refreshProgress.addToNumberOfTasksAndRemaining(2) self.refreshCredentials(for: account) { self.refreshProgress.completeTask() self.caller.renameSubscription(feedID: feed.webFeedID, newName: name) { result in self.refreshProgress.completeTask() switch result { case .success: DispatchQueue.main.async { feed.editedName = name completion(.success(())) } case .failure(let error): DispatchQueue.main.async { let wrappedError = AccountError.wrappedError(error: error, account: account) completion(.failure(wrappedError)) } } } } } func addWebFeed(for account: Account, with feed: WebFeed, to container: Container, completion: @escaping (Result<Void, Error>) -> Void) { // just add to account, folders are not supported DispatchQueue.main.async { account.addFeedIfNotInAnyFolder(feed) completion(.success(())) } } func removeWebFeed(for account: Account, with feed: WebFeed, from container: Container, completion: @escaping (Result<Void, Error>) -> Void) { refreshProgress.addToNumberOfTasksAndRemaining(2) self.refreshCredentials(for: account) { self.refreshProgress.completeTask() self.caller.removeSubscription(feedID: feed.webFeedID) { result in self.refreshProgress.completeTask() switch result { case .success: DispatchQueue.main.async { account.clearWebFeedMetadata(feed) account.removeWebFeed(feed) completion(.success(())) } case .failure(let error): DispatchQueue.main.async { let wrappedError = AccountError.wrappedError(error: error, account: account) completion(.failure(wrappedError)) } } } } } func moveWebFeed(for account: Account, with feed: WebFeed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func restoreWebFeed(for account: Account, feed: WebFeed, container: Container, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) { fatalError() } func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool) -> Set<Article>? { let syncStatuses = articles.map { SyncStatus(articleID: $0.articleID, key: statusKey, flag: flag)} database.insertStatuses(syncStatuses) database.selectPendingCount { result in if let count = try? result.get(), count > 0 { self.sendArticleStatus(for: account) { _ in } } } return try? account.update(articles, statusKey: statusKey, flag: flag) } func accountDidInitialize(_ account: Account) { credentials = try? account.retrieveCredentials(type: .feedWranglerToken) } static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: @escaping (Result<Credentials?, Error>) -> Void) { let caller = FeedWranglerAPICaller(transport: transport) caller.credentials = credentials caller.validateCredentials() { result in DispatchQueue.main.async { completion(result) } } } // MARK: Suspend and Resume (for iOS) /// Suspend all network activity func suspendNetwork() { caller.cancelAll() } /// Suspend the SQLLite databases func suspendDatabase() { database.suspend() } /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { database.resume() } } // MARK: Private private extension FeedWranglerAccountDelegate { func syncFeeds(_ account: Account, _ subscriptions: [FeedWranglerSubscription]) { assert(Thread.isMainThread) let feedIds = subscriptions.map { String($0.feedID) } let feedsToRemove = account.topLevelWebFeeds.filter { !feedIds.contains($0.webFeedID) } account.removeFeeds(feedsToRemove) var subscriptionsToAdd = Set<FeedWranglerSubscription>() subscriptions.forEach { subscription in let subscriptionId = String(subscription.feedID) if let feed = account.existingWebFeed(withWebFeedID: subscriptionId) { feed.name = subscription.title feed.editedName = nil feed.homePageURL = subscription.siteURL feed.externalID = nil // MARK: TODO What should this be? } else { subscriptionsToAdd.insert(subscription) } } subscriptionsToAdd.forEach { subscription in let feedId = String(subscription.feedID) let feed = account.createWebFeed(with: subscription.title, url: subscription.feedURL, webFeedID: feedId, homePageURL: subscription.siteURL) feed.externalID = nil account.addWebFeed(feed) } } func syncFeedItems(_ account: Account, _ feedItems: [FeedWranglerFeedItem], completion: @escaping VoidCompletionBlock) { let parsedItems = feedItems.map { (item: FeedWranglerFeedItem) -> ParsedItem in let itemID = String(item.feedItemID) // let authors = ... let parsedItem = ParsedItem(syncServiceID: itemID, uniqueID: itemID, feedURL: String(item.feedID), url: nil, externalURL: item.url, title: item.title, contentHTML: item.body, contentText: nil, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: item.publishedDate, dateModified: item.updatedDate, authors: nil, tags: nil, attachments: nil) return parsedItem } let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { $0.feedURL }).mapValues { Set($0) } account.update(webFeedIDsAndItems: feedIDsAndItems, defaultRead: true) { _ in completion() } } func syncArticleReadState(_ account: Account, _ unreadFeedItems: [FeedWranglerFeedItem]) { let unreadServerItemIDs = Set(unreadFeedItems.map { String($0.feedItemID) }) account.fetchUnreadArticleIDs { articleIDsResult in guard let unreadLocalItemIDs = try? articleIDsResult.get() else { return } account.markAsUnread(unreadServerItemIDs) let readItemIDs = unreadLocalItemIDs.subtracting(unreadServerItemIDs) account.markAsRead(readItemIDs) } } func syncArticleStarredState(_ account: Account, _ starredFeedItems: [FeedWranglerFeedItem]) { let starredServerItemIDs = Set(starredFeedItems.map { String($0.feedItemID) }) account.fetchStarredArticleIDs { articleIDsResult in guard let starredLocalItemIDs = try? articleIDsResult.get() else { return } account.markAsStarred(starredServerItemIDs) let unstarredItemIDs = starredLocalItemIDs.subtracting(starredServerItemIDs) account.markAsUnstarred(unstarredItemIDs) } } func syncArticleState(_ account: Account, key: ArticleStatus.Key, flag: Bool, serverFeedItems: [FeedWranglerFeedItem]) { let _ /*serverFeedItemIDs*/ = serverFeedItems.map { String($0.feedID) } // todo generalize this logic } }
31.52509
355
0.696151
6240e343483fa8810a9bda594bc95755dc2471d5
275
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var message = "Hello, world" print(message) var a = 10 var b = 5 var total = a+b print(total) if (total < 20){ print("hello") }
11.458333
52
0.552727
39df3403ac3f66e2a512c3a794a90a1c13ce306e
4,379
// // OvalProgressLayerView.swift // CarLens // import UIKit final class OvalProgressLayerView: View { private enum Constants { static let animationKey = "strokeEnd" static let fullOvalStartAngle: CGFloat = 3/2 * .pi } private let startAngle: CGFloat private let endAngle: CGFloat private let progressStrokeColor: UIColor private let trackStrokeColor: UIColor private let lineWidth: CGFloat private let animationDuration: Double private let progressLayer = CAShapeLayer() /// Initializes the view with given angles and stroke color /// /// - Parameters: /// - startAngle: Starting angle of layer /// - endAngle: Ending angle of layer /// - animationDuration: Duration of the progress animation /// - lineWidth: Width of line /// - progressStrokeColor: Color of progress stroke /// - trackStrokeColor: Color of track stroke init(startAngle: CGFloat, endAngle: CGFloat, animationDuration: Double = 0.5, lineWidth: CGFloat = 6, progressStrokeColor: UIColor, trackStrokeColor: UIColor = .crProgressDarkGray) { self.startAngle = startAngle self.endAngle = endAngle self.animationDuration = animationDuration self.lineWidth = lineWidth self.progressStrokeColor = progressStrokeColor self.trackStrokeColor = trackStrokeColor super.init() } /// - SeeAlso: UIView.layoutSubviews() override func layoutSubviews() { super.layoutSubviews() drawCustomLayer() } } extension OvalProgressLayerView { /// Set progress value either animated or not animated func set(progress: Double, animated: Bool) { guard animated else { progressLayer.isHidden = progress == 0 CATransaction.begin() CATransaction.setDisableActions(true) progressLayer.strokeEnd = CGFloat(progress) CATransaction.commit() return } progressLayer.isHidden = false let initialAnimation = CABasicAnimation(keyPath: Constants.animationKey) initialAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) initialAnimation.toValue = progress initialAnimation.duration = animationDuration initialAnimation.fillMode = CAMediaTimingFillMode.forwards initialAnimation.isRemovedOnCompletion = false progressLayer.add(initialAnimation, forKey: "PartOvalProgressView.ProgressLayer.animation") } private func drawCustomLayer() { let circularPath = UIBezierPath(arcCenter: center, radius: bounds.height / 2.2, startAngle: startAngle, endAngle: endAngle, clockwise: true) let trackLayer = CAShapeLayer() trackLayer.path = circularPath.cgPath trackLayer.strokeColor = trackStrokeColor.cgColor trackLayer.lineWidth = lineWidth trackLayer.fillColor = UIColor.clear.cgColor trackLayer.lineCap = CAShapeLayerLineCap.round layer.addSublayer(trackLayer) progressLayer.path = circularPath.cgPath progressLayer.strokeColor = progressStrokeColor.cgColor progressLayer.lineWidth = lineWidth progressLayer.fillColor = UIColor.clear.cgColor progressLayer.lineCap = CAShapeLayerLineCap.round let gradientLayer = generateGradient() gradientLayer.mask = progressLayer layer.addSublayer(gradientLayer) } private func generateGradient() -> CAGradientLayer { let gradientLayer = CAGradientLayer() /// Checks if start angle is indicating that it is full oval instead of of partial oval progress view if startAngle == Constants.fullOvalStartAngle { gradientLayer.startPoint = CGPoint(x: 1, y: 0.5) gradientLayer.endPoint = CGPoint(x: 0, y: 0.5) } else { gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) } gradientLayer.colors = [UIColor.crShadowOrange.cgColor, UIColor.crDeepOrange.cgColor] gradientLayer.frame = bounds return gradientLayer } }
34.480315
109
0.653117
14ac5a4a986eccc488bd5a9e1e658d5515ac1b87
2,524
// // PKAutoListView.swift // PKAutofillTextField_Example // // Created by Praveen Kumar Shrivastava on 19/09/18. // Copyright © 2018 CocoaPods. All rights reserved. // import Foundation import UIKit public protocol PKAutoListViewControllerDelegate: class { func selectedValue(value: String) func removeItem(value: String) } open class PKAutoListViewController:UITableViewController { var items = Set<String>() weak var delegate: PKAutoListViewControllerDelegate? required public init(delegate: PKAutoListViewControllerDelegate) { self.delegate = delegate super.init(style: .plain) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // print("number of records \(lists.count)") return items.count } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) for (index, element) in items.enumerated() { if indexPath.row == index { cell.textLabel!.text = element } } return cell } open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { for (index, element) in items.enumerated() { if indexPath.row == index { self.deleteRow(tableView, forRowAt: indexPath, element: element) } } } } private func deleteRow(_ tableView: UITableView, forRowAt indexPath: IndexPath, element: String) { items.remove(element) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) delegate?.removeItem(value: element) } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { for (index, element) in items.enumerated() { if indexPath.row == index { delegate?.selectedValue(value: element) } } } }
32.779221
141
0.642235
d6f87ea1a292104817923584a1d1a1593786a25c
827
// // TodayViewController.swift // Widget // // Created by Jean Haberer on 15/07/2020. // Copyright © 2020 CocoaPods. All rights reserved. // import UIKit import NotificationCenter import Faberbabel class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet private var label: UILabel! @IBOutlet private var button: UIButton! override func viewDidLoad() { super.viewDidLoad() guard let url = URL(string: "base_url") else { return } Faberbabel.configure( projectId: "project_id", baseURL: url, appGroupIdentifier: "group.faberbabel.com" ) } @IBAction private func localize() { label.text = "hello_world_title".fb_translation button.setTitle("localize_button".fb_translation, for: .normal) } }
23.628571
71
0.663845
5da7f5a9adff2c3758b8cc8e44a935ae434b3894
217
// // SSController.swift // SpeedySwift // // Created by 2020 on 2020/11/27. // import UIKit open class SSController:NSObject{ var view:UIView! public init(view:UIView) { self.view = view } }
13.5625
34
0.626728
f9499adcfc74539aff4b43fdc11b4e42b80b3c8e
2,344
import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. backgroundTask.setTaskCompletedWithSnapshot(false) case let snapshotTask as WKSnapshotRefreshBackgroundTask: // Snapshot tasks have a unique completion call, make sure to set your expiration date snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // Be sure to complete the connectivity task once you’re done. connectivityTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // Be sure to complete the URL session task once you’re done. urlSessionTask.setTaskCompletedWithSnapshot(false) default: // make sure to complete unhandled task types task.setTaskCompletedWithSnapshot(false) } } } }
54.511628
285
0.698805
eba5098f02143d774e74be52363c72d3547fb031
3,980
// // CameraViewController+Constraints.swift // GiniCapture // // Created by Enrique del Pozo Gómez on 1/26/18. // import UIKit extension CameraViewController { func addConstraints() { addPreviewViewConstraints() addControlsViewConstraints() } fileprivate func addPreviewViewConstraints() { if UIDevice.current.isIpad { Constraints.active(item: cameraPreviewViewController.view, attr: .top, relatedBy: .equal, to: self.view, attr: .top) Constraints.active(item: cameraPreviewViewController.view, attr: .bottom, relatedBy: .equal, to: self.view, attr: .bottom) Constraints.active(item: cameraPreviewViewController.view, attr: .leading, relatedBy: .equal, to: self.view, attr: .leading) Constraints.active(item: cameraPreviewViewController.view, attr: .trailing, relatedBy: .equal, to: cameraButtonsViewController.view, attr: .leading) } else { // lower priority constraints - will make the preview "want" to get bigger Constraints.active(item: cameraPreviewViewController.view, attr: .top, relatedBy: .equal, to: self.view, attr: .top) Constraints.active(item: cameraPreviewViewController.view, attr: .leading, relatedBy: .equal, to: self.view, attr: .leading) Constraints.active(item: cameraPreviewViewController.view, attr: .trailing, relatedBy: .equal, to: self.view, attr: .trailing) Constraints.active(item: cameraPreviewViewController.view, attr: .bottom, relatedBy: .equal, to: cameraButtonsViewController.view, attr: .top) } } fileprivate func addControlsViewConstraints() { if UIDevice.current.isIpad { Constraints.active(item: cameraButtonsViewController.view, attr: .width, relatedBy: .equal, to: nil, attr: .notAnAttribute, constant: 102) Constraints.active(item: cameraButtonsViewController.view, attr: .top, relatedBy: .equal, to: self.view, attr: .top) Constraints.active(item: cameraButtonsViewController.view, attr: .trailing, relatedBy: .equal, to: self.view, attr: .trailing) Constraints.active(item: cameraButtonsViewController.view, attr: .bottom, relatedBy: .equal, to: self.view, attr: .bottom) Constraints.active(item: cameraButtonsViewController.view, attr: .leading, relatedBy: .equal, to: cameraPreviewViewController.view, attr: .trailing, priority: 750) } else { Constraints.active(item: cameraButtonsViewController.view, attr: .height, relatedBy: .equal, to: nil, attr: .notAnAttribute, constant: 102) Constraints.active(item: cameraButtonsViewController.view, attr: .top, relatedBy: .equal, to: cameraPreviewViewController.view, attr: .bottom) Constraints.active(item: cameraButtonsViewController.view, attr: .bottom, relatedBy: .equal, to: view.safeAreaLayoutGuide, attr: .bottom) Constraints.active(item: cameraButtonsViewController.view, attr: .trailing, relatedBy: .equal, to: self.view, attr: .trailing) Constraints.active(item: cameraButtonsViewController.view, attr: .leading, relatedBy: .equal, to: self.view, attr: .leading) } } }
54.520548
113
0.566834
03d8d201a38bb509c66fcb7381c5a50230ffd389
1,385
// // Created by Esteban Torres on 21.04.17. // Copyright (c) 2017 Esteban Torres. All rights reserved. // import Foundation import XCTest @testable import MammutAPI public class AttachmentTests: XCTestCase { func test_sameAttachments_equal() { let subject1 = AttachmentTests.makeAttachment() let subject2 = AttachmentTests.makeAttachment() XCTAssertEqual(subject1, subject2) } func test_differentAttachments_notEqual() { let subject1 = AttachmentTests.makeAttachment(id: #line) let subject2 = AttachmentTests.makeAttachment(id: #line) XCTAssertNotEqual(subject1, subject2) } } // MARK: - Linux Support extension AttachmentTests { static var allTests: [(String, (AttachmentTests) -> () throws -> Void)] { return [ ("test_sameAttachments_equal", test_sameAttachments_equal), ("test_differentAttachments_notEqual", test_differentAttachments_notEqual) ] } } // MARK: Test Helpers fileprivate extension AttachmentTests { static func makeAttachment(id: Int = Int.max) -> Attachment { return Attachment( id: id, type: .image, url: URL(string: "www.example.com")!, remoteURL: nil, previewURL: URL(string: "www.example.com")!, textURL: nil ) } }
28.265306
90
0.636101
0310ba5c855025e0ac47b843726989cfc1c45446
4,585
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension IBPortalApi.Portfolio { /** Account Alloction (All Accounts) Similar to /portfolio/{accountId}/allocation but returns a consolidated view of of all the accounts returned by /portfolio/accounts. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint. */ public enum PostPortfolioAllocation { public static let service = APIService<Response>(id: "postPortfolioAllocation", tag: "Portfolio", method: "POST", path: "/portfolio/allocation", hasBody: true, securityRequirements: []) public final class Request: APIRequest<Response> { /** Similar to /portfolio/{accountId}/allocation but returns a consolidated view of of all the accounts returned by /portfolio/accounts. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint. */ public struct Body: APIModel { public let acctIds: [String]? public init(acctIds: [String]? = nil) { self.acctIds = acctIds } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) acctIds = try container.decodeArrayIfPresent("acctIds") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(acctIds, forKey: "acctIds") } } public struct Options { public var acctIds: [String]? public init(acctIds: [String]? = nil) { self.acctIds = acctIds } } public var options: Options public var body: Body public init(body: Body, options: Options, encoder: RequestEncoder? = nil) { self.body = body self.options = options super.init(service: PostPortfolioAllocation.service) { defaultEncoder in return try (encoder ?? defaultEncoder).encode(body) } } /// convenience initialiser so an Option doesn't have to be created public convenience init(acctIds: [String]? = nil, body: Body) { let options = Options(acctIds: acctIds) self.init(body: body, options: options) } public override var formParameters: [String: Any] { var params: [String: Any] = [:] if let acctIds = options.acctIds { params["acctIds"] = acctIds } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = IBAllocations /** returns an object of three different allocations */ case status200(IBAllocations) public var success: IBAllocations? { switch self { case .status200(let response): return response } } public var response: Any { switch self { case .status200(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 } } public var successful: Bool { switch self { case .status200: return true } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(IBAllocations.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: 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 } } } }
34.734848
236
0.544166
9c900470bc6cb982d74420a78d6a9c65489656ae
4,572
// // StoreView.swift // Simplists // // Created by Tom Hartnett on 12/20/20. // import SimplistsKit import SwiftUI struct StoreView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @EnvironmentObject var storeDataSource: StoreDataSource @State private var purchaseStatusMessage: String? @State private var showPurchasedView = false @State private var showCannotPurchaseView = false var freeLimitMessage: String? var body: some View { ScrollView { VStack(alignment: .leading) { HStack { Text("Snaplists Premium") .font(.system(size: 24, weight: .semibold)) Spacer() Button(action: { presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: "xmark") .font(.system(size: 24)) .foregroundColor(Color("TextSecondary")) }) } if let message = freeLimitMessage { ErrorMessageView(message: message) } if !storeDataSource.isAuthorizedForPayments { ErrorMessageView(message: "Not authorized to make purchases.".localize()) } if let message = purchaseStatusMessage { ErrorMessageView(message: message) } Text("store-header-text") .padding(.top, 15) .fixedSize(horizontal: false, vertical: true) HStack { ZStack { PurchaseButtonsView() .disabled(storeDataSource.hasPurchasedIAP || !storeDataSource.isAuthorizedForPayments) PurchasedView() .opacity(showPurchasedView ? 1.0 : 0.0) CannotPurchaseView() .opacity(showCannotPurchaseView ? 1.0 : 0.0) } .padding([.top, .bottom], 50) .frame(maxWidth: .infinity) } FeaturesView(headerText: "Premium features".localize(), bulletPoints: [ "Unlimited number of lists".localize(), "Unlimited number of items".localize() ]) .padding(.bottom, 15) FeaturesView(headerText: "Free limits".localize(), bulletPoints: [ String.localizedStringWithFormat( "free limit list count".localize(), FreeLimits.numberOfLists.limit), String.localizedStringWithFormat( "free limit item count".localize(), FreeLimits.numberOfItems.limit) ]) .padding(.bottom, 15) Text("store-support-the-app-text") Spacer() } .padding() .onReceive(storeDataSource.objectWillChange.eraseToAnyPublisher()) { displayPurchaseStatus() } .onAppear { displayPurchaseStatus() } } } func displayPurchaseStatus() { switch storeDataSource.premiumIAPPurchaseStatus { case .purchased: withAnimation(Animation.easeIn.delay(0.5)) { showPurchasedView.toggle() } purchaseStatusMessage = nil case .failed(errorMessage: let errorMessage): purchaseStatusMessage = errorMessage case .deferred: purchaseStatusMessage = "Purchase is pending approval.".localize() default: purchaseStatusMessage = nil } if !storeDataSource.isAuthorizedForPayments { withAnimation(Animation.easeIn.delay(0.5)) { showCannotPurchaseView.toggle() } } } } struct StoreView_Previews: PreviewProvider { static var previews: some View { let client = StoreClient() let dataSource = StoreDataSource(service: client) let message = "You've reached the maximum number of lists in the free version of the app." StoreView(freeLimitMessage: message).environmentObject(dataSource) } }
34.900763
114
0.508749
5d8c7beb6fba0b96a44363d7c269ed0ee57c9920
1,796
// Last generated at: 2017-04-19 21:27:22.395626885 -0700 PDT import Foundation class StringKeys { private static var _shared: StringKeys? = nil static var shared: StringKeys { if let s = _shared { return s } let s = StringKeys() _shared = s return s } private func localize(_ key: String) -> String { return NSLocalizedString(key, comment: "") } var raw_argTest2: String { return localize("11") } func argTest2(_ arg1: String, arg2: String) -> String { let s = localize("11") return String(format: s, arg1, arg2) } var test3: String { return localize("0") } var raw_argTest1: String { return localize("1") } func argTest1(_ arg1: String) -> String { let s = localize("1") return String(format: s, arg1) } var raw_namedArgTest2: String { return localize("2") } func namedArgTest2(anotherValue: String, value2: String) -> String { let s = localize("2") return String(format: s, anotherValue, value2) } var appName: String { return "StringValueTest" } var test2: String { return localize("6") } var iAmMissingInOther: String { return localize("8") } var raw_namedArgTest3: String { return localize("3") } func namedArgTest3(anotherValue: String, value2: String) -> String { let s = localize("3") return String(format: s, anotherValue, value2) } var iAmMissingInRoot: String { return localize("4") } var raw_argTest3: String { return localize("7") } func argTest3(_ arg1: String, arg2: String, arg3: String) -> String { let s = localize("7") return String(format: s, arg1, arg2, arg3) } var raw_namedArgTest1: String { return localize("9") } func namedArgTest1(value1: String) -> String { let s = localize("9") return String(format: s, value1) } var test1: String { return localize("10") } }
23.025641
70
0.673163
5d6ac19d2508624e65e151748583847946fe9f54
581
// // CAPersistentAnimationsLayer.swift // Notifire // // Created by David Bielik on 31/08/2018. // Copyright © 2018 David Bielik. All rights reserved. // import UIKit class CAPersistentAnimationsLayer: BaseLayer, PersistentAnimationsObserving { // MARK: - Properties var observers = [NSObjectProtocol]() var persistentAnimations: [String: CAAnimation] = [:] var persistentSpeed: Float = 0.0 // MARK: - Inherited override func setupSublayers() { startObservingNotifications() } deinit { stopObservingNotifications() } }
21.518519
77
0.683305
110d32a3929bb73e4f634467dc69c68ea58f7443
11,079
import Combine import CoreLocation import HyperTrack import Model import Prelude import Store import SwiftUI import ViewsComponents private let shadowContentOffSet: CGFloat = 10.0 struct ManuHomeAddressView: View { @EnvironmentObject var store: Store<AppState, Action> @ObservedObject var searcher: LocationSearcher @ObservedObject var monitor: ReachabilityMonitor @ObservedObject private var keyboard: KeyboardResponder = KeyboardResponder() @Binding var alertIdentifier: AlertIdentifier? @Binding var sheetIdentifier: SheetIdentifier? @State private var inputViewState: ManuHomeAddressView.ViewState = .list @State private var isFirstResponder: Bool = true @State private var isActivityIndicatorVisible = false var inputData: HyperTrackData var apiClient: ApiClientProvider var hyperTrack: HyperTrack fileprivate enum ViewState { case list case map } var body: some View { return GeometryReader { geometry in ZStack { VStack(spacing: 0) { VStack(spacing: 0) { Rectangle() .fill(Color.clear) .frame( height: geometry.safeAreaInsets.top > 0 ? geometry .safeAreaInsets.top : 20 ) HStack { Button(action: { print("Push .primaryMapView") self.store.update(.updateFlow(.primaryMapView)) }) { Image("close") .padding(.leading, 16) } Spacer() Text("Set home address") .padding(.top, 0) .offset(x: -16) .font( Font.system(size: 20) .weight(.medium)) .foregroundColor(Color("TitleColor")) Spacer() } .frame( height: 24 ) .padding(.top, 8) Text("We will use this to make your sharing experience better.") .font( Font.system(size: 14) .weight(.medium)) .foregroundColor(Color("TitleColor")) .padding(.top, 16) HStack { Image("home_icon") ZStack { HStack { if self.inputViewState == .map { Text(!self.searcher.searchDisplayStringForMap.isEmpty ? self.searcher.searchDisplayStringForMap : "Search for home address") .frame( width: geometry.size.width - 126, height: 20, alignment: .leading ) .font( Font.system(size: 14) .weight(.medium)) .clipped() .offset(x: 16) .padding(.trailing, 16) .animation(nil) } else { LiveTextField( text: self.$searcher.searchStringForList, isFirstResponder: self.$isFirstResponder, placeholder: "Search for home address" ) .frame(width: geometry.size.width - 126) .clipped() .offset(x: 16) .padding(.trailing, 16) .animation(nil) } Image("search") .padding(.trailing, 12) } if self.inputViewState == .map { Button(action: { self.inputViewState = .list }) { Rectangle() .fill(Color("TextFieldBackgroundColor")) .opacity(0.1) } .background(Color.clear) } } .frame(width: geometry.size.width - 60, height: 44) .background(Color("TextFieldBackgroundColor")) .cornerRadius(22) .modifier(RoundedEdge( width: 0.5, color: Color("TextFiledBorderColor"), cornerRadius: 22 )) } .padding([.leading, .trailing, .top, .bottom], 16) } .background(Color("NavigationBarColor")) .clipped() .shadow(radius: 5) self.destinationInputView(geometry) } .modifier(HideKeyboard(callback: { DispatchQueue.main.async { self.isFirstResponder = false } })) .navigationBarTitle("") .navigationBarHidden(true) .background(Color("BackgroundColor")) if self.isActivityIndicatorVisible { LottieView() } } .edgesIgnoringSafeArea(.all) .onReceive(self.searcher.$pickedPlaceFromList) { guard let item = $0 else { return } self.saveHomeAddress(item) } .modifier(ContentPresentationModifier( alertIdentifier: self.$alertIdentifier, exceptionIdentifier: self.$sheetIdentifier, onAppear: { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { self.isFirstResponder = false } }, geofenceAlertDisappear: { DispatchQueue.main.async { self.store.update(.updateFlow(.primaryMapView)) } } )) } } private func destinationInputView(_ geometry: GeometryProxy) -> some View { switch inputViewState { case .list: return getSearchList(geometry) .onAppear { self.searcher.searchStringForList = "" DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { self.isFirstResponder = true } }.any case .map: return getSearchMap(geometry) .onAppear { self.isFirstResponder = false UIApplication.shared.endEditing() } .onDisappear { self.searcher.removeSearchData() }.any } } private func getSearchList(_ geometry: GeometryProxy) -> some View { VStack(spacing: 0.0) { if !self.monitor.isReachable { ReachabilityView(state: .fillwidth) } List { ForEach(self.searcher.searchDataSource, id: \.self) { item in AddressCell(model: item) { selected in self.searcher.search(for: selected) } .frame(height: 64) .listRowInsets(EdgeInsets( top: 0, leading: 0, bottom: 0, trailing: 0 )) } } .offset(y: shadowContentOffSet) .animation(nil) Button(action: { self.inputViewState = .map }) { VStack(spacing: 0.0) { HStack { Spacer() Image("setOnMap") Text("Set on map") .font( Font.system(size: 14) .weight(.medium)) .foregroundColor(Color("TitleColor")) Spacer() } .frame( width: geometry.size.width, height: 48 ) .background(Color("NavigationBarColor")) .clipped() .shadow(radius: 5) Rectangle() .fill(Color("NavigationBarColor")) .frame( width: geometry.size.width, height: geometry.safeAreaInsets.bottom > 0 ? 34 : 0 ) } .offset( y: self.keyboard.isKeyboardShown ? geometry.safeAreaInsets.bottom > 0 ? 34 : 0 : 0 ) } } .padding(.bottom, keyboard.currentHeight) .animation(.interpolatingSpring( mass: 2.3, stiffness: 1000, damping: 500, initialVelocity: 0.5 )) } private func getSearchMap(_ geometry: GeometryProxy) -> some View { ZStack { DestinationMapView( inputCoordinateForSearch: self.$searcher.searchCoordinate ) VStack { if !self.monitor.isReachable { ReachabilityView(state: .fillwidth) } Spacer() Button(action: { guard let place = self.searcher.pickedPlaceFromMap else { return } self.saveHomeAddress(place) }) { HStack { Spacer() Text("Confirm") .font( Font.system(size: 20) .weight(.bold)) .foregroundColor(Color.white) Spacer() } } .buttonStyle(LiveGreenButtonStyle(true)) .padding([.trailing, .leading], 64) .padding( .bottom, geometry.safeAreaInsets.bottom > 0 ? geometry.safeAreaInsets .bottom : 24 ) } } } private func saveHomeAddress(_ homePlace: Place?) { guard let addrress = homePlace else { print("Can't unwrapp homeAddress") return } inputData.update(.updateHomeAddress(addrress)) var dictionary: [String: Any] = [:] if inputData.name.count > 0 { dictionary[Constant.MetadataKeys.nameKey] = inputData.name } if inputData.phone.count > 0 { dictionary[Constant.MetadataKeys.phoneKey] = inputData.phone } if dictionary.count > 0 { if let metadata = HyperTrack.Metadata(dictionary: dictionary) { hyperTrack.setDeviceMetadata(metadata) } } if inputData.geofenceId.isEmpty { DispatchQueue.main.async { self.isActivityIndicatorVisible = true } self.apiClient.createGeofence(self.inputData, self.hyperTrack.deviceID) { result in DispatchQueue.main.async { self.isActivityIndicatorVisible = false } switch result { case let .success(geofence): self.inputData.update(.updateGeofenceId(geofence.geofenceId)) self.alertIdentifier = AlertIdentifier(id: .addedGeofence) case let .failure(error): LiveEventPublisher.postError(error: error) } } } else { DispatchQueue.main.async { self.isActivityIndicatorVisible = true } apiClient.removeGeofence(inputData, hyperTrack.deviceID) { result in switch result { case .success: self.inputData.update(.updateGeofenceId("")) self.apiClient.createGeofence(self.inputData, self.hyperTrack.deviceID) { result in DispatchQueue.main.async { self.isActivityIndicatorVisible = false } switch result { case let .success(geofence): self.inputData.update(.updateGeofenceId(geofence.geofenceId)) self.alertIdentifier = AlertIdentifier(id: .addedGeofence) case let .failure(error): LiveEventPublisher.postError(error: error) } } case let .failure(error): DispatchQueue.main.async { self.isActivityIndicatorVisible = false } LiveEventPublisher.postError(error: error) } } } } }
31.927954
144
0.531817
7217825f4c3512bf34ef0947549f6e4f8f1e67d1
2,723
// // MockRefreshTokenRequest.swift // KarhooSDKTests // // // Copyright © 2020 Karhoo. All rights reserved. // import Foundation import XCTest @testable import KarhooSDK class MockRefreshTokenRequest: RequestSender { var payloadSet: KarhooRequestModel? var endpointSet: APIEndpoint? var requestCalled = false var beforeResponse: (() -> Void)! private var errorCallback: ((KarhooError) -> Void)? private var valueCallback: ((Any) -> Void)? func request(payload: KarhooRequestModel?, endpoint: APIEndpoint, callback: @escaping CallbackClosure<HttpResponse>) { fatalError("Not Implemented") } func requestAndDecode<T: KarhooCodableModel>(payload: KarhooRequestModel?, endpoint: APIEndpoint, callback: @escaping CallbackClosure<T>) { requestCalled = true payloadSet = payload endpointSet = endpoint self.errorCallback = { error in callback(.failure(error: error)) } self.valueCallback = { value in guard let value = value as? T else { return } callback(.success(result: value)) } } func encodedRequest<T: KarhooCodableModel>(endpoint: APIEndpoint, body: URLComponents?, callback: @escaping CallbackClosure<T>) { requestCalled = true endpointSet = endpoint self.errorCallback = { error in callback(.failure(error: error)) } self.valueCallback = { value in guard let value = value as? T else { return } callback(.success(result: value)) } } func cancelNetworkRequest() {} func success(response: KarhooCodableModel) { beforeResponse?() valueCallback?(response) } func fail(error: KarhooError = TestUtil.getRandomError()) { beforeResponse?() errorCallback?(error) } func assertRequestSend(endpoint: APIEndpoint, method: HttpMethod? = nil, path: String? = nil, payload: KarhooCodableModel? = nil) { XCTAssertTrue(requestCalled) XCTAssertEqual(endpoint, endpointSet) XCTAssertEqual(method ?? endpoint.method, endpointSet?.method) XCTAssertEqual(path ?? endpoint.path, endpointSet?.path) // test payload only if it's set if let payload = payload { XCTAssertNotNil(payloadSet) XCTAssertEqual(payload.encode(), payloadSet?.encode()) } } }
31.662791
90
0.575101
0ea38e9571924f880ad964d2cd8ce1eeb25bf9b1
194
// // Item.swift // SharedTodo // // Created by Kawthar Khalid al-Tamimi on 26/01/2021. // import Foundation struct Item { var title: String = "" var done: Bool = false }
12.125
54
0.592784
0988a363f2f72c751b6c240e8fb34952722cc6e1
5,070
// // ViewController.swift // JLConsoleLog // // Created by jack on 2020/4/25. // Copyright © 2020 jack. All rights reserved. // import UIKit import JLConsoleLog let TestLog:JLConsoleLogCategory = "com.consolelog.test" class ViewController: UIViewController { var count:Int = 0 override func viewDidLoad() { super.viewDidLoad() let showConsoleButton = UIButton(frame: CGRect(x: 100, y: 300, width: 200, height: 40)) showConsoleButton.setTitle("show console", for: .normal) showConsoleButton.setTitleColor(.cyan, for: .normal) showConsoleButton.backgroundColor = .black showConsoleButton.addTarget(self, action: #selector(pressShowButton(button:)), for: .touchUpInside) self.view.addSubview(showConsoleButton) let startLogButton = UIButton(frame: CGRect(x: 100, y: 350, width: 200, height: 40)) startLogButton.setTitle("start to log", for: .normal) startLogButton.setTitleColor(.green, for: .normal) startLogButton.backgroundColor = .purple startLogButton.addTarget(self, action: #selector(startLog(button:)), for: .touchUpInside) self.view.addSubview(startLogButton) let addDebugLogButton = UIButton(frame: CGRect(x: 100, y: 400, width: 200, height: 40)) addDebugLogButton.setTitle("add a debug log", for: .normal) addDebugLogButton.setTitleColor(.green, for: .normal) addDebugLogButton.backgroundColor = .gray addDebugLogButton.addTarget(self, action: #selector(addDebugLog(button:)), for: .touchUpInside) self.view.addSubview(addDebugLogButton) let nextPageButton = UIButton(frame: CGRect(x: 100, y: 450, width: 200, height: 40)) nextPageButton.setTitle("next page", for: .normal) nextPageButton.setTitleColor(.systemPink, for: .normal) nextPageButton.backgroundColor = .blue nextPageButton.addTarget(self, action: #selector(gotoNextPage(button:)), for: .touchUpInside) self.view.addSubview(nextPageButton) let controlMonitorButton = UIButton(frame: CGRect(x: 100, y: 500, width: 200, height: 40)) controlMonitorButton.setTitle("open monitor", for: .normal) controlMonitorButton.setTitleColor(.yellow, for: .normal) controlMonitorButton.backgroundColor = .gray controlMonitorButton.addTarget(self, action: #selector(controlMonitor(button:)), for: .touchUpInside) self.view.addSubview(controlMonitorButton) if #available(iOS 10.0, *) { let timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { _ in JLVerboseLog(category: TestLog, needPrint: true , contextData: ["test":1], formats: String(self.count), #function,String(#line)) self.count += 1 }) RunLoop.main.add(timer, forMode: .common) } JLConsoleLogManager.consoleLogNotificationCenter.addObserver(forName: ConsoleHasDismissedNotification, object: nil, queue: .main, using: { _ in showConsoleButton.setTitle("show console", for: .normal) }) JLConsoleController.shared.followingAction = { options in print("add a log \(options.level.rawValue) \(options.category)") //send a track log to server or other actions } JLConsoleController.shared.register(newCategory: TestLog) //registered category could be filtered } @objc func pressShowButton(button:UIButton) { if JLConsoleController.shared.style == .Hidden { button.setTitle("hide console", for: .normal) JLConsoleController.shared.style = .Floating //show console in floating fashion } else { button.setTitle("show console", for: .normal) JLConsoleController.shared.style = .Hidden //hide console } } @objc func startLog(button:UIButton) { if JLConsoleController.shared.logEnabled { JLConsoleController.shared.logEnabled = false button.setTitle("start to log", for: .normal) } else { JLConsoleController.shared.logEnabled = true button.setTitle("end to log", for: .normal) } } @objc func addDebugLog(button:UIButton) { JLDebugLog(category: TestLog,hasFollowingAction: true, contextData: ["test":2], formats: "debug info", #function,String(#line)) } @objc func gotoNextPage(button:UIButton) { let vc = SecondaryViewController() self.navigationController?.pushViewController(vc, animated: true) } @objc func controlMonitor(button:UIButton) { if JLConsoleController.shared.performanceMonitable { JLConsoleController.shared.performanceMonitable = false button.setTitle("turn on monitor", for: .normal) } else { JLConsoleController.shared.performanceMonitable = true button.setTitle("turn off monitor", for: .normal) } } }
43.333333
151
0.655227
fc28e1b34468c242020ef2b4cc91d2b8a5632d08
377
#if canImport(UIKit) && !os(watchOS) import UIKit extension UINavigationController { // MARK: - Instance Methods public func pushViewControllers(_ viewControllers: [UIViewController], animated: Bool = true) { setViewControllers( self.viewControllers.appending(contentsOf: viewControllers), animated: animated ) } } #endif
23.5625
99
0.676393
f7ee6a39556ddc63432d267dc6a34c0bffd5ac80
1,009
// // SwiftIconFontTests.swift // SwiftIconFontTests // // Created by Sedat Gökbek ÇİFTÇİ on 12/07/16. // Copyright © 2016 Sedat Gökbek ÇİFTÇİ. All rights reserved. // import XCTest @testable import SwiftIconFont class SwiftIconFontTests: 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. } } }
27.27027
111
0.644202
bfec73e6cce4b5445065e1c43af0b07e5bb10f87
4,991
public func dropFirst<T>(_ count: Int = 1) -> Operator<T, T> { return { source in return { sink in var talkback: Optional<SourceTalkback<T>> = .none var count = count source { payload in switch payload { case let .start(tb): talkback = .some(tb) sink(.talkback(tb)) case .next: if count < 1 { sink(payload) } else { count = count - 1 talkback?(.next(.none)) } case .completed: sink(payload) } } } } } public func dropLast<T>(_ count: Int = 1) -> Operator<T, T> { return { source in return { sink in var talkback: Optional<SourceTalkback<T>> = .none var buffer: Array<Optional<T>> = .init(repeating: .none, count: count) var currentIndex: Int = 0 var isBufferFull: Bool { return buffer.allSatisfy(notEquals(.none)) } source { payload in switch payload { case let .start(tb): talkback = .some(tb) sink(.talkback(tb)) case let .next(element): let e = buffer[currentIndex] buffer[currentIndex] = element currentIndex = (currentIndex + 1) % count if case let .some(element) = e { sink(.next(element)) } else { talkback?(.next(.none)) } case .completed: sink(payload) } } } } } public func dropWhile<T>(_ predicate: @escaping (T) throws -> Bool) -> Operator<T, T> { return { source in return { sink in var talkback: Optional<SourceTalkback<T>> = .none var failure: Optional<Completion> = .none var didStopDropping: Bool = false source { payload in switch payload { case let .start(tb): talkback = tb sink(.talkback(tb)) case let .next(element): do { if didStopDropping { sink(payload) } else if try !predicate(element) { didStopDropping = true sink(payload) } else { talkback?(.next(.none)) } } catch { failure = .failed(error) talkback?(.completed(.finished)) } case .completed: if case let .some(failed) = failure { sink(.completed(failed)) } else { sink(payload) } } } } } } public func dropWhile<T, U>(_ notifier: @escaping Producer<U>) -> Operator<T, T> { return { source in return { sink in let lock: RecursiveLock = RecursiveLock(label: DOMAIN("dropWhile")) var talkback: Optional<SourceTalkback<T>> = .none var notifierTalkback: Optional<SourceTalkback<U>> = .none var didReceiveNotifierCompletion: Bool = false source { payload in lock.withLock { switch payload { case let .start(tb): talkback = tb notifier { payload in lock.withLock { switch payload { case let .start(tb): notifierTalkback = tb notifierTalkback?(.next(.none)) case .next: notifierTalkback?(.next(.none)) case .completed: didReceiveNotifierCompletion = true } } } sink(.talkback(tb)) case .next: if didReceiveNotifierCompletion { sink(payload) } else { talkback?(.next(.none)) } case .completed: sink(payload) } } } } } } public func dropUntil<T, U>(_ notifier: @escaping Producer<U>) -> Operator<T, T> { return { source in return { sink in let lock: RecursiveLock = RecursiveLock(label: DOMAIN("dropUntil")) var talkback: Optional<SourceTalkback<T>> = .none var notifierTalkback: Optional<SourceTalkback<U>> = .none var didReceiveElementFromNotifier: Bool = false source { payload in lock.withLock { switch payload { case let .start(tb): talkback = tb notifier { payload in lock.withLock { switch payload { case let .start(tb): notifierTalkback = tb notifierTalkback?(.next(.none)) case .next: didReceiveElementFromNotifier = true notifierTalkback?(.completed(.finished)) case .completed: return } } } sink(.talkback(tb)) case .next: if didReceiveElementFromNotifier { sink(payload) } else { talkback?(.next(.none)) } case .completed: sink(payload) } } } } } }
28.683908
88
0.493288
e40ee13e8b23d342e6bbfe99ac58b76485cc9cf5
10,012
// // HFCryptorRSA.swift // Pods // // Created by DragonCherry on 6/30/16. // // import CoreFoundation import Security import RNCryptor import TinyLog open class HFCryptorRSA { fileprivate let kTemporaryKeyTag: String = "kTemporaryKeyTag" fileprivate enum HFCryptorRSAProcessType { case encrypt case decrypt } public enum HFCryptorRSAKeySize: Int { case bits512 = 512 case bits1024 = 1024 case bits2048 = 2048 case bits4096 = 4096 } var keySize: HFCryptorRSAKeySize = .bits2048 // MARK: - Private Key fileprivate var privateTag: String! fileprivate var privateSecKey: SecKey? = nil open var privateKey: Data? { return keyData(forTag: privateTag) } // MARK: - Public Key fileprivate var publicTag: String! fileprivate var publicSecKey: SecKey? = nil open var publicKey: Data? { return keyData(forTag: publicTag) } // MARK: - Initializer public init(privateTag: String, publicTag: String) { self.privateSecKey = self.secKey(forTag: privateTag) self.privateTag = privateTag self.publicSecKey = self.secKey(forTag: publicTag) self.publicTag = publicTag } // MARK: - API open func generateKeyPair(_ size: HFCryptorRSAKeySize = .bits2048, writeOnKeychain: Bool = false, regenerate: Bool = false) -> Bool { keySize = size // clear if regeneration flag is on if regenerate { updateKey(privateTag, keyData: nil) updateKey(publicTag, keyData: nil) } // set option for private key let privateAttributes = [ String(kSecAttrIsPermanent): writeOnKeychain, String(kSecAttrCanEncrypt): false, String(kSecAttrCanDecrypt): true, String(kSecAttrCanSign): true, String(kSecAttrCanVerify): false, String(kSecAttrApplicationTag): self.privateTag ] as [String : Any] // set option for public key let publicAttributes = [ String(kSecAttrIsPermanent): writeOnKeychain, String(kSecAttrCanEncrypt): true, String(kSecAttrCanDecrypt): false, String(kSecAttrCanSign): false, String(kSecAttrCanVerify): true, String(kSecAttrApplicationTag): self.publicTag ] as [String : Any] // set option for key pair let pairAttributes = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeySizeInBits): size.rawValue, String(kSecPublicKeyAttrs): publicAttributes, String(kSecPrivateKeyAttrs): privateAttributes ] as [String : Any] // generate key pair let status = SecKeyGeneratePair(pairAttributes as CFDictionary, &publicSecKey, &privateSecKey) if errSecSuccess == status { log("Successfully generated key pair on \(writeOnKeychain ? "keychain" : "memory") with size of \(size.rawValue) bit.") log("[Private Key] \(keyData(forTag: privateTag)?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) ?? "Fail")") log("[Public Key] \(keyData(forTag: publicTag)?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) ?? "Fail")") return true } else { loge("Failed to generate RSA key pair with code: \(status)") return false } } /// encrypt open func encrypt(_ data: Data, key: Data? = nil, padding: SecPadding = SecPadding()) -> Data? { return process(data, type: .encrypt, key: key, padding: padding) } open func decrypt(_ data: Data, key: Data? = nil, padding: SecPadding = SecPadding()) -> Data? { return process(data, type: .decrypt, key: key, padding: padding) } /// encrypt or decrypt data with given key fileprivate func process(_ data: Data, type: HFCryptorRSAProcessType, key: Data? = nil, padding: SecPadding = SecPadding()) -> Data? { var processingSecKey: SecKey? = nil // log data size log("Data size to process: \(data.count), key size: \(self.keySize.rawValue)") if type == .encrypt { guard data.count < (self.keySize.rawValue / 8) else { loge("Data size exceeds its limit.") return nil } } // save public key data on temporary space in keychain and retrieve it as SecKey type if it has designated key if let designatedKey = key { if self.updateKey(kTemporaryKeyTag, keyData: designatedKey) { // check key first guard let designatedSecKey = secKey(forTag: kTemporaryKeyTag) else { return nil } processingSecKey = designatedSecKey log("Retrieved SecKey using designated key data.") } else { loge("Failed to make SecKey using external key data.") return nil } } else { // retrieve key by given tag passed by init var existingKey: SecKey? = nil if type == .encrypt { existingKey = self.publicSecKey } else { existingKey = self.privateSecKey } if let existingKey = existingKey { log("Retrieved SecKey using existing key.") processingSecKey = existingKey } else { loge("Cannot retrieve any valid key for \(type == .encrypt ? "encryption" : "decryption").") return nil } } // process data using SecKey if let processingSecKey = processingSecKey { let plainBytes = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count) let plainBytesLength = data.count var cipherBytesLength = SecKeyGetBlockSize(processingSecKey) guard let cipherData = NSMutableData(length: cipherBytesLength) else { log("Failed to allocate NSMutableData with length \(cipherBytesLength)") return nil } let cipherBytes = cipherData.mutableBytes.assumingMemoryBound(to: UInt8.self) var status = errSecSuccess if type == .encrypt { status = SecKeyEncrypt(processingSecKey, padding, plainBytes, plainBytesLength, cipherBytes, &cipherBytesLength) } else { status = SecKeyDecrypt(processingSecKey, padding, plainBytes, plainBytesLength, cipherBytes, &cipherBytesLength) } if status == errSecSuccess { log("Successfully \(type == .encrypt ? "encrypted" : "decrypted") data with RSA key.") return cipherData.subdata(with: NSMakeRange(0, cipherBytesLength)) } else { loge("Failed to \(type == .encrypt ? "encrypt" : "decrypt") data with RSA key.") return nil } } else { loge("Critical logic error at \(#function)") return nil } } // MARK: - Internal Utilities fileprivate func secKey(forTag tag: String) -> SecKey? { var keyRef: AnyObject? = nil let query = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecReturnData): kCFBooleanTrue as CFBoolean, String(kSecClass): kSecClassKey as CFString, String(kSecAttrApplicationTag): tag as CFString, ] as [String : Any] let status = SecItemCopyMatching(query as CFDictionary, &keyRef) guard let secKey = keyRef as! SecKey?, status == errSecSuccess else { loge("Failed to retrieve key with result code: \(status), for tag: \(tag)") return nil } return secKey } fileprivate func keyData(forTag tag: String) -> Data? { var keyRef: AnyObject? = nil let query = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecReturnData): kCFBooleanTrue as CFBoolean, String(kSecClass): kSecClassKey as CFString, String(kSecAttrApplicationTag): tag as CFString, ] as [String : Any] let status = SecItemCopyMatching(query as CFDictionary, &keyRef) guard let keyData = keyRef as? Data, status == errSecSuccess else { loge("Failed to retrieve key data with result code: \(status), for tag: \(tag)") return nil } return keyData } @discardableResult fileprivate func updateKey(_ tag: String, keyData: Data?) -> Bool { let query: Dictionary<String, AnyObject> = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecClass): kSecClassKey as CFString, String(kSecAttrApplicationTag): tag as CFString] if let keyData = keyData { let status = SecItemUpdate(query as CFDictionary, [String(kSecValueData): keyData] as CFDictionary) if status == errSecSuccess { log("Successfully updated key for tag: \(tag)") return true } else { loge("Failed to update key with result code: \(status), for tag: \(tag)") return false } } else { let status = SecItemDelete(query as CFDictionary) if status == errSecSuccess { log("Successfully deleted key for tag: \(tag)") return true } else { loge("Failed to delete key with result code: \(status), for tag: \(tag)") return false } } } }
38.360153
146
0.576209
c198f0847afbcaedb7ae056b42525252bc176011
1,795
import Foundation import Mapbox class OfflineRegionDefinition { let bounds: [[Double]] let mapStyleUrl: URL let minZoom: Double let maxZoom: Double init(bounds: [[Double]], mapStyleUrl: URL, minZoom: Double, maxZoom: Double) { self.bounds = bounds self.mapStyleUrl = mapStyleUrl self.minZoom = minZoom self.maxZoom = maxZoom } func getBounds() -> MGLCoordinateBounds { return MGLCoordinateBounds( sw: CLLocationCoordinate2D(latitude: bounds[0][0], longitude: bounds[0][1]), ne: CLLocationCoordinate2D(latitude: bounds[1][0], longitude: bounds[1][1]) ) } static func fromDictionary(_ jsonDict: [String: Any]) -> OfflineRegionDefinition? { guard let bounds = jsonDict["bounds"] as? [[Double]], let mapStyleUrlString = jsonDict["mapStyleUrl"] as? String, let mapStyleUrl = URL(string: mapStyleUrlString), let minZoom = jsonDict["minZoom"] as? Double, let maxZoom = jsonDict["maxZoom"] as? Double else { return nil } return OfflineRegionDefinition( bounds: bounds, mapStyleUrl: mapStyleUrl, minZoom: minZoom, maxZoom: maxZoom ) } func toDictionary() -> [String: Any] { return [ "bounds": self.bounds, "mapStyleUrl": self.mapStyleUrl.absoluteString, "minZoom": self.minZoom, "maxZoom": self.maxZoom, ]; } func toMGLTilePyramidOfflineRegion() -> MGLTilePyramidOfflineRegion { return MGLTilePyramidOfflineRegion( styleURL: mapStyleUrl, bounds: getBounds(), fromZoomLevel: minZoom, toZoomLevel: maxZoom ) } }
31.491228
88
0.596657
380be908bacb188358710adae7a0d511c4516da6
1,306
//---------------------------------------------------------------------------------------------------------------------- // VectorGraphicsView.swift ©2021 Stevo Brock All rights reserved. //---------------------------------------------------------------------------------------------------------------------- import AppKit //---------------------------------------------------------------------------------------------------------------------- // MARK: VectorGraphicsView public class VectorGraphicsView : NSView { // MARK: Content public enum Content { case color(color :NSColor) case oval(color :NSColor) case shape(path :NSBezierPath, color :NSColor) } // MARK: Properties public var content :Content? // MARK: NSView methods //------------------------------------------------------------------------------------------------------------------ override public func draw(_ dirtyRect :NSRect) { // Check if have content guard let content = self.content else { return } // Check content switch content { case let .color(color): // Color color.set() dirtyRect.fill() case let .oval(color: color): // Oval color.set() NSBezierPath(ovalIn: self.bounds).fill() case let .shape(path, color): // Shape color.set() path.fill() } } }
28.391304
120
0.421133
4699ee03d35a2411d35b09df144eb7765f445f66
1,985
// // Conductor.swift // AnalogSynthX // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit class Conductor: AKMIDIListener { /// Globally accessible singleton static let sharedInstance = Conductor() var core = CoreInstrument(voiceCount: 5) var bitCrusher: AKBitCrusher var fatten: Fatten var filterSection: FilterSection var multiDelay: MultiDelay var multiDelayMixer: AKDryWetMixer var masterVolume = AKMixer() var reverb: AKCostelloReverb var reverbMixer: AKDryWetMixer var midiBendRange: Double = 2.0 init() { AKSettings.audioInputEnabled = true bitCrusher = AKBitCrusher(core) bitCrusher.stop() filterSection = FilterSection(bitCrusher) filterSection.output.stop() fatten = Fatten(filterSection) multiDelay = MultiDelay(fatten) multiDelayMixer = AKDryWetMixer(fatten, multiDelay, balance: 0.0) masterVolume = AKMixer(multiDelayMixer) reverb = AKCostelloReverb(masterVolume) reverb.stop() reverbMixer = AKDryWetMixer(masterVolume, reverb, balance: 0.0) // uncomment this to allow background operation // AKSettings.playbackWhileMuted = true AudioKit.output = reverbMixer AudioKit.start() let midi = AKMIDI() midi.createVirtualPorts() midi.openInput("Session 1") midi.addListener(self) } // MARK: - AKMIDIListener protocol functions func receivedMIDINoteOn(note: Int, velocity: Int, channel: Int) { core.playNote(note, velocity: velocity) } func receivedMIDINoteOff(note: Int, velocity: Int, channel: Int) { core.stopNote(note) } func receivedMIDIPitchWheel(pitchWheelValue: Int, channel: Int) { let bendSemi = (Double(pitchWheelValue - 8192) / 8192.0) * midiBendRange core.globalbend = bendSemi } }
27.569444
81
0.671033
64dacf492ab6767e7405546ddea204d5a86766ff
691
// // AFWrapper.swift // Empresario // // Created by Prashant on 01/03/18. // import Foundation import UIKit class AFWrapper { class func requestGETURL(_ strURL: String, success:@escaping (Data) -> Void, failure:@escaping (Error) -> Void) { guard let url = URL(string:strURL) else { failure(NSError(domain: "Invalid URL", code: 1000, userInfo: nil)); return } let dataTask = URLSession.shared.dataTask(with: url) { (data, responase, error) in guard error == nil else { failure(error!) return } success(data!) } dataTask.resume() } }
22.290323
127
0.54848
f71c6665915782f26666f191cd10c6edd0b5df66
1,544
// // ChooseImageViewController.swift // TestSwift // // Created by heming on 16/4/20. // Copyright © 2016年 Mr.Tai. All rights reserved. // import Foundation import UIKit class ChooseImageViewController: UIViewController { var imageView: UIImageView? let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() self.title = "选择图片" self.view.backgroundColor = UIColor.white imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-64)) self.view.addSubview(imageView!) imagePicker.delegate = self } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } } } extension ChooseImageViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { imageView?.image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")] as! UIImage? imageView?.contentMode = .scaleAspectFit imageView?.clipsToBounds = true dismiss(animated: true, completion: nil) } }
35.906977
144
0.712435
9c61f08c672a0845d7bede35ba68af59205158ad
18,416
// // PermissionButton.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // 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. // open class PermissionButton: UIButton { /// The permission of the button. open let permission: Permission /// The permission domain of the button. open var domain: PermissionType { return permission.type } /// The permission status of the button. open var status: PermissionStatus { return permission.status } fileprivate var titles: [UIControlState: [PermissionStatus: String]] = [:] fileprivate var attributedTitles: [UIControlState: [PermissionStatus: NSAttributedString]] = [:] fileprivate var titleColors: [UIControlState: [PermissionStatus: UIColor]] = [:] fileprivate var titleShadowColors: [UIControlState: [PermissionStatus: UIColor]] = [:] fileprivate var images: [UIControlState: [PermissionStatus: UIImage]] = [:] fileprivate var backgroundImages: [UIControlState: [PermissionStatus: UIImage]] = [:] /// The alert when the permission was denied. open var deniedAlert: PermissionAlert { return permission.deniedAlert } /// The alert when the permission is disabled. open var disabledAlert: PermissionAlert { return permission.disabledAlert } /// The textual representation of self. open override var description: String { return permission.description } // MARK: - Initialization /** Creates and returns a new button for the specified permission. - parameter permission: The permission. - returns: A newly created button. */ public init(_ permission: Permission) { self.permission = permission super.init(frame: .zero) self.addTarget(self, action: .tapped, for: .touchUpInside) self.addTarget(self, action: .highlight, for: .touchDown) } /** Returns an object initialized from data in a given unarchiver. - parameter aDecoder: An unarchiver object. - returns: self, initialized using the data in decoder. */ public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Titles /** Returns the title associated with the specified permission status and state. - parameter status: The permission status that uses the title. - parameter state: The state that uses the title. - returns: The title for the specified permission status and state. */ open func titleForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> String? { return titles[state]?[status] } /** Sets the title to use for the specified state. - parameter title: The title to use for the specified state. - parameter state: The state that uses the specified title. */ open override func setTitle(_ title: String?, for state: UIControlState) { titles[state] = nil super.setTitle(title, for: state) } /** Sets the title to use for the specified permission status and state. - parameter title: The title to use for the specified state. - parameter status: The permission status that uses the specified title. - parameter state: The state that uses the specified title. */ open func setTitle(_ title: String?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if titles[state] == nil { titles[state] = [:] } titles[state]?[status] = title } /** Sets the titles to use for the specified permission statuses and state. - parameter titles: The titles to use for the specified statuses. - parameter state: The state that uses the specifed titles. */ open func setTitles(_ titles: [PermissionStatus: String?], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if self.titles[state] == nil { self.titles[state] = [:] } for (status, title) in titles { self.titles[state]?[status] = title } } // MARK: - Attributed titles /** Returns the styled title associated with the specified permission status and state. - parameter status: The permission status that uses the styled title. - parameter state: The state that uses the styled title. - returns: The title for the specified permission status and state. */ open func attributedTitleForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> NSAttributedString? { return attributedTitles[state]?[status] } /** Sets the styled title to use for the specified state. - parameter title: The styled text string to use for the title. - parameter state: The state that uses the specified title. */ open override func setAttributedTitle(_ title: NSAttributedString?, for state: UIControlState) { attributedTitles[state] = nil super.setAttributedTitle(title, for: state) } /** Sets the styled title to use for the specifed permission status and state. - parameter title: The styled text string to use for the title. - parameter status: The permission status that uses the specified title. - parameter state: The state that uses the specified title. */ open func setAttributedTitle(_ title: NSAttributedString?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if attributedTitles[state] == nil { attributedTitles[state] = [:] } attributedTitles[state]?[status] = title } /** Sets the styled titles to use for the specified permission statuses and state. - parameter titles: The titles to use for the specified statuses. - parameter state: The state that uses the specified titles. */ open func setAttributedTitles(_ titles: [PermissionStatus: NSAttributedString?], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if attributedTitles[state] == nil { attributedTitles[state] = [:] } for (status, title) in titles { attributedTitles[state]?[status] = title } } // MARK: - Title colors /** Returns the title color used for a permission status and state. - parameter status: The permission status that uses the title color. - parameter state: The state that uses the title color. - returns: The color of the title for the specified permission status and state. */ open func titleColorForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> UIColor? { return titleColors[state]?[status] } /** Sets the color of the title to use for the specified state. - parameter color: The color of the title to use for the specified state. - parameter state: The state that uses the specified color. */ open override func setTitleColor(_ color: UIColor?, for state: UIControlState) { titleColors[state] = nil super.setTitleColor(color, for: state) } /** Sets the color of the title to use for the specified permission status and state. - parameter color: The color of the title to use for the specified permission status and state. - parameter status: The permission status that uses the specified color. - parameter state: The state that uses the specified color. */ open func setTitleColor(_ color: UIColor?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if titleColors[state] == nil { titleColors[state] = [:] } titleColors[state]?[status] = color } /** Sets the colors of the title to use for the specified permission statuses and state. - parameter colors: The colors to use for the specified permission statuses. - parameter state: The state that uses the specified colors. */ open func setTitleColors(_ colors: [PermissionStatus: UIColor?], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if titleColors[state] == nil { titleColors[state] = [:] } for (status, color) in colors { titleColors[state]?[status] = color } } // MARK: - Title shadow colors /** Returns the shadow color of the title used for a permission status and state. - parameter status: The permission status that uses the title shadow color. - parameter state: The state that uses the title shadow color. - returns: The color of the title's shadow for the specified permission status and state. */ open func titleShadowColorForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> UIColor? { return titleShadowColors[state]?[status] } /** Sets the color of the title shadow to use for the specified state. - parameter color: The color of the title shadow to use for the specified state. - parameter state: The state that uses the specified color. */ open override func setTitleShadowColor(_ color: UIColor?, for state: UIControlState) { titleShadowColors[state] = nil super.setTitleShadowColor(color, for: state) } /** Sets the color of the title shadow to use for the specified permission status and state. - parameter color: The color of the title shadow to use for the specified permission status and state. - parameter status: The permission status that uses the specified color. - parameter state: The state that uses the specified color. */ open func setTitleShadowColor(_ color: UIColor?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if titleShadowColors[state] == nil { titleShadowColors[state] = [:] } titleShadowColors[state]?[status] = color } /** Sets the colors of the title shadow to use for the specified permission statuses and state. - parameter colors: The colors to use for the specified permission statuses. - parameter state: The state that uses the specified colors. */ open func setTitleShadowColors(_ colors: [PermissionStatus: UIColor?], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if titleShadowColors[state] == nil { titleShadowColors[state] = [:] } for (status, color) in colors { titleShadowColors[state]?[status] = color } } // MARK: - Images /** Returns the image used for a permission status and state - parameter status: The permission status that uses the image. - parameter state: The state that uses the image. - returns: The image used for the specified permission status and state. */ open func imageForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> UIImage? { return images[state]?[status] } /** Sets the image to use for the specified state. - parameter image: The image to use for the specified state. - parameter state: The state that uses the specified image. */ open override func setImage(_ image: UIImage?, for state: UIControlState) { images[state] = nil super.setImage(image, for: state) } /** Sets the image to use for the specified permission status and state. - parameter image: The image to use for the specified permission status and state. - parameter status: The permission status that uses the specified image. - parameter state: The state that uses the specified image. */ open func setImage(_ image: UIImage?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if images[state] == nil { images[state] = [:] } images[state]?[status] = image } /** Sets the images for the specified permission statuses and state. - parameter images: The images to use for the specified permission statuses. - parameter state: The state that uses the specified images. */ open func setImages(_ images: [PermissionStatus: UIImage], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if self.images[state] == nil { self.images[state] = [:] } for (status, image) in images { self.images[state]?[status] = image } } // MARK: - Background images /** Returns the background image used for a permission status and a button state. - parameter status: The permission status that uses the background image. - parameter state: The state that uses the background image. - returns: The background image used for the specified permission status and state. */ open func backgroundImageForStatus(_ status: PermissionStatus, andState state: UIControlState = .normal) -> UIImage? { return backgroundImages[state]?[status] } /** Sets the background image to use for the specified button state. - parameter image: The background image to use for the specified state. - parameter state: The state that uses the specified image. */ open override func setBackgroundImage(_ image: UIImage?, for state: UIControlState) { backgroundImages[state] = nil super.setBackgroundImage(image, for: state) } /** Sets the background image to use for the specified permission status and button state. - parameter image: The background image to use for the specified permission status and button state. - parameter status: The permission status that uses the specified image. - parameter state: The state that uses the specified image. */ open func setBackgroundImage(_ image: UIImage?, forStatus status: PermissionStatus, andState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if backgroundImages[state] == nil { backgroundImages[state] = [:] } backgroundImages[state]?[status] = image } /** Set the background images to use for the specified permission statuses and button state. - parameter images: The background images to use for the specified permission statuses. - parameter state: The state that uses the specified images. */ open func setBackgroundImages(_ images: [PermissionStatus: UIImage], forState state: UIControlState = .normal) { guard [.normal, .highlighted].contains(state) else { return } if backgroundImages[state] == nil { backgroundImages[state] = [:] } for (status, image) in images { backgroundImages[state]?[status] = image } } // MARK: - UIView /** Tells the view that its superview changed. */ open override func didMoveToSuperview() { render(.normal) } } internal extension PermissionButton { @objc func highlight(_ button: PermissionButton) { render(.highlighted) } @objc func tapped(_ button: PermissionButton) { permission.request { [weak self] status in self?.render() } } } private extension PermissionButton { func render(_ state: UIControlState = .normal) { if let title = titleForStatus(status, andState: state) { super.setTitle(title, for: state) } if let title = attributedTitleForStatus(status, andState: state) { super.setAttributedTitle(title, for: state) } if let color = titleColorForStatus(status, andState: state) { super.setTitleColor(color, for: state) } if let color = titleShadowColorForStatus(status, andState: state) { super.setTitleShadowColor(color, for: state) } if let image = imageForStatus(status, andState: state) { super.setImage(image, for: state) } if let image = backgroundImageForStatus(status, andState: state) { super.setBackgroundImage(image, for: state) } } }
37.129032
142
0.648132
1e724f40629d3db88f08b8754d20fe6e004aaf74
22,839
#!/usr/bin/env xcrun swift // // JustTrack // // Copyright © 2017 Just Eat Holding Ltd. // import Foundation private enum EventTemplate : String { case eventList = "EventListTemplate.jet" case event = "EventTemplate.jet" case keyName = "EventKeyNameTemplate.jet" case keyVar = "EventKeyVarTemplate.jet" case eventInit = "EventInitTemplate.jet" case eventInitAssignsList = "EventInitAssignTemplate.jet" case eventInitParam = "EventInitParam.jet" case eventObjectStruct = "EventObjectStructTemplate.jet" case objectKeyVar = "EventObjectKeyVarTemplate.jet" } private enum EventTemplatePlaceholder : String { case eventList = "events_list" case event = "event" case eventName = "name" case keyValueChain = "event_keyValueChain" case eventTrackers = "event_cs_trackers_str" case keysNames = "event_keysNames" case keysVars = "event_keysVars" case keyName = "key_name" case formattedObjectKeyName = "formatted_object_key_name" case keyNameOriginal = "key_name_original" case eventInit = "event_init" case eventInitParams = "event_init_params" case eventInitAssignsList = "event_init_assigns_list" //Facilitates array of objects case objectKeyChain = "event_objectKeyChain" case objectName = "object_name" case objectKeyName = "object_key_name" case objectKeysVars = "object_keysVars" case objectKeyNames = "object_keyNames" case objectStruct = "event_ObjectStructs" case objectStructParams = "object_paramter_list" } private enum EventPlistKey : String { case payload = "payloadKeys" case objectPayload = "objectPayloadKeys" case trackrs = "registeredTrackers" } enum EventGeneratorError: Error { //generic case invalidParameter(wrongParameterIndex: Int) //templates case templateNotFound case templateMalformed //event plist case plistNotFound case trackerMissing //swift file case swiftFileNotFound //events case eventMalformed } //MARK - Utility // Log string prepending the nameof the project func log(msg: String) { print("TRACK: \(msg)") } //return the current script path func scriptPath() -> NSString { let cwd = FileManager.default.currentDirectoryPath let script = CommandLine.arguments[0]; var path: NSString? //get script working dir if script.hasPrefix("/") { path = script as NSString? } else { let urlCwd = URL(fileURLWithPath: cwd) if let urlPath = URL(string: script, relativeTo: urlCwd) { path = urlPath.path as NSString? } } path = path!.deletingLastPathComponent as NSString? return path! } func urlForTemplate(_ templateName: String) throws -> URL { var url: URL? let path: String? = Bundle.main.path(forResource: templateName, ofType: nil) //uses]d by test target if path != nil { url = URL(fileURLWithPath: path!) } else { let dir = scriptPath() url = URL(fileURLWithPath: dir as String).appendingPathComponent(templateName) //used in the build phase } guard url != nil else { throw EventGeneratorError.templateNotFound } return url! } //Load the specific template func stringFromTemplate(_ templateName: String) throws -> String { let url: URL = try urlForTemplate(templateName) var result: String? //reading do { log(msg: "Load template \(url)") result = try String(contentsOf: url) result = result?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } catch { log(msg: "Error loading template \(templateName)") throw EventGeneratorError.templateMalformed } return result! } private func loadEventPlist(_ plistPath: String) throws -> NSDictionary { let result: NSMutableDictionary = NSMutableDictionary() if FileManager.default.fileExists(atPath: plistPath) { var eventsDict: NSDictionary? = NSDictionary(contentsOfFile: plistPath) eventsDict = eventsDict?.object(forKey: "events") as? NSDictionary if eventsDict != nil { result.setDictionary(eventsDict as! [AnyHashable : Any]) } } else { throw EventGeneratorError.plistNotFound } return result } private func sanitised(_ originalString: String) -> String { var result = originalString let components = result.components(separatedBy: .whitespacesAndNewlines) result = components.joined(separator: "") let componantsByUnderscore = result.components(separatedBy: CharacterSet.alphanumerics.inverted) if !componantsByUnderscore.isEmpty { result = "" for component in componantsByUnderscore { if component != componantsByUnderscore[0] { result.append(component.capitalizingFirstLetter()) } else { result.append(component) } } } return result } func printHelp() { log(msg: "HELP: //TODO") } //MARK - Structs generator helpers private func generateEvents(_ events: [String : AnyObject]) throws -> NSString { //load templates let structListTemplateString: String = try stringFromTemplate(EventTemplate.eventList.rawValue) let structTemplate: String = try stringFromTemplate(EventTemplate.event.rawValue) let resultString: NSMutableString = NSMutableString(string: structListTemplateString) var structsArray: [String] = Array() for event: String in events.keys.sorted(by: >) { var objectNames: [String] = [] let eventDic: [String : AnyObject]? = events[event] as? [String : AnyObject] let sanitisedValue = sanitised(event) var structString = structTemplate structString = replacePlaceholder(structString, placeholder: "<*!\(EventTemplatePlaceholder.event.rawValue)*>", value: sanitisedValue, placeholderType: "routine") //<*!event*> = Example structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.eventName.rawValue)*>", value: event, placeholderType: "routine") //<*event*> = example let originalKeys:[Any] = eventDic![EventPlistKey.payload.rawValue] as! [Any] var originalStringKeys: [String] = [] var cleanKeys: [String] = [] //array of string items var objects: [Any] = [] //array of object items? for key in originalKeys { //Go through payload items if key is String { let setKey = key as! String cleanKeys.append(sanitised(setKey)) //sanitise keys //let cleanKeys:[String] = originalKeys.map{ sanitised($0) } originalStringKeys.append(setKey) } else if key is NSDictionary { objects.append(key) } } if !objects.isEmpty { for item in objects { let object = (item as! NSDictionary) let objectName = object["name"] as! String objectNames.append(objectName) } } // <*event_keyValueChain*> = kKey1 : key1 == "" ? NSNull() : key1 as NSString let eventKeyValueChain = generateEventKeyValueChain(cleanKeys, eventHasObjects: !objects.isEmpty) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.keyValueChain.rawValue)*>", value: eventKeyValueChain, placeholderType: "routine") if !objects.isEmpty { //Create array definition for each object item using name definiton let objectKeyValueKeyChain = generateObjectKeyValue(objectNames) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectKeyChain.rawValue)*>", value: objectKeyValueKeyChain, placeholderType: "routine") } else { structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectKeyChain.rawValue)*>", value: "", placeholderType: "routine") } //<*event_cs_trackers_str*> = "console", "GA" let eventCsTrackers: String = try generateEventCsTrackers(eventDic![EventPlistKey.trackrs.rawValue] as! [String]) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.eventTrackers.rawValue)*>", value: eventCsTrackers, placeholderType: "routine") /* <*event_keysNames*> = private let kKey1 = "key1" private let kKey2 = "key2" */ let eventKeyNames: String = try generateEventKeysNames(originalStringKeys) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.keysNames.rawValue)*>", value: eventKeyNames, placeholderType: "routine") let objectKeyNames: String = try generateEventKeysNames(objectNames) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectKeyNames.rawValue)*>", value: objectKeyNames, placeholderType: "routine") if !objects.isEmpty { let objectStructure = try generateObjectStructs(objects) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectStruct.rawValue)*>", value: objectStructure, placeholderType: "routine") } else { structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectStruct.rawValue)*>", value: "", placeholderType: "routine") } /* <*event_keysVars*> = let key1 : String let key2 : String */ let eventKeysVars: String = try generateKeyVariables(cleanKeys, keyType: "eventKey") let objectKeysVars: String = try generateObjectKeysVariables(objectNames) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.keysVars.rawValue)*>", value: eventKeysVars, placeholderType: "routine") structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.objectKeysVars.rawValue)*>", value: objectKeysVars, placeholderType: "routine") /* <*event_init*> = init(<*event_init_params*>) { super.init() <*event_init_assigns_list*> } <*event_init_params*> = test1: String, test2: String, test3: String <*event_init_assigns_list*> = self.test1 = test1 self.test2 = test2 self.test3 = test3 */ let eventInit: String = try generateEventInit(cleanKeys, objectNames) structString = replacePlaceholder(structString, placeholder: "<*\(EventTemplatePlaceholder.eventInit.rawValue)*>", value: eventInit, placeholderType: "routine") structsArray.append(structString) } //base list template resultString.replaceOccurrences(of: "<*\(EventTemplatePlaceholder.eventList.rawValue)*>", with: structsArray.joined(separator: "\n"), options: NSString.CompareOptions.caseInsensitive, range: NSRange(location: 0, length: resultString.length) ) return resultString } private func replacePlaceholder(_ original: String, placeholder: String, value: String, placeholderType: String) -> String { if original.lengthOfBytes(using: String.Encoding.utf8) < 1 || placeholder.lengthOfBytes(using: String.Encoding.utf8) < 1 { return original } let valueToReplace: String var mutableValue = value if placeholder.contains("<*!") { mutableValue.replaceSubrange(mutableValue.startIndex...mutableValue.startIndex, with: String(mutableValue[value.startIndex]).capitalized) //only first capitalised letter, maintain the rest immutated valueToReplace = mutableValue } else { valueToReplace = value } switch placeholderType { case "routine": return original.replacingOccurrences(of: placeholder, with: valueToReplace) case "eventParameter": return original.replacingOccurrences(of: placeholder, with: valueToReplace + ": String") case "objectPlaceholder": return original.replacingOccurrences(of: placeholder, with: valueToReplace + ": [\(sanitised(valueToReplace).capitalizingFirstLetter())]") default: return original.replacingOccurrences(of: placeholder, with: valueToReplace) } } //MARK Components generator func generateEventKeyValueChain(_ keys: [String], eventHasObjects: Bool) -> String { var resultArray: [String] = Array() for keyString in keys { var capKeyString = keyString capKeyString.replaceSubrange(capKeyString.startIndex...capKeyString.startIndex, with: String(capKeyString[capKeyString.startIndex]).capitalized) resultArray.append("k\(capKeyString): \(keyString) == \"\" ? NSNull() : \(keyString) as NSString") } if (eventHasObjects) { return "\n " + resultArray.joined(separator: ", \n ") + ",\n " } else if (resultArray.count > 0) { return "\n " + resultArray.joined(separator: ", \n ") + "\n " } return ":" } func generateObjectKeyValue(_ keys: [String]) -> String { var resultArray: [String] = Array() for keyString in keys { var capKeyString = keyString capKeyString.replaceSubrange(capKeyString.startIndex...capKeyString.startIndex, with: String(capKeyString[capKeyString.startIndex]).capitalized) resultArray.append("k\(capKeyString): \(keyString) == [] ? NSNull() : \(keyString) as [\(sanitised(capKeyString))] ") } if (resultArray.count > 0) { return "\n " + resultArray.joined(separator: ", \n ") + "\n " } return ":" } func generateObjectStructs(_ objects: [Any]) throws -> String { var resultArray: [String] = Array() let structEventObjectTemplate: String = try stringFromTemplate(EventTemplate.eventObjectStruct.rawValue) for object in objects { let key = (object as! NSDictionary) let objectName = key["name"] as! String let objectParamters: [String] = key[EventPlistKey.objectPayload.rawValue] as! [String] var capItemName = objectName capItemName.replaceSubrange(capItemName.startIndex...capItemName.startIndex, with: String(capItemName[capItemName.startIndex]).capitalized) var structObjectKeyString = replacePlaceholder(structEventObjectTemplate, placeholder: "<*\(EventTemplatePlaceholder.objectName.rawValue)*>", value: sanitised(capItemName), placeholderType: "routine") let objectKeysVars: String = try generateKeyVariables(objectParamters, keyType: "objectKey") structObjectKeyString = replacePlaceholder(structObjectKeyString, placeholder: "<*\(EventTemplatePlaceholder.objectStructParams.rawValue)*>\n", value: objectKeysVars, placeholderType: "routine") resultArray.append(structObjectKeyString) } if (resultArray.count > 0) { return "\n " + resultArray.joined(separator: "\n\n ") + "\n " } else { return "\n" + resultArray.joined(separator: "\n") + "\n " } } private func generateEventCsTrackers(_ trackers: [String]) throws -> String { var resultArray: [String] = Array() for keyString in trackers { resultArray.append("\"\(keyString)\"") } if resultArray.count < 1 { throw EventGeneratorError.trackerMissing } return resultArray.joined(separator: ", ") } private func generateEventKeysNames(_ keys: [String]) throws -> String { let structKeyNameTemplate: String = try stringFromTemplate(EventTemplate.keyName.rawValue) var resultArray: [String] = Array() for keyString in keys { var structKeyNameString = replacePlaceholder(structKeyNameTemplate, placeholder: "<*\(EventTemplatePlaceholder.keyNameOriginal.rawValue)*>", value: keyString, placeholderType: "routine") structKeyNameString = replacePlaceholder(structKeyNameString, placeholder: "<*!\(EventTemplatePlaceholder.keyName.rawValue)*>", value: sanitised(keyString), placeholderType: "routine") resultArray.append(structKeyNameString) } return resultArray.count > 0 ? resultArray.joined(separator: "\n ") : "" } private func generateKeyVariables(_ keys: [String], keyType: String) throws -> String { let structVarTemplate: String = try stringFromTemplate(EventTemplate.keyVar.rawValue) var resultArray: [String] = Array() for keyString in keys { let structVarString = replacePlaceholder(structVarTemplate, placeholder: "<*\(EventTemplatePlaceholder.keyName.rawValue)*>", value: sanitised(keyString), placeholderType: "routine") resultArray.append(structVarString) } switch keyType { case "eventKey": return resultArray.count > 0 ? resultArray.joined(separator: "\n ") : "" case "objectKey": return resultArray.count > 0 ? resultArray.joined(separator: "\n ") : "" default: return resultArray.count > 0 ? resultArray.joined(separator: "\n ") : "" } } private func generateObjectKeysVariables(_ keys: [String]) throws -> String { let structVarTemplate: String = try stringFromTemplate(EventTemplate.objectKeyVar.rawValue) var resultArray: [String] = Array() for keyString in keys { var structVarString = replacePlaceholder(structVarTemplate, placeholder: "<*\(EventTemplatePlaceholder.objectKeyName.rawValue)*>", value: keyString, placeholderType: "routine") structVarString = replacePlaceholder(structVarString, placeholder: "<*\(EventTemplatePlaceholder.formattedObjectKeyName.rawValue)*>", value: keyString.capitalizingFirstLetter(), placeholderType: "routine") resultArray.append(structVarString) } return resultArray.count > 0 ? resultArray.joined(separator: "\n ") : "" } private func generateEventInit(_ keys: [String], _ objectKeys: [String]) throws -> String { if keys.count == 0 { return "//MARK: Payload not configured" } var initTemplateString: String = try stringFromTemplate(EventTemplate.eventInit.rawValue) //replace event_init_assigns_list let initAssignsTemplateString: String = try stringFromTemplate(EventTemplate.eventInitAssignsList.rawValue) //replace event_init_params let initParamTemplateString: String = try stringFromTemplate(EventTemplate.eventInitParam.rawValue) var assignsResultArray: [String] = Array() var paramsResultArray: [String] = Array() for keyString in keys { let assignsResultString = replacePlaceholder(initAssignsTemplateString, placeholder: "<*\(EventTemplatePlaceholder.keyName.rawValue)*>", value: keyString, placeholderType: "routine") assignsResultArray.append(assignsResultString) let paramResultString = replacePlaceholder(initParamTemplateString, placeholder: "<*\(EventTemplatePlaceholder.keyName.rawValue)*>", value: keyString, placeholderType: "eventParameter") paramsResultArray.append(paramResultString) } // Object Keys if !objectKeys.isEmpty { for key in objectKeys { let assignsResultString = replacePlaceholder(initAssignsTemplateString, placeholder: "<*\(EventTemplatePlaceholder.keyName.rawValue)*>", value: key, placeholderType: "routine") assignsResultArray.append(assignsResultString) let paramResultString = replacePlaceholder(initParamTemplateString, placeholder: "<*\(EventTemplatePlaceholder.keyName.rawValue)*>", value: key,placeholderType: "objectPlaceholder") paramsResultArray.append(paramResultString) } } let eventInitAssignsString: String = assignsResultArray.joined(separator: "\n ") initTemplateString = replacePlaceholder(initTemplateString, placeholder: "<*\(EventTemplatePlaceholder.eventInitAssignsList.rawValue)*>", value: eventInitAssignsString, placeholderType: "routine") let eventInitParamsAssignsString: String = paramsResultArray.joined(separator: ",\n ") initTemplateString = replacePlaceholder(initTemplateString, placeholder: "<*\(EventTemplatePlaceholder.eventInitParams.rawValue)*>", value: eventInitParamsAssignsString, placeholderType: "routine" ) return initTemplateString } private func exitWithError() { // printHelp() exit(1) } //------------------------------------------------------------------------------------------------------------------------------ //MARK - Main script log(msg: "Generating Events Swift code...") log(msg: "Script arguments:") for argument in CommandLine.arguments { log(msg: "- \(argument)") } //validate if CommandLine.arguments.count < 3 { log(msg: "Wrong arguments") exitWithError() } do { //load plist let plistPath = CommandLine.arguments[1] let structsDict = try loadEventPlist(plistPath) log(msg: "Events Plist loaded \(structsDict)") //write struct file let structSwiftFilePath = CommandLine.arguments[2] if !FileManager.default.fileExists(atPath: structSwiftFilePath) { throw EventGeneratorError.swiftFileNotFound } //generate struct string let structsString: NSString = try generateEvents(structsDict as! [String : AnyObject]) log(msg: "Events code correctly generated") //write struct string in file log(msg: "Generating swift code in: \(structSwiftFilePath)") try structsString.write(toFile: structSwiftFilePath, atomically: true, encoding: String.Encoding.utf8.rawValue) } catch EventGeneratorError.plistNotFound { log(msg: "Invalid plist path") exitWithError() } catch EventGeneratorError.trackerMissing { log(msg: "Tracker(s) missing in one or more event(s)") exitWithError() } catch EventGeneratorError.templateNotFound { log(msg: "Error generating events code") exitWithError() } catch EventGeneratorError.templateMalformed { log(msg: "Error generating events code") exitWithError() } catch EventGeneratorError.swiftFileNotFound { log(msg: "Swift file not found") exitWithError() } catch { log(msg: "Generic error") exitWithError() } log(msg: "**Swift code generated successfully**") extension String { func capitalizingFirstLetter() -> String { return prefix(1).uppercased() + self.dropFirst() } }
39.513841
213
0.671045
8a15c3507e73a2ad5804d23479f9eb780568a22c
2,439
// // Extensions.swift // ApesterKit // // Created by Hasan Sa on 10/07/2019. // Copyright © 2019 Apester. All rights reserved. // import Foundation import WebKit // MARK:- String extension String { var dictionary: [String: Any]? { if let data = self.data(using: .utf8) { return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } return nil } } extension Dictionary { func floatValue(for key: Key) -> CGFloat { CGFloat(self[key] as? Double ?? 0) } } extension WKWebView { struct Options { typealias Delegate = WKNavigationDelegate & UIScrollViewDelegate & WKScriptMessageHandler & WKUIDelegate let events: [String] let contentBehavior: UIScrollView.ContentInsetAdjustmentBehavior weak var delegate: Delegate? } private static let navigatorUserAgent = "navigator.userAgent" static func make(with options: Options, params: [String: String]?) -> WKWebView { let delegate = options.delegate let configuration = WKWebViewConfiguration() configuration.websiteDataStore = WKWebsiteDataStore.default() configuration.userContentController.register(to: options.events, delegate: delegate) if let rawParams = params { configuration.userContentController.addScript(params: rawParams); } configuration.allowsInlineMediaPlayback = true configuration.mediaTypesRequiringUserActionForPlayback = [] let webView = WKWebView(frame: .zero, configuration: configuration) webView.navigationDelegate = delegate webView.insetsLayoutMarginsFromSafeArea = true webView.scrollView.isScrollEnabled = false webView.scrollView.bouncesZoom = false webView.scrollView.delegate = delegate webView.uiDelegate = delegate webView.scrollView.contentInsetAdjustmentBehavior = options.contentBehavior return webView } } extension UIColor { var rgba: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) let rgba = "rgba(\(Int(r * 255)),\(Int(g * 255)),\(Int(b * 255)),\(Int(a * 255.0)))" return rgba } } extension UIView { var allSubviews: [UIView] { return subviews + subviews.flatMap { $0.allSubviews } } }
31.269231
112
0.654777
9c5558201e1cd8ddfaebc87af264870e1f82effc
666
// // main.swift // // // Created by Kit Transue on 2020-08-14. // Copyright © 2020 Kit Transue // SPDX-License-Identifier: Apache-2.0 // import Foundation // utilities import DeftLog import LEDUtils import PlatformSPI // the device: import ShiftLED do { DeftLog.settings = [ ("com.didactek", .trace) ] let configurationGuru = PlatformDeviceBroker.shared let spi = try! configurationGuru.platformSPI(speedHz: 30_500) let ledCount = 73 let leds = ShiftLED(bus: spi, stringLength: ledCount, current: 0.05) leds.clear() leds.all(color: .blue) leds[ledCount / 2] = .red leds.flushUpdates() sleep(5) leds.clear() }
18
72
0.671171
e2478d12b19381fe974c9ad218fe88e950a32e07
1,632
import Foundation import TSCBasic import TuistGraph /// A protocol that defines an interface to map dependency graphs. public protocol GraphMapping { /// Given a value graph, it maps it into another value graph. /// - Parameter graph: Graph to be mapped. func map(graph: Graph) throws -> (Graph, [SideEffectDescriptor]) } /// A mapper that is initialized with a mapping function. public final class AnyGraphMapper: GraphMapping { /// A function to map the graph. let mapper: (Graph) throws -> (Graph, [SideEffectDescriptor]) /// Default initializer /// - Parameter mapper: Function to map the graph. public init(mapper: @escaping (Graph) throws -> (Graph, [SideEffectDescriptor])) { self.mapper = mapper } public func map(graph: Graph) throws -> (Graph, [SideEffectDescriptor]) { try mapper(graph) } } public final class SequentialGraphMapper: GraphMapping { /// List of mappers to be executed sequentially. private let mappers: [GraphMapping] /// Default initializer /// - Parameter mappers: List of mappers to be executed sequentially. public init(_ mappers: [GraphMapping]) { self.mappers = mappers } public func map(graph: Graph) throws -> (Graph, [SideEffectDescriptor]) { try mappers.reduce((graph, [SideEffectDescriptor]())) { input, mapper in let graph = input.0 var sideEffects = input.1 let (mappedGraph, newSideEffects) = try mapper.map(graph: graph) sideEffects.append(contentsOf: newSideEffects) return (mappedGraph, sideEffects) } } }
34
86
0.669118
f4cea01c8cbf502c296805925bf3e0c0fcbc5185
5,640
// // File.swift // RMBT // // Created by Tomas Baculák on 17/03/2017. // Copyright © 2017 SPECURE GmbH. All rights reserved. // import Foundation import RMBTClient protocol ManageMeasurement: AnyObject, RMBTClientDelegate, ManageMeasurementView { // // allocate with client type - .nkom for NKOM project, .standard for SPECURE, AKOS, .original for original solution var rmbtClient: RMBTClient { get } /// var measurementResultUuid: String? { get set } /// var isQosAvailable: Bool { get set } /// var wasTestExecuted: Bool { get set } /// // func startMeasurementAction() // func abortMeasurementAction() -> UIAlertController? func abortLoopModeMeasurementAction(abortAction: AlertAction, keepAction: AlertAction) -> UIAlertController? } // Default implementation extension ManageMeasurement { // func abortMeasurementAction() -> UIAlertController? { if rmbtClient.running { return UIAlertController.presentAbortAlert(nil, abortAction: ({ [weak self] _ in self?.rmbtClient.delegate = nil self?.stopMeasurement() self?.manageViewControllerAbort() })) } return nil } // func abortLoopModeMeasurementAction(abortAction: AlertAction, keepAction: AlertAction) -> UIAlertController? { return UIAlertController.presentAbortLoopModeAlert(nil, abortAction: ({ [weak self] action in self?.rmbtClient.delegate = nil self?.stopMeasurement() abortAction?(action) }), keepAction: { [weak self] action in self?.rmbtClient.delegate = nil self?.stopMeasurement() keepAction?(action) }) } // func startMeasurementAction() { RMBTLocationTracker.sharedTracker.startAfterDeterminingAuthorizationStatus { [weak self] in guard let strongSelf = self else { return } // self?.rmbtClient.delegate = strongSelf // self?.rmbtClient.startMeasurement() // manage view self?.manageViewNewStart() } } // func startQosMeasurementAction() { RMBTLocationTracker.sharedTracker.startAfterDeterminingAuthorizationStatus { [weak self] in guard let strongSelf = self else { return } // self?.rmbtClient.delegate = strongSelf // self?.rmbtClient.startQosMeasurement(inMain: false) } } // MARK: RMBTClientDelegate // NKOM DEFAULT func speedMeasurementDidMeasureSpeed(throughputs: [RMBTThroughput], inPhase phase: SpeedMeasurementPhase) { if let throughput = throughputs.last { // last? let speedString = RMBTSpeedMbpsString(throughput.kilobitsPerSecond(), withMbps: false) let speedLogValue = RMBTSpeedLogValue(throughput.kilobitsPerSecond(), gaugeParts: 4, log10Max: log10(1000)) // manage view manageViewProgress(phase: phase, title: speedString, value: speedLogValue) } } // func speedMeasurementDidUpdateWith(progress: Float, inPhase phase: SpeedMeasurementPhase) { } func measurementDidComplete(_ client: RMBTClient, withResult result: String) { logger.debug("Main Meaasurement - DID COMPLETE") self.rmbtClient.delegate = nil self.wasTestExecuted = true self.measurementResultUuid = result // manage view manageViewFinishMeasurement(uuid: result) } /// func measurementDidFail(_ client: RMBTClient, withReason reason: RMBTClientCancelReason) { DispatchQueue.main.async { logger.debug("MEASUREMENT FAILED: \(reason)") self.rmbtClient.delegate = nil // _ = UIAlertController.presentDidFailAlert(reason, dismissAction: ({ [weak self] _ in self?.manageViewsAbort() self?.manageViewControllerAbort() }), startAction: ({ [weak self] _ in self?.startMeasurementAction() }) ) } } /// func speedMeasurementDidStartPhase(_ phase: SpeedMeasurementPhase) { manageViewProcess(phase) } /// func speedMeasurementDidFinishPhase(_ phase: SpeedMeasurementPhase, withResult result: Double) { manageViewFinishPhase(phase, withResult: result) } // MARK: QoS /// func qosMeasurementDidStart(_ client: RMBTClient) { // self.isQosAvailable = true // manage view manageViewAfterQosStart() } /// func qosMeasurementDidUpdateProgress(_ client: RMBTClient, progress: Float) { let progressPercentValue = Int(progress * 100) // manage view manageViewAfterQosUpdated(value: progressPercentValue) } /// func qosMeasurementList(_ client: RMBTClient, list: [QosMeasurementType]) { // manageViewAfterQosGetList(list: list) } /// func qosMeasurementFinished(_ client: RMBTClient, type: QosMeasurementType) { // manageViewAfterQosFinishedTest(type: type) } // Mark : Helpers private func stopMeasurement() { // self.wasTestExecuted = false // self.rmbtClient.stopMeasurement() // manage view manageViewsAbort() } }
32.413793
122
0.602305
e5943214b63c6a4a46b333f6643c1c72fb0f0ced
340
// // QXOperators..swift // QXUIKitExtension // // Created by labi3285 on 2020/1/4. // Copyright © 2020 labi3285_lab. All rights reserved. // import Foundation //precedencegroup QXOperatorAB { // higherThan: AdditionPrecedence // associativity: left // assignment: false //} infix operator /+: LogicalConjunctionPrecedence
17.894737
55
0.714706
2107df9c85e6e338de7c68471e255fcb2613914b
1,259
// // ListFileNames.swift // Flare // // Created by Chris on 3/2/20. // Copyright © 2020 Splinter. All rights reserved. // import Foundation /// https://www.backblaze.com/b2/docs/b2_list_file_names.html /// This is different to ListFileVersions in that it should only return one entry per file. enum ListFileNames { static func send(token: String, apiUrl: String, bucketId: String, startFileName: String?, maxFileCount: Int?, prefix: String?, delimiter: String?) throws -> ListFileVersionsResponse { guard let url = URL(string: apiUrl + "/b2api/v2/b2_list_file_names") else { throw Service.Errors.badApiUrl } var body: [String: Any] = [ "bucketId": bucketId, ] if let startFileName = startFileName { body["startFileName"] = startFileName } if let maxFileCount = maxFileCount { body["maxFileCount"] = maxFileCount } if let prefix = prefix { body["prefix"] = prefix } if let delimiter = delimiter { body["delimiter"] = delimiter } let (json, _) = try Service.shared.post(url: url, payload: body, token: token) return ListFileVersionsResponse.from(json: json) } }
34.027027
187
0.621922
fe3465252a993d9f13c0f7cb00eaec54ebb8d5bb
719
// // UIHelper.swift // TrillDemo // // Created by magic-devel on 2020/10/9. // import UIKit extension UIView { @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable public var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable public var borderColor: UIColor { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue.cgColor } } }
18.435897
55
0.522949
76db59fa778b4eb185a61417db3ca1f180681c83
9,666
// // The MIT License (MIT) - Copyright © 2018 Unsigned Apps Pty Ltd // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit // MARK: Convenience Conditions: UIView extension ViewStyle.Condition where T: UIView { /// Creates and returns a `Condition` that checks a UIView's `traitCollection.horizontalSizeClass` for a matching `UIUserInterfaceSizeClass` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIUserInterfaceSizeClass` to match against. /// /// - Returns: The new Condition. /// public static func horizontalSizeClass (equals sizeClass: UIUserInterfaceSizeClass) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.horizontalSizeClass == sizeClass } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.verticalSizeClass` for a matching `UIUserInterfaceSizeClass` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIUserInterfaceSizeClass` to match against. /// /// - Returns: The new Condition. /// public static func verticalSizeClass (equals sizeClass: UIUserInterfaceSizeClass) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.verticalSizeClass == sizeClass } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.userInterfaceIdiom` for a matching `UIUserInterfaceIdiom` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIUserInterfaceIdiom` to match against. /// /// - Returns: The new Condition. /// public static func userInterfaceIdiom (equals idiom: UIUserInterfaceIdiom) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.userInterfaceIdiom == idiom } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.forceTouchCapability` for a matching `UIForceTouchCapability` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIForceTouchCapability` to match against. /// /// - Returns: The new Condition. /// public static func forceTouchCapability (equals capability: UIForceTouchCapability) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.forceTouchCapability == capability } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.preferredContentSizeCategory` for a matching `UIContentSizeCategory` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIContentSizeCategory` to match against. /// /// - Returns: The new Condition. /// public static func preferredContentSizeCategory (equals category: UIContentSizeCategory) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.preferredContentSizeCategory == category } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.displayGamut` for a matching `UIDisplayGamut` /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The `UIDisplayGamut` to match against. /// /// - Returns: The new Condition. /// public static func displayGamut (equals gamut: UIDisplayGamut) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.displayGamut == gamut } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.displayScale` for a matching display scale. /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The display scale to match against. /// /// - Returns: The new Condition. /// public static func displayScale (equals scale: CGFloat) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.displayScale == scale } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.displayScale` for a display scale that is greater /// than the specified one. /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The display scale to test against. /// /// - Returns: The new Condition. /// public static func displayScale (greaterThan scale: CGFloat) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.displayScale > scale } } /// Creates and returns a `Condition` that checks a UIView's `traitCollection.displayScale` for a display scale that is less /// than the specified one. /// /// The the documentation for `UITraitCollection` for more information. /// /// - Parameters: /// - equals: The display scale to test against. /// /// - Returns: The new Condition. /// public static func displayScale (lessThan scale: CGFloat) -> ViewStyle.Condition { return ViewStyle.Condition { $0.traitCollection.displayScale < scale } } } // MARK: - Convenience Conditions: UIControl extension ViewStyle.Condition where T: UIControl { /// Creates and returns a `Condition` that checks a UIControl's `state` for a matching `UIControlState` /// /// The the documentation for `UIControlState` for more information. /// /// - Parameters: /// - equals: The `UIControlState` to match against. /// /// - Returns: The new Condition. /// public static func controlState (equals state: UIControl.State) -> ViewStyle.Condition { return ViewStyle.Condition { $0.state == state } } } // MARK: - Convenience Conditions: UICollectionViewCell extension ViewStyle.Condition where T: UICollectionViewCell { /// A derived enum that reflects the state of the UICollectionViewCell /// /// Remember that a cell can be `.selected` AND `.highlighted`. So test for both if you /// want both at the same time. /// public enum UICollectionViewCellState { /// Normal State: when `cell.isHighlighted == false && cell.isSelected == false` case normal /// Selected State: when `cell.isSelected == true` case selected /// Highlighted State: when `cell.isHighlighted == true` case highlighted } /// Creates and returns a `Condition` that checks a UICollectionViewCell's. /// /// Note that `State` is derived based on `UICollectionViewCell.isSelected` and `UICollectionViewCell.isHighlighted` /// /// - Parameters: /// - equals: The state to test against. /// /// - Returns: The new Condition. /// public static func cellState (equals state: UICollectionViewCellState) -> ViewStyle.Condition { return ViewStyle.Condition { cell in switch state { case .normal: return cell.isHighlighted == false && cell.isSelected == false case .selected: return cell.isSelected == true case .highlighted: return cell.isHighlighted == true } } } } // MARK: - Convenience Conditions: UITableViewCell extension ViewStyle.Condition where T: UITableViewCell { /// A derived enum that reflects the state of the UITableViewCell /// /// Remember that a cell can be in multiple states at a time (except `.normal`), so test for all the ones /// you want to match against. /// public enum UITableViewCellState { /// Normal State: when `cell.isHighlighted == false && cell.isSelected == false && cell.isEditing == false` case normal /// Editing State: when `cell.isEditing == true` case editing /// Selected State: when `cell.isSelected == true` case selected /// Highlighted State: when `cell.isHighlighted == true` case highlighted } /// Creates and returns a `Condition` that checks a UITableViewCell's. /// /// Note that `State` is derived based on the various `isSelected`, `isHighlighted` and `isEditing` methods /// and can be in more than state at a time, so make sure you test for all the ones you want to match. /// /// - Parameters: /// - equals: The state to test against. /// /// - Returns: The new Condition. /// public static func cellState (equals state: UITableViewCellState) -> ViewStyle.Condition { return ViewStyle.Condition { cell in switch state { case .normal: return cell.isHighlighted == false && cell.isSelected == false && cell.isEditing == false case .editing: return cell.isEditing == true case .selected: return cell.isSelected == true case .highlighted: return cell.isHighlighted == true } } } }
38.664
150
0.654666
71237619c45f135d53374e1c00f79f1d0de3e6ed
4,400
// // DIDHashView.swift // DIDHashView // // Created by zY on 2022/2/24. // import UIKit import CoreGraphics public enum DIDMotifShage { case square case rectangle case circle case hexagon } /// 理论上讲这个view都是正方形,根据type去裁剪展示区域 public class DIDMotifView: UIView { // MARK: - Public Properties private var address: String? // 用户固定设置的shape // 若未设置,则shape默认为address解出来的 private var shape: DIDMotifShage? // MARK: - Properties private lazy var shapeLayer: CAShapeLayer = { let layer = CAShapeLayer() return layer }() private var info: (Int, [Int], DIDMotifShage)? private var hexagonLayers: [CAShapeLayer] = [] // MARK: - Init Functions override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("DIDMotifView deinit") } public override func layoutSubviews() { super.layoutSubviews() setupUI() } } // MARK: - UI Functions extension DIDMotifView { private func commonInit() { layer.addSublayer(shapeLayer) for _ in 0...7 { let subLayer = CAShapeLayer() subLayer.isHidden = true subLayer.fillColor = UIColor(white: 1, alpha: 0.5).cgColor shapeLayer.addSublayer(subLayer) hexagonLayers.append(subLayer) } } private func setupUI() { if let colorIndex = info?.0, let hexStr = DIDMotifUtils.backgroundColors.objectAtIndexSafely(index: colorIndex) { shapeLayer.fillColor = UIColor(hex: hexStr).cgColor } clipToShape() layoutItems() } private func clipToShape() { guard let shape = info?.2 else { return } let side = self.frame.width switch shape { case .square: shapeLayer.path = DIDMotifUtils.squarePathWith(side: side).cgPath case .rectangle: shapeLayer.path = DIDMotifUtils.rectanglePathWith(side: side).cgPath case .circle: shapeLayer.path = DIDMotifUtils.circlePathWith(side: side).cgPath case .hexagon: shapeLayer.path = DIDMotifUtils.hexagonPathWith(side: side).cgPath } let mask = CAShapeLayer() mask.path = shapeLayer.path layer.mask = mask } private func layoutItems() { let gridWidth = min(self.frame.width/9, self.frame.height) let points = info?.1.map({ CGPoint(x: CGFloat($0/8 + 1)*gridWidth, y: CGFloat($0%8 + 1)*gridWidth) }) let sideLength = self.frame.width*0.25 let itemWidth = sideLength*2 for (index, subLayer) in hexagonLayers.enumerated() { subLayer.isHidden = false subLayer.path = DIDMotifUtils.hexagonPathWith(side: itemWidth).cgPath subLayer.bounds = CGRect(x: 0, y: 0, width: itemWidth, height: itemWidth) subLayer.fillColor = UIColor(white: 1, alpha: 0.3).cgColor let point = points?.objectAtIndexSafely(index: index) ?? CGPoint.zero subLayer.position = point subLayer.add(animTo(point: point), forKey: "move") } } private func animTo(point: CGPoint) -> CASpringAnimation { let anim = CASpringAnimation(keyPath: "position") anim.repeatCount = 1 anim.duration = 0.5 anim.beginTime = CACurrentMediaTime() anim.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) anim.fromValue = CGPoint(x: self.frame.width/2, y: self.frame.height/2) anim.toValue = point anim.damping = 6.5 anim.stiffness = 80 anim.initialVelocity = 4 return anim } } // MARK: - Action Functions extension DIDMotifView { private func decodeAddress() { guard let address = address else { return } info = DIDMotifUtils.getMotifInfo(did: address) if let shape = shape { info?.2 = shape } setupUI() } } // MARK: Public extension DIDMotifView { public func renderWith(address: String, shape: DIDMotifShage?) { self.address = address self.shape = shape decodeAddress() } }
28.571429
109
0.596591
5dae738b5b1629f3cc058297b7ea205b19f644b2
1,189
// // OneTableViewController.swift // LZPageMenu // // Created by Randy Liu on 2018/1/25. // Copyright © 2018年 Randy Liu. All rights reserved. // import UIKit class OneTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private let indentifire = "Indentifire" override func viewDidLoad() { super.viewDidLoad() let tableView = UITableView.init(frame: view.bounds) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.white view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: indentifire) if cell == nil { cell = UITableViewCell.init(style: .value1, reuseIdentifier: indentifire) } cell!.textLabel?.text = "Row:\(indexPath.row)" return cell! } }
29.725
100
0.664424
f5040909ca595871f00983d8b5404aa1055a8851
287
// // MovieRepository.swift // TheOneApp // // Created by Silvia España on 16/12/21. // import Foundation import Combine protocol MovieRepository { func getAllMovies() -> AnyPublisher<[Movie], Error> func getMovieDetail(id: String) -> AnyPublisher<Movie, Error> }
16.882353
65
0.682927
d50257479d2d19ac88541106a5e5f17d8b68c9d6
2,747
import Foundation import os.log /// A property wrapper which reads and writes the wrapped value in the **Keychain**. /// /// The wrapped value must conform to **SecureStorable**. @propertyWrapper public struct SecureStored<Value: SecureStorable> { /// The default value if a value of the given type is not specified for the given key. public let defaultValue: Value /// The key to read and write the value to in the **Keychain**. public let key: SecureStoreKey /// The level of accessibility. public let accessibility: SecureStoreAccessibility /// Creates a property wrapper which reads and writes the wrapped value in the **Keychain**. /// - Parameters: /// - defaultValue: The default value if a value of the given type is not specified for the given key. /// - key: The key to read and write the value to in the **Keychain**. /// - accessibility: The level of accessibility. Defaults to `SecureStoreAccessibility.afterFirstUnlockThisDeviceOnly` public init(wrappedValue defaultValue: Value = .defaultStoredValue, _ key: SecureStoreKey, accessibility: SecureStoreAccessibility = .afterFirstUnlockThisDeviceOnly) { self.defaultValue = defaultValue self.key = key self.accessibility = accessibility } public var wrappedValue: Value { get { do { return try Value.read(key: key, accessibility: accessibility) ?? defaultValue } catch { _logError(error) return defaultValue } } set { do { try newValue.write(key: key, accessibility: accessibility) } catch { _logError(error) } } } public var projectedValue: SecureStored { return self } /// Remove the stored value from the **Keychain**. /// /// To access this method you have to access the property wrapper via the projected value. /// ```swift /// @SecureStored("test") var test = "" /// $test.remove() /// ``` public func remove() { let query = _KeychainQuery(key: key, accessibility: accessibility) do { try _KeychainDelete(query: query) } catch { _logError(error) } } } // MARK: - Log extension SecureStored { private func _logError(_ error: Error) { if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { os_log("Error: %@", log: OSLog(subsystem: "com.felixherrmann.FHPropertyWrappers", category: "SecureStored"), type: .error, String(describing: error)) } else { NSLog("Error: %@", String(describing: error)) } } }
33.91358
171
0.611212
d6fe5360afcc6253267775adc03f9f11285fde70
1,895
// // Notifier.swift // uPic // // Created by Svend Jin on 2019/6/13. // Copyright © 2019 Svend Jin. All rights reserved. // import Foundation public protocol Notifier { associatedtype Notification: RawRepresentable } public extension Notifier where Notification.RawValue == String { private static func nameFor(notification: Notification) -> String { return "\(self).\(notification.rawValue)" } // instance func postNotification(notification: Notification, object: String? = nil) { Self.postNotification(notification, object: object) } func postNotification(notification: Notification, object: String? = nil, userInfo: [String: AnyObject]? = nil) { Self.postNotification(notification, object: object, userInfo: userInfo) } // static static func postNotification(_ notification: Notification, object: String? = nil, userInfo: [AnyHashable: Any]? = nil) { let name = nameFor(notification: notification) DistributedNotificationCenter.default() .postNotificationName(NSNotification.Name(rawValue: name), object: object, userInfo: userInfo, deliverImmediately: true) } // addObserver static func addObserver(observer: AnyObject, selector: Selector, notification: Notification, object: String? = nil) { let name = nameFor(notification: notification) DistributedNotificationCenter.default() .addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: name), object: object) } // removeObserver static func removeObserver(observer: AnyObject, notification: Notification, object: String? = nil) { let name = nameFor(notification: notification) DistributedNotificationCenter.default() .removeObserver(observer, name: NSNotification.Name(rawValue: name), object: object) } }
31.065574
136
0.697098
871d41b183fd43c4bf4467534e760767eac066d2
795
// // SearchCellTableViewCell.swift // Stocks // // Created by Daniel Klinkert Houfer on 4/23/17. // Copyright © 2017 Daniel Klinkert Houfer. All rights reserved. // import UIKit class SearchCellTableViewCell: UITableViewCell { var selectedClousure:(()->())? @IBOutlet weak var name: UILabel! 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 } func setupCell(preview:StockPreview) { name.text = preview.name } @IBAction func buttonAction(_ sender: Any) { selectedClousure?() } }
21.486486
65
0.631447
505db22b0db603042d298d5f4ef4db4c6f83aab5
3,101
// // ItemViewTests.swift // // Created by Hans Seiffert on 24.11.20. // // --- // MIT License // // Copyright © 2020 Hans Seiffert // // 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 // import XCTest import QAMenu @testable import QAMenuUIKit class ItemViewTests: XCTestCase { // MARK: - containerTableViewCell func test_containerTableViewCell_whenHavingNoParent_returnsNil() throws { let sut = CustomItemView() XCTAssertNil(sut.containerTableViewCell) } func test_containerTableViewCell_whenHavingNoContainerParent_returnsNil() throws { let sut = CustomItemView() let view = UIView() view.addSubview(sut) XCTAssertNil(sut.containerTableViewCell) } func test_containerTableViewCell_whenHavingDirectContainerParent_returnsContainer() throws { let sut = CustomItemView() let view = UIView() let container = ContainerTableViewCell() view.addSubview(container) container.addSubview(sut) XCTAssertNotNil(sut.containerTableViewCell) } func test_containerTableViewCell_whenHavingNonDirectContainerParent_returnsContainer() throws { let sut = CustomItemView() let view = UIView() let container = ContainerTableViewCell() container.addSubview(view) view.addSubview(sut) XCTAssertNotNil(sut.containerTableViewCell) } func test_containerTableViewCell_whenHavingOnlyContainerParent_returnsContainer() throws { let sut = CustomItemView() let container = ContainerTableViewCell() container.addSubview(sut) XCTAssertNotNil(sut.containerTableViewCell) } func test_containerTableViewCell_whenHavingMultipleContainerParents_returnsNearestContainer() throws { let sut = CustomItemView() let container1 = ContainerTableViewCell() let container2 = ContainerTableViewCell() container2.addSubview(container1) container1.addSubview(sut) XCTAssertEqual(sut.containerTableViewCell, container1) } }
31.969072
106
0.726217
18bfca6ab7da2556098b871c1c210b73f0ad74fe
772
// // Constants.swift // SpotIAP // // Created by Shawn Clovie on 30/1/2018. // Copyright © 2018 Shawn Clovie. All rights reserved. // import Foundation import Spot public enum IAPTransactionState: String { case idle case purchasing case validating case shouldValidate case validated case invalided } public struct IAPErrorSource { public static let productFetchFailed = AttributedError.Source("iap.productFetchFailed") public static let invalidReceipt = AttributedError.Source("iap.invalidReceipt") public static let purchaseFailed = AttributedError.Source("iap.purchaseFailed") public static let purchaseDeferred = AttributedError.Source("iap.purchaseDeferred") public static let receiptFetchFailed = AttributedError.Source("iap.receiptFetchFailed") }
27.571429
88
0.794041
26b7287c3eb5d53b34a782311fa184513e428e01
1,988
// // Meal.swift // FoodTracker // // Created by Mohdi Habibi on 7/13/16. // import UIKit class Meal: NSObject, NSCoding{ //MARK: Properties var name: String var photo: UIImage? //var rating: Int var chef: String? //MARK: Archiving Paths static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("meals") static let ArchiveURLSalad = DocumentsDirectory.appendingPathComponent("salad") static let ArchiveURLApp = DocumentsDirectory.appendingPathComponent("appetizer") static let ArchiveURLDes = DocumentsDirectory.appendingPathComponent("desert") //MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" // static let ratingKey = "rating" static let chefKey = "chef" } init? (name: String, photo: UIImage?, chef: String?){ self.name = name self.photo = photo //self.rating = rating self.chef = chef super.init() if name.isEmpty { return nil } } //MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.nameKey) aCoder.encode(chef, forKey: PropertyKey.chefKey) aCoder.encode(photo, forKey: PropertyKey.photoKey) //aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String let photo = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage //let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey) let chef = aDecoder.decodeObject(forKey: PropertyKey.chefKey) as? String self.init(name: name, photo: photo, chef: chef!) } }
29.235294
107
0.644366
1cd04d6962d1a9d32926cef0c8d17475adb265e0
407
// // Applicable.swift // Velik // // Created by Grigory Avdyushin on 23/06/2020. // Copyright © 2020 Grigory Avdyushin. All rights reserved. // import CoreData protocol Applicable { } extension Applicable where Self: AnyObject { @inlinable func apply(_ block: (Self) throws -> Void) rethrows -> Self { try block(self) return self } } extension NSObject: Applicable { }
17.695652
65
0.660934
670454d7964bc26f7732d3e6fb8f22aa3e30fb8f
2,611
/* ----------------------------------------------------------------------------- This source file is part of MedKitMIP. Copyright 2017-2018 Jon Griffeth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ import Foundation import MedKitCore import SecurityKit /** MIP Version 1, server connection policy. */ class MIPV1ServerPolicy: TLSDelegate { // MARK: Private Properties private let principalManager: PrincipalManager // MARK: - Initializers init(principalManager: PrincipalManager) { self.principalManager = principalManager } // MARK: - func tlsCredentials(_ tls: TLS) -> PublicKeyCredentials? { return principalManager.primary?.credentials as? PublicKeyCredentials } func tlsPeerName(_ tls: TLS) -> String? { return nil } func tlsPeerAuthenticationComplete(_ tls: TLS) -> Error? { var error: Error? if !verifyCredentials() { error = SecurityKitError.badCredentials } return error } func tlsShouldAuthenticatePeer(_ tls: TLS) -> Bool { return false } func tls(_ tls: TLS, shouldAccept peer: Principal) -> Bool { return true } /** */ private func verifyCredentials() -> Bool { /* if let trust = tls.peerTrust { var status: OSStatus var result: SecTrustResultType = .invalid // set anchor certificates let (anchorCertificates, error) = Keychain.main.findRootCertificates() guard error == nil else { return false } status = trust.setAnchorCertificates(anchorCertificates!) guard status == errSecSuccess else { return false } // evaluate trust status = trust.evaluate(&result) guard status == errSecSuccess else { return false } return result == .unspecified } return false */ return true } } // End of File
24.175926
82
0.592493
d6def0800218fec8d0a86433a48d4ceb960a9f70
3,049
// // RemoteSource.swift // HostsX // // Created by zm on 2021/12/7. // import Foundation import AppKit struct RemoteSource { private enum RemoteSourceKey { static let data = "remoteSourceKey.data" } private static let defaultData = [ Hosts("Hosts01", url: HostsUrl.h1, isOrigin: true), Hosts("Hosts02", url: HostsUrl.h2) ] private static var data: [Hosts] { set { let encoder = JSONEncoder() if let data = try? encoder.encode(newValue) { UserDefaults.standard.setValue(data, forKey: RemoteSourceKey.data) } } get { guard let data = UserDefaults.standard.value(forKey: RemoteSourceKey.data) as? Data else { return defaultData } let decoder = JSONDecoder() if let result = try? decoder.decode([Hosts].self, from: data) { return result } return defaultData } } private static var row = 0 private static var current: Hosts { self[row] } private static var origin: Hosts { data.first(where: {$0.isOrigin}) ?? data[0]} static var originUrl: String { origin.url } static var currentAlias: String { current.alias } static var rows: Int { data.count } static var canAdd: Bool { rows <= 10 } static var canRemove: Bool { !current.isOrigin } static var canSetAsOrigin: Bool { current.isAvailable && canRemove } } extension RemoteSource { static subscript(_ row: Int) -> Hosts { get { data[row] } set { data[row] = newValue } } static func cancel() { Network.cancel() } static func select(_ row: Int, completion: VoidClosure? = .none) { guard row > -1 else { return } self.row = row completion?() } static func check(completion: @escaping (Hosts) -> Void) { completion(current) Network.check(current.url) { let hosts = current hosts.status = $0 self[row] = hosts completion(current) } } @discardableResult static func removed() -> Int { let _row = row data.remove(at: _row) row = 0 return _row } static func insert(_ alias: String, urlString: String) { data.insert(Hosts(alias, url: urlString), at: 1) row = 1 } static func setAsOrigin() { let hosts = current hosts.isOrigin.toggle() removed() for (i, val) in data.enumerated() { val.isOrigin.toggle() data[i] = val } data.insert(hosts, at: 0) } static func restore() { data = defaultData row = 0 } static func open() { NSWorkspace.open(current.url) } static func containsAlias(_ alias: String) -> Bool { data.contains(where: {$0.alias == alias }) } static func containsURL(_ url: String) -> Bool { data.contains(where: {$0.url == url }) } }
24.007874
102
0.557888
fc368df923738959668703d7560dd942706fa42c
211
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { init( = { case let b = [ { class case ,
17.583333
87
0.720379