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
|
---|---|---|---|---|---|
283206821a9202ebfd10cb5ec91f48c813cc416e | 397 | //
// NetworkStackTypes.swift
// UBCore
//
// Created by Леван Чикваидзе on 11/09/2019.
// Copyright © 2019 UnitBean. All rights reserved.
//
import Moya
public typealias NetworkProvider<T: TargetType> = MoyaProvider<T>
public typealias Task = Moya.Task
public typealias Method = Moya.Method
public typealias URLEncoding = Moya.URLEncoding
public typealias JSONEncoding = Moya.JSONEncoding
| 23.352941 | 65 | 0.768262 |
23b0b283fd04583910f13441ab116491cb22d9a2 | 3,070 | //
// Xcodeproj.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
import XcodeEdit
struct BuildConfiguration {
let name: String
}
struct Xcodeproj: WhiteListedExtensionsResourceType {
static let supportedExtensions: Set<String> = ["xcodeproj"]
private let projectFile: XCProjectFile
let developmentLanguage: String
init(url: URL) throws {
try Xcodeproj.throwIfUnsupportedExtension(url.pathExtension)
let projectFile: XCProjectFile
// Parse project file
do {
do {
projectFile = try XCProjectFile(xcodeprojURL: url)
}
catch let error as ProjectFileError {
warn(error.localizedDescription)
projectFile = try XCProjectFile(xcodeprojURL: url, ignoreReferenceErrors: true)
}
}
catch {
throw ResourceParsingError.parsingFailed("Project file at '\(url)' could not be parsed, is this a valid Xcode project file ending in *.xcodeproj?\n\(error.localizedDescription)")
}
self.projectFile = projectFile
self.developmentLanguage = projectFile.project.developmentRegion
}
private func findTarget(name: String) throws -> PBXTarget {
// Look for target in project file
let allTargets = projectFile.project.targets.compactMap { $0.value }
guard let target = allTargets.filter({ $0.name == name }).first else {
let availableTargets = allTargets.compactMap { $0.name }.joined(separator: ", ")
throw ResourceParsingError.parsingFailed("Target '\(name)' not found in project file, available targets are: \(availableTargets)")
}
return target
}
func resourcePaths(forTarget targetName: String) throws -> [Path] {
let target = try findTarget(name: targetName)
let resourcesFileRefs = target.buildPhases
.compactMap { $0.value as? PBXResourcesBuildPhase }
.flatMap { $0.files }
.compactMap { $0.value?.fileRef }
let fileRefPaths = resourcesFileRefs
.compactMap { $0.value as? PBXFileReference }
.compactMap { $0.fullPath }
let variantGroupPaths = resourcesFileRefs
.compactMap { $0.value as? PBXVariantGroup }
.flatMap { $0.fileRefs }
.compactMap { $0.value?.fullPath }
return fileRefPaths + variantGroupPaths
}
func scriptBuildPhases(forTarget targetName: String) throws -> [PBXShellScriptBuildPhase] {
let target = try findTarget(name: targetName)
return target.buildPhases
.compactMap { $0.value as? PBXShellScriptBuildPhase }
}
func buildConfigurations(forTarget targetName: String) throws -> [BuildConfiguration] {
let target = try findTarget(name: targetName)
guard let buildConfigurationList = target.buildConfigurationList.value else { return [] }
let buildConfigurations = buildConfigurationList.buildConfigurations
.compactMap { $0.value }
.compactMap { configuration -> BuildConfiguration? in
return BuildConfiguration(name: configuration.name)
}
return buildConfigurations
}
}
| 31.010101 | 184 | 0.707166 |
1dea09aace0620966147ee97258cc3ada0af2b73 | 2,616 | //
// SubWebUIView.swift
// unitool
//
// Created by Shuangbing on 2018/12/07.
// Copyright © 2018 Shuangbing. All rights reserved.
//
import UIKit
import Alamofire
import WebKit
class SubPolicyWebView: UIViewController, UIWebViewDelegate{
var url_string = "https://www.uni-t.cc/about/policy/"
let webView = WKWebView()
private lazy var AgreeReturn : UIButton = {
let originalColor = Color_Main
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.backgroundColor = Color_Sub
button.setTitle("同意する", for: UIControl.State.normal)
button.tintColor = .white
button.isUserInteractionEnabled = true
button.addTarget(self, action: #selector(AgreePolicy), for: UIControl.Event.touchUpInside)
return button
}()
private lazy var disAgreeReturn : UIButton = {
let originalColor = Color_Main
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.backgroundColor = originalColor
button.setTitle("同意しない", for: UIControl.State.normal)
button.tintColor = .white
button.isUserInteractionEnabled = true
button.addTarget(self, action: #selector(disAgreePolicy), for: UIControl.Event.touchUpInside)
return button
}()
@objc func disAgreePolicy(){
isAgreePolicy = false
self.dismiss(animated: true)
}
@objc func AgreePolicy(){
isAgreePolicy = true
self.dismiss(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
setupVC()
}
func setupVC(){
self.title = "プライバシーポリシー"
let url = URL(string: self.url_string)!
let request: URLRequest = URLRequest(url: url)
webView.load(request)
self.view.addSubview(webView)
self.view.addSubview(AgreeReturn)
self.view.addSubview(disAgreeReturn)
AgreeReturn.snp.makeConstraints { (make) in
make.width.equalToSuperview().dividedBy(2)
make.left.bottom.equalToSuperview()
make.height.equalTo(80)
}
disAgreeReturn.snp.makeConstraints { (make) in
make.width.equalToSuperview().dividedBy(2)
make.right.bottom.equalToSuperview()
make.height.equalTo(80)
}
webView.snp.makeConstraints { (make) in
make.top.left.width.right.equalToSuperview()
make.bottom.equalTo(AgreeReturn.snp.top)
}
}
}
| 30.776471 | 101 | 0.632263 |
722fbdc21e533e61621745e38f907047775be31f | 18,667 | //
// SettingsPro.swift
// Slide for Reddit
//
// Created by Carlos Crane on 6/07/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import UIKit
import BiometricAuthentication
import LicensesViewController
import SDWebImage
import MaterialComponents.MaterialSnackbar
import RealmSwift
import RLBAlertsPickers
import MessageUI
class SettingsPro: UITableViewController, MFMailComposeViewControllerDelegate {
static var changed = false
var restore: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "restore")
var shadowbox: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "shadow")
var gallery: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "gallery")
var biometric: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "bio")
var multicolumn: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "multi")
var autocache: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "auto")
var night: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "night")
var username: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "username")
var custom: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "custom")
var themes: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "themes")
var backup: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "backup")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: "")
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.setToolbarHidden(true, animated: false)
doCells()
}
override func loadView() {
super.loadView()
}
var three = UILabel()
var six = UILabel()
var purchasePro = UILabel()
var purchaseBundle = UILabel()
func doCells(_ reset: Bool = true) {
self.view.backgroundColor = ColorUtil.backgroundColor
// set the title
self.title = "Support Slide for Reddit!"
self.tableView.separatorStyle = .none
self.night.textLabel?.text = "Auto night mode"
self.night.detailTextLabel?.text = "Select a custom night theme and night hours, Slide does the rest"
self.night.backgroundColor = ColorUtil.foregroundColor
self.night.textLabel?.textColor = ColorUtil.fontColor
self.night.imageView?.image = UIImage.init(named: "night")?.toolbarIcon()
self.night.imageView?.tintColor = ColorUtil.fontColor
self.night.detailTextLabel?.textColor = ColorUtil.fontColor
self.username.textLabel?.text = "Username scrubbing"
self.username.detailTextLabel?.text = "Keep your account names a secret"
self.username.backgroundColor = ColorUtil.foregroundColor
self.username.textLabel?.textColor = ColorUtil.fontColor
self.username.imageView?.image = UIImage.init(named: "hide")?.toolbarIcon()
self.username.imageView?.tintColor = ColorUtil.fontColor
self.username.detailTextLabel?.textColor = ColorUtil.fontColor
self.backup.textLabel?.text = "Backup and Restore"
self.backup.detailTextLabel?.text = "Sync your Slide settings between devices"
self.backup.backgroundColor = ColorUtil.foregroundColor
self.backup.textLabel?.textColor = ColorUtil.fontColor
self.backup.imageView?.image = UIImage.init(named: "download")?.toolbarIcon()
self.backup.imageView?.tintColor = ColorUtil.fontColor
self.backup.detailTextLabel?.textColor = ColorUtil.fontColor
self.custom.textLabel?.text = "Custom theme colors"
self.custom.detailTextLabel?.text = "Choose a custom color for your themes"
self.custom.backgroundColor = ColorUtil.foregroundColor
self.custom.detailTextLabel?.textColor = ColorUtil.fontColor
self.custom.textLabel?.textColor = ColorUtil.fontColor
self.custom.imageView?.image = UIImage.init(named: "accent")?.toolbarIcon()
self.custom.imageView?.tintColor = ColorUtil.fontColor
self.themes.textLabel?.text = "More base themes"
self.themes.detailTextLabel?.text = "Unlocks AMOLED, Sepia, and Deep themes"
self.themes.backgroundColor = .black
self.themes.detailTextLabel?.textColor = .white
self.themes.textLabel?.textColor = .white
self.themes.imageView?.image = UIImage.init(named: "colors")?.toolbarIcon().withColor(tintColor: .white)
self.themes.imageView?.tintColor = .white
self.restore.textLabel?.text = "Already a supporter?"
self.restore.accessoryType = .disclosureIndicator
self.restore.backgroundColor = ColorUtil.foregroundColor
self.restore.textLabel?.textColor = GMColor.lightGreen300Color()
self.restore.imageView?.image = UIImage.init(named: "restore")?.toolbarIcon().withColor(tintColor: GMColor.lightGreen300Color())
self.restore.imageView?.tintColor = GMColor.lightGreen300Color()
self.restore.detailTextLabel?.textColor = GMColor.lightGreen300Color()
self.restore.detailTextLabel?.text = "Restore your purchase!"
var about = PaddingLabel(frame: CGRect.init(x: 0, y: 200, width: self.tableView.frame.size.width, height: 30))
about.font = UIFont.systemFont(ofSize: 16)
about.backgroundColor = ColorUtil.foregroundColor
about.textColor = ColorUtil.fontColor
about.text = "Upgrade to Slide Pro to enjoy awesome new features while supporting ad-free and open source software!\n\nI'm an indie software developer currently studying at university, and every donation helps keep Slide going :)\n\n\n\n"
about.numberOfLines = 0
about.textAlignment = .center
about.lineBreakMode = .byClipping
about.sizeToFit()
three = UILabel(frame: CGRect.init(x: (self.tableView.frame.size.width / 4) - 50, y: 160, width: 100, height: 45))
three.text = "$4.99"
three.backgroundColor = GMColor.lightGreen300Color()
three.layer.cornerRadius = 22.5
three.clipsToBounds = true
three.numberOfLines = 0
three.lineBreakMode = .byWordWrapping
three.textColor = .white
three.font = UIFont.boldSystemFont(ofSize: 20)
three.textAlignment = .center
six = UILabel(frame: CGRect.init(x: (self.tableView.frame.size.width / 4) - 50, y: 160, width: 100, height: 45))
six.text = "$7.99"
six.backgroundColor = GMColor.lightBlue300Color()
six.layer.cornerRadius = 22.5
six.clipsToBounds = true
six.textColor = .white
six.numberOfLines = 0
six.lineBreakMode = .byWordWrapping
six.font = UIFont.boldSystemFont(ofSize: 20)
six.textAlignment = .center
self.shadowbox.textLabel?.text = "Shadowbox mode"
self.shadowbox.detailTextLabel?.text = "View your favorite subreddits distraction free"
self.shadowbox.backgroundColor = ColorUtil.foregroundColor
self.shadowbox.textLabel?.textColor = ColorUtil.fontColor
self.shadowbox.imageView?.image = UIImage.init(named: "shadowbox")?.toolbarIcon()
self.shadowbox.imageView?.tintColor = ColorUtil.fontColor
self.shadowbox.detailTextLabel?.textColor = ColorUtil.fontColor
self.gallery.textLabel?.text = "Gallery mode"
self.gallery.detailTextLabel?.text = "r/pics never looked better"
self.gallery.backgroundColor = ColorUtil.foregroundColor
self.gallery.textLabel?.textColor = ColorUtil.fontColor
self.gallery.imageView?.image = UIImage.init(named: "image")?.toolbarIcon()
self.gallery.imageView?.tintColor = ColorUtil.fontColor
self.gallery.detailTextLabel?.textColor = ColorUtil.fontColor
self.biometric.textLabel?.text = "Biometric lock"
self.biometric.detailTextLabel?.text = "Keep your Reddit content safe"
self.biometric.backgroundColor = ColorUtil.foregroundColor
self.biometric.textLabel?.textColor = ColorUtil.fontColor
self.biometric.imageView?.image = UIImage.init(named: "lockapp")?.toolbarIcon()
self.biometric.imageView?.tintColor = ColorUtil.fontColor
self.biometric.detailTextLabel?.textColor = ColorUtil.fontColor
self.multicolumn.textLabel?.text = "Multicolumn mode"
self.multicolumn.detailTextLabel?.text = "A must-have for iPads!"
self.multicolumn.backgroundColor = ColorUtil.foregroundColor
self.multicolumn.textLabel?.textColor = ColorUtil.fontColor
self.multicolumn.imageView?.image = UIImage.init(named: "multicolumn")?.toolbarIcon()
self.multicolumn.imageView?.tintColor = ColorUtil.fontColor
self.multicolumn.detailTextLabel?.textColor = ColorUtil.fontColor
self.autocache.textLabel?.text = "Autocache subreddits"
self.autocache.detailTextLabel?.text = "Cache your favorite subs for your morning commute"
self.autocache.backgroundColor = ColorUtil.foregroundColor
self.autocache.textLabel?.textColor = ColorUtil.fontColor
self.autocache.imageView?.image = UIImage.init(named: "download")?.toolbarIcon()
self.autocache.imageView?.tintColor = ColorUtil.fontColor
self.autocache.detailTextLabel?.textColor = ColorUtil.fontColor
purchasePro = UILabel(frame: CGRect.init(x: 0, y: -30, width: (self.view.frame.size.width / 2), height: 200))
purchasePro.backgroundColor = ColorUtil.foregroundColor
purchasePro.text = "Purchase\nPro"
purchasePro.textAlignment = .center
purchasePro.textColor = ColorUtil.fontColor
purchasePro.font = UIFont.boldSystemFont(ofSize: 18)
purchasePro.numberOfLines = 0
purchasePro.addSubview(three)
purchasePro.isUserInteractionEnabled = true
purchaseBundle = UILabel(frame: CGRect.init(x: (self.view.frame.size.width / 2), y: -30, width: (self.view.frame.size.width / 2), height: 200))
purchaseBundle.backgroundColor = ColorUtil.foregroundColor
purchaseBundle.text = "Purchase Pro\nWith $3 Donation"
purchaseBundle.textAlignment = .center
purchaseBundle.textColor = ColorUtil.fontColor
purchaseBundle.numberOfLines = 0
purchaseBundle.font = UIFont.boldSystemFont(ofSize: 18)
purchaseBundle.addSubview(six)
purchaseBundle.isUserInteractionEnabled = true
purchasePro.addTapGestureRecognizer {
IAPHandler.shared.purchaseMyProduct(index: 0)
}
purchaseBundle.addTapGestureRecognizer {
IAPHandler.shared.purchaseMyProduct(index: 1)
}
about.frame.size.height = about.frame.size.height + 200
about.addSubview(purchasePro)
about.addSubview(purchaseBundle)
tableView.tableHeaderView = about
tableView.tableHeaderView?.isUserInteractionEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
IAPHandler.shared.fetchAvailableProducts()
IAPHandler.shared.getItemsBlock = {(items) in
let numberFormatter = NumberFormatter()
numberFormatter.formatterBehavior = .behavior10_4
numberFormatter.numberStyle = .currency
numberFormatter.locale = items[0].priceLocale
let price1Str = numberFormatter.string(from: items[0].price)
let price2Str = numberFormatter.string(from: items[1].price)
if(self.three.text! != price1Str!){
//Is a sale
let crossedString = NSMutableAttributedString.init(string: "$4.99\n", attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12), NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)])
let crossedString2 = NSMutableAttributedString.init(string: "$7.99\n", attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12), NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)])
let newString = NSMutableAttributedString.init(string: price1Str!, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)])
let newString2 = NSMutableAttributedString.init(string: price2Str!, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)])
var finalString = NSMutableAttributedString()
var finalString2 = NSMutableAttributedString()
finalString.append(crossedString)
finalString.append(newString)
finalString2.append(crossedString2)
finalString2.append(newString2)
self.three.attributedText = finalString
self.six.attributedText = finalString2
self.three.frame = CGRect.init(x: (self.tableView.frame.size.width / 4) - 50, y: 150, width: 100, height: 80)
self.six.frame = CGRect.init(x: (self.tableView.frame.size.width / 4) - 50, y: 150, width: 100, height: 80)
}
}
IAPHandler.shared.purchaseStatusBlock = {[weak self] (type) in
guard let strongSelf = self else{ return }
if type == .purchased || type == .restored {
let alertView = UIAlertController(title: "", message: type.message(), preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
strongSelf.navigationController?.dismiss(animated: true)
})
alertView.addAction(action)
strongSelf.present(alertView, animated: true, completion: nil)
SettingValues.isPro = true
UserDefaults.standard.set(true, forKey: SettingValues.pref_pro)
UserDefaults.standard.synchronize()
SettingsPro.changed = true
} else {
let alertView = UIAlertController(title: "", message: "Slide Pro purchase not found. Make sure you are signed in with the same Apple ID as you purchased Slide Pro with originally.\nIf this issue persists, feel free to send me an email!", preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
})
alertView.addAction(action)
alertView.addAction(UIAlertAction.init(title: "Message me", style: .default, handler: { (alert) in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = strongSelf
mail.setToRecipients(["[email protected]"])
mail.setSubject("Slide Pro Purchase Restore")
mail.setMessageBody("<p>Apple ID: \nName:\n\n</p>", isHTML: true)
strongSelf.present(mail, animated: true)
}
}))
strongSelf.present(alertView, animated: true, completion: nil)
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 0 : 70
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0: return self.restore
case 1: return self.multicolumn
case 2: return self.shadowbox
case 3: return self.backup
case 4: return self.night
case 5: return self.biometric
case 6: return self.themes
case 7: return self.gallery
case 8: return self.autocache
case 9: return self.username
default: fatalError("Unknown row in section 0")
}
default: fatalError("Unknown section")
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if(indexPath.row == 0){
IAPHandler.shared.restorePurchase()
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label: UILabel = UILabel()
label.textColor = ColorUtil.baseAccent
label.font = FontGenerator.boldFontOfSize(size: 20, submission: true)
let toReturn = label.withPadding(padding: UIEdgeInsets.init(top: 0, left: 12, bottom: 0, right: 0))
toReturn.backgroundColor = ColorUtil.backgroundColor
switch (section) {
case 0: label.text = "General"
break
case 1: label.text = "Already a Slide supporter?"
break
default: label.text = ""
break
}
return toReturn
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section) {
case 0: return 10
default: fatalError("Unknown number of sections")
}
}
}
class PaddingLabel: UILabel {
var topInset: CGFloat = 220.0
var bottomInset: CGFloat = 20.0
var leftInset: CGFloat = 20.0
var rightInset: CGFloat = 20.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
| 49.253298 | 277 | 0.668399 |
ef16ffaa76494611c123ec95a86da6ccfacccf6c | 3,314 | //
// GooglePlacesService.swift
// Column
//
// Created by Stephen Wu on 5/10/19.
// Copyright © 2019 Stephen Wu. All rights reserved.
//
import Foundation
/// The service structs are responsible for making network requests and deserializing the responses.
struct GooglePlacesService {
enum Query: String {
// Search request query keys
case query = "query"
case key = "key"
case location = "location"
case radius = "radius"
// Detail request query keys
case fields = "fields"
case placeId = "placeid"
func item(value: String) -> URLQueryItem {
return URLQueryItem(name: self.rawValue, value: value)
}
}
private struct Endpoint {
static let search = GooglePlacesEndpoint(path: "/maps/api/place/textsearch/json")
static let detail = GooglePlacesEndpoint(path: "/maps/api/place/details/json")
}
private let webservice: Webservice
private let decoder: JSONDecoder
init(webservice: Webservice = Webservice(), decoder: JSONDecoder = JSONDecoder()) {
self.webservice = webservice
self.decoder = decoder
}
/// Retrieve a list of places relevant to the given query
///
/// - Parameters:
/// - query: The search term to match
/// - type: The kind of place to search for (hotel, car rental, etc)
/// - completion: Callback executed on response.
func search(query: String, completion: @escaping([GooglePlacesSearchResult], Error?) -> Void) {
let url = Endpoint.search
.adding([
Query.location.item(value: "40.785276,-73.9651827"),
Query.radius.item(value: "50000"),
Query.query.item(value: query)
])
.url
webservice.get(url: url) { (data, response, error) in
if let error = error {
completion([], error) // Network error
}
if let data = data {
do {
let response = try self.decoder.decode(GooglePlacesSearchResponse.self, from: data)
completion(response.results, nil)
} catch {
completion([], error) // Decoding error
}
}
}
}
/// Retrieves the details about a place by ID. We only need the phone number here, but we can
/// get a lot more.
func getDetails(for placeId: String, fields: [GooglePlaceDetailField], completion: @escaping (GooglePlacesDetail?, Error?) -> Void) {
let url = Endpoint.detail
.adding([
Query.fields.item(value: fields.map { $0.rawValue }.joined(separator: ",")),
Query.placeId.item(value: placeId)
])
.url
webservice.get(url: url) { (data, response, error) in
if let error = error {
completion(nil, error) // Network error
}
if let data = data {
do {
let response = try self.decoder.decode(GooglePlacesDetailResponse.self, from: data)
completion(response.result, nil)
} catch {
completion(nil, error) // Decoding error
}
}
}
}
}
| 32.490196 | 137 | 0.560048 |
76fef7b1eff3c65d9efec2d5bdbf86f6caa9d5a9 | 4,079 | //
// NSControl Glue.swift
// macOS
//
// Created by Károly Lőrentey on 2017-09-05.
// Copyright © 2017 Károly Lőrentey. All rights reserved.
//
#if os(macOS)
import AppKit
extension NSControl {
@objc open dynamic override var glue: GlueForNSControl { return _glue() }
}
public func <-- <Value, Model: UpdatableValueType>(target: GlueForNSControl.ValueSlot<Value>, model: Model) where Model.Value == Value {
target.glue.setValueModel(model.anyUpdatableValue)
}
public func <-- <Value, V: UpdatableValueType>(target: GlueForNSControl.ValueSlot<Value>, model: V) where V.Value == Value? {
target.glue.setValueModel(model.anyUpdatableValue)
}
public func <-- <Value, Model: ObservableValueType>(target: GlueForNSControl.ConfigSlot<Value>, model: Model) where Model.Value == Value {
target.glue.setConfigSlot(target.keyPath, to: model.anyObservableValue)
}
open class GlueForNSControl: GlueForNSObject {
private var object: NSControl { return owner as! NSControl }
private var modelConnection: Connection? = nil
fileprivate var valueModel: AnyObservableValue<Any?>? = nil {
didSet {
modelConnection?.disconnect()
if let model = valueModel {
modelConnection = model.values.subscribe { [unowned self] value in
self.object.objectValue = value
}
object.target = self
object.action = #selector(GlueForNSControl.controlAction(_:))
}
}
}
fileprivate var valueUpdater: ((Any?) -> Bool)? = nil
fileprivate func setValueModel<V>(_ model: AnyUpdatableValue<V>) {
self.valueUpdater = { value in
guard let v = value as? V else { return false }
model.value = v
return true
}
self.valueModel = model.map { $0 as Any? }
}
fileprivate func setValueModel<V>(_ model: AnyUpdatableValue<V?>) {
self.valueUpdater = { value in
model.value = value as? V
return true
}
self.valueModel = model.map { $0 as Any? }
}
@objc func controlAction(_ sender: NSControl) {
if valueUpdater?(sender.objectValue) != true {
sender.objectValue = valueModel?.value
}
}
public struct ValueSlot<Value> {
fileprivate let glue: GlueForNSControl
}
public var intValue: ValueSlot<Int> { return ValueSlot<Int>(glue: self) }
public var doubleValue: ValueSlot<Double> { return ValueSlot(glue: self) }
public var stringValue: ValueSlot<String> { return ValueSlot(glue: self) }
public var attributedStringValue: ValueSlot<NSAttributedString> { return ValueSlot(glue: self) }
public struct ConfigSlot<Value> {
fileprivate let glue: GlueForNSControl
fileprivate let keyPath: ReferenceWritableKeyPath<NSControl, Value>
}
var configModels: [AnyKeyPath: Connection] = [:]
func setConfigSlot<Value>(_ keyPath: ReferenceWritableKeyPath<NSControl, Value>, to model: AnyObservableValue<Value>) {
let connection = model.values.subscribe { [unowned object] value in
object[keyPath: keyPath] = value
_ = object
}
configModels.updateValue(connection, forKey: keyPath)?.disconnect()
}
public var isEnabled: ConfigSlot<Bool> { return ConfigSlot(glue: self, keyPath: \.isEnabled) }
public var alignment: ConfigSlot<NSTextAlignment> { return ConfigSlot(glue: self, keyPath: \.alignment) }
public var font: ConfigSlot<NSFont?> { return ConfigSlot(glue: self, keyPath: \.font) }
public var lineBreakMode: ConfigSlot<NSLineBreakMode> { return ConfigSlot(glue: self, keyPath: \.lineBreakMode) }
public var usesSingleLineMode: ConfigSlot<Bool> { return ConfigSlot(glue: self, keyPath: \.usesSingleLineMode) }
public var formatter: ConfigSlot<Formatter?> { return ConfigSlot(glue: self, keyPath: \.formatter) }
public var baseWritingDirection: ConfigSlot<NSWritingDirection> { return ConfigSlot(glue: self, keyPath: \.baseWritingDirection) }
}
#endif
| 40.386139 | 138 | 0.672224 |
79e7b0a76ecb4018f6f44347c9ce61d73aa7e7ad | 846 | //
// FollowController.swift
// douyuzhibo
//
// Created by 刘威 on 2018/3/21.
// Copyright © 2018年 刘威. All rights reserved.
//
import UIKit
class FollowController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 23.5 | 106 | 0.665485 |
5665c92ed6feb23c0ed3540d7416751afda08c59 | 39,543 | //
// ViewController.swift
// CamFoV
//
// Created by Gerrit Grunwald on 27.03.20.
// Copyright © 2020 Gerrit Grunwald. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import CoreGraphics
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, MapPinEventObserver, UIPickerViewDataSource, UIPickerViewDelegate {
// Toolbar items
@IBOutlet weak var mapButton : UIBarButtonItem!
@IBOutlet weak var camerasButton : UIBarButtonItem!
@IBOutlet weak var lensesButton : UIBarButtonItem!
@IBOutlet weak var viewsButton : UIBarButtonItem!
// View items
@IBOutlet weak var mapView : MKMapView!
@IBOutlet weak var focalLengthSlider : UISlider!
@IBOutlet weak var focalLengthLabel : UILabel!
@IBOutlet weak var minFocalLengthLabel: UILabel!
@IBOutlet weak var maxFocalLengthLabel: UILabel!
@IBOutlet weak var apertureSlider : UISlider!
@IBOutlet weak var apertureLabel : UILabel!
@IBOutlet weak var minApertureLabel : UILabel!
@IBOutlet weak var maxApertureLabel : UILabel!
@IBOutlet weak var orientationSwitch : UISwitch!
@IBOutlet weak var orientationLabel : UILabel!
@IBOutlet weak var lensPicker : UIPickerView!
@IBOutlet weak var lensLabel : UILabel!
@IBOutlet weak var dofSwitch : UISwitch!
@IBOutlet weak var dofLabel : UILabel!
@IBOutlet weak var saveViewButton : UIButton!
@IBOutlet weak var cameraButton : UIButton!
@IBOutlet weak var mapStyleSelector : UISegmentedControl!
var locationManager : CLLocationManager!
var cameraPin : MapPin?
var motifPin : MapPin?
var mapPins : [MapPin] = [MapPin]()
var triangle : Triangle?
var minTriangle : Triangle?
var maxTriangle : Triangle?
var trapezoid : Trapezoid?
var fovTriangle : MKPolygon?
var minFovTriangle : MKPolygon?
var maxFovTriangle : MKPolygon?
var fovTriangleFrame : MKPolygon?
var fovCenterLine : MKPolyline?
var dofTrapezoid : MKPolygon?
var data : Data?
var fovVisible : Bool = true
var dofVisible : Bool = false
var focalLength : Double = 50
var aperture : Double = 2.8
var orientation : Orientation = Orientation.LANDSCAPE
var camera : Camera?
var cameras : [Camera] = [ Helper.DEFAULT_CAMERA ]
var lens : Lens?
var lenses : [Lens] = [
Helper.DEFAULT_LENS,
Lens(name: "Tamron SP 15-30mm f2.8", minFocalLength: 15, maxFocalLength: 30, minAperture: 2.8, maxAperture: 22),
Lens(name: "Tamron SP 24-70mm f2.8", minFocalLength: 24, maxFocalLength: 70, minAperture: 2.8, maxAperture: 22),
Lens(name: "Tamron SP 35mm f1.8", focalLength: 35, minAperture: 1.8, maxAperture: 22),
Lens(name: "Tamron SP 90mm f2.8 Macro", focalLength: 90, minAperture: 2.8, maxAperture: 32),
Lens(name: "Sigma 14mm f1.8 ART", focalLength: 14, minAperture: 1.8, maxAperture: 22),
Lens(name: "Sigma 105mm f1.4 ART", focalLength: 105, minAperture: 1.4, maxAperture: 22),
Lens(name: "Tokina 50mm f1.4 Opera", focalLength: 50, minAperture: 1.4, maxAperture: 22),
Lens(name: "Nikon 85mm f1.8", focalLength: 85, minAperture: 1.8, maxAperture: 22),
Lens(name: "Nikon 24-70mm f2.8", minFocalLength: 24, maxFocalLength: 70, minAperture: 2.8, maxAperture: 22),
Lens(name: "Nikon 70-200mm f2.8", minFocalLength: 70, maxFocalLength: 200, minAperture: 2.8, maxAperture: 22),
Lens(name: "Nikon 200-500mm f5.6", minFocalLength: 200, maxFocalLength: 500, minAperture: 5.6, maxAperture: 22),
Lens(name: "Irix 11mm f4", focalLength: 11, minAperture: 4, maxAperture: 22),
Lens(name: "MAK 1000", focalLength: 1000, minAperture: 10, maxAperture: 10)
]
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.mapView.delegate = self
self.lensPicker.dataSource = self
self.lensPicker.delegate = self
self.camera = Camera(name: "Nikon D850", sensorFormat: SensorFormat.FULL_FORMAT)
self.lens = lenses[0]
self.focalLengthSlider.minimumValue = Float(self.lens!.minFocalLength)
self.focalLengthSlider.maximumValue = Float(self.lens!.maxFocalLength)
self.focalLengthSlider.value = self.focalLengthSlider.minimumValue + (self.focalLengthSlider.maximumValue - self.focalLengthSlider.minimumValue) / 2
self.focalLengthLabel.text = String(format: "%.0f mm", Double(round(self.focalLengthSlider!.value)))
self.minFocalLengthLabel.text = String(format: "%.0f", Double(round(self.lens!.minFocalLength)))
self.maxFocalLengthLabel.text = String(format: "%.0f", Double(round(self.lens!.maxFocalLength)))
self.apertureSlider.minimumValue = Float(self.lens!.minAperture)
self.apertureSlider.maximumValue = Float(self.lens!.maxAperture)
self.apertureSlider.value = self.apertureSlider.minimumValue + (self.apertureSlider.maximumValue - self.apertureSlider.minimumValue) / 2
self.apertureLabel.text = String(format: "f %.1f", Double(round(self.apertureSlider!.value * 10) / 10))
self.minApertureLabel.text = String(format: "%.1f", Double(round(self.lens!.minAperture * 10) / 10))
self.maxApertureLabel.text = String(format: "%.1f", Double(round(self.lens!.maxAperture * 10) / 10))
self.dofLabel.text = self.dofSwitch.isOn ? "DoF Visible" : "DoF Hidden"
self.orientationLabel.text = "Landscape"
self.lensLabel.text = "Selected lens"
let mapTypeSelectorTextAttr = [NSAttributedString.Key.foregroundColor: UIColor.systemTeal]
let mapTypeSelectorTextAttrSelected = [NSAttributedString.Key.foregroundColor: UIColor.white]
mapStyleSelector.setTitleTextAttributes(mapTypeSelectorTextAttr, for: .normal)
mapStyleSelector.setTitleTextAttributes(mapTypeSelectorTextAttrSelected, for: .selected)
createMapView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
getCurrentLocation()
}
// MARK: Event Handlers
@IBAction func mapButtonPressed(_ sender: Any) {
}
@IBAction func camerasButtonPressed(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let camerasVC = storyboard.instantiateViewController(identifier: "CamerasViewController")
show(camerasVC, sender: self)
}
@IBAction func lensesButtonPressed(_ sender: Any) {
}
@IBAction func viewsButtonPressed(_ sender: Any) {
}
@IBAction func focalLengthChanged(_ sender: Any) {
//print("focalLength: \(Double(round(focalLengthSlider!.value)))")
self.focalLengthLabel.text = String(format: "%.0f mm", Double(round(focalLengthSlider!.value)))
self.focalLength = Double(round(focalLengthSlider!.value))
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
@IBAction func apertureChanged(_ sender: Any) {
//print("aperture: \(Double(round(apertureSlider!.value * 10) / 10))")
self.apertureLabel.text = String(format: "f %.1f", Double(round(apertureSlider!.value * 10) / 10))
self.aperture = Double(round(apertureSlider!.value * 10) / 10)
if dofVisible {
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
}
@IBAction func orientationChanged(_ sender: Any) {
self.orientationLabel.text = orientationSwitch.isOn ? "Landscape" : "Portrait"
self.orientation = orientationSwitch.isOn ? Orientation.LANDSCAPE : Orientation.PORTRAIT
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
updateDragOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
@IBAction func dofChanged(_ sender: Any) {
self.dofLabel.text = dofSwitch.isOn ? "DoF visible" : "DoF hidden"
self.dofVisible = dofSwitch.isOn
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
@IBAction func saveViewPressed(_ sender: Any) {
let view : View = getView(name: "Current", description: "The current view")
let dictionary : Dictionary<String,String> = Helper.viewToDictionary(view: view)
print(dictionary)
let newView = Helper.dictionaryToView(dictionary: dictionary, cameras: cameras, lenses: lenses)
print(newView.toJsonString())
UserDefaults.standard.set(dictionary, forKey: "fovView")
}
@IBAction func cameraButtonPressed(_ sender: Any) {
let dX = motifPin!.point().x - cameraPin!.point().x
let dY = motifPin!.point().y - cameraPin!.point().y
mapView.removeAnnotations(mapPins)
self.cameraPin!.coordinate = mapView.centerCoordinate
self.motifPin!.coordinate = MKMapPoint(x: self.cameraPin!.point().x + dX, y: self.cameraPin!.point().y + dY).coordinate
mapView.addAnnotations(mapPins)
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
@IBAction func mapStyleChanged(_ sender: Any) {
switch mapStyleSelector.selectedSegmentIndex {
case 0 : mapView.mapType = MKMapType.standard
case 1 : mapView.mapType = MKMapType.satellite
case 2 : mapView.mapType = MKMapType.hybrid
default: mapView.mapType = MKMapType.standard
}
}
func createMapView() {
let cameraLocation: CLLocationCoordinate2D = Helper.DEFAULT_POSITION.coordinate
let motifLocation : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: cameraLocation.latitude + 0.005, longitude: cameraLocation.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: cameraLocation, span: span)
mapView.mapType = MKMapType.standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
mapView.showsScale = true
mapView.showsCompass = true
mapView.showsUserLocation = true
mapView.setRegion(region, animated: true)
mapView.register(MapPinAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
self.triangle = Triangle()
self.minTriangle = Triangle()
self.maxTriangle = Triangle()
self.trapezoid = Trapezoid()
self.cameraPin = MapPin(pinType: PinType.CAMERA, coordinate: cameraLocation)
self.motifPin = MapPin(pinType: PinType.MOTIF, coordinate: motifLocation)
mapPins.append(self.cameraPin!)
mapPins.append(self.motifPin!)
mapView.addAnnotations(mapPins)
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
func getCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
//locationManager.startUpdatingHeading()
//locationManager.startUpdatingLocation()
}
}
// UIPickerViewDataSource and UIPickerViewDelegate methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return lenses.count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var pickerLabel = view as? UILabel;
if (pickerLabel == nil){
pickerLabel = UILabel()
pickerLabel?.font = UIFont(name: "System", size: 17)
pickerLabel?.textColor = UIColor.systemTeal
pickerLabel?.backgroundColor = UIColor.clear
pickerLabel?.textAlignment = NSTextAlignment.center
}
pickerLabel?.text = lenses[row].name
return pickerLabel!
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
updateLens(lens: lenses[row])
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
}
// CLLocationManagerDelegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
manager.stopUpdatingLocation()
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
mapView.setRegion(region, animated: true)
/* Drop a pin at user's Current Location
let myAnnotation: MKPointAnnotation = MKPointAnnotation()
myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
myAnnotation.title = "Current location"
mapView.addAnnotation(myAnnotation)
*/
}
private func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error \(error)")
}
// MKMapViewDelegate methods
func mapView(_ mapView: MKMapView, annotationView: MKAnnotationView, didChange: MKAnnotationView.DragState, fromOldState: MKAnnotationView.DragState) {
switch (didChange) {
case .starting:
break;
case .dragging:
break;
case .ending, .canceling:
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDoFTrapezoid(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point())
break;
default: break
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MapPin {
let mapPin : MapPin = annotation as! MapPin
print("MapPin: \(String(describing: mapPin.title)) found")
if mapPin.title == "Camera" || mapPin.title == "Motif" {
let mapPinAnnotationView : MapPinAnnotationView = MapPinAnnotationView(annotation: annotation, reuseIdentifier: mapPin.title)
mapPinAnnotationView.mapView = mapView
mapPinAnnotationView.setOnMapPinEvent(observer: self)
print("Observer added")
return mapPinAnnotationView
}
}
return nil
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
// Draw Overlays
if let overlay = overlay as? Polygon {
if overlay.id == "dof" && dofVisible {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.fillColor = UIColor.init(displayP3Red: 0.45490196, green: 0.80784314, blue: 1.0, alpha: 0.25)
polygonView.strokeColor = UIColor.init(displayP3Red: 0.45490196, green: 0.80784314, blue: 1.0, alpha: 1.0)
polygonView.lineWidth = 1.0
polygonView.lineDashPattern = [10, 10]
polygonView.lineDashPhase = 10
return polygonView
} else if overlay.id == "maxFov" && fovVisible {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.fillColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 0.15)
polygonView.strokeColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 1.0)
polygonView.lineWidth = 1.0
return polygonView
} else if overlay.id == "minFov" && fovVisible {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.fillColor = UIColor.clear
polygonView.strokeColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 1.0)
polygonView.lineWidth = 1.0
return polygonView
} else if overlay.id == "fov" && fovVisible {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.fillColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 0.45)
polygonView.strokeColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 1.0)
polygonView.lineWidth = 1.0
return polygonView
} else if overlay.id == "fovFrame" && fovVisible {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.fillColor = UIColor.clear
polygonView.strokeColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 1.0)
polygonView.lineWidth = 1.0
return polygonView
} else {
return MKPolylineRenderer()
}
} else if let overlay = overlay as? Line {
if overlay.id == "centerLine" && fovVisible {
let polylineView = MKPolylineRenderer(overlay: overlay)
polylineView.strokeColor = UIColor.init(displayP3Red: 0.0, green: 0.56078431, blue: 0.8627451, alpha: 1.0)
polylineView.lineWidth = 1.0
return polylineView
} else {
return MKPolylineRenderer()
}
}
return MKPolylineRenderer()
}
// MapPin event handling
func onMapPinEvent(evt: MapPinEvent) {
if evt.src === cameraPin {
updateFoVTriangle(cameraPoint: evt.point, motifPoint: self.motifPin!.point(), focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDragOverlay(cameraPoint: evt.point, motifPoint: self.motifPin!.point())
} else if evt.src === motifPin {
updateFoVTriangle(cameraPoint: self.cameraPin!.point(), motifPoint: evt.point, focalLength: self.focalLength, aperture: self.aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation)
updateDragOverlay(cameraPoint: self.cameraPin!.point(), motifPoint: evt.point)
}
}
// Update methods
func updateLens(lens: Lens) -> Void {
self.lens! = lens
self.focalLength = lens.minFocalLength + (lens.maxFocalLength - lens.minFocalLength)
self.aperture = lens.minAperture + (lens.maxAperture - lens.minAperture)
focalLengthSlider.minimumValue = Float(lens.minFocalLength)
focalLengthSlider.maximumValue = Float(lens.maxFocalLength)
focalLengthSlider.value = focalLengthSlider.minimumValue + (focalLengthSlider.maximumValue - focalLengthSlider.minimumValue) / 2
focalLengthLabel.text = String(format: "%.0f mm", Double(round(focalLengthSlider!.value)))
minFocalLengthLabel.text = String(format: "%.0f", Double(round(lens.minFocalLength)))
maxFocalLengthLabel.text = String(format: "%.0f", Double(round(lens.maxFocalLength)))
apertureSlider.minimumValue = Float(lens.minAperture)
apertureSlider.maximumValue = Float(lens.maxAperture)
apertureSlider.value = apertureSlider.minimumValue + (apertureSlider.maximumValue - apertureSlider.minimumValue) / 2
apertureLabel.text = String(format: "f %.1f", Double(round(apertureSlider!.value * 10) / 10))
minApertureLabel.text = String(format: "%.1f", Double(round(lens.minAperture * 10) / 10))
maxApertureLabel.text = String(format: "%.1f", Double(round(lens.maxAperture * 10) / 10))
}
func updateFoVTriangle(cameraPoint: MKMapPoint, motifPoint: MKMapPoint, focalLength: Double, aperture: Double, sensorFormat: SensorFormat, orientation: Orientation) -> Void {
let distance : CLLocationDistance = cameraPoint.distance(to: motifPoint)
if distance < 0.01 || distance > 9999 { return }
self.data = try! Helper.calc(camera: cameraPoint, motif: motifPoint, focalLengthInMM: focalLength, aperture: aperture, sensorFormat: sensorFormat, orientation: orientation)
// Update FoV Triangle
Helper.updateTriangle(camera: cameraPoint, motif: motifPoint, focalLengthInMM: focalLength, aperture: aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation, triangle: self.triangle!)
let angle: Double = Helper.toRadians(degrees: Helper.calculateBearing(location1: cameraPoint, location2: motifPoint))
self.triangle!.p2 = Helper.rotatePointAroundCenter(point: self.triangle!.p2, rotationCenter: cameraPoint, rad: angle)
self.triangle!.p3 = Helper.rotatePointAroundCenter(point: self.triangle!.p3, rotationCenter: cameraPoint, rad: angle)
// Update min FoV Triangle
Helper.updateTriangle(camera: cameraPoint, motif: motifPoint, focalLengthInMM: self.lens!.maxFocalLength, aperture: aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation, triangle: self.minTriangle!)
let minAngle: Double = Helper.toRadians(degrees: Helper.calculateBearing(location1: cameraPoint, location2: motifPoint))
self.minTriangle!.p2 = Helper.rotatePointAroundCenter(point: self.minTriangle!.p2, rotationCenter: cameraPoint, rad: minAngle)
self.minTriangle!.p3 = Helper.rotatePointAroundCenter(point: self.minTriangle!.p3, rotationCenter: cameraPoint, rad: minAngle)
// Update max FoV Triangle
Helper.updateTriangle(camera: cameraPoint, motif: motifPoint, focalLengthInMM: self.lens!.minFocalLength, aperture: aperture, sensorFormat: self.camera!.sensorFormat, orientation: self.orientation, triangle: self.maxTriangle!)
let maxAngle: Double = Helper.toRadians(degrees: Helper.calculateBearing(location1: cameraPoint, location2: motifPoint))
self.maxTriangle!.p2 = Helper.rotatePointAroundCenter(point: self.maxTriangle!.p2, rotationCenter: cameraPoint, rad: maxAngle)
self.maxTriangle!.p3 = Helper.rotatePointAroundCenter(point: self.maxTriangle!.p3, rotationCenter: cameraPoint, rad: maxAngle)
}
func updateDoFTrapezoid(cameraPoint: MKMapPoint, motifPoint: MKMapPoint, focalLength: Double, aperture: Double, sensorFormat: SensorFormat, orientation: Orientation) -> Void {
let distance : CLLocationDistance = cameraPoint.distance(to: motifPoint)
if distance < 0.01 || distance > 9999 { return }
// Update DoF Trapzoid
Helper.updateTrapezoid(camera: cameraPoint, motif: motifPoint, focalLengthInMM: focalLength, aperture: aperture, sensorFormat: sensorFormat, orientation: orientation, trapezoid: self.trapezoid!)
let angle: Double = Helper.toRadians(degrees: Helper.calculateBearing(location1: cameraPoint, location2: motifPoint))
trapezoid!.p1 = Helper.rotatePointAroundCenter(point: trapezoid!.p1, rotationCenter: cameraPoint, rad: angle)
trapezoid!.p2 = Helper.rotatePointAroundCenter(point: trapezoid!.p2, rotationCenter: cameraPoint, rad: angle)
trapezoid!.p3 = Helper.rotatePointAroundCenter(point: trapezoid!.p3, rotationCenter: cameraPoint, rad: angle)
trapezoid!.p4 = Helper.rotatePointAroundCenter(point: trapezoid!.p4, rotationCenter: cameraPoint, rad: angle)
}
func updateDragOverlay(cameraPoint: MKMapPoint, motifPoint: MKMapPoint) -> Void {
if let fovTriangleFrame = self.fovTriangleFrame {
mapView.removeOverlay(fovTriangleFrame)
}
self.fovTriangleFrame = nil
if let fovCenterLine = self.fovCenterLine {
mapView.removeOverlay(fovCenterLine)
}
self.fovCenterLine = nil
// Create coordinates for fov triangle frame
let fovTriangleCoordinates = triangle!.getPoints().map({ $0.coordinate })
let fovTriangleFrame = Polygon(coordinates: fovTriangleCoordinates, count: fovTriangleCoordinates.count)
fovTriangleFrame.id = "fovFrame"
mapView.addOverlay(fovTriangleFrame)
self.fovTriangleFrame = fovTriangleFrame
// Create coordinates for fov center line
let fovCenterLineCoordinates = [cameraPoint, motifPoint].map({ $0.coordinate })
let fovCenterLine = Line(coordinates: fovCenterLineCoordinates, count: fovCenterLineCoordinates.count)
fovCenterLine.id = "centerLine"
mapView.addOverlay(fovCenterLine)
self.fovCenterLine = fovCenterLine
}
func updateOverlay(cameraPoint: MKMapPoint, motifPoint: MKMapPoint) -> Void {
if let fovTriangleFrame = self.fovTriangleFrame {
mapView.removeOverlay(fovTriangleFrame)
}
self.fovTriangleFrame = nil
if let minFovTriangle = self.minFovTriangle {
mapView.removeOverlay(minFovTriangle)
}
self.minFovTriangle = nil
if let maxFovTriangle = self.maxFovTriangle {
mapView.removeOverlay(maxFovTriangle)
}
self.maxFovTriangle = nil
if let fovTriangle = self.fovTriangle {
mapView.removeOverlay(fovTriangle)
}
self.fovTriangle = nil
if let fovCenterLine = self.fovCenterLine {
mapView.removeOverlay(fovCenterLine)
}
self.fovCenterLine = nil
if let dofTrapezoid = self.dofTrapezoid {
mapView.removeOverlay(dofTrapezoid)
}
self.dofTrapezoid = nil
// Create coordinates for min fov triangle
let minFovTriangleCoordinates = minTriangle!.getPoints().map({ $0.coordinate })
let minFovTriangle = Polygon(coordinates: minFovTriangleCoordinates, count: minFovTriangleCoordinates.count)
minFovTriangle.id = "minFov"
mapView.addOverlay(minFovTriangle)
self.minFovTriangle = minFovTriangle
// Create coordinates for max fov triangle
let maxFovTriangleCoordinates = maxTriangle!.getPoints().map({ $0.coordinate })
let maxFovTriangle = Polygon(coordinates: maxFovTriangleCoordinates, count: maxFovTriangleCoordinates.count)
maxFovTriangle.id = "maxFov"
mapView.addOverlay(maxFovTriangle)
self.maxFovTriangle = maxFovTriangle
// Create coordinates for fov triangle
let fovTriangleCoordinates = triangle!.getPoints().map({ $0.coordinate })
let fovTriangle = Polygon(coordinates: fovTriangleCoordinates, count: fovTriangleCoordinates.count)
fovTriangle.id = "fov"
mapView.addOverlay(fovTriangle)
self.fovTriangle = fovTriangle
// Create coordinates for fov center line
let fovCenterLineCoordinates = [cameraPoint, motifPoint].map({ $0.coordinate })
let fovCenterLine = Line(coordinates: fovCenterLineCoordinates, count: fovCenterLineCoordinates.count)
fovCenterLine.id = "centerLine"
mapView.addOverlay(fovCenterLine)
self.fovCenterLine = fovCenterLine
// Create coordinates for dof trapezoid
let dofTrapezoidCoordinates = trapezoid!.getPoints().map({ $0.coordinate })
let dofTrapezoid = Polygon(coordinates: dofTrapezoidCoordinates, count: dofTrapezoidCoordinates.count)
dofTrapezoid.id = "dof"
mapView.addOverlay(dofTrapezoid)
self.dofTrapezoid = dofTrapezoid
}
func getView(name: String, description: String) -> View {
return View(name: name, description: description, cameraPoint: self.cameraPin!.point(), motifPoint: self.motifPin!.point(), camera: self.camera!, lens: self.lens!, focalLength: self.focalLength, aperture: self.aperture, orientation: self.orientation)
}
func getElevation(camera: MapPin, motif: MapPin) -> Void {
getJson { (json) in
print("finished")
}
}
func getJson(completion: @escaping (Response) ->()) {
var urlString = "https://api.elevationapi.com/api/Elevation/line/"
urlString += String(format: "%.7f", Double((cameraPin?.coordinate.latitude)!))
urlString += ","
urlString += String(format: "%.7f", Double((cameraPin?.coordinate.longitude)!))
urlString += ","
urlString += String(format: "%.7f", Double((motifPin?.coordinate.latitude)!))
urlString += ","
urlString += String(format: "%.7f", Double((motifPin?.coordinate.longitude)!))
urlString += "?dataSet=SRTM_GL3&reduceResolution=0"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { data, res, err in
if let data = data {
print("hey")
let decoder = JSONDecoder()
if let json = try? decoder.decode(Response.self, from: data) {
completion(json)
}
}
}.resume()
}
}
}
public enum PinType {
case CAMERA
case MOTIF
}
public class MapPin: NSObject, MKAnnotation {
public var coordinate: CLLocationCoordinate2D
public let pinType : PinType
public var imageName: String? {
switch pinType {
case PinType.CAMERA: return "camerapin.png"
case PinType.MOTIF : return "motifpin.png"
}
}
public var title: String? {
switch pinType {
case PinType.CAMERA: return "Camera"
case PinType.MOTIF : return "Motif"
}
}
convenience init(pinType: PinType, latitude: Double, longitude: Double) {
self.init(pinType: pinType, coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
}
init(pinType: PinType, coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
self.pinType = pinType
super.init()
}
public func point() -> MKMapPoint {
return MKMapPoint(coordinate)
}
}
class MapPinAnnotationView: MKAnnotationView {
var observers : [MapPinEventObserver] = []
var mapPin : MapPin?
var mapView : MKMapView?
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.isDraggable = true
self.canShowCallout = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var annotation: MKAnnotation? {
willSet {
guard let mapPin = newValue as? MapPin else { return }
self.mapPin = mapPin
canShowCallout = false // enable/disable popups of pins
calloutOffset = CGPoint(x: -5, y: 5)
rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
if let imageName = mapPin.imageName {
image = UIImage(named: imageName)
self.centerOffset = CGPoint(x: 0, y: -image!.size.height / 2)
} else {
image = nil
}
}
}
public func getMapPin() -> MapPin {
return mapPin!
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if dragState == MKAnnotationView.DragState.dragging {
if mapView != nil {
let anchorPoint: CGPoint = CGPoint(x: self.center.x, y: self.center.y - self.centerOffset.y)
let coordinate : CLLocationCoordinate2D = mapView!.convert(anchorPoint, toCoordinateFrom: mapView)
fireMapPinEvent(evt: MapPinEvent(src: mapPin!, coordinate: coordinate))
setDragState(MKAnnotationView.DragState.dragging, animated: false)
}
}
}
override func setDragState(_ dragState: MKAnnotationView.DragState, animated: Bool) {
super.setDragState(dragState, animated: animated)
switch dragState {
case .starting:
startDragging()
case .ending, .canceling:
endDragging()
case .none, .dragging:
break
@unknown default:
fatalError("Unknown drag state")
}
}
func startDragging() {
setDragState(MKAnnotationView.DragState.dragging, animated: false)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
self.layer.opacity = 0.8
self.transform = CGAffineTransform.identity.scaledBy(x: 1.25, y: 1.25)
}, completion: nil)
if #available(iOS 10.0, *) {
let hapticFeedback = UIImpactFeedbackGenerator(style: .light)
hapticFeedback.impactOccurred()
}
}
func endDragging() {
transform = CGAffineTransform.identity.scaledBy(x: 1.5, y: 1.5)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
self.layer.opacity = 1
self.transform = CGAffineTransform.identity.scaledBy(x: 1, y: 1)
}, completion: nil)
// Give the user more haptic feedback when they drop the annotation.
if #available(iOS 10.0, *) {
let hapticFeedback = UIImpactFeedbackGenerator(style: .light)
hapticFeedback.impactOccurred()
}
setDragState(MKAnnotationView.DragState.none, animated: false)
}
// Event handling
func setOnMapPinEvent(observer: MapPinEventObserver) -> Void {
if !observers.isEmpty {
for i in 0..<observers.count {
if observers[i] === observer { return }
}
}
observers.append(observer)
}
func removeOnMapPinEvent(observer: MapPinEventObserver) -> Void {
for i in 0..<observers.count {
if observers[i] === observer {
observers.remove(at: i)
return
}
}
}
func fireMapPinEvent(evt: MapPinEvent) -> Void {
observers.forEach { observer in observer.onMapPinEvent(evt: evt) }
}
}
class MapPinEvent {
var src : MapPin
var coordinate: CLLocationCoordinate2D
var point : MKMapPoint
init(src: MapPin, coordinate: CLLocationCoordinate2D) {
self.src = src
self.coordinate = coordinate
self.point = MKMapPoint(self.coordinate)
}
}
protocol MapPinEventObserver : class {
func onMapPinEvent(evt: MapPinEvent)
}
class Polygon: MKPolygon {
var id: String?
}
class Line: MKPolyline {
var id: String?
}
class Response: Codable {
}
| 49.739623 | 258 | 0.654705 |
fb5a878547f9ff05fd8a0c69b6ad0f7ecd2e80d3 | 679 | //
// CycleModel.swift
// DouYu
//
// Created by 张萌 on 2017/10/23.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
class CycleModel: NSObject {
var id : Int = 0
var title : String = ""
var pic_url : String = ""
var tv_pic_url : String = ""
var room : [String : NSObject]? {
didSet {
guard let room = room else {return}
anchor = AnchorRoomModel(dict: room)
}
}
var anchor : AnchorRoomModel?
/// MARK:- 自定义构造函数
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| 21.903226 | 73 | 0.575847 |
e2ccaeddad13c23b8915e927df73b044572dea41 | 888 | //
// LoggerUtils.swift
// xray
//
// Created by Anton Kononenko on 7/10/20.
// Copyright © 2020 Applicaster. All rights reserved.
//
import Foundation
let subsystemNameSeparator = "/"
class LoggerUtils {
class func getNextSubsystem(subsystem: String, parentSubsystem: String) -> String? {
let parentSubsystemWithSeparator = parentSubsystem.count > 0 ? parentSubsystem + subsystemNameSeparator : parentSubsystem
let subsystemWithoutParent = subsystem.deletingPrefix(parentSubsystemWithSeparator)
guard parentSubsystemWithSeparator != subsystemWithoutParent,
let nextSubsystemSection = subsystemWithoutParent.split(separator: Character(subsystemNameSeparator)).first else {
return nil
}
let subsystemToSearch = parentSubsystemWithSeparator + nextSubsystemSection
return subsystemToSearch
}
}
| 32.888889 | 129 | 0.730856 |
f46907e1fc6bed6c07fab9f0e7dfe8a3f242ee9a | 1,505 | //
// ViewController.swift
// NekiLib
//
// Created by myCRObaM on 09/19/2019.
// Copyright (c) 2019 myCRObaM. All rights reserved.
//
import UIKit
import NekiLib
class ViewController: UIViewController {
var customSwitch: CustomSwitch = {
let customSwitch = CustomSwitch()
customSwitch.translatesAutoresizingMaskIntoConstraints = false
customSwitch.onTintColor = UIColor.orange
customSwitch.offTintColor = UIColor.darkGray
customSwitch.cornerRadius = 0.1
customSwitch.thumbCornerRadius = 0.1
customSwitch.thumbTintColor = UIColor.white
customSwitch.animationDuration = 0.25
return customSwitch
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupUI()
}
func setupUI(){
self.view.addSubview(customSwitch)
setupConstraints()
}
private func setupConstraints(){
NSLayoutConstraint.activate([
customSwitch.topAnchor.constraint(equalTo: self.view.centerYAnchor),
customSwitch.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
customSwitch.widthAnchor.constraint(equalToConstant: 80),
customSwitch.heightAnchor.constraint(equalToConstant: 30)])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 30.1 | 84 | 0.677741 |
d942ad5bb2879cf5e668f28d796d2ca0f2c4c47d | 3,467 | //
// MainViewController.swift
// BEPureLayout_Example
//
// Created by Chung Tran on 5/25/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import Foundation
import BEPureLayout
class MainViewController: BEViewController {
override func setUp() {
super.setUp()
// Corner views
let topLeftView = UIView(width: 100, height: 100, backgroundColor: .green, cornerRadius: 16)
view.addSubview(topLeftView)
topLeftView.autoPinToTopLeftCornerOfSuperviewSafeArea(xInset: 16, yInset: 16)
let topRightView = UIView(width: 100, height: 100, backgroundColor: .red, cornerRadius: 16)
view.addSubview(topRightView)
topRightView.autoPinToTopRightCornerOfSuperviewSafeArea(xInset: 16)
let bottomLeftView = UIView(width: 100, height: 100, backgroundColor: .blue, cornerRadius: 16)
view.addSubview(bottomLeftView)
bottomLeftView.autoPinToBottomLeftCornerOfSuperview(xInset: 16)
let bottomRightView = UIView(width: 100, height: 100, backgroundColor: .yellow, cornerRadius: 16)
view.addSubview(bottomRightView)
bottomRightView.autoPinToBottomRightCornerOfSuperview(xInset: 16)
// buttons
let buttonStackView = UIStackView(axis: .vertical, spacing: 10, alignment: .center, distribution: .fillEqually)
view.addSubview(buttonStackView)
buttonStackView.autoCenterInSuperview()
buttonStackView.addArrangedSubviews {
UIButton(label: "UIButton+UILabel", textColor: .blue)
.onTap(self, action: #selector(openButtonsLabelsVC))
UIButton(label: "UIImageView", textColor: .blue)
.onTap(self, action: #selector(openImagesVC))
UIButton(label: "UITextView", textColor: .blue)
.onTap(self, action: #selector(openTextViewVC))
UIButton(label: "UITextField", textColor: .blue)
.onTap(self, action: #selector(openTextFieldVC))
UIButton(label: "ContentHuggingScrollView", textColor: .blue)
.onTap(self, action: #selector(openContentHuggingScrollVC))
UIButton(label: "TableHeaderView", textColor: .blue)
.onTap(self, action: #selector(openTableViewController))
UIButton(label: "NavBarVC", textColor: .blue)
.onTap(self, action: #selector(openNavBarVC))
}
}
// MARK: - Actions
@objc func openButtonsLabelsVC() {
let vc = ButtonsLabelsViewController()
show(vc, sender: self)
}
@objc func openImagesVC() {
let vc = ImagesViewController()
show(vc, sender: self)
}
@objc func openTextViewVC() {
let vc = TextViewVC()
show(vc, sender: self)
}
@objc func openTextFieldVC() {
let vc = TextFieldVC()
show(vc, sender: self)
}
@objc func openContentHuggingScrollVC() {
let vc = ContentHuggingScrollVC()
show(vc, sender: self)
}
@objc func openTableViewController() {
let vc = TableViewController()
show(vc, sender: self)
}
@objc func openNavBarVC() {
let vc = NavBarVC(preferedNavBarStyle: .normal(backgroundColor: .blue, textColor: .white))
let nc = BENavigationController(rootViewController: vc)
nc.modalPresentationStyle = .fullScreen
show(nc, sender: self)
}
}
| 36.882979 | 119 | 0.636573 |
6a38f14ff2ac5845b54cb29c8f9135171ab31528 | 1,265 | import Foundation
public struct File: Saveable, Fetchable {
private let __type: String = "File" // swiftlint:disable:this identifier_name
public var data: Data?
public var url: URL?
public init(data: Data?, url: URL?) {
self.data = data
self.url = url
}
public func save(options: API.Options) throws -> File {
// upload file
// store in server
// callback with the data
fatalError()
}
public func encode(to encoder: Encoder) throws {
if data == nil && url == nil {
throw ParseError(code: .unknownError, message: "cannot encode file")
}
var container = encoder.container(keyedBy: CodingKeys.self)
if let url = url {
try container.encode(__type, forKey: .__type)
try container.encode(url.absoluteString, forKey: .url)
}
if let data = data {
try container.encode(__type, forKey: .__type)
try container.encode(data, forKey: .data)
}
}
public func fetch(options: API.Options) -> File {
fatalError()
}
enum CodingKeys: String, CodingKey {
case url
case data
case __type // swiftlint:disable:this identifier_name
}
}
| 27.5 | 81 | 0.588142 |
5d47f842b7f08aec09f04889382bc8ec07a788b7 | 5,720 | import Foundation
import TSCBasic
import TuistAutomation
import TuistGraph
import TuistGraphTesting
import TuistSupport
import XCTest
@testable import TuistCache
@testable import TuistCore
@testable import TuistCoreTesting
@testable import TuistSupportTesting
final class CacheFrameworkBuilderIntegrationTests: TuistTestCase {
var subject: CacheFrameworkBuilder!
var frameworkMetadataProvider: FrameworkMetadataProvider!
override func setUp() {
super.setUp()
frameworkMetadataProvider = FrameworkMetadataProvider()
subject = CacheFrameworkBuilder(xcodeBuildController: XcodeBuildController())
}
override func tearDown() {
subject = nil
frameworkMetadataProvider = nil
super.tearDown()
}
func test_build_ios() throws {
// Given
let temporaryPath = try temporaryPath()
let frameworksPath = try temporaryFixture("Frameworks")
let projectPath = frameworksPath.appending(component: "Frameworks.xcodeproj")
let scheme = Scheme.test(name: "iOS")
// When
try subject.build(
scheme: scheme,
projectTarget: XcodeBuildTarget(with: projectPath),
configuration: "Debug",
osVersion: nil,
deviceName: nil,
into: temporaryPath
)
// Then
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.framework").count, 1)
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.dSYM").count, 1)
let frameworkPath = try XCTUnwrap(FileHandler.shared.glob(temporaryPath, glob: "*.framework").first)
XCTAssertEqual(try binaryLinking(path: frameworkPath), .dynamic)
XCTAssertTrue((try architectures(path: frameworkPath)).onlySimulator)
XCTAssertEqual(try architectures(path: frameworkPath).count, 1)
}
func test_build_macos() throws {
// Given
let temporaryPath = try temporaryPath()
let frameworksPath = try temporaryFixture("Frameworks")
let projectPath = frameworksPath.appending(component: "Frameworks.xcodeproj")
let scheme = Scheme.test(name: "macOS")
// When
try subject.build(
scheme: scheme,
projectTarget: XcodeBuildTarget(with: projectPath),
configuration: "Debug",
osVersion: nil,
deviceName: nil,
into: temporaryPath
)
// Then
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.framework").count, 1)
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.dSYM").count, 1)
let frameworkPath = try XCTUnwrap(FileHandler.shared.glob(temporaryPath, glob: "*.framework").first)
XCTAssertEqual(try binaryLinking(path: frameworkPath), .dynamic)
XCTAssertTrue(try architectures(path: frameworkPath).contains(.x8664))
XCTAssertEqual(try architectures(path: frameworkPath).count, 1)
}
func test_build_tvOS() throws {
// Given
let temporaryPath = try temporaryPath()
let frameworksPath = try temporaryFixture("Frameworks")
let projectPath = frameworksPath.appending(component: "Frameworks.xcodeproj")
let scheme = Scheme.test(name: "tvOS")
// When
try subject.build(
scheme: scheme,
projectTarget: XcodeBuildTarget(with: projectPath),
configuration: "Debug",
osVersion: nil,
deviceName: nil,
into: temporaryPath
)
// Then
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.framework").count, 1)
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.dSYM").count, 1)
let frameworkPath = try XCTUnwrap(FileHandler.shared.glob(temporaryPath, glob: "*.framework").first)
XCTAssertEqual(try binaryLinking(path: frameworkPath), .dynamic)
XCTAssertTrue((try architectures(path: frameworkPath)).onlySimulator)
XCTAssertEqual(try architectures(path: frameworkPath).count, 1)
}
func test_build_watchOS() throws {
// Given
let temporaryPath = try temporaryPath()
let frameworksPath = try temporaryFixture("Frameworks")
let projectPath = frameworksPath.appending(component: "Frameworks.xcodeproj")
let scheme = Scheme.test(name: "watchOS")
// When
try subject.build(
scheme: scheme,
projectTarget: XcodeBuildTarget(with: projectPath),
configuration: "Debug",
osVersion: nil,
deviceName: nil,
into: temporaryPath
)
// Then
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.framework").count, 1)
XCTAssertEqual(FileHandler.shared.glob(temporaryPath, glob: "*.dSYM").count, 1)
let frameworkPath = try XCTUnwrap(FileHandler.shared.glob(temporaryPath, glob: "*.framework").first)
XCTAssertEqual(try binaryLinking(path: frameworkPath), .dynamic)
XCTAssertTrue((try architectures(path: frameworkPath)).onlySimulator)
XCTAssertEqual(try architectures(path: frameworkPath).count, 1)
}
fileprivate func binaryLinking(path: AbsolutePath) throws -> BinaryLinking {
let binaryPath = try FrameworkMetadataProvider().loadMetadata(at: path).binaryPath
return try frameworkMetadataProvider.linking(binaryPath: binaryPath)
}
fileprivate func architectures(path: AbsolutePath) throws -> [BinaryArchitecture] {
let binaryPath = try FrameworkMetadataProvider().loadMetadata(at: path).binaryPath
return try frameworkMetadataProvider.architectures(binaryPath: binaryPath)
}
}
| 40 | 108 | 0.672902 |
0ae19f5b7232c7dd24921abdfd125397670fb45e | 27,612 | import Foundation
import Ink
import Plot
import Publish
extension A2 {
public static var theme: Theme<Website> {
Theme(htmlFactory: HTMLFactory(), resourcePaths: [], file: "HTMLFactory.swift")
}
private struct HTMLFactory: Publish.HTMLFactory {
func makeStylesCSS(context: PublishingContext<Website>) throws -> String {
let sass = """
@function unit($value) {
@return 0.02rem * $value;
}
:root {
--background-color: #fff;
--blockquote-background-color: #{rgba(#787880, 20%)};
--elevated-background-color: #fff;
--horizontal-rule-color: #c6c6c8;
--link-color: #0A7AFF;
--mail-button-color: #3478F6;
--mail-button-invalid-color: #dbdbdc;
--mail-input-placeholder-color: #{rgba(#3c3c43, 30%)};
--mail-label-text-color: #8a8a8d;
--navigation-bar-backdrop-filter: blur(20px) saturate(100%);
--navigation-bar-background-color: #{rgba(#f9f9f9, 94%)};
--navigation-bar-border-color: #{rgba(#000, 30%)};
--search-bar-background-color: #{rgba(#767680, 12%)};
--search-bar-text-color: #000;
--status-bar-color: #000;
--text-color: #000;
--toolbar-background-color: #{rgba(#f9f9f9, 94%)};
--toolbar-border-color: #{rgba(#000, 30%)};
--toolbar-disabled-item-color: #BFBFBF;
--toolbar-item-color: #0A7AFF;
--unelevated-background-color: #e0e0e0;
@media (prefers-color-scheme: dark) {
--background-color: #000;
--blockquote-background-color: #{rgba(#787880, 36%)};
--elevated-background-color: #1c1c1e;
--horizontal-rule-color: #3d3d41;
--link-color: #0084FF;
--mail-button-color: #3b82f6;
--mail-button-invalid-color: #414144;
--mail-input-placeholder-color: #{rgba(#ebebf5, 30%)};
--mail-label-text-color: #98989e;
--navigation-bar-backdrop-filter: blur(20px) saturate(130%);
--navigation-bar-background-color: #{rgba(#1d1d1d, 94%)};
--navigation-bar-border-color: #{rgba(#fff, 15%)};
--search-bar-background-color: #{rgba(#767680, 24%)};
--search-bar-text-color: #fff;
--status-bar-color: #fff;
--text-color: #fff;
--toolbar-background-color: #{rgba(#161616, 80%)};
--toolbar-border-color: #{rgba(#fff, 16%)};
--toolbar-disabled-item-color: #4D4D4D;
--toolbar-item-color: #5A91F7;
--unelevated-background-color: #141415;
}
}
html {
background: var(--background-color);
color: var(--text-color);
}
body {
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
font-size: 16px;
margin: 2.5rem;
}
a {
color: var(--link-color);
text-decoration: none;
}
footer {
margin-bottom: 2.5rem;
text-align: center;
}
.target {
left: 0;
position: absolute;
top: 0;
}
.content {
display: flex;
margin: 0 auto;
width: 61rem;
h1, h2 {
margin: 0;
}
p {
line-height: 1.5;
}
}
.text-content {
margin-left: 2.5rem;
min-width: 32rem;
}
.content-default {
blockquote {
background: var(--blockquote-background-color);
border-radius: 1rem;
margin: 0;
padding: 1rem;
p {
margin: 0;
}
}
}
$transition-duration: 0.4s;
@media (prefers-reduced-motion) {
.animated {
transition: none !important;
}
}
.phone {
background: #233a4a;
border-radius: unit(205);
box-shadow: inset 0 0 unit(3) unit(2) rgba(0, 0, 0, 0.5), inset 0 0 unit(2) unit(5) #203747, inset 0 0 unit(2) unit(8) #ADCEE4, inset 0 unit(1) unit(4) unit(10) rgba(0, 0, 0, 0.35);
flex-shrink: 0;
font-size: unit(36);
height: unit(2658);
position: relative;
width: unit(1296);
&::before, &::after {
border-radius: unit(183);
content: "";
}
&::before {
background: #2e2c2a;
box-shadow: unit(-6) 0 unit(3) 0 rgba(255, 255, 255, 0.08), 0 0 unit(2) unit(1) rgba(0, 0, 0, 0.6), inset 0 0 unit(1) unit(1) rgba(0, 0, 0, 0.5);
height: calc(100% - #{unit(36)});
position: absolute;
top: unit(18);
left: unit(18);
width: calc(100% - #{unit(36)});
}
&::after {
background: #000;
height: calc(100% - #{unit(42)});
top: unit(21);
left: unit(21);
position: absolute;
width: calc(100% - #{unit(42)});
}
.buttons {
* {
border-radius: unit(2);
box-shadow: inset unit(-10) 0 unit(3) 0 rgba(0, 0, 0, 0.4), inset unit(2) 0 unit(1) 0 rgba(0, 0, 0, 0.6), inset 0 unit(3) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(-3) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(6) unit(1) 0 #BDE1F7, inset 0 unit(-6) unit(1) 0 #BDE1F7, inset unit(4) 0 unit(1) 0 #BDE1F7;
position: absolute;
width: unit(17);
z-index: -1;
}
.power {
background: linear-gradient(0deg, #0B212B 3%, #668091 8%, #668192 93%, #11232E 98%);
border-radius: unit(4);
box-shadow: inset unit(-10) 0 unit(3) 0 rgba(0, 0, 0, 0.4), inset unit(2) 0 unit(1) 0 rgba(0, 0, 0, 0.6), inset 0 unit(3) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(-3) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(6) unit(1) 0 #BDE1F7, inset 0 unit(-6) unit(1) 0 #BDE1F7, inset unit(4) 0 unit(1) 0 #BDE1F7;
height: unit(316);
right: unit(-8.5);
top: unit(681);
}
.mute {
background: linear-gradient(0deg, #0B212B 5%, #668091 14%, #668192 86%, #11232E 96%);
box-shadow: inset unit(-9) 0 unit(3) 0 rgba(0, 0, 0, 0.5), inset unit(1) 0 unit(1) 0 rgba(0, 0, 0, 0.6), inset 0 unit(2) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(-2) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(4) unit(1) 0 #BDE1F7, inset 0 unit(-4) unit(1) 0 #BDE1F7, inset unit(3) 0 unit(1) 0 rgba(189,225,247, 0.75);
height: unit(100);
left: unit(-8.5);
top: unit(422);
}
.volume-up,
.volume-down {
background: linear-gradient(0deg, #0B212B 5%, #668091 10%, #668192 90%, #11232E 96%);
box-shadow: inset unit(-11) 0 unit(3) 0 rgba(0, 0, 0, 0.5), inset unit(1) 0 unit(1) 0 rgba(0, 0, 0, 0.6), inset 0 unit(2) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(-2) unit(2) 0 rgba(0, 0, 0, 0.85), inset 0 unit(4) unit(1) 0 #BDE1F7, inset 0 unit(-4) unit(1) 0 #BDE1F7, inset unit(3) 0 unit(1) 0 rgba(189, 225, 247, 0.75);
height: unit(200);
left: unit(-8.5);
}
.volume-up {
top: unit(613);
}
.volume-down {
top: unit(867);
}
}
.bands {
* {
opacity: 0.8;
width: unit(19);
height: unit(18);
position: absolute;
}
.right {
right: 0;
}
.left {
left: 0;
}
.bottom.left,
.bottom.right {
bottom: unit(269);
}
.bottom.right {
background: #3C494F;
}
.bottom.center {
background: #39464E;
width: unit(18);
height: unit(19);
left: unit(262);
bottom: 0;
}
.bottom.left {
background: #3C464F;
width: unit(19);
height: unit(17);
}
.top.left,
.top.right {
top: unit(269);
}
.top.center {
background: #59656F;
top: 0;
right: unit(259);
}
.top.left {
background: #56646C;
}
.top.right {
background: #57646C;
}
}
.display {
border-radius: unit(142);
width: unit(1170);
height: unit(2532);
position: absolute;
top: unit(63);
left: unit(63);
background: black;
z-index: 1;
overflow: hidden;
.notch {
background-color: #000;
border-radius: 0 0 unit(66) unit(66);
content: "";
height: unit(95.5);
left: 50%;
transform: translateX(-50%);
position: absolute;
top: 0;
width: unit(632);
z-index: 2;
&::before,
&::after {
background-image: radial-gradient(circle at 0 100%, transparent unit(18), #000 unit(18));
background-repeat: no-repeat;
background-size: 50% 100%;
content: "";
height: unit(18);
left: unit(-18);
position: absolute;
top: 0;
width: unit(36);
}
&::after {
background-image: radial-gradient(circle at 100% 100%, transparent unit(18), #000 unit(18));
left: 100%;
}
}
.homescreen {
color: #fff;
display: flex;
flex-direction: column;
height: 100%;
transition: $transition-duration filter;
width: 100%;
:target ~ & {
filter: blur(30px) brightness(0.5);
}
.background {
border-radius: unit(142);
background: url("/images/background.jpg") center/115% no-repeat;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
@media (prefers-color-scheme: dark) {
background-image: url("/images/background~dark.jpg");
}
}
.icons {
flex: 1;
margin-top: unit(231);
transition-duration: $transition-duration;
transition-property: transform, opacity;
width: 100%;
:target ~ & {
transform: scale(0.8);
opacity: 0.8;
}
}
}
}
.status-bar {
color: #fff;
display: flex;
flex-direction: row;
font-size: unit(48);
font-weight: 500;
height: unit(144);
justify-content: space-between;
position: absolute;
transition: $transition-duration color;
width: 100%;
z-index: 2;
> * {
align-self: center;
text-align: center;
width: unit(312);
}
.status {
height: unit(36);
}
.path-fill {
transition: $transition-duration fill;
}
.path-stroke {
transition: $transition-duration stroke;
}
}
.icons ul {
column-gap: unit(30);
margin: 0 unit(60);
row-gap: unit(54);
li {
width: unit(240);
a {
color: #fff;
text-decoration: none;
text-overflow: clip;
}
}
}
.icons ul,
.dock ul {
list-style: none;
padding-left: 0;
display: grid;
grid-template-columns: repeat(4, 1fr);
li {
overflow: hidden;
padding-top: unit(192);
position: relative;
text-align: center;
text-overflow: ellipsis;
}
}
.dock {
-webkit-backdrop-filter: blur(30px) saturate(110%);
backdrop-filter: blur(30px) saturate(110%);
background: rgba(255, 255, 255, 0.3);
border-radius: unit(93);
height: unit(287);
margin: unit(36);
.app::before {
left: 0;
}
ul {
column-gap: unit(90);
margin: unit(51) unit(42);
li {
font-size: unit(0);
width: unit(180);
}
}
}
.screen {
background-size: cover;
border-radius: unit(141);
height: 100%;
left: 0;
opacity: 0;
position: absolute;
text-indent: -9999rem;
top: 0;
transform: scale(0.1);
transition-duration: $transition-duration;
transition-property: opacity, transform, z-index;
width: 100%;
z-index: -1;
}
.screen-mail {
background: #000;
input, textarea {
background: transparent;
color: var(--text-color);
font-size: unit(48);
&::placeholder {
color: var(--mail-input-placeholder-color);
}
}
hr {
margin: 0 unit(50);
border: 0;
border-top: unit(1) solid var(--horizontal-rule-color);
}
.page {
border-radius: unit(30);
bottom: 0;
position: absolute;
&.foreground {
background: var(--elevated-background-color);
height: calc(100% - #{unit(170)});
width: 100%;
z-index: 1;
}
&.background {
background: var(--unelevated-background-color);
width: calc(100% - #{unit(48)});
height: calc(100% - #{unit(140)});
left: unit(24);
border-radius: unit(30);
}
}
form {
font-size: unit(48);
}
.captcha-container {
display: flex;
justify-content: center;
}
.fieldset {
padding: unit(40) 0;
margin: 0 unit(50);
&.flex {
display: flex;
}
label, .label {
color: var(--mail-label-text-color);
margin-right: unit(16);
}
textarea {
border: 0;
font-family: inherit;
height: unit(900);
padding: 0;
resize: none;
width: 100%;
}
.signature {
margin-top: unit(16);
}
input {
flex: 1;
border: 0;
padding: 0;
margin: 0;
}
}
.cancel {
color: var(--mail-button-color);
display: inline-block;
margin: unit(65) unit(50);
font-size: unit(48);
text-decoration: none;
}
.header {
display: flex;
padding: unit(40) unit(50);
.title {
flex: 1;
font-weight: bold;
display: block;
font-size: unit(96);
}
}
.submit {
background: transparent;
border: 0;
height: unit(107);
padding: 0;
width: unit(108);
svg {
height: 100%;
width: 100%;
}
path {
fill: var(--mail-button-invalid-color);
transition: $transition-duration fill;
}
}
form:valid .submit {
cursor: pointer;
path {
fill: var(--mail-button-color);
}
}
}
.screen-safari {
background: #fff;
color: #000;
.navigation-bar {
-webkit-backdrop-filter: var(--navigation-bar-backdrop-filter);
background: var(--navigation-bar-background-color);
backdrop-filter: var(--navigation-bar-backdrop-filter);
border-bottom: unit(1) solid var(--navigation-bar-border-color);
height: unit(300);
left: 0;
position: absolute;
top: 0;
width: 100%;
z-index: 1;
}
.search-bar {
background: var(--search-bar-background-color);
border-radius: unit(30);
color: var(--search-bar-text-color);
font-size: unit(51);
height: unit(108);
left: unit(29);
position: absolute;
text-align: center;
top: unit(153);
width: calc(100% - #{unit(58)});
display: flex;
z-index: 1;
> div {
align-self: center;
flex: 1;
}
}
.toolbar {
width: calc(100% - #{unit(48)});
height: unit(133);
left: 0;
bottom: 0;
position: absolute;
display: flex;
justify-content: space-between;
padding: unit(9) unit(24) unit(108);
-webkit-backdrop-filter: blur(20px) saturate(100%);
background: var(--toolbar-background-color);
backdrop-filter: blur(20px) saturate(100%);
border-top: unit(1) solid var(--toolbar-border-color);
svg {
height: unit(132);
width: unit(132);
}
> a svg path {
fill: var(--toolbar-item-color);
}
> svg path {
fill: var(--toolbar-disabled-item-color);
}
}
.iframe-container {
width: 100%;
height: 100%;
position: absolute;
}
iframe {
$scale: 0.5;
background-color: var(--background-color);
padding-bottom: unit(250) / $scale;
padding-top: unit(300) / $scale;
width: 100% / $scale;
height: calc(#{100% / $scale} - #{unit(550) / $scale});
transform: scale($scale);
transform-origin: 0 0;
}
}
.home-indicator, .screen-bean::after, .screen-potluck::after {
background: #000;
border-radius: unit(7.5);
bottom: unit(30);
height: unit(15);
position: absolute;
left: 50%;
transform: translate(-50%);
width: unit(417);
}
.screen-mail .home-indicator, .screen-safari .home-indicator {
background: var(--status-bar-color);
}
.screen-bean::after, .screen-potluck::after {
background: #fff;
content: "";
}
.app::before {
$mask: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.4" clip-rule="evenodd" viewBox="0 0 460 460"%3E%3Cpath d="M460 316v30a202 202 0 01-3 31c-2 10-5 19-9 28a97 97 0 01-43 43 102 102 0 01-28 9c-10 2-20 3-31 3a649 649 0 01-13 0H127a649 649 0 01-13 0 201 201 0 01-31-3c-10-2-19-5-28-9a97 97 0 01-43-43 102 102 0 01-9-28 202 202 0 01-3-31v-13-189-17-13a202 202 0 013-31c2-10 5-19 9-28a97 97 0 0143-43 102 102 0 0128-9 203 203 0 0144-3h206a649 649 0 0113 0c11 0 21 1 31 3s19 5 28 9a97 97 0 0143 43 102 102 0 019 28 202 202 0 013 31 643 643 0 010 30v172z"/%3E%3C/svg%3E') center/100% 100% no-repeat;
-webkit-mask: $mask;
background: url("/images/icons/blank.png") center/cover;
content: "";
height: unit(180);
left: unit(30);
mask: $mask;
position: absolute;
top: 0;
width: unit(180);
}
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .darkContent }.map { app in "#\(app.id):target ~ .phone .status-bar" }.joined(separator: ",\n")) {
color: #000;
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .darkContent }.map { app in "#\(app.id):target ~ .phone .status-bar .path-fill" }.joined(separator: ",\n")) {
fill: #000;
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .darkContent }.map { app in "#\(app.id):target ~ .phone .status-bar .path-stroke" }.joined(separator: ",\n")) {
stroke: #000;
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .adaptive }.map { app in "#\(app.id):target ~ .phone .status-bar" }.joined(separator: ",\n")) {
color: var(--status-bar-color);
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .adaptive }.map { app in "#\(app.id):target ~ .phone .status-bar .path-fill" }.joined(separator: ",\n")) {
fill: var(--status-bar-color);
}
\(context.site.apps.filter { app in !(app is StubApp) && app.screen.statusBarStyle == .adaptive }.map { app in "#\(app.id):target ~ .phone .status-bar .path-stroke" }.joined(separator: ",\n")) {
stroke: var(--status-bar-color);
}
\(context.site.apps.map { app in """
.phone .app-\(app.id)::before {
background-image: url("/images/icons/\(app.id).png");
}
""" }.joined(separator: "\n\n"))
\(context.site.apps.filter { app in app is DefaultApp }.map { app in """
.phone .screen-\(app.id) {
background-image: url("/images/screens/\(app.id).jpg");\((try? context.outputFile(at: "/images/screens/\(app.id)~dark.jpg")) == nil ? "" : """
@media (prefers-color-scheme: dark) {
background-image: url("/images/screens/\(app.id)~dark.jpg");
}
""")
}
""" }.joined(separator: "\n\n"))
\(context.site.apps.filter { app in !(app is StubApp || app is DefaultApp) }.map { app in ".phone .screen-\(app.id)" }.joined(separator: ", ")) {
overflow: hidden;
text-indent: unset;
}
\(context.site.apps.filter { app in !(app is StubApp) }.map { app in ".content-\(app.id)" }.joined(separator: ", ")) {
display: none;
}
\(context.site.apps.filter { app in !(app is StubApp || app is MailApp || app is SafariApp) }.map { app in "#\(app.id):target ~ .text-content .content-default" }.joined(separator: ", ")) {
display: none;
}
\(context.site.apps.filter { app in !(app is StubApp) }.map { app in "#\(app.id):target ~ .text-content .content-\(app.id)" }.joined(separator: ", ")) {
display: unset;
}
\(context.site.apps.filter { app in !(app is StubApp) }.map { app in "#\(app.id):target ~ .phone .screen-\(app.id)" }.joined(separator: ", ")) {
opacity: unset;
transform: unset;
z-index: 1; // bug in Chrome: use `1` not `unset`
}
"""
let archiveResource: LocalResource = #fileLiteral(resourceName: "sass.dart.js") // sass.dart.js
return try Sass(scriptSource: String(contentsOf: archiveResource.fileURL))
.compileSync(styles: sass, options: Sass.Options(outputStyle: .compressed))
}
func makeIndexHTML(for index: Index, context: PublishingContext<Website>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: index, on: context.site, inlineStyles: [try makeStylesCSS(context: context)]),
.body {
ContentWrapper {
ComponentGroup(members: context.site.apps.filter { app in !(app is StubApp) }.map { app in
Div()
.class("target")
.id(app.id)
})
Phone(apps: context.site.apps)
Div {
H1(context.site.name)
Div(index.body)
.class("content-default")
let parser = MarkdownParser()
ComponentGroup(members: context.site.apps.filter { app in app.location == .homescreen }.compactMap { app in
guard let markdownPath = app.markdownPath else {
return nil
}
let file = try! context.file(at: markdownPath)
let contents = try! file.readAsString()
let markdown = parser.parse(contents)
return Div {
H2(markdown.metadata["title"] ?? app.name)
Div.init(html: markdown.html)
Link("← Back", url: "#")
}
.class("content-\(app.id)")
})
SiteFooter()
}
.class("text-content")
}
}
)
}
func makeSectionHTML(for section: Section<Website>, context: PublishingContext<Website>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: section, on: context.site, stylesheetPaths: []),
.body {
SiteHeader(context: context, selectedSelectionID: section.id)
ContentWrapper {
H1(section.title)
ItemList(items: section.items, site: context.site)
}
SiteFooter()
}
)
}
func makeItemHTML(for item: Item<Website>, context: PublishingContext<Website>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: item, on: context.site, stylesheetPaths: []),
.body(
.class("item-page"),
.components {
SiteHeader(context: context, selectedSelectionID: item.sectionID)
ContentWrapper {
Article {
Div(item.content.body).class("content")
Span("Tagged with: ")
ItemTagList(item: item, site: context.site)
}
}
SiteFooter()
}
)
)
}
func makePageHTML(for page: Page, context: PublishingContext<Website>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: page, on: context.site, stylesheetPaths: []),
.body {
SiteHeader(context: context, selectedSelectionID: nil)
ContentWrapper(page.body)
SiteFooter()
}
)
}
func makeTagListHTML(for page: TagListPage, context: PublishingContext<Website>) throws -> HTML? {
nil
}
func makeTagDetailsHTML(for page: TagDetailsPage, context: PublishingContext<Website>) throws -> HTML? {
nil
}
}
}
extension Node where Context == HTML.DocumentContext {
static func head<T: Website>(
for location: Location,
on site: T,
titleSeparator: String = " | ",
inlineStyles: [String] = [],
stylesheetPaths: [Path] = []
) -> Node {
var title = location.title
if title.isEmpty {
title = site.name
} else {
title.append(titleSeparator + site.name)
}
var description = location.description
if description.isEmpty {
description = site.description
}
return .head(
.encoding(.utf8),
.siteName(site.name),
.url(site.url(for: location)),
.title(title),
.description(description),
.twitterCardType(location.imagePath == nil ? .summary : .summaryLargeImage),
.forEach(stylesheetPaths, { .stylesheet($0) }),
.meta(.name("viewport"), .content("width=1100")),
.unwrap(site.favicon, { .favicon($0) }),
.link(.rel(.maskIcon), .href("/favicon.svg"), .attribute(named: "color", value: "black")),
.unwrap(location.imagePath ?? site.imagePath, { path in
let url = site.url(for: path)
return .socialImageLink(url)
}),
.forEach(inlineStyles, { .style($0) }),
.script(.src("//gc.zgo.at/count.js"), .data(named: "goatcounter", value: "https://a2io.goatcounter.com/count"))
)
}
}
private struct ContentWrapper: ComponentContainer {
var content: ContentProvider
init(@ComponentBuilder content: @escaping ContentProvider) {
self.content = content
}
@ComponentBuilder var body: Component {
Div(content: content)
.class("content")
}
}
private struct SiteHeader<Site: Website>: Component {
var context: PublishingContext<Site>
var selectedSelectionID: Site.SectionID?
@ComponentBuilder var body: Component {
Header {
ContentWrapper {
Link(context.site.name, url: "/")
.class("site-name")
if Site.SectionID.allCases.count > 1 {
navigation
}
}
}
}
@ComponentBuilder private var navigation: Component {
Navigation {
List(Site.SectionID.allCases) { sectionID in
let section = context.sections[sectionID]
return Link(section.title, url: section.path.absoluteString)
.class(sectionID == selectedSelectionID ? "selected" : "")
}
}
}
}
private struct ItemList<Site: Website>: Component {
var items: [Item<Site>]
var site: Site
@ComponentBuilder var body: Component {
List(items) { item in
Article {
H1(Link(item.title, url: item.path.absoluteString))
ItemTagList(item: item, site: site)
Paragraph(item.description)
}
}
.class("item-list")
}
}
private struct ItemTagList<Site: Website>: Component {
var item: Item<Site>
var site: Site
@ComponentBuilder var body: Component {
List(item.tags) { tag in
Link(tag.string, url: site.path(for: tag).absoluteString)
}
.class("tag-list")
}
}
private struct SiteFooter: Component {
@ComponentBuilder var body: Component {
Footer {
Paragraph {
Text("Generated with ")
Link("Swift Playgrounds", url: "https://github.com/a2/site-playground")
.data(named: "goatcounter-click", value: "github")
}
}
}
}
| 27.722892 | 682 | 0.541467 |
eb460802a99024ad2ddf83d60059bfb6c5ceeb1c | 571 | import Flutter
import UIKit
import MLKit
public class SwiftLearningTextRecognitionPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "LearningTextRecognition", binaryMessenger: registrar.messenger())
let instance = SwiftLearningTextRecognitionPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
result("iOS " + UIDevice.current.systemVersion)
}
}
| 31.722222 | 111 | 0.78634 |
1170660abd01e234d85ad69835ee2c2f0fe6c44d | 3,319 | // Created by adong666 on 2018/8/22. Copyright © 2018年 adong666666. All rights reserved.
import UIKit
class colectTableViewCell: UITableViewCell {
override func awakeFromNib() { allthings() }
var llabel: PowerLabel = {
let frame1 = CGRect (x: 0.fitScreen, y: 0.fitHeight, width: 414.fitScreen, height: 40.fitHeight)
let label = PowerLabel(frame: frame1)
label.alpha = 0.1
label.backgroundColor = UIColor.init(r: 237, g: 237, b: 237)
return label
}()
var llabel2: PowerLabel = {
let frame1 = CGRect (x: 60.fitScreen, y: 0.fitHeight, width: 414.fitScreen, height: 40.fitHeight)
let label = PowerLabel(frame: frame1)
label.font = UIFont(name: "Arial", size: 12)
label.textAlignment = .left
label.text = "某某基地 >"
return label
}()
var llabel3: PowerLabel = {
let frame1 = CGRect (x: 310.fitScreen, y: 0.fitHeight, width: 414.fitScreen, height: 40.fitHeight)
let label = PowerLabel(frame: frame1)
label.font = UIFont(name: "Arial", size: 12)
label.textAlignment = .left
label.text = "已完成"
return label
}()
var btn1: PowerButton = {
let frame = CGRect(x: 10.fitScreen, y: 5.fitHeight, width: 30.fitScreen, height: 30.fitHeight)
let bt1 = PowerButton(frame: frame)
bt1.setBackgroundImage(UIImage(named: "aaaaa"), for: UIControl.State.normal)
bt1.layer.cornerRadius = 12
bt1.layer.masksToBounds = true
return bt1
}()
var llabel5: PatientInfoCustomLabel = {
let bt1 = PatientInfoCustomLabel()
bt1.frame = CGRect(x: 124.fitScreen, y: 80.fitHeight, width: 250.fitScreen, height: 100.fitHeight)
bt1.lineBreakMode = NSLineBreakMode.byWordWrapping
bt1.numberOfLines = 0
bt1.textAlignment = .left
bt1.text = "7月17日-月18日 共一晚\n\n整套出租 一套\n\n订单总额: ¥280.00"
return bt1
}()
var llabel6: PatientInfoCustomLabel = {
let bt1 = PatientInfoCustomLabel()
bt1.frame = CGRect(x: 10.fitScreen, y: 50.fitHeight, width: 300.fitScreen, height: 100.fitHeight)
bt1.lineBreakMode = NSLineBreakMode.byWordWrapping
bt1.numberOfLines = 0
bt1.textAlignment = .left
bt1.font = UIFont(name: "Arial", size: 14)
bt1.text = "【逅湖民宿】美式复古大床房201"
return bt1
}()
var llabel9: PowerButton = {
let bt1 = PowerButton()
bt1.frame = CGRect(x: 380.fitScreen, y: 110.fitHeight, width: 30.fitScreen, height: 30.fitHeight)
bt1.setBackgroundImage(UIImage(named: "右"), for: UIControl.State.normal)
return bt1
}()
var img1 : UIImageView = {
let img = UIImageView(image: UIImage(named: "1"))
img.frame = CGRect(x:15.fitScreen, y: 80.fitHeight, width: 94.fitScreen, height: 80.fitHeight)
return img
}()
}
extension colectTableViewCell{
func allthings(){
super.awakeFromNib()
add()
}
}
extension colectTableViewCell{
func add(){
self.selectionStyle = UITableViewCell.SelectionStyle.none
addSubview(llabel)
addSubview(btn1)
addSubview(llabel2)
addSubview(llabel3)
addSubview(llabel5)
addSubview(llabel6)
addSubview(llabel9)
addSubview(img1)
}
}
| 37.292135 | 106 | 0.6279 |
e8f5745cf835971fc15b544d2e51e1615016d119 | 3,742 | import CoreLocation
import Foundation
import UIKit
/// Designates the kind of deeplinking to perform
///
/// - native: Launches the native Lyft app if available
/// - web: Launches a safari view controller without leaving the app, enabling ride request function
public enum LyftDeepLinkBehavior {
case native
case web
fileprivate var baseUrl: URL {
switch self {
case .native:
return URL(staticString: "lyft://ridetype")
case .web:
return URL(staticString: "https://ride.lyft.com/u")
}
}
}
/// Collection of deep links into the main Lyft application
public struct LyftDeepLink {
/// Prepares to request a ride with the given parameters
///
/// - parameter behavior: The deep linking mode to use for this deep link
/// - parameter kind: The kind of ride to create a request for
/// - parameter pickup: The pickup position of the ride
/// - parameter destination: The destination position of the ride
/// - parameter couponCode: A coupon code to be applied to the user
public static func requestRide(using behavior: LyftDeepLinkBehavior = .native, kind: RideKind = .Standard,
from pickup: CLLocationCoordinate2D? = nil,
to destination: CLLocationCoordinate2D? = nil,
couponCode: String? = nil)
{
var parameters = [String: Any]()
parameters["partner"] = LyftConfiguration.developer?.clientId
parameters["credits"] = couponCode
parameters["id"] = kind.rawValue
parameters["pickup[latitude]"] = pickup.map { $0.latitude }
parameters["pickup[longitude]"] = pickup.map { $0.longitude }
parameters["destination[latitude]"] = destination.map { $0.latitude }
parameters["destination[longitude]"] = destination.map { $0.longitude }
self.launch(using: behavior, parameters: parameters)
}
private static func launch(using behavior: LyftDeepLinkBehavior, parameters: [String: Any])
{
let request = lyftURLEncodedInURL(request: URLRequest(url: behavior.baseUrl),
parameters: parameters).0
guard let url = request.url else {
return
}
switch behavior {
case .native:
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:]) { success in
if !success {
self.launchAppStore()
}
}
} else {
UIApplication.shared.openURL(url)
}
case .web:
Safari.openURL(url, from: UIApplication.shared.topViewController)
}
}
@available(iOS 10.0, *)
private static func launchAppStore() {
let signUp = LyftConfiguration.signUpIdentifier
let id = LyftConfiguration.developer?.clientId ?? "unknown"
let infoDictionary = Bundle.lyftSDKBundle?.infoDictionary
let version = infoDictionary?["CFBundleShortVersionString"] as? String ?? "?.?.?"
let url = "https://www.lyft.com/signup/\(signUp)?clientId=\(id)&sdkName=iOS&sdkVersion=\(version)"
if let signUpUrl = URL(string: url) {
UIApplication.shared.open(signUpUrl, options: [:], completionHandler: nil)
}
}
}
private extension UIApplication {
var topViewController: UIViewController? {
var topController = self.keyWindow?.rootViewController
while let viewController = topController?.presentedViewController {
topController = viewController
}
return topController
}
}
| 38.183673 | 110 | 0.608498 |
3380e936eb71c54dc8f7d21c4f589711af2fa9a1 | 6,769 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// 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.
extension SFSymbol {
public static var arrowtriangle: Arrowtriangle { .init(name: "arrowtriangle") }
open class Arrowtriangle: SFSymbol {
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backward: SFSymbol { ext(.start + ".backward") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backwardCircle: SFSymbol { ext(.start + ".backward".circle) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backwardCircleFill: SFSymbol { ext(.start + ".backward".circle.fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backwardFill: SFSymbol { ext(.start + ".backward".fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backwardSquare: SFSymbol { ext(.start + ".backward".square) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var backwardSquareFill: SFSymbol { ext(.start + ".backward".square.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var down: SFSymbol { ext(.start + ".down") }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var downCircle: SFSymbol { ext(.start + ".down".circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var downCircleFill: SFSymbol { ext(.start + ".down".circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var downFill: SFSymbol { ext(.start + ".down".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var downSquare: SFSymbol { ext(.start + ".down".square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var downSquareFill: SFSymbol { ext(.start + ".down".square.fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forward: SFSymbol { ext(.start + ".forward") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forwardCircle: SFSymbol { ext(.start + ".forward".circle) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forwardCircleFill: SFSymbol { ext(.start + ".forward".circle.fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forwardFill: SFSymbol { ext(.start + ".forward".fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forwardSquare: SFSymbol { ext(.start + ".forward".square) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var forwardSquareFill: SFSymbol { ext(.start + ".forward".square.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var left: SFSymbol { ext(.start + ".left") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var leftAndLineVerticalAndArrowtriangleRight: SFSymbol { ext(.start + ".left.and.line.vertical.and.arrowtriangle.right") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var leftAndLineVerticalAndArrowtriangleRightFill: SFSymbol { ext(.start + ".left.and.line.vertical.and.arrowtriangle.right".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var leftCircle: SFSymbol { ext(.start + ".left".circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var leftCircleFill: SFSymbol { ext(.start + ".left".circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var leftFill: SFSymbol { ext(.start + ".left".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var leftSquare: SFSymbol { ext(.start + ".left".square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var leftSquareFill: SFSymbol { ext(.start + ".left".square.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var right: SFSymbol { ext(.start + ".right") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var rightAndLineVerticalAndArrowtriangleLeft: SFSymbol { ext(.start + ".right.and.line.vertical.and.arrowtriangle.left") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var rightAndLineVerticalAndArrowtriangleLeftFill: SFSymbol { ext(.start + ".right.and.line.vertical.and.arrowtriangle.left".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var rightCircle: SFSymbol { ext(.start + ".right".circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var rightCircleFill: SFSymbol { ext(.start + ".right".circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var rightFill: SFSymbol { ext(.start + ".right".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var rightSquare: SFSymbol { ext(.start + ".right".square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var rightSquareFill: SFSymbol { ext(.start + ".right".square.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var up: SFSymbol { ext(.start + ".up") }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var upCircle: SFSymbol { ext(.start + ".up".circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var upCircleFill: SFSymbol { ext(.start + ".up".circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var upFill: SFSymbol { ext(.start + ".up".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var upSquare: SFSymbol { ext(.start + ".up".square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var upSquareFill: SFSymbol { ext(.start + ".up".square.fill) }
}
} | 59.377193 | 138 | 0.683262 |
c12fb7a15c6d87cf34b11b5f2f3b5cbfbe214c80 | 623 | //
// Driver.swift
// Yomu
//
// Created by Sendy Halim on 7/24/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import RxCocoa
import RxSwift
import Swiftz
precedencegroup YomuDriverBindPrecedence {
associativity: left
lowerThan: CategoryPrecedence, DefaultPrecedence
higherThan: YomuAddToDisposeBagPrecedence
}
infix operator ~~> : YomuDriverBindPrecedence
func ~~> <T>(driver: Driver<T>, f: @escaping (T) -> Void) -> Disposable {
return driver.drive(onNext: f)
}
func ~~> <T, O: ObserverType>(driver: Driver<T>, observer: O) -> Disposable where O.E == T {
return driver.drive(observer)
}
| 21.482759 | 92 | 0.712681 |
e48931ee5d02bc8c3d4131aac63adc89eb1db815 | 449 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
// REQUIRES: asserts
struct c{class A:A{}var f=A.s
| 40.818182 | 79 | 0.74833 |
e238cf76f52b860a503e00584ed8f0a82e54c3c3 | 2,690 | //
// ContributeViewController.swift
// animalhelp
//
// Created by Aamir on 20/01/18.
// Copyright © 2018 AamirAnwar. All rights reserved.
//
import Foundation
class ContributeViewController:BaseViewController {
let tableView = UITableView(frame: CGRect.zero, style: .plain)
let kCellReuseID = "ContributeCellReuseIdentifier"
var tableData:[(title:String, detailText:String)] {
get {
var data = [(title:String, detailText:String)]()
data += [("Spreading the word", "Letting people know that they can use this platform in a time of need can help speed up the process of finding missing pets. The more people aware, the more chances of the pet being found.")]
data += [("Helping catalog and verifying help centers", "Writing to us about how good a clinic is can really help in not just finding the nearest clinic to you but also helps us factor in the quality of service.")]
data += [("Sending stories and feedback","The more feedback we get the more we can do better, if you see something amiss or any improvements it would mean the world to us if you could let us know.")]
return data
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.customNavBar.setTitle("How to help")
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { (make) in
make.top.equalTo(self.customNavBar.snp.bottom)
make.leading.equalToSuperview()
make.trailing.equalToSuperview()
make.bottom.equalToSuperview()
}
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .none
self.tableView.tableFooterView = UIView(frame:CGRect.zero)
self.tableView.register(ListItemDetailTableViewCell.self, forCellReuseIdentifier: self.kCellReuseID)
}
}
extension ContributeViewController:UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.kCellReuseID) as! ListItemDetailTableViewCell
cell.setTitleFont(CustomFontBodyMedium)
let (title,subtitle) = tableData[indexPath.row]
cell.setTitle(title, subtitle: subtitle)
if indexPath.row < self.tableData.count - 1 {
cell.showBottomPaddedSeparator()
}
return cell
}
}
| 42.698413 | 236 | 0.67658 |
031a79d4cded1d7ff1c3897bcd3bb552b7f2e924 | 18,484 | //
// Preferences.swift
// Aerial
//
// Created by John Coates on 9/21/16.
// Copyright © 2016 John Coates. All rights reserved.
//
import Foundation
import ScreenSaver
// swiftlint:disable:next type_body_length
class Preferences {
// MARK: - Types
fileprivate enum Identifiers: String {
case differentAerialsOnEachDisplay = "differentAerialsOnEachDisplay"
case multiMonitorMode = "multiMonitorMode"
case cacheAerials = "cacheAerials"
case customCacheDirectory = "cacheDirectory"
case videoFormat = "videoFormat"
case showDescriptions = "showDescriptions"
case useCommunityDescriptions = "useCommunityDescriptions"
case showDescriptionsMode = "showDescriptionsMode"
case neverStreamVideos = "neverStreamVideos"
case neverStreamPreviews = "neverStreamPreviews"
case localizeDescriptions = "localizeDescriptions"
case timeMode = "timeMode"
case manualSunrise = "manualSunrise"
case manualSunset = "manualSunset"
case fadeMode = "fadeMode"
case fadeModeText = "fadeModeText"
case descriptionCorner = "descriptionCorner"
case fontName = "fontName"
case fontSize = "fontSize"
case showClock = "showClock"
case withSeconds = "withSeconds"
case showMessage = "showMessage"
case showMessageString = "showMessageString"
case extraFontName = "extraFontName"
case extraFontSize = "extraFontSize"
case extraCorner = "extraCorner"
case debugMode = "debugMode"
case logToDisk = "logToDisk"
case versionCheck = "versionCheck"
case alsoVersionCheckBeta = "alsoVersionCheckBeta"
case latitude = "latitude"
case longitude = "longitude"
case dimBrightness = "dimBrightness"
case startDim = "startDim"
case endDim = "endDim"
case dimOnlyAtNight = "dimOnlyAtNight"
case dimOnlyOnBattery = "dimOnlyOnBattery"
case dimInMinutes = "dimInMinutes"
case overrideDimInMinutes = "overrideDimInMinutes"
case solarMode = "solarMode"
case overrideMargins = "overrideMargins"
case marginX = "marginX"
case marginY = "marginY"
case alternateVideoFormat = "alternateVideoFormat"
case overrideOnBattery = "overrideOnBattery"
case powerSavingOnLowBattery = "powerSavingOnLowBattery"
case darkModeNightOverride = "darkModeNightOverride"
}
enum SolarMode: Int {
case strict, official, civil, nautical, astronomical
}
enum VersionCheck: Int {
case never, daily, weekly, monthly
}
enum ExtraCorner: Int {
case same, hOpposed, dOpposed
}
enum DescriptionCorner: Int {
case topLeft, topRight, bottomLeft, bottomRight, random
}
enum FadeMode: Int {
// swiftlint:disable:next identifier_name
case disabled, t0_5, t1, t2
}
enum MultiMonitorMode: Int {
case mainOnly, mirrored, independant
}
enum TimeMode: Int {
case disabled, nightShift, manual, lightDarkMode, coordinates
}
enum VideoFormat: Int {
case v1080pH264, v1080pHEVC, v4KHEVC
}
enum AlternateVideoFormat: Int {
case powerSaving, v1080pH264, v1080pHEVC, v4KHEVC
}
enum DescriptionMode: Int {
case fade10seconds, always
}
static let sharedInstance = Preferences()
lazy var userDefaults: UserDefaults = {
let module = "com.JohnCoates.Aerial"
guard let userDefaults = ScreenSaverDefaults(forModuleWithName: module) else {
warnLog("Couldn't create ScreenSaverDefaults, creating generic UserDefaults")
return UserDefaults()
}
return userDefaults
}()
// MARK: - Setup
init() {
registerDefaultValues()
}
func registerDefaultValues() {
var defaultValues = [Identifiers: Any]()
defaultValues[.differentAerialsOnEachDisplay] = false
defaultValues[.cacheAerials] = true
defaultValues[.videoFormat] = VideoFormat.v1080pH264
defaultValues[.showDescriptions] = true
defaultValues[.useCommunityDescriptions] = true
defaultValues[.showDescriptionsMode] = DescriptionMode.fade10seconds
defaultValues[.neverStreamVideos] = false
defaultValues[.neverStreamPreviews] = false
defaultValues[.localizeDescriptions] = false
defaultValues[.timeMode] = TimeMode.disabled
defaultValues[.manualSunrise] = "09:00"
defaultValues[.manualSunset] = "19:00"
defaultValues[.multiMonitorMode] = MultiMonitorMode.mainOnly
defaultValues[.fadeMode] = FadeMode.t1
defaultValues[.fadeModeText] = FadeMode.t1
defaultValues[.descriptionCorner] = DescriptionCorner.bottomLeft
defaultValues[.fontName] = "Helvetica Neue Medium"
defaultValues[.fontSize] = 28
defaultValues[.showClock] = false
defaultValues[.withSeconds] = false
defaultValues[.showMessage] = false
defaultValues[.showMessageString] = ""
defaultValues[.extraFontName] = "Monaco"
defaultValues[.extraFontSize] = 28
defaultValues[.extraCorner] = ExtraCorner.same
defaultValues[.debugMode] = false
defaultValues[.logToDisk] = false
defaultValues[.versionCheck] = VersionCheck.weekly
defaultValues[.alsoVersionCheckBeta] = false
defaultValues[.latitude] = ""
defaultValues[.longitude] = ""
defaultValues[.dimBrightness] = false
defaultValues[.startDim] = 0.5
defaultValues[.endDim] = 0.0
defaultValues[.dimOnlyAtNight] = false
defaultValues[.dimOnlyOnBattery] = false
defaultValues[.dimInMinutes] = 30
defaultValues[.overrideDimInMinutes] = false
defaultValues[.solarMode] = SolarMode.official
defaultValues[.overrideMargins] = false
defaultValues[.marginX] = 50
defaultValues[.marginY] = 50
defaultValues[.overrideOnBattery] = false
defaultValues[.powerSavingOnLowBattery] = false
defaultValues[.alternateVideoFormat] = AlternateVideoFormat.powerSaving
defaultValues[.darkModeNightOverride] = false
let defaults = defaultValues.reduce([String: Any]()) { (result, pair:(key: Identifiers, value: Any)) -> [String: Any] in
var mutable = result
mutable[pair.key.rawValue] = pair.value
return mutable
}
userDefaults.register(defaults: defaults)
}
// MARK: - Variables
var alternateVideoFormat: Int? {
get {
return optionalValue(forIdentifier: .alternateVideoFormat)
}
set {
setValue(forIdentifier: .alternateVideoFormat, value: newValue)
}
}
var overrideDimInMinutes: Bool {
get {
return value(forIdentifier: .overrideDimInMinutes)
}
set {
setValue(forIdentifier: .overrideDimInMinutes, value: newValue)
}
}
var darkModeNightOverride: Bool {
get {
return value(forIdentifier: .darkModeNightOverride)
}
set {
setValue(forIdentifier: .darkModeNightOverride, value: newValue)
}
}
var overrideOnBattery: Bool {
get {
return value(forIdentifier: .overrideOnBattery)
}
set {
setValue(forIdentifier: .overrideOnBattery, value: newValue)
}
}
var powerSavingOnLowBattery: Bool {
get {
return value(forIdentifier: .powerSavingOnLowBattery)
}
set {
setValue(forIdentifier: .powerSavingOnLowBattery, value: newValue)
}
}
var useCommunityDescriptions: Bool {
get {
return value(forIdentifier: .useCommunityDescriptions)
}
set {
setValue(forIdentifier: .useCommunityDescriptions, value: newValue)
}
}
var dimBrightness: Bool {
get {
return value(forIdentifier: .dimBrightness)
}
set {
setValue(forIdentifier: .dimBrightness, value: newValue)
}
}
var dimOnlyAtNight: Bool {
get {
return value(forIdentifier: .dimOnlyAtNight)
}
set {
setValue(forIdentifier: .dimOnlyAtNight, value: newValue)
}
}
var dimOnlyOnBattery: Bool {
get {
return value(forIdentifier: .dimOnlyOnBattery)
}
set {
setValue(forIdentifier: .dimOnlyOnBattery, value: newValue)
}
}
var overrideMargins: Bool {
get {
return value(forIdentifier: .overrideMargins)
}
set {
setValue(forIdentifier: .overrideMargins, value: newValue)
}
}
var dimInMinutes: Int? {
get {
return optionalValue(forIdentifier: .dimInMinutes)
}
set {
setValue(forIdentifier: .dimInMinutes, value: newValue)
}
}
var marginX: Int? {
get {
return optionalValue(forIdentifier: .marginX)
}
set {
setValue(forIdentifier: .marginX, value: newValue)
}
}
var marginY: Int? {
get {
return optionalValue(forIdentifier: .marginY)
}
set {
setValue(forIdentifier: .marginY, value: newValue)
}
}
var solarMode: Int? {
get {
return optionalValue(forIdentifier: .solarMode)
}
set {
setValue(forIdentifier: .solarMode, value: newValue)
}
}
var debugMode: Bool {
get {
return value(forIdentifier: .debugMode)
}
set {
setValue(forIdentifier: .debugMode, value: newValue)
}
}
var logToDisk: Bool {
get {
return value(forIdentifier: .logToDisk)
}
set {
setValue(forIdentifier: .logToDisk, value: newValue)
}
}
var alsoVersionCheckBeta: Bool {
get {
return value(forIdentifier: .alsoVersionCheckBeta)
}
set {
setValue(forIdentifier: .alsoVersionCheckBeta, value: newValue)
}
}
var showClock: Bool {
get {
return value(forIdentifier: .showClock)
}
set {
setValue(forIdentifier: .showClock, value: newValue)
}
}
var withSeconds: Bool {
get {
return value(forIdentifier: .withSeconds)
}
set {
setValue(forIdentifier: .withSeconds, value: newValue)
}
}
var showMessage: Bool {
get {
return value(forIdentifier: .showMessage)
}
set {
setValue(forIdentifier: .showMessage, value: newValue)
}
}
var latitude: String? {
get {
return optionalValue(forIdentifier: .latitude)
}
set {
setValue(forIdentifier: .latitude, value: newValue)
}
}
var longitude: String? {
get {
return optionalValue(forIdentifier: .longitude)
}
set {
setValue(forIdentifier: .longitude, value: newValue)
}
}
var showMessageString: String? {
get {
return optionalValue(forIdentifier: .showMessageString)
}
set {
setValue(forIdentifier: .showMessageString, value: newValue)
}
}
var differentAerialsOnEachDisplay: Bool {
get {
return value(forIdentifier: .differentAerialsOnEachDisplay)
}
set {
setValue(forIdentifier: .differentAerialsOnEachDisplay, value: newValue)
}
}
var cacheAerials: Bool {
get {
return value(forIdentifier: .cacheAerials)
}
set {
setValue(forIdentifier: .cacheAerials, value: newValue)
}
}
var neverStreamVideos: Bool {
get {
return value(forIdentifier: .neverStreamVideos)
}
set {
setValue(forIdentifier: .neverStreamVideos, value: newValue)
}
}
var neverStreamPreviews: Bool {
get {
return value(forIdentifier: .neverStreamPreviews)
}
set {
setValue(forIdentifier: .neverStreamPreviews, value: newValue)
}
}
var localizeDescriptions: Bool {
get {
return value(forIdentifier: .localizeDescriptions)
}
set {
setValue(forIdentifier: .localizeDescriptions, value: newValue)
}
}
var fontName: String? {
get {
return optionalValue(forIdentifier: .fontName)
}
set {
setValue(forIdentifier: .fontName, value: newValue)
}
}
var startDim: Double? {
get {
return optionalValue(forIdentifier: .startDim)
}
set {
setValue(forIdentifier: .startDim, value: newValue)
}
}
var endDim: Double? {
get {
return optionalValue(forIdentifier: .endDim)
}
set {
setValue(forIdentifier: .endDim, value: newValue)
}
}
var fontSize: Double? {
get {
return optionalValue(forIdentifier: .fontSize)
}
set {
setValue(forIdentifier: .fontSize, value: newValue)
}
}
var extraFontName: String? {
get {
return optionalValue(forIdentifier: .extraFontName)
}
set {
setValue(forIdentifier: .extraFontName, value: newValue)
}
}
var extraFontSize: Double? {
get {
return optionalValue(forIdentifier: .extraFontSize)
}
set {
setValue(forIdentifier: .extraFontSize, value: newValue)
}
}
var manualSunrise: String? {
get {
return optionalValue(forIdentifier: .manualSunrise)
}
set {
setValue(forIdentifier: .manualSunrise, value: newValue)
}
}
var manualSunset: String? {
get {
return optionalValue(forIdentifier: .manualSunset)
}
set {
setValue(forIdentifier: .manualSunset, value: newValue)
}
}
var customCacheDirectory: String? {
get {
return optionalValue(forIdentifier: .customCacheDirectory)
}
set {
setValue(forIdentifier: .customCacheDirectory, value: newValue)
}
}
var versionCheck: Int? {
get {
return optionalValue(forIdentifier: .versionCheck)
}
set {
setValue(forIdentifier: .versionCheck, value: newValue)
}
}
var descriptionCorner: Int? {
get {
return optionalValue(forIdentifier: .descriptionCorner)
}
set {
setValue(forIdentifier: .descriptionCorner, value: newValue)
}
}
var extraCorner: Int? {
get {
return optionalValue(forIdentifier: .extraCorner)
}
set {
setValue(forIdentifier: .extraCorner, value: newValue)
}
}
var fadeMode: Int? {
get {
return optionalValue(forIdentifier: .fadeMode)
}
set {
setValue(forIdentifier: .fadeMode, value: newValue)
}
}
var fadeModeText: Int? {
get {
return optionalValue(forIdentifier: .fadeModeText)
}
set {
setValue(forIdentifier: .fadeModeText, value: newValue)
}
}
var timeMode: Int? {
get {
return optionalValue(forIdentifier: .timeMode)
}
set {
setValue(forIdentifier: .timeMode, value: newValue)
}
}
var videoFormat: Int? {
get {
return optionalValue(forIdentifier: .videoFormat)
}
set {
setValue(forIdentifier: .videoFormat, value: newValue)
}
}
var showDescriptionsMode: Int? {
get {
return optionalValue(forIdentifier: .showDescriptionsMode)
}
set {
setValue(forIdentifier: .showDescriptionsMode, value: newValue)
}
}
var multiMonitorMode: Int? {
get {
return optionalValue(forIdentifier: .multiMonitorMode)
}
set {
setValue(forIdentifier: .multiMonitorMode, value: newValue)
}
}
var showDescriptions: Bool {
get {
return value(forIdentifier: .showDescriptions)
}
set {
setValue(forIdentifier: .showDescriptions,
value: newValue)
}
}
func videoIsInRotation(videoID: String) -> Bool {
let key = "remove\(videoID)"
let removed = userDefaults.bool(forKey: key)
return !removed
}
func setVideo(videoID: String, inRotation: Bool,
synchronize: Bool = true) {
let key = "remove\(videoID)"
let removed = !inRotation
userDefaults.set(removed, forKey: key)
if synchronize {
self.synchronize()
}
}
// MARK: - Setting, Getting
fileprivate func value(forIdentifier identifier: Identifiers) -> Bool {
let key = identifier.rawValue
return userDefaults.bool(forKey: key)
}
fileprivate func optionalValue(forIdentifier identifier: Identifiers) -> String? {
let key = identifier.rawValue
return userDefaults.string(forKey: key)
}
fileprivate func optionalValue(forIdentifier identifier: Identifiers) -> Int? {
let key = identifier.rawValue
return userDefaults.integer(forKey: key)
}
fileprivate func optionalValue(forIdentifier identifier: Identifiers) -> Double? {
let key = identifier.rawValue
return userDefaults.double(forKey: key)
}
fileprivate func setValue(forIdentifier identifier: Identifiers, value: Any?) {
let key = identifier.rawValue
if value == nil {
userDefaults.removeObject(forKey: key)
} else {
userDefaults.set(value, forKey: key)
}
synchronize()
}
func synchronize() {
userDefaults.synchronize()
}
} //swiftlint:disable:this file_length
| 27.670659 | 128 | 0.590619 |
f5369f5f150b2e16856e05f50a1cf60da91a6f73 | 296 | //
// Copyright © 2020 MBition GmbH. All rights reserved.
//
import Foundation
public enum ConsumptionUnit: String, Codable, CaseIterable {
case litersPer100Km = "l/100km"
case kilometersPerLiter = "km/l"
case milesPerGallonUK = "mpg (UK)"
case milesPerGallonUS = "mpg (US)"
}
| 22.769231 | 60 | 0.695946 |
1d1b11f40a9a77fa7d01832e3092189ac8db096f | 1,254 | //
// CompilationError.swift
// ReasonML
//
// Created by Jacob Parker on 18/04/2020.
// Copyright © 2020 Jacob Parker. All rights reserved.
//
import Foundation
struct CompilationError: Equatable {
static func == (lhs: CompilationError, rhs: CompilationError) -> Bool {
lhs.message == rhs.message
}
fileprivate static let compilationErrorLocationRegex = try? NSRegularExpression(
pattern: "Preview (\\d+):(\\d+)",
options: []
)
let message: String
let location: (Int, Int)?
init(_ message: String) {
self.message = message
if let matches = CompilationError.compilationErrorLocationRegex?.matches(
in: message,
options: [],
range: NSRange(location: 0, length: message.utf16.count)
),
let match = matches.first,
let lineRange = Range(match.range(at: 1), in: message),
let columnRange = Range(match.range(at: 2), in: message),
let lineNumber = Int(message[lineRange]),
let columnNumber = Int(message[columnRange]) {
self.location = (lineNumber, columnNumber)
} else {
self.location = nil
}
}
}
| 29.162791 | 84 | 0.579745 |
90a63c7bb74f1d24d69fd290452afbbb03efde9a | 1,345 | //
// Stream.swift
// YAML.framework
//
// Created by Martin Kiss on 7 May 2016.
// https://github.com/Tricertops/YAML
//
// The MIT License (MIT)
// Copyright © 2016 Martin Kiss
//
/// Represents a YAML file parsed using Parser or constructed programatically for Emitter.
public class Stream {
/// Whether the stream has explicit `%YAML 1.1` at the beginning.
public var hasVersion: Bool = false
/// List of tag directives preceding the documents.
public var tags: [Tag.Directive] = []
/// Whether the stream *wants* explicit `---` mark at the beginning.
/// - Note: In some cases the mark is required.
/// - SeeAlso: `.hasStartMark`
public var prefersStartMark: Bool = false
/// Whether the stream *has* explicit `---` mark at the beginning.
public var hasStartMark: Bool {
return hasVersion || !tags.isEmpty || prefersStartMark
}
/// Documents contained in the stream.
public var documents: [Node] = []
/// Whether the stream has explicit `...` mark at the end.
public var hasEndMark: Bool = false
/// Creates sn empty Stream.
public init() {}
/// Creates a Stream with a list of document Nodes.
public convenience init(documents: [Node]) {
self.init()
self.documents = documents
}
}
| 27.44898 | 90 | 0.628996 |
7290975793c788e5621d497f0d8ac320cd255a58 | 7,371 | //
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
import Foundation
internal class InternalProtoDecoder: Decoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any]
let data: Data
// Building two data structures here:
// - dictionary: for the keyed container (to have fast access via key)
// - entries: for the unkeyed container (to preserve order, which dictionary does not)
var dictionary: [Int: [Data]]
var entries: [[Data]]
// helper to keep track of which key is placed at which index in entries
// only needed for build-up of entries (to ensure all values with same key end up at same index)
var keyIndices: [Int: Int]
/// The strategy that this encoder uses to encode `Int`s and `UInt`s.
var integerWidthCodingStrategy: IntegerWidthCodingStrategy
init(from data: Data, with integerWidthCodingStrategy: IntegerWidthCodingStrategy) {
self.data = data
self.integerWidthCodingStrategy = integerWidthCodingStrategy
dictionary = [:]
entries = []
keyIndices = [:]
codingPath = []
userInfo = [:]
decode(from: data)
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
KeyedDecodingContainer(
KeyedProtoDecodingContainer(from: self.dictionary, integerWidthCodingStrategy: integerWidthCodingStrategy)
)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
UnkeyedProtoDecodingContainer(from: entries, codingPath: codingPath, integerWidthCodingStrategy: integerWidthCodingStrategy)
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
throw ProtoError.unsupportedDecodingStrategy("Single value decoding not supported")
}
func decode(from: Data) {
dictionary = [Int: [Data]]()
entries = []
// points to the byte we want to read next
var readIndex = 0
// jump over any leading zero-bytes
while readIndex < from.count,
from[readIndex] == UInt8(0) {
readIndex += 1
}
// start reading the non-zero bytes
while readIndex < from.count {
// byte contains: 5 bits of field tag, 3 bits of field data type
let byte = from[readIndex]
let fieldTag = Int(byte >> 3) // shift "out" last 3 bytes
let fieldType = Int(byte & 0b00000111) // only keep last 3 bytes
do {
// find the field in T with the according CodingKey to the fieldTag
let (value, newIndex) = try readField(from: from,
fieldTag: fieldTag,
fieldType: fieldType,
fieldStartIndex: readIndex + 1)
// set cursor forward to the next field tag
readIndex = newIndex
if dictionary[fieldTag] == nil {
dictionary[fieldTag] = [value]
keyIndices[fieldTag] = entries.count
entries.append([value])
} else if let index = keyIndices[fieldTag] {
dictionary[fieldTag]?.append(value)
entries[index].append(value)
}
} catch {
print("Unable to decode field with tag=\(fieldTag) and type=\(fieldType). Stop decoding.")
return
}
}
}
private func readLengthDelimited(from data: Data, fieldStartIndex: Int) throws -> (Data, Int) {
// the first VarInt contains the length of the value
let (length, _) = try VarInt.decodeToInt(data, offset: fieldStartIndex)
// assure we have enough bytes left to read
if data.count - (fieldStartIndex + 1) < length {
throw ProtoError.decodingError("Not enough data left to code length-delimited value")
}
// here we make a copy, since the data here might be a nested data structure
// this ensures the copy's byte indexing starts with 0 in the case the ProtoDecoder is invoked on it again
let byteValue = data.subdata(in: (fieldStartIndex + 1) ..< (fieldStartIndex + length + 1))
return (byteValue, fieldStartIndex + length + 1)
}
// Function reads the value of a field from data, starting at byte-index fieldStartIndex.
// The length of the read data depends on the field-type.
// The function returns the value, and the starting index of the next field tag.
private func readField(from data: Data, fieldTag: Int, fieldType: Int, fieldStartIndex: Int) throws -> (Data, Int) {
guard let wireType = WireType(rawValue: fieldType) else {
throw ProtoError.unknownType(fieldType)
}
switch wireType {
case WireType.varInt:
return try VarInt.decode(data, offset: fieldStartIndex)
case WireType.bit64:
if fieldStartIndex + 7 >= data.count {
throw ProtoError.decodingError("Not enough data left to read 64-bit value")
}
let byteValue = data[fieldStartIndex ... (fieldStartIndex + 7)]
return (byteValue, fieldStartIndex + 8)
case WireType.lengthDelimited:
return try readLengthDelimited(from: data, fieldStartIndex: fieldStartIndex)
case WireType.startGroup, WireType.endGroup: // groups are deprecated
throw ProtoError.unsupportedDataType("Groups are deprecated and not supported by this decoder")
case WireType.bit32:
if fieldStartIndex + 3 >= data.count {
throw ProtoError.decodingError("Not enough data left to read 32-bit value")
}
let byteValue = data[fieldStartIndex ... (fieldStartIndex + 3)]
return (byteValue, fieldStartIndex + 4)
}
}
}
/// Decoder for Protobuffer data.
/// Coforms to `TopLevelDecoder` from `Combine`, however this is currently ommitted due to compatibility issues.
public class ProtobufferDecoder {
/// The strategy that this encoder uses to encode `Int`s and `UInt`s.
public var integerWidthCodingStrategy: IntegerWidthCodingStrategy = .native
/// Init new decoder instance
public init() {}
/// Decodes a Data that was encoded using Protobuffers into
/// a given struct of type T (T has to conform to Decodable).
public func decode<T>(_ type: T.Type, from data: Data) throws
-> T where T: Decodable {
let decoder = InternalProtoDecoder(from: data, with: integerWidthCodingStrategy)
return try T(from: decoder)
}
/// Can be used to decode an unknown type, e.g. when no `Decodable` struct is available.
/// Returns a `UnkeyedDecodingContainer` that can be used to sequentially decode the values the data contains.
public func decode(from data: Data) throws -> UnkeyedDecodingContainer {
let decoder = InternalProtoDecoder(from: data, with: integerWidthCodingStrategy)
return try decoder.unkeyedContainer()
}
}
| 43.875 | 135 | 0.632207 |
096a940eb47f059f944f3156b8defb77029d5b87 | 4,368 | //
// AppleAuthenticationService.swift
// TogglDesktop
//
// Created by Nghia Tran on 3/3/20.
// Copyright © 2020 Alari. All rights reserved.
//
import Foundation
// Apple Sign In is only available in MAS build
#if APP_STORE
import AuthenticationServices
@objc protocol AppleAuthenticationServiceDelegate: class {
func appleAuthenticationDidComplete(with token: String, fullName: String?)
func appleAuthenticationDidFailed(with error: Error)
func appleAuthenticationPresentOnWindow() -> NSWindow
}
/// Handle Apple Authentication logic
@available(OSX 10.15, *)
@objc
final class AppleAuthenticationService: NSObject {
@objc static let shared = AppleAuthenticationService()
private struct Constants {
static let UserAppleID = "UserAppleID"
}
// MARK: Variables
@objc weak var delegate: AppleAuthenticationServiceDelegate?
// MARK: Public
/// Request authentication with Apple Service
@objc func requestAuth() {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
/// It's crucial to validate the state
/// Some users can revork the permission, thus they must be logged out
@objc func validateCredentialState() {
guard let userID = UserDefaults.standard.string(forKey: Constants.UserAppleID) else { return }
// Validate again since the user can revork the permission later
// Logout if the credential is invalid
let appleIDProvider = ASAuthorizationAppleIDProvider()
appleIDProvider.getCredentialState(forUserID: userID) { (credentialState, error) in
switch credentialState {
case .authorized:
break // The Apple ID credential is valid.
case .revoked, .notFound:
// The Apple ID credential is either revoked or was not found, so show the sign-in UI.
NotificationCenter.default.postNotificationOnMainThread(NSNotification.Name(kInvalidAppleUserCrendential), object: nil)
default:
break
}
}
}
/// Reset all caching data
@objc func reset() {
UserDefaults.standard.removeObject(forKey: Constants.UserAppleID)
}
}
// MARK: ASAuthorizationControllerDelegate
@available(OSX 10.15, *)
extension AppleAuthenticationService: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
delegate?.appleAuthenticationDidFailed(with: error)
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
switch authorization.credential {
case let appleIDCredential as ASAuthorizationAppleIDCredential:
// Convert token data to string
guard let tokenData = appleIDCredential.identityToken,
let token = String(data: tokenData, encoding: .utf8) else {
return
}
// Save for later validation
UserDefaults.standard.set(appleIDCredential.user, forKey: Constants.UserAppleID)
// Get full name
var fullName: String?
if let fullNameComponent = appleIDCredential.fullName {
fullName = PersonNameComponentsFormatter().string(from: fullNameComponent)
}
delegate?.appleAuthenticationDidComplete(with: token, fullName: fullName)
default:
break
}
}
}
// MARK: ASAuthorizationControllerPresentationContextProviding
@available(OSX 10.15, *)
extension AppleAuthenticationService: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return delegate?.appleAuthenticationPresentOnWindow() ?? NSApplication.shared.mainWindow!
}
}
#else
@objc protocol AppleAuthenticationServiceDelegate {} // Dummy protocol for objc code
#endif
| 34.666667 | 135 | 0.706502 |
0a64d0ce4086c61ade627746932721ffddb52cea | 4,802 | import UIKit
import Spring
class CircleView: SpringView {
init(topColor: UIColor, bottomColor: UIColor) {
self.topColor = topColor
self.bottomColor = bottomColor
super.init(frame: .zero)
clipsToBounds = true
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width / 2
// self.drawRect(layerF:layer)
// self.drawFiveRect(layerF: layer)
gradientLayer = createGradientLayer(withColors: [topColor, bottomColor])
}
func createLayer(layer :CALayer) {
let path = UIBezierPath.init(roundedRect: layer.bounds, byRoundingCorners: [.topRight,.bottomRight] , cornerRadii: layer.bounds.size)
let layerC = CAShapeLayer.init()
layerC.path = path.cgPath
layerC.lineWidth = 5
layerC.lineCap = kCALineCapSquare
layerC.strokeColor = UIColor.red.cgColor
// 注意直接填充layer的颜色,不需要设置控件view的backgroundColor
layerC.fillColor = UIColor.yellow.cgColor
layer.addSublayer(layerC)
}
func drawRect(layerF:CALayer){
let imageWH = (layerF.frame.width ) * 1.0
let path = UIBezierPath.init()
path.lineWidth = 2
let single = CGFloat.init(sin(M_1_PI / 180*60))
let point1 = CGPoint.init(x: single * (imageWH/2), y: imageWH / 4)
let point2 = CGPoint.init(x: imageWH/2, y: 0)
let point3 = CGPoint.init(x: imageWH - single * (imageWH/2), y: imageWH / 4)
let point4 = CGPoint.init(x: imageWH - single * (imageWH/2), y: imageWH / 4 + imageWH / 2)
let point5 = CGPoint.init(x: imageWH / 2, y: imageWH)
// let point6 = CGPoint.init(x: single * (imageWH/2), y: imageWH / 4 + imageWH/2)
path.move(to: point1)
path.addLine(to: point2)
path.addLine(to: point3)
path.addLine(to: point4)
path.addLine(to: point5)
// path.addLine(to: point6)
path.close()
let laryS = CAShapeLayer.init()
laryS.lineWidth = 2
laryS.path = path.cgPath
layerF.mask = laryS
}
func drawFiveRect(layerF:CALayer) { // 五边形
let imageWH = (layerF.frame.width ) * 1.0
let path = UIBezierPath.init()
path.lineWidth = 2
let color = UIColor.red
color.set() // 设置线条颜色
let aPath = UIBezierPath()
aPath.lineWidth = 5.0 // 线条宽度
aPath.lineCapStyle = CGLineCap.round // 线条拐角
aPath.lineJoinStyle = CGLineJoin.round // 终点处理
let single = CGFloat.init(sin(M_1_PI / 180*60))
// Set the starting point of the shape.
aPath.move(to: CGPoint.init(x: 100.0, y: 10.0))//(100, 10))
aPath.addLine(to: CGPoint.init(x: 200, y: 140))
aPath.addLine(to: CGPoint.init(x: 160, y: 10.0))
aPath.addLine(to: CGPoint.init(x: 40, y: 140))
aPath.addLine(to: CGPoint.init(x: 10, y: 40))
aPath.close()
// 最后一条线通过调用closePath方法得到
let laryS = CAShapeLayer.init()
laryS.lineWidth = 2
laryS.path = path.cgPath
layerF.mask = laryS
}
func creatSix(mlayer:CALayer) {
let path = UIBezierPath.init()
path.lineWidth = 2
let width = (mlayer.frame.width ) * 1.0
// path.move(to: CGPoint.init(x: (sin(M_1_PI/(180*60.0))*(width*0.5), y: width*0.25))
path.move(to: CGPoint.init(x: 0.2*(width*0.5), y: width*0.25))
path.addLine(to: CGPoint.init(x: width * 0.5, y: 0))
path.addLine(to: CGPoint.init(x: width - 0.2*(width*0.5), y: width/2 + width/4))
path.addLine(to: CGPoint.init(x: width, y: width))
path.addLine(to: CGPoint.init(x: 0.5 * width/2, y: width/2 + width/4))
path.close()
let laryS = CAShapeLayer.init()
laryS.lineWidth = 2
laryS.path = path.cgPath
mlayer.mask = laryS
// mlayer.addSublayer(laryS)
}
// MARK: Gradient backgorund
private var gradientLayer: CAGradientLayer? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperlayer()
}
if let newValue = gradientLayer {
layer.insertSublayer(newValue, at: 0)
}
}
}
private func createGradientLayer(withColors colors: [UIColor]) -> CAGradientLayer {
let layer = CAGradientLayer()
layer.frame = bounds
layer.colors = colors.map { $0.cgColor }
return layer
}
// MARK: Private
private let topColor: UIColor
private let bottomColor: UIColor
}
| 33.117241 | 141 | 0.582674 |
285889f5771cb069ff3e88751faf9d04b495b1a4 | 1,913 | //
// Device.swift
// SimpleDALPlugin
//
// Created by 池上涼平 on 2020/04/25.
// Copyright © 2020 com.seanchas116. All rights reserved.
//
import Foundation
import IOKit
class Device: Object {
var objectID: CMIOObjectID = 0
var streamID: CMIOStreamID = 0
let name = "Heyoh Camera"
let manufacturer = "seanchas116"
let deviceUID = "HeyohPlugin Device"
let modelUID = "HeyohPlugin Model"
var excludeNonDALAccess: Bool = false
var deviceMaster: Int32 = -1
lazy var properties: [Int: Property] = [
kCMIOObjectPropertyName: Property(name),
kCMIOObjectPropertyManufacturer: Property(manufacturer),
kCMIODevicePropertyDeviceUID: Property(deviceUID),
kCMIODevicePropertyModelUID: Property(modelUID),
kCMIODevicePropertyTransportType: Property(UInt32(kIOAudioDeviceTransportTypeBuiltIn)),
kCMIODevicePropertyDeviceIsAlive: Property(UInt32(1)),
kCMIODevicePropertyDeviceIsRunning: Property(UInt32(1)),
kCMIODevicePropertyDeviceIsRunningSomewhere: Property(UInt32(1)),
kCMIODevicePropertyDeviceCanBeDefaultDevice: Property(UInt32(1)),
kCMIODevicePropertyCanProcessAVCCommand: Property(UInt32(0)),
kCMIODevicePropertyCanProcessRS422Command: Property(UInt32(0)),
kCMIODevicePropertyHogMode: Property(Int32(-1)),
kCMIODevicePropertyStreams: Property { [unowned self] in self.streamID },
kCMIODevicePropertyExcludeNonDALAccess: Property(
getter: { [unowned self] () -> UInt32 in self.excludeNonDALAccess ? 1 : 0 },
setter: { [unowned self] (value: UInt32) -> Void in self.excludeNonDALAccess = value != 0 }
),
kCMIODevicePropertyDeviceMaster: Property(
getter: { [unowned self] () -> Int32 in self.deviceMaster },
setter: { [unowned self] (value: Int32) -> Void in self.deviceMaster = value }
),
]
}
| 41.586957 | 103 | 0.696289 |
0a85ba6022dbf80f2968ed447d4f346092cc193d | 2,192 | //
// AppDelegate.swift
// CustomRangeSelection
//
// Created by Tejasree Marthy on 01/11/17.
// Copyright © 2017 Tejasree Marthy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.638298 | 285 | 0.757299 |
d5008456e8fbfa133e140b04149d913e2d8c30c8 | 15,628 | //
// MessageEvaluationManagerTests.swift
// Simply Filter SMS Tests
//
// Created by Adi Ben-Dahan on 01/02/2022.
//
import Foundation
import XCTest
import CoreData
import NaturalLanguage
import IdentityLookup
@testable import Simply_Filter_SMS
class MessageEvaluationManagerTests: XCTestCase {
struct MessageTestCase {
let sender: String
let body: String
let expectedAction: ILMessageFilterAction
}
//MARK: Test Lifecycle
override func setUp() {
super.setUp()
self.testSubject = MessageEvaluationManager(inMemory: true)
self.loadTestingData()
}
override func tearDown() {
super.tearDown()
self.flushPersistanceManager()
}
//MARK: Tests
func test_evaluateMessage() {
struct MessageTestCase {
let sender: String
let body: String
let expectedAction: ILMessageFilterAction
}
let testCases: [MessageTestCase] = [
MessageTestCase(sender: "1234567", body: "מה המצב עדי?", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "מה המצב עדי? רוצה לקנות weed?", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "הלוואה חינם התקשר עכשיו", expectedAction: .promotion),
MessageTestCase(sender: "1234567", body: "הודעה עם לינק http://123.com", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "הודעה עם לינק http://adi.com", expectedAction: .allow),
MessageTestCase(sender: "123", body: "מה המצב עדי?", expectedAction: .allow),
MessageTestCase(sender: "123", body: "מה המצב?", expectedAction: .junk),
MessageTestCase(sender: "text", body: "מה המצב?", expectedAction: .junk),
MessageTestCase(sender: "text", body: "מה המצב עדי?", expectedAction: .allow),
MessageTestCase(sender: "[email protected]", body: "מה המצב?", expectedAction: .junk),
MessageTestCase(sender: "[email protected]", body: "מה המצב עדי?", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "مح لزواره الكرام بتحويل الكتابة العربي الى", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "עברית וערבית ביחד, הרוב בעברית العربي الى", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "مح لزواره الكرام بتحويل الكتابة العربي الى עם עברית", expectedAction: .junk),
MessageTestCase(sender: "", body: "asdasdasdasd", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "סינון אוטומטי קורונה", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "סינון אוטומטי spam", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "htTp://link.com", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "Bet", expectedAction: .transaction)
]
for testCase in testCases {
let actualAction = self.testSubject.evaluateMessage(body: testCase.body, sender: testCase.sender).action
XCTAssert(testCase.expectedAction == actualAction,
"sender \"\(testCase.sender)\", body \"\(testCase.body)\": \(testCase.expectedAction.debugName) != \(actualAction.debugName).")
}
}
func test_evaluateMessage_allUnknownFilteringOn() {
let automaticFilterRule = AutomaticFiltersRule(context: self.testSubject.context)
automaticFilterRule.ruleId = RuleType.allUnknown.rawValue
automaticFilterRule.isActive = true
automaticFilterRule.selectedChoice = 0
let testCases: [MessageTestCase] = [
MessageTestCase(sender: "1234567", body: "עברית וערבית ביחד, הרוב בעברית العربي الى", expectedAction: .junk),
MessageTestCase(sender: "1234567", body: "סינון אוטומטי spam", expectedAction: .junk)
]
for testCase in testCases {
let actualAction = self.testSubject.evaluateMessage(body: testCase.body, sender: testCase.sender).action
XCTAssert(testCase.expectedAction == actualAction,
"sender \"\(testCase.sender)\", body \"\(testCase.body)\": \(testCase.expectedAction.debugName) != \(actualAction.debugName).")
}
}
func test_evaluateMessage_advanced() {
self.flushPersistanceManager()
let advancedFilter = Filter(context: self.testSubject.context)
advancedFilter.filterMatching = .exact
advancedFilter.filterTarget = .body
advancedFilter.filterCase = .caseSensitive
advancedFilter.text = "Discount"
advancedFilter.denyFolderType = .transaction
advancedFilter.filterType = .deny
let advancedFilter2 = Filter(context: self.testSubject.context)
advancedFilter2.filterMatching = .exact
advancedFilter2.filterTarget = .sender
advancedFilter2.filterCase = .caseInsensitive
advancedFilter2.text = "Apple"
advancedFilter2.filterType = .allow
let advancedFilter3 = Filter(context: self.testSubject.context)
advancedFilter3.filterMatching = .contains
advancedFilter3.filterTarget = .sender
advancedFilter3.filterCase = .caseSensitive
advancedFilter3.text = "Wallmart"
advancedFilter3.filterType = .allow
let testCases: [MessageTestCase] = [
MessageTestCase(sender: "1234567", body: "A message from @##43432@Discount2 Banks! Store", expectedAction: .transaction),
MessageTestCase(sender: "1234567", body: "A message from @##4@1 Discount", expectedAction: .transaction),
MessageTestCase(sender: "1234567", body: "A message from @##4@1 Discounted", expectedAction: .allow),
MessageTestCase(sender: "1234567", body: "Discount", expectedAction: .transaction),
MessageTestCase(sender: "1234567", body: "discount", expectedAction: .allow),
MessageTestCase(sender: "Apple", body: "discount", expectedAction: .allow),
MessageTestCase(sender: "Wallmart", body: "Discount", expectedAction: .allow),
MessageTestCase(sender: "Wallmart Store", body: "Discount", expectedAction: .allow),
MessageTestCase(sender: "Apple Store", body: "Discount", expectedAction: .allow),
MessageTestCase(sender: "WallmarT Store", body: "Discount", expectedAction: .transaction)
]
for testCase in testCases {
let actualAction = self.testSubject.evaluateMessage(body: testCase.body, sender: testCase.sender).action
XCTAssert(testCase.expectedAction == actualAction,
"sender \"\(testCase.sender)\", body \"\(testCase.body)\": \(testCase.expectedAction.debugName) != \(actualAction.debugName).")
}
}
func test_evaluateMessage_automatic() {
self.flushPersistanceManager()
let automaticFilterLists = AutomaticFilterListsResponse(filterLists: [
"he" : LanguageFilterListResponse(allowSenders: ["BituahLeumi", "Taasuka", "bit", "100", "ontopo"],
allowBody: [],
denySender: [],
denyBody: ["הלוואה"])
])
let cacheRecord = AutomaticFiltersCache(context: self.testSubject.context)
cacheRecord.uuid = UUID()
cacheRecord.filtersData = automaticFilterLists.encoded
cacheRecord.hashed = automaticFilterLists.hashed
cacheRecord.age = Date()
let noLinks = AutomaticFiltersRule(context: self.testSubject.context)
noLinks.isActive = true
noLinks.ruleType = .links
noLinks.selectedChoice = 0
let numbersOnly = AutomaticFiltersRule(context: self.testSubject.context)
numbersOnly.isActive = true
numbersOnly.ruleType = .numbersOnly
numbersOnly.selectedChoice = 0
let noEmojis = AutomaticFiltersRule(context: self.testSubject.context)
noEmojis.isActive = true
noEmojis.ruleType = .emojis
noEmojis.selectedChoice = 0
let automaticFiltersLanguageHE = AutomaticFiltersLanguage(context: self.testSubject.context)
automaticFiltersLanguageHE.lang = NLLanguage.hebrew.rawValue
automaticFiltersLanguageHE.isActive = true
try? self.testSubject.context.save()
let testCases: [MessageTestCase] = [
MessageTestCase(sender: "BituahLeumi", body: "בלה בלה בלה https://link.com", expectedAction: .allow),
MessageTestCase(sender: "100", body: "בלה בלה בלה https://link.com", expectedAction: .allow),
MessageTestCase(sender: "BituahLeumit", body: "בלה בלה בלה https://link.com", expectedAction: .junk),
MessageTestCase(sender: "1000", body: "בלה בלה בלה https://link.com", expectedAction: .junk),
MessageTestCase(sender: "bit", body: "הלוואה ולינק https://link.com", expectedAction: .allow),
MessageTestCase(sender: "bit ", body: "הלוואה ולינק https://link.com", expectedAction: .junk),
MessageTestCase(sender: "054123465", body: "bla bla btl.gov.il/asdasdf", expectedAction: .junk),
MessageTestCase(sender: "054123465", body: "bla bla bit.ly/1224dsf4 bla", expectedAction: .junk),
MessageTestCase(sender: "054123465", body: "bla bla [email protected] bla", expectedAction: .allow),
MessageTestCase(sender: "054123465", body: "bla bla 054-123456 bla", expectedAction: .allow),
MessageTestCase(sender: "Taasuka", body: "bla bla btl.gov.il/asdasdf", expectedAction: .allow),
MessageTestCase(sender: "Ontopo", body: "אנא אשרו הזמנתכם לשילה בקישור. tinyurl.com/ycq952f לחצו לצפייה", expectedAction: .allow),
MessageTestCase(sender: "054123465", body: "bla bla 💀 bla", expectedAction: .junk)
]
for testCase in testCases {
let actualAction = self.testSubject.evaluateMessage(body: testCase.body, sender: testCase.sender).action
XCTAssert(testCase.expectedAction == actualAction,
"sender \"\(testCase.sender)\", body \"\(testCase.body)\": \(testCase.expectedAction.debugName) != \(actualAction.debugName).")
}
numbersOnly.isActive = false
noEmojis.isActive = false
try? self.testSubject.context.save()
let secondTestCases: [MessageTestCase] = [
MessageTestCase(sender: "not a number", body: "אנא אשרו הזמנתכם לשילה בקישור.לחצו לצפייה", expectedAction: .allow),
MessageTestCase(sender: "054123465", body: "bla bla 💀 bla", expectedAction: .allow)
]
for testCase in secondTestCases {
let actualAction = self.testSubject.evaluateMessage(body: testCase.body, sender: testCase.sender).action
XCTAssert(testCase.expectedAction == actualAction,
"sender \"\(testCase.sender)\", body \"\(testCase.body)\": \(testCase.expectedAction.debugName) != \(actualAction.debugName).")
}
}
// MARK: Private Variables and Helpers
private var testSubject: MessageEvaluationManagerProtocol = MessageEvaluationManager(inMemory: true)
private func flushEntity(name: String) {
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest<NSFetchRequestResult>(entityName: name)
let objs = try! self.testSubject.context.fetch(fetchRequest)
for case let obj as NSManagedObject in objs {
self.testSubject.context.delete(obj)
}
}
private func flushPersistanceManager() {
self.flushEntity(name: "Filter")
self.flushEntity(name: "AutomaticFiltersCache")
self.flushEntity(name: "AutomaticFiltersLanguage")
self.flushEntity(name: "AutomaticFiltersRule")
do {
try self.testSubject.context.save()
} catch {
XCTAssert(false, "flushMessageEvaluationManager failed")
}
}
private func loadTestingData() {
struct AllowEntry {
let text: String
let folder: DenyFolderType
}
let _ = [AllowEntry(text: "נתניהו", folder: .junk),
AllowEntry(text: "הלוואה", folder: .promotion),
AllowEntry(text: "הימור", folder: .transaction),
AllowEntry(text: "גנץ", folder: .junk),
AllowEntry(text: "Weed", folder: .junk),
AllowEntry(text: "Bet", folder: .transaction)].map { entry -> Filter in
let newFilter = Filter(context: self.testSubject.context)
newFilter.uuid = UUID()
newFilter.filterType = .deny
newFilter.denyFolderType = entry.folder
newFilter.text = entry.text
return newFilter
}
let _ = ["Adi", "דהאן", "דהן", "עדי"].map { allowText -> Filter in
let newFilter = Filter(context: self.testSubject.context)
newFilter.uuid = UUID()
newFilter.filterType = .allow
newFilter.text = allowText
return newFilter
}
let langFilter = Filter(context: self.testSubject.context)
langFilter.uuid = UUID()
langFilter.filterType = .denyLanguage
langFilter.text = NLLanguage.arabic.filterText
for rule in RuleType.allCases {
let automaticFilterRule = AutomaticFiltersRule(context: self.testSubject.context)
automaticFilterRule.ruleId = rule.rawValue
automaticFilterRule.isActive = rule != .allUnknown
automaticFilterRule.selectedChoice = rule == .shortSender ? 5 : 0
}
let filtersList = AutomaticFilterListsResponse(filterLists: [
NLLanguage.hebrew.rawValue : LanguageFilterListResponse(allowSenders: [],
allowBody: [],
denySender: [],
denyBody: ["קורונה", "חדשות"]),
NLLanguage.english.rawValue : LanguageFilterListResponse(allowSenders: [],
allowBody: [],
denySender: [],
denyBody: ["test1", "spam"])
])
let cache = AutomaticFiltersCache(context: self.testSubject.context)
cache.uuid = UUID()
cache.hashed = filtersList.hashed
cache.filtersData = filtersList.encoded
cache.age = Date()
let automaticFiltersLanguageHE = AutomaticFiltersLanguage(context: self.testSubject.context)
automaticFiltersLanguageHE.lang = NLLanguage.hebrew.rawValue
automaticFiltersLanguageHE.isActive = true
let automaticFiltersLanguageEN = AutomaticFiltersLanguage(context: self.testSubject.context)
automaticFiltersLanguageEN.lang = NLLanguage.english.rawValue
automaticFiltersLanguageEN.isActive = false
try? self.testSubject.context.save()
}
}
| 48.685358 | 149 | 0.615114 |
1dd9116cb7d99d31b8090f866d461c2586c0b1e2 | 7,092 | /*
* Copyright 2019 Google
*
* 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 FirebaseFirestore
import FirebaseFirestoreSwift
class CodableIntegrationTests: FSTIntegrationTestCase {
private enum WriteFlavor {
case docRef
case writeBatch
case transaction
}
private let allFlavors: [WriteFlavor] = [.docRef, .writeBatch, .transaction]
private func setData<T: Encodable>(from value: T,
forDocument doc: DocumentReference,
withFlavor flavor: WriteFlavor = .docRef,
merge: Bool? = nil,
mergeFields: [Any]? = nil) throws {
let completion = completionForExpectation(withName: "setData")
switch flavor {
case .docRef:
if let merge = merge {
try doc.setData(from: value, merge: merge, completion: completion)
} else if let mergeFields = mergeFields {
try doc.setData(from: value, mergeFields: mergeFields, completion: completion)
} else {
try doc.setData(from: value, completion: completion)
}
case .writeBatch:
if let merge = merge {
try doc.firestore.batch().setData(from: value, forDocument: doc, merge: merge).commit(completion: completion)
} else if let mergeFields = mergeFields {
try doc.firestore.batch().setData(from: value, forDocument: doc, mergeFields: mergeFields).commit(completion: completion)
} else {
try doc.firestore.batch().setData(from: value, forDocument: doc).commit(completion: completion)
}
case .transaction:
doc.firestore.runTransaction({ (transaction, errorPointer) -> Any? in
do {
if let merge = merge {
try transaction.setData(from: value, forDocument: doc, merge: merge)
} else if let mergeFields = mergeFields {
try transaction.setData(from: value, forDocument: doc, mergeFields: mergeFields)
} else {
try transaction.setData(from: value, forDocument: doc)
}
} catch {
XCTFail("setData with transation failed.")
}
return nil
}) { object, error in
completion?(error)
} }
awaitExpectations()
}
func testCodableRoundTrip() throws {
struct Model: Codable, Equatable {
var name: String
var age: Int32
var ts: Timestamp
var geoPoint: GeoPoint
var docRef: DocumentReference
}
let docToWrite = documentRef()
let model = Model(name: "test",
age: 42,
ts: Timestamp(seconds: 987_654_321, nanoseconds: 0),
geoPoint: GeoPoint(latitude: 45, longitude: 54),
docRef: docToWrite)
for flavor in allFlavors {
try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
let readAfterWrite = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertEqual(readAfterWrite!, model, "Failed with flavor \(flavor)")
}
}
func testServerTimestamp() throws {
struct Model: Codable, Equatable {
var name: String
var ts: ServerTimestamp
}
let model = Model(name: "name", ts: ServerTimestamp.pending)
let docToWrite = documentRef()
for flavor in allFlavors {
try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertNotNil(decoded?.ts, "Failed with flavor \(flavor)")
switch decoded!.ts {
case let .resolved(ts):
XCTAssertGreaterThan(ts.seconds, 1_500_000_000, "Failed with flavor \(flavor)")
case .pending:
XCTFail("Expect server timestamp is set, but getting .pending")
}
}
}
func testFieldValue() throws {
struct Model: Encodable {
var name: String
var array: FieldValue
var intValue: FieldValue
}
let model = Model(
name: "name",
array: FieldValue.arrayUnion([1, 2, 3]),
intValue: FieldValue.increment(3 as Int64)
)
let docToWrite = documentRef()
for flavor in allFlavors {
try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
let data = readDocument(forRef: docToWrite)
XCTAssertEqual(data["array"] as! [Int], [1, 2, 3], "Failed with flavor \(flavor)")
XCTAssertEqual(data["intValue"] as! Int, 3, "Failed with flavor \(flavor)")
}
}
func testExplicitNull() throws {
struct Model: Encodable {
var name: String
var explicitNull: ExplicitNull<String>
var optional: Optional<String>
}
let model = Model(
name: "name",
explicitNull: .none,
optional: nil
)
let docToWrite = documentRef()
for flavor in allFlavors {
try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
let data = readDocument(forRef: docToWrite).data()
XCTAssertTrue(data!.keys.contains("explicitNull"), "Failed with flavor \(flavor)")
XCTAssertEqual(data!["explicitNull"] as! NSNull, NSNull(), "Failed with flavor \(flavor)")
XCTAssertFalse(data!.keys.contains("optional"), "Failed with flavor \(flavor)")
}
}
func testSetThenMerge() throws {
struct Model: Codable, Equatable {
var name: String? = nil
var age: Int32? = nil
var hobby: String? = nil
}
let docToWrite = documentRef()
let model = Model(name: "test",
age: 42, hobby: nil)
// 'name' will be skipped in merge because it's Optional.
let update = Model(name: nil, age: 43, hobby: "No")
for flavor in allFlavors {
try setData(from: model, forDocument: docToWrite, withFlavor: flavor)
try setData(from: update, forDocument: docToWrite, withFlavor: flavor, merge: true)
var readAfterUpdate = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertEqual(readAfterUpdate!, Model(name: "test",
age: 43, hobby: "No"), "Failed with flavor \(flavor)")
let newUpdate = Model(name: "xxxx", age: 10, hobby: "Play")
// Note 'name' is not updated.
try setData(from: newUpdate, forDocument: docToWrite, withFlavor: flavor, mergeFields: ["age", FieldPath(["hobby"])])
readAfterUpdate = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertEqual(readAfterUpdate!, Model(name: "test",
age: 10, hobby: "Play"), "Failed with flavor \(flavor)")
}
}
}
| 35.108911 | 129 | 0.632262 |
89f6c84db486c9ec7fae9be1cdc8b42e71cde29f | 5,788 |
// RUN: %target-swift-emit-silgen -module-name collection_upcast -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class BridgedObjC : NSObject { }
func == (x: BridgedObjC, y: BridgedObjC) -> Bool { return true }
struct BridgedSwift : Hashable, _ObjectiveCBridgeable {
var hashValue: Int { return 0 }
func _bridgeToObjectiveC() -> BridgedObjC {
return BridgedObjC()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedObjC,
result: inout BridgedSwift?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedObjC,
result: inout BridgedSwift?
) -> Bool {
return true
}
}
func == (x: BridgedSwift, y: BridgedSwift) -> Bool { return true }
// CHECK-LABEL: sil hidden @$S17collection_upcast15testArrayUpcast{{.*}}F :
// CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<BridgedObjC>):
func testArrayUpcast(_ array: [BridgedObjC]) {
// CHECK: [[ARRAY_COPY:%.*]] = copy_value [[ARRAY]]
// CHECK: [[UPCAST_FN:%[0-9]+]] = function_ref @$Ss15_arrayForceCast{{.*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: [[RESULT:%.*]] = apply [[UPCAST_FN]]<BridgedObjC, AnyObject>([[ARRAY_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[ARRAY]]
let anyObjectArr: [AnyObject] = array
}
// CHECK: } // end sil function '$S17collection_upcast15testArrayUpcast{{.*}}F'
// CHECK-LABEL: sil hidden @$S17collection_upcast22testArrayUpcastBridged{{.*}}F
// CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<BridgedSwift>):
func testArrayUpcastBridged(_ array: [BridgedSwift]) {
// CHECK: [[ARRAY_COPY:%.*]] = copy_value [[ARRAY]]
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @$Ss15_arrayForceCast{{.*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE_FN]]<BridgedSwift, AnyObject>([[ARRAY_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[ARRAY]]
let anyObjectArr = array as [AnyObject]
}
// CHECK: } // end sil function '$S17collection_upcast22testArrayUpcastBridged{{.*}}F'
// CHECK-LABEL: sil hidden @$S17collection_upcast20testDictionaryUpcast{{.*}}F
// CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<BridgedObjC, BridgedObjC>):
func testDictionaryUpcast(_ dict: Dictionary<BridgedObjC, BridgedObjC>) {
// CHECK: [[DICT_COPY:%.*]] = copy_value [[DICT]]
// CHECK: [[UPCAST_FN:%[0-9]+]] = function_ref @$Ss17_dictionaryUpCast{{.*}}F : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: [[RESULT:%.*]] = apply [[UPCAST_FN]]<BridgedObjC, BridgedObjC, NSObject, AnyObject>([[DICT_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[DICT]]
let anyObjectDict: Dictionary<NSObject, AnyObject> = dict
}
// CHECK-LABEL: sil hidden @$S17collection_upcast27testDictionaryUpcastBridged{{.*}}F
// CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<BridgedSwift, BridgedSwift>):
func testDictionaryUpcastBridged(_ dict: Dictionary<BridgedSwift, BridgedSwift>) {
// CHECK: [[DICT_COPY:%.*]] = copy_value [[DICT]]
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @$Ss17_dictionaryUpCast{{.*}}F
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE_FN]]<BridgedSwift, BridgedSwift, NSObject, AnyObject>([[DICT_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[DICT]]
let anyObjectDict = dict as Dictionary<NSObject, AnyObject>
}
// CHECK-LABEL: sil hidden @$S17collection_upcast13testSetUpcast{{.*}}F
// CHECK: bb0([[SET:%[0-9]+]] : $Set<BridgedObjC>):
func testSetUpcast(_ dict: Set<BridgedObjC>) {
// CHECK: [[SET_COPY:%.*]] = copy_value [[SET]]
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @$Ss10_setUpCast{{.*}}F : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned Set<τ_0_1>
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE_FN]]<BridgedObjC, NSObject>([[SET_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned Set<τ_0_1>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[SET]]
let anyObjectSet: Set<NSObject> = dict
}
// CHECK-LABEL: sil hidden @$S17collection_upcast20testSetUpcastBridged{{.*}}F
// CHECK: bb0([[SET:%.*]] : $Set<BridgedSwift>):
func testSetUpcastBridged(_ set: Set<BridgedSwift>) {
// CHECK: [[SET_COPY:%.*]] = copy_value [[SET]]
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @$Ss10_setUpCast{{.*}}F
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE_FN]]<BridgedSwift, NSObject>([[SET_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned Set<τ_0_1>
// CHECK: destroy_value [[RESULT]]
// CHECK-NOT: destroy_value [[SET]]
let anyObjectSet = set as Set<NSObject>
}
| 51.678571 | 277 | 0.682619 |
ed04115a21314e0e81884491d7bc2ae37f275fa1 | 37,416 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/unittest_proto3_optional.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// 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
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct ProtobufUnittest_TestProto3Optional {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Singular
var optionalInt32: Int32 {
get {return _storage._optionalInt32 ?? 0}
set {_uniqueStorage()._optionalInt32 = newValue}
}
/// Returns true if `optionalInt32` has been explicitly set.
var hasOptionalInt32: Bool {return _storage._optionalInt32 != nil}
/// Clears the value of `optionalInt32`. Subsequent reads from it will return its default value.
mutating func clearOptionalInt32() {_uniqueStorage()._optionalInt32 = nil}
var optionalInt64: Int64 {
get {return _storage._optionalInt64 ?? 0}
set {_uniqueStorage()._optionalInt64 = newValue}
}
/// Returns true if `optionalInt64` has been explicitly set.
var hasOptionalInt64: Bool {return _storage._optionalInt64 != nil}
/// Clears the value of `optionalInt64`. Subsequent reads from it will return its default value.
mutating func clearOptionalInt64() {_uniqueStorage()._optionalInt64 = nil}
var optionalUint32: UInt32 {
get {return _storage._optionalUint32 ?? 0}
set {_uniqueStorage()._optionalUint32 = newValue}
}
/// Returns true if `optionalUint32` has been explicitly set.
var hasOptionalUint32: Bool {return _storage._optionalUint32 != nil}
/// Clears the value of `optionalUint32`. Subsequent reads from it will return its default value.
mutating func clearOptionalUint32() {_uniqueStorage()._optionalUint32 = nil}
var optionalUint64: UInt64 {
get {return _storage._optionalUint64 ?? 0}
set {_uniqueStorage()._optionalUint64 = newValue}
}
/// Returns true if `optionalUint64` has been explicitly set.
var hasOptionalUint64: Bool {return _storage._optionalUint64 != nil}
/// Clears the value of `optionalUint64`. Subsequent reads from it will return its default value.
mutating func clearOptionalUint64() {_uniqueStorage()._optionalUint64 = nil}
var optionalSint32: Int32 {
get {return _storage._optionalSint32 ?? 0}
set {_uniqueStorage()._optionalSint32 = newValue}
}
/// Returns true if `optionalSint32` has been explicitly set.
var hasOptionalSint32: Bool {return _storage._optionalSint32 != nil}
/// Clears the value of `optionalSint32`. Subsequent reads from it will return its default value.
mutating func clearOptionalSint32() {_uniqueStorage()._optionalSint32 = nil}
var optionalSint64: Int64 {
get {return _storage._optionalSint64 ?? 0}
set {_uniqueStorage()._optionalSint64 = newValue}
}
/// Returns true if `optionalSint64` has been explicitly set.
var hasOptionalSint64: Bool {return _storage._optionalSint64 != nil}
/// Clears the value of `optionalSint64`. Subsequent reads from it will return its default value.
mutating func clearOptionalSint64() {_uniqueStorage()._optionalSint64 = nil}
var optionalFixed32: UInt32 {
get {return _storage._optionalFixed32 ?? 0}
set {_uniqueStorage()._optionalFixed32 = newValue}
}
/// Returns true if `optionalFixed32` has been explicitly set.
var hasOptionalFixed32: Bool {return _storage._optionalFixed32 != nil}
/// Clears the value of `optionalFixed32`. Subsequent reads from it will return its default value.
mutating func clearOptionalFixed32() {_uniqueStorage()._optionalFixed32 = nil}
var optionalFixed64: UInt64 {
get {return _storage._optionalFixed64 ?? 0}
set {_uniqueStorage()._optionalFixed64 = newValue}
}
/// Returns true if `optionalFixed64` has been explicitly set.
var hasOptionalFixed64: Bool {return _storage._optionalFixed64 != nil}
/// Clears the value of `optionalFixed64`. Subsequent reads from it will return its default value.
mutating func clearOptionalFixed64() {_uniqueStorage()._optionalFixed64 = nil}
var optionalSfixed32: Int32 {
get {return _storage._optionalSfixed32 ?? 0}
set {_uniqueStorage()._optionalSfixed32 = newValue}
}
/// Returns true if `optionalSfixed32` has been explicitly set.
var hasOptionalSfixed32: Bool {return _storage._optionalSfixed32 != nil}
/// Clears the value of `optionalSfixed32`. Subsequent reads from it will return its default value.
mutating func clearOptionalSfixed32() {_uniqueStorage()._optionalSfixed32 = nil}
var optionalSfixed64: Int64 {
get {return _storage._optionalSfixed64 ?? 0}
set {_uniqueStorage()._optionalSfixed64 = newValue}
}
/// Returns true if `optionalSfixed64` has been explicitly set.
var hasOptionalSfixed64: Bool {return _storage._optionalSfixed64 != nil}
/// Clears the value of `optionalSfixed64`. Subsequent reads from it will return its default value.
mutating func clearOptionalSfixed64() {_uniqueStorage()._optionalSfixed64 = nil}
var optionalFloat: Float {
get {return _storage._optionalFloat ?? 0}
set {_uniqueStorage()._optionalFloat = newValue}
}
/// Returns true if `optionalFloat` has been explicitly set.
var hasOptionalFloat: Bool {return _storage._optionalFloat != nil}
/// Clears the value of `optionalFloat`. Subsequent reads from it will return its default value.
mutating func clearOptionalFloat() {_uniqueStorage()._optionalFloat = nil}
var optionalDouble: Double {
get {return _storage._optionalDouble ?? 0}
set {_uniqueStorage()._optionalDouble = newValue}
}
/// Returns true if `optionalDouble` has been explicitly set.
var hasOptionalDouble: Bool {return _storage._optionalDouble != nil}
/// Clears the value of `optionalDouble`. Subsequent reads from it will return its default value.
mutating func clearOptionalDouble() {_uniqueStorage()._optionalDouble = nil}
var optionalBool: Bool {
get {return _storage._optionalBool ?? false}
set {_uniqueStorage()._optionalBool = newValue}
}
/// Returns true if `optionalBool` has been explicitly set.
var hasOptionalBool: Bool {return _storage._optionalBool != nil}
/// Clears the value of `optionalBool`. Subsequent reads from it will return its default value.
mutating func clearOptionalBool() {_uniqueStorage()._optionalBool = nil}
var optionalString: String {
get {return _storage._optionalString ?? String()}
set {_uniqueStorage()._optionalString = newValue}
}
/// Returns true if `optionalString` has been explicitly set.
var hasOptionalString: Bool {return _storage._optionalString != nil}
/// Clears the value of `optionalString`. Subsequent reads from it will return its default value.
mutating func clearOptionalString() {_uniqueStorage()._optionalString = nil}
var optionalBytes: Data {
get {return _storage._optionalBytes ?? Data()}
set {_uniqueStorage()._optionalBytes = newValue}
}
/// Returns true if `optionalBytes` has been explicitly set.
var hasOptionalBytes: Bool {return _storage._optionalBytes != nil}
/// Clears the value of `optionalBytes`. Subsequent reads from it will return its default value.
mutating func clearOptionalBytes() {_uniqueStorage()._optionalBytes = nil}
var optionalCord: String {
get {return _storage._optionalCord ?? String()}
set {_uniqueStorage()._optionalCord = newValue}
}
/// Returns true if `optionalCord` has been explicitly set.
var hasOptionalCord: Bool {return _storage._optionalCord != nil}
/// Clears the value of `optionalCord`. Subsequent reads from it will return its default value.
mutating func clearOptionalCord() {_uniqueStorage()._optionalCord = nil}
var optionalNestedMessage: ProtobufUnittest_TestProto3Optional.NestedMessage {
get {return _storage._optionalNestedMessage ?? ProtobufUnittest_TestProto3Optional.NestedMessage()}
set {_uniqueStorage()._optionalNestedMessage = newValue}
}
/// Returns true if `optionalNestedMessage` has been explicitly set.
var hasOptionalNestedMessage: Bool {return _storage._optionalNestedMessage != nil}
/// Clears the value of `optionalNestedMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalNestedMessage() {_uniqueStorage()._optionalNestedMessage = nil}
var lazyNestedMessage: ProtobufUnittest_TestProto3Optional.NestedMessage {
get {return _storage._lazyNestedMessage ?? ProtobufUnittest_TestProto3Optional.NestedMessage()}
set {_uniqueStorage()._lazyNestedMessage = newValue}
}
/// Returns true if `lazyNestedMessage` has been explicitly set.
var hasLazyNestedMessage: Bool {return _storage._lazyNestedMessage != nil}
/// Clears the value of `lazyNestedMessage`. Subsequent reads from it will return its default value.
mutating func clearLazyNestedMessage() {_uniqueStorage()._lazyNestedMessage = nil}
var optionalNestedEnum: ProtobufUnittest_TestProto3Optional.NestedEnum {
get {return _storage._optionalNestedEnum ?? .unspecified}
set {_uniqueStorage()._optionalNestedEnum = newValue}
}
/// Returns true if `optionalNestedEnum` has been explicitly set.
var hasOptionalNestedEnum: Bool {return _storage._optionalNestedEnum != nil}
/// Clears the value of `optionalNestedEnum`. Subsequent reads from it will return its default value.
mutating func clearOptionalNestedEnum() {_uniqueStorage()._optionalNestedEnum = nil}
/// Add some non-optional fields to verify we can mix them.
var singularInt32: Int32 {
get {return _storage._singularInt32}
set {_uniqueStorage()._singularInt32 = newValue}
}
var singularInt64: Int64 {
get {return _storage._singularInt64}
set {_uniqueStorage()._singularInt64 = newValue}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
enum NestedEnum: SwiftProtobuf.Enum {
typealias RawValue = Int
case unspecified // = 0
case foo // = 1
case bar // = 2
case baz // = 3
/// Intentionally negative.
case neg // = -1
case UNRECOGNIZED(Int)
init() {
self = .unspecified
}
init?(rawValue: Int) {
switch rawValue {
case -1: self = .neg
case 0: self = .unspecified
case 1: self = .foo
case 2: self = .bar
case 3: self = .baz
default: self = .UNRECOGNIZED(rawValue)
}
}
var rawValue: Int {
switch self {
case .neg: return -1
case .unspecified: return 0
case .foo: return 1
case .bar: return 2
case .baz: return 3
case .UNRECOGNIZED(let i): return i
}
}
}
struct NestedMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The field name "b" fails to compile in proto1 because it conflicts with
/// a local variable named "b" in one of the generated methods. Doh.
/// This file needs to compile in proto1 to test backwards-compatibility.
var bb: Int32 {
get {return _bb ?? 0}
set {_bb = newValue}
}
/// Returns true if `bb` has been explicitly set.
var hasBb: Bool {return self._bb != nil}
/// Clears the value of `bb`. Subsequent reads from it will return its default value.
mutating func clearBb() {self._bb = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _bb: Int32? = nil
}
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
#if swift(>=4.2)
extension ProtobufUnittest_TestProto3Optional.NestedEnum: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
static var allCases: [ProtobufUnittest_TestProto3Optional.NestedEnum] = [
.unspecified,
.foo,
.bar,
.baz,
.neg,
]
}
#endif // swift(>=4.2)
struct ProtobufUnittest_TestProto3OptionalMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var nestedMessage: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage {
get {return _nestedMessage ?? ProtobufUnittest_TestProto3OptionalMessage.NestedMessage()}
set {_nestedMessage = newValue}
}
/// Returns true if `nestedMessage` has been explicitly set.
var hasNestedMessage: Bool {return self._nestedMessage != nil}
/// Clears the value of `nestedMessage`. Subsequent reads from it will return its default value.
mutating func clearNestedMessage() {self._nestedMessage = nil}
var optionalNestedMessage: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage {
get {return _optionalNestedMessage ?? ProtobufUnittest_TestProto3OptionalMessage.NestedMessage()}
set {_optionalNestedMessage = newValue}
}
/// Returns true if `optionalNestedMessage` has been explicitly set.
var hasOptionalNestedMessage: Bool {return self._optionalNestedMessage != nil}
/// Clears the value of `optionalNestedMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalNestedMessage() {self._optionalNestedMessage = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
struct NestedMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var s: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
init() {}
fileprivate var _nestedMessage: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage? = nil
fileprivate var _optionalNestedMessage: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage? = nil
}
struct ProtobufUnittest_Proto3OptionalExtensions {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Extension support defined in unittest_proto3_optional.proto.
// MARK: - Extension Properties
// Swift Extensions on the exteneded Messages to add easy access to the declared
// extension fields. The names are based on the extension field name from the proto
// declaration. To avoid naming collisions, the names are prefixed with the name of
// the scope where the extend directive occurs.
extension SwiftProtobuf.Google_Protobuf_MessageOptions {
var ProtobufUnittest_Proto3OptionalExtensions_extNoOptional: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional`
/// has been explicitly set.
var hasProtobufUnittest_Proto3OptionalExtensions_extNoOptional: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional)
}
/// Clears the value of extension `ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_Proto3OptionalExtensions_extNoOptional() {
clearExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional)
}
var ProtobufUnittest_Proto3OptionalExtensions_extWithOptional: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional`
/// has been explicitly set.
var hasProtobufUnittest_Proto3OptionalExtensions_extWithOptional: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional)
}
/// Clears the value of extension `ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_Proto3OptionalExtensions_extWithOptional() {
clearExtensionValue(ext: ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional)
}
}
// MARK: - File's ExtensionMap: ProtobufUnittest_UnittestProto3Optional_Extensions
/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by
/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed
/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create
/// a larger `SwiftProtobuf.SimpleExtensionMap`.
let ProtobufUnittest_UnittestProto3Optional_Extensions: SwiftProtobuf.SimpleExtensionMap = [
ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_no_optional,
ProtobufUnittest_Proto3OptionalExtensions.Extensions.ext_with_optional
]
// Extension Objects - The only reason these might be needed is when manually
// constructing a `SimpleExtensionMap`, otherwise, use the above _Extension Properties_
// accessors for the extension fields on the messages directly.
extension ProtobufUnittest_Proto3OptionalExtensions {
enum Extensions {
static let ext_no_optional = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, SwiftProtobuf.Google_Protobuf_MessageOptions>(
_protobuf_fieldNumber: 355886728,
fieldName: "protobuf_unittest.Proto3OptionalExtensions.ext_no_optional"
)
static let ext_with_optional = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, SwiftProtobuf.Google_Protobuf_MessageOptions>(
_protobuf_fieldNumber: 355886729,
fieldName: "protobuf_unittest.Proto3OptionalExtensions.ext_with_optional"
)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_TestProto3Optional: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestProto3Optional"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "optional_int32"),
2: .standard(proto: "optional_int64"),
3: .standard(proto: "optional_uint32"),
4: .standard(proto: "optional_uint64"),
5: .standard(proto: "optional_sint32"),
6: .standard(proto: "optional_sint64"),
7: .standard(proto: "optional_fixed32"),
8: .standard(proto: "optional_fixed64"),
9: .standard(proto: "optional_sfixed32"),
10: .standard(proto: "optional_sfixed64"),
11: .standard(proto: "optional_float"),
12: .standard(proto: "optional_double"),
13: .standard(proto: "optional_bool"),
14: .standard(proto: "optional_string"),
15: .standard(proto: "optional_bytes"),
16: .standard(proto: "optional_cord"),
18: .standard(proto: "optional_nested_message"),
19: .standard(proto: "lazy_nested_message"),
21: .standard(proto: "optional_nested_enum"),
22: .standard(proto: "singular_int32"),
23: .standard(proto: "singular_int64"),
]
fileprivate class _StorageClass {
var _optionalInt32: Int32? = nil
var _optionalInt64: Int64? = nil
var _optionalUint32: UInt32? = nil
var _optionalUint64: UInt64? = nil
var _optionalSint32: Int32? = nil
var _optionalSint64: Int64? = nil
var _optionalFixed32: UInt32? = nil
var _optionalFixed64: UInt64? = nil
var _optionalSfixed32: Int32? = nil
var _optionalSfixed64: Int64? = nil
var _optionalFloat: Float? = nil
var _optionalDouble: Double? = nil
var _optionalBool: Bool? = nil
var _optionalString: String? = nil
var _optionalBytes: Data? = nil
var _optionalCord: String? = nil
var _optionalNestedMessage: ProtobufUnittest_TestProto3Optional.NestedMessage? = nil
var _lazyNestedMessage: ProtobufUnittest_TestProto3Optional.NestedMessage? = nil
var _optionalNestedEnum: ProtobufUnittest_TestProto3Optional.NestedEnum? = nil
var _singularInt32: Int32 = 0
var _singularInt64: Int64 = 0
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_optionalInt32 = source._optionalInt32
_optionalInt64 = source._optionalInt64
_optionalUint32 = source._optionalUint32
_optionalUint64 = source._optionalUint64
_optionalSint32 = source._optionalSint32
_optionalSint64 = source._optionalSint64
_optionalFixed32 = source._optionalFixed32
_optionalFixed64 = source._optionalFixed64
_optionalSfixed32 = source._optionalSfixed32
_optionalSfixed64 = source._optionalSfixed64
_optionalFloat = source._optionalFloat
_optionalDouble = source._optionalDouble
_optionalBool = source._optionalBool
_optionalString = source._optionalString
_optionalBytes = source._optionalBytes
_optionalCord = source._optionalCord
_optionalNestedMessage = source._optionalNestedMessage
_lazyNestedMessage = source._lazyNestedMessage
_optionalNestedEnum = source._optionalNestedEnum
_singularInt32 = source._singularInt32
_singularInt64 = source._singularInt64
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularInt32Field(value: &_storage._optionalInt32) }()
case 2: try { try decoder.decodeSingularInt64Field(value: &_storage._optionalInt64) }()
case 3: try { try decoder.decodeSingularUInt32Field(value: &_storage._optionalUint32) }()
case 4: try { try decoder.decodeSingularUInt64Field(value: &_storage._optionalUint64) }()
case 5: try { try decoder.decodeSingularSInt32Field(value: &_storage._optionalSint32) }()
case 6: try { try decoder.decodeSingularSInt64Field(value: &_storage._optionalSint64) }()
case 7: try { try decoder.decodeSingularFixed32Field(value: &_storage._optionalFixed32) }()
case 8: try { try decoder.decodeSingularFixed64Field(value: &_storage._optionalFixed64) }()
case 9: try { try decoder.decodeSingularSFixed32Field(value: &_storage._optionalSfixed32) }()
case 10: try { try decoder.decodeSingularSFixed64Field(value: &_storage._optionalSfixed64) }()
case 11: try { try decoder.decodeSingularFloatField(value: &_storage._optionalFloat) }()
case 12: try { try decoder.decodeSingularDoubleField(value: &_storage._optionalDouble) }()
case 13: try { try decoder.decodeSingularBoolField(value: &_storage._optionalBool) }()
case 14: try { try decoder.decodeSingularStringField(value: &_storage._optionalString) }()
case 15: try { try decoder.decodeSingularBytesField(value: &_storage._optionalBytes) }()
case 16: try { try decoder.decodeSingularStringField(value: &_storage._optionalCord) }()
case 18: try { try decoder.decodeSingularMessageField(value: &_storage._optionalNestedMessage) }()
case 19: try { try decoder.decodeSingularMessageField(value: &_storage._lazyNestedMessage) }()
case 21: try { try decoder.decodeSingularEnumField(value: &_storage._optionalNestedEnum) }()
case 22: try { try decoder.decodeSingularInt32Field(value: &_storage._singularInt32) }()
case 23: try { try decoder.decodeSingularInt64Field(value: &_storage._singularInt64) }()
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._optionalInt32 {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
if let v = _storage._optionalInt64 {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 2)
}
if let v = _storage._optionalUint32 {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)
}
if let v = _storage._optionalUint64 {
try visitor.visitSingularUInt64Field(value: v, fieldNumber: 4)
}
if let v = _storage._optionalSint32 {
try visitor.visitSingularSInt32Field(value: v, fieldNumber: 5)
}
if let v = _storage._optionalSint64 {
try visitor.visitSingularSInt64Field(value: v, fieldNumber: 6)
}
if let v = _storage._optionalFixed32 {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 7)
}
if let v = _storage._optionalFixed64 {
try visitor.visitSingularFixed64Field(value: v, fieldNumber: 8)
}
if let v = _storage._optionalSfixed32 {
try visitor.visitSingularSFixed32Field(value: v, fieldNumber: 9)
}
if let v = _storage._optionalSfixed64 {
try visitor.visitSingularSFixed64Field(value: v, fieldNumber: 10)
}
if let v = _storage._optionalFloat {
try visitor.visitSingularFloatField(value: v, fieldNumber: 11)
}
if let v = _storage._optionalDouble {
try visitor.visitSingularDoubleField(value: v, fieldNumber: 12)
}
if let v = _storage._optionalBool {
try visitor.visitSingularBoolField(value: v, fieldNumber: 13)
}
if let v = _storage._optionalString {
try visitor.visitSingularStringField(value: v, fieldNumber: 14)
}
if let v = _storage._optionalBytes {
try visitor.visitSingularBytesField(value: v, fieldNumber: 15)
}
if let v = _storage._optionalCord {
try visitor.visitSingularStringField(value: v, fieldNumber: 16)
}
if let v = _storage._optionalNestedMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 18)
}
if let v = _storage._lazyNestedMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 19)
}
if let v = _storage._optionalNestedEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 21)
}
if _storage._singularInt32 != 0 {
try visitor.visitSingularInt32Field(value: _storage._singularInt32, fieldNumber: 22)
}
if _storage._singularInt64 != 0 {
try visitor.visitSingularInt64Field(value: _storage._singularInt64, fieldNumber: 23)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestProto3Optional, rhs: ProtobufUnittest_TestProto3Optional) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._optionalInt32 != rhs_storage._optionalInt32 {return false}
if _storage._optionalInt64 != rhs_storage._optionalInt64 {return false}
if _storage._optionalUint32 != rhs_storage._optionalUint32 {return false}
if _storage._optionalUint64 != rhs_storage._optionalUint64 {return false}
if _storage._optionalSint32 != rhs_storage._optionalSint32 {return false}
if _storage._optionalSint64 != rhs_storage._optionalSint64 {return false}
if _storage._optionalFixed32 != rhs_storage._optionalFixed32 {return false}
if _storage._optionalFixed64 != rhs_storage._optionalFixed64 {return false}
if _storage._optionalSfixed32 != rhs_storage._optionalSfixed32 {return false}
if _storage._optionalSfixed64 != rhs_storage._optionalSfixed64 {return false}
if _storage._optionalFloat != rhs_storage._optionalFloat {return false}
if _storage._optionalDouble != rhs_storage._optionalDouble {return false}
if _storage._optionalBool != rhs_storage._optionalBool {return false}
if _storage._optionalString != rhs_storage._optionalString {return false}
if _storage._optionalBytes != rhs_storage._optionalBytes {return false}
if _storage._optionalCord != rhs_storage._optionalCord {return false}
if _storage._optionalNestedMessage != rhs_storage._optionalNestedMessage {return false}
if _storage._lazyNestedMessage != rhs_storage._lazyNestedMessage {return false}
if _storage._optionalNestedEnum != rhs_storage._optionalNestedEnum {return false}
if _storage._singularInt32 != rhs_storage._singularInt32 {return false}
if _storage._singularInt64 != rhs_storage._singularInt64 {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestProto3Optional.NestedEnum: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
-1: .same(proto: "NEG"),
0: .same(proto: "UNSPECIFIED"),
1: .same(proto: "FOO"),
2: .same(proto: "BAR"),
3: .same(proto: "BAZ"),
]
}
extension ProtobufUnittest_TestProto3Optional.NestedMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestProto3Optional.protoMessageName + ".NestedMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "bb"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularInt32Field(value: &self._bb) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._bb {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestProto3Optional.NestedMessage, rhs: ProtobufUnittest_TestProto3Optional.NestedMessage) -> Bool {
if lhs._bb != rhs._bb {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestProto3OptionalMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestProto3OptionalMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "nested_message"),
2: .standard(proto: "optional_nested_message"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._nestedMessage) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._optionalNestedMessage) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._nestedMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = self._optionalNestedMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestProto3OptionalMessage, rhs: ProtobufUnittest_TestProto3OptionalMessage) -> Bool {
if lhs._nestedMessage != rhs._nestedMessage {return false}
if lhs._optionalNestedMessage != rhs._optionalNestedMessage {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestProto3OptionalMessage.NestedMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestProto3OptionalMessage.protoMessageName + ".NestedMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "s"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.s) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.s.isEmpty {
try visitor.visitSingularStringField(value: self.s, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage, rhs: ProtobufUnittest_TestProto3OptionalMessage.NestedMessage) -> Bool {
if lhs.s != rhs.s {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_Proto3OptionalExtensions: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Proto3OptionalExtensions"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_Proto3OptionalExtensions, rhs: ProtobufUnittest_Proto3OptionalExtensions) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 46.249691 | 179 | 0.744521 |
50979db92651a1f4e095aaf9cb2f3a2a6296a9ab | 7,014 | @testable import MatomoTracker
import Quick
import Nimble
class TrackerSpec: QuickSpec {
override func spec() {
Nimble.AsyncDefaults.timeout = .seconds(5)
describe("init") {
it("should be able to initialized the MatomoTracker with a URL ending on `matomo.php`") {
let tracker = MatomoTracker(siteId: "5", baseURL: URL(string: "https://example.com/matomo.php")!)
expect(tracker).toNot(beNil())
}
it("should be released if no external strong reference exists (no retain cycles") {
weak var tracker = MatomoTracker(siteId: "5", baseURL: URL(string: "https://example.com/matomo.php")!)
expect(tracker).to(beNil())
}
}
describe("queue") {
it("should enqueue the item in the queue") {
var queuedEvent: Event? = nil
let queue = QueueMock()
let tracker = MatomoTracker.fixture(queue: queue, dispatcher: DispatcherMock())
queue.enqueueEventsHandler = { events, _ in
queuedEvent = events.first
}
let event = Event.fixture()
tracker.queue(event: event)
expect(queuedEvent).toNot(beNil())
}
it("should not throw an assertion if called from a background thread") {
let tracker = MatomoTracker.fixture(queue: MemoryQueue(), dispatcher: DispatcherMock())
var queued = false
DispatchQueue.global(qos: .background).async {
expect{ tracker.queue(event: .fixture()) }.toNot(throwAssertion())
queued = true
}
expect(queued).toEventually(beTrue())
}
}
describe("dispatch") {
context("with an idle tracker and queued events") {
it("should ask the queue for event") {
let queue = QueueMock()
queue.eventCount = 1
let tracker = MatomoTracker.fixture(queue: queue, dispatcher: DispatcherMock())
tracker.dispatch()
expect(queue.firstCallCount == 1).to(beTrue())
}
it("should give dequeued events to the dispatcher") {
var eventsDispatched: [Event] = []
let dispatcher = DispatcherMock()
let tracker = MatomoTracker.fixture(queue: MemoryQueue(), dispatcher: dispatcher)
dispatcher.sendEventsHandler = { events, _,_ in
eventsDispatched = events
}
tracker.track(.fixture())
tracker.dispatch()
expect(eventsDispatched.count).toEventually(equal(1))
}
it("should set isDispatching to true") {
let queue = QueueMock()
queue.eventCount = 1
let tracker = MatomoTracker.fixture(queue: queue, dispatcher: DispatcherMock())
tracker.dispatch()
expect(tracker.isDispatching).to(beTrue())
}
it("should not throw an assertion if called from a background thread") {
let tracker = MatomoTracker.fixture(queue: MemoryQueue(), dispatcher: DispatcherMock())
tracker.queue(event: .fixture())
var dispatched = false
DispatchQueue.global(qos: .background).async {
expect{ tracker.dispatch() }.toNot(throwAssertion())
dispatched = true
}
expect(dispatched).toEventually(beTrue(), timeout: .seconds(20))
}
it("should cancel dispatching if the dispatcher failes") {
}
it("should ask for the next events if the dispatcher succeeds") {
}
it("should stop dispatching if the queue is empty") {
}
}
it("should start a new DispatchTimer if dispatching failed") {
let dispatcher = DispatcherMock()
let tracker = MatomoTracker.fixture(queue: MemoryQueue(), dispatcher: dispatcher)
dispatcher.sendEventsHandler = { _, _, failure in
failure(NSError(domain: "spec", code: 0))
}
tracker.queue(event: .fixture())
tracker.dispatchInterval = 0.5
expect(dispatcher.sendEventsCallCount).toEventually(equal(5), timeout: .seconds(10))
}
it("should start a new DispatchTimer if dispatching succeeded") {
let dispatcher = DispatcherMock()
let tracker = MatomoTracker.fixture(queue: MemoryQueue(), dispatcher: dispatcher)
dispatcher.sendEventsHandler = { _, success, _ in
tracker.queue(event: .fixture())
success()
}
tracker.queue(event: .fixture())
tracker.dispatchInterval = 0.01
expect(dispatcher.sendEventsCallCount).toEventually(beGreaterThan(5))
}
context("with an already dispatching tracker") {
it("should not ask the queue for events") {
// TODO
}
}
}
describe("forcedVisitorID") {
it("populates the cid value if set") {
var queuedEvent: Event? = nil
let queue = QueueMock()
let tracker = MatomoTracker.fixture(queue: queue, dispatcher: DispatcherMock())
queue.enqueueEventsHandler = { events, _ in
queuedEvent = events.first
}
tracker.forcedVisitorId = "0123456789abcdef"
tracker.track(view: ["spec_view"])
expect(queuedEvent?.visitor.forcedId).toEventually(equal("0123456789abcdef"))
}
it("it doesn't change the existing value if set to an invalid one") {
let tracker = MatomoTracker.init(siteId: "spec", baseURL: URL(string: "http://matomo.org/spec/piwik.php")!)
tracker.forcedVisitorId = "0123456789abcdef"
tracker.forcedVisitorId = "invalid"
expect(tracker.forcedVisitorId) == "0123456789abcdef"
}
it("should persist and restore the value") {
let tracker = MatomoTracker.init(siteId: "spec", baseURL: URL(string: "http://matomo.org/spec/piwik.php")!)
tracker.forcedVisitorId = "0123456789abcdef"
let tracker2 = MatomoTracker.init(siteId: "spec", baseURL: URL(string: "http://matomo.org/spec/piwik.php")!)
expect(tracker2.forcedVisitorId) == "0123456789abcdef"
}
}
}
}
| 50.1 | 124 | 0.529798 |
cceed294ede92ac544c0eb8ea6d1b49f6577eae1 | 24,295 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: cosmwasm/wasm/v1/proposal.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// StoreCodeProposal gov proposal content type to submit WASM code to the system
public struct Cosmwasm_Wasm_V1_StoreCodeProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// RunAs is the address that is passed to the contract's environment as sender
public var runAs: String = String()
/// WASMByteCode can be raw or gzip compressed
public var wasmByteCode: Data = Data()
/// InstantiatePermission to apply on contract creation, optional
public var instantiatePermission: Cosmwasm_Wasm_V1_AccessConfig {
get {return _instantiatePermission ?? Cosmwasm_Wasm_V1_AccessConfig()}
set {_instantiatePermission = newValue}
}
/// Returns true if `instantiatePermission` has been explicitly set.
public var hasInstantiatePermission: Bool {return self._instantiatePermission != nil}
/// Clears the value of `instantiatePermission`. Subsequent reads from it will return its default value.
public mutating func clearInstantiatePermission() {self._instantiatePermission = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _instantiatePermission: Cosmwasm_Wasm_V1_AccessConfig? = nil
}
/// InstantiateContractProposal gov proposal content type to instantiate a
/// contract.
public struct Cosmwasm_Wasm_V1_InstantiateContractProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// RunAs is the address that is passed to the contract's environment as sender
public var runAs: String = String()
/// Admin is an optional address that can execute migrations
public var admin: String = String()
/// CodeID is the reference to the stored WASM code
public var codeID: UInt64 = 0
/// Label is optional metadata to be stored with a constract instance.
public var label: String = String()
/// Msg json encoded message to be passed to the contract on instantiation
public var msg: Data = Data()
/// Funds coins that are transferred to the contract on instantiation
public var funds: [Cosmos_Base_V1beta1_Coin] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// MigrateContractProposal gov proposal content type to migrate a contract.
public struct Cosmwasm_Wasm_V1_MigrateContractProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// RunAs is the address that is passed to the contract's environment as sender
public var runAs: String = String()
/// Contract is the address of the smart contract
public var contract: String = String()
/// CodeID references the new WASM code
public var codeID: UInt64 = 0
/// Msg json encoded message to be passed to the contract on migration
public var msg: Data = Data()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// UpdateAdminProposal gov proposal content type to set an admin for a contract.
public struct Cosmwasm_Wasm_V1_UpdateAdminProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// NewAdmin address to be set
public var newAdmin: String = String()
/// Contract is the address of the smart contract
public var contract: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// ClearAdminProposal gov proposal content type to clear the admin of a
/// contract.
public struct Cosmwasm_Wasm_V1_ClearAdminProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// Contract is the address of the smart contract
public var contract: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// PinCodesProposal gov proposal content type to pin a set of code ids in the
/// wasmvm cache.
public struct Cosmwasm_Wasm_V1_PinCodesProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// CodeIDs references the new WASM codes
public var codeIds: [UInt64] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// UnpinCodesProposal gov proposal content type to unpin a set of code ids in
/// the wasmvm cache.
public struct Cosmwasm_Wasm_V1_UnpinCodesProposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Title is a short summary
public var title: String = String()
/// Description is a human readable text
public var description_p: String = String()
/// CodeIDs references the WASM codes
public var codeIds: [UInt64] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "cosmwasm.wasm.v1"
extension Cosmwasm_Wasm_V1_StoreCodeProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".StoreCodeProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "run_as"),
4: .standard(proto: "wasm_byte_code"),
7: .standard(proto: "instantiate_permission"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.runAs) }()
case 4: try { try decoder.decodeSingularBytesField(value: &self.wasmByteCode) }()
case 7: try { try decoder.decodeSingularMessageField(value: &self._instantiatePermission) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.runAs.isEmpty {
try visitor.visitSingularStringField(value: self.runAs, fieldNumber: 3)
}
if !self.wasmByteCode.isEmpty {
try visitor.visitSingularBytesField(value: self.wasmByteCode, fieldNumber: 4)
}
if let v = self._instantiatePermission {
try visitor.visitSingularMessageField(value: v, fieldNumber: 7)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_StoreCodeProposal, rhs: Cosmwasm_Wasm_V1_StoreCodeProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.runAs != rhs.runAs {return false}
if lhs.wasmByteCode != rhs.wasmByteCode {return false}
if lhs._instantiatePermission != rhs._instantiatePermission {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_InstantiateContractProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".InstantiateContractProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "run_as"),
4: .same(proto: "admin"),
5: .standard(proto: "code_id"),
6: .same(proto: "label"),
7: .same(proto: "msg"),
8: .same(proto: "funds"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.runAs) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.admin) }()
case 5: try { try decoder.decodeSingularUInt64Field(value: &self.codeID) }()
case 6: try { try decoder.decodeSingularStringField(value: &self.label) }()
case 7: try { try decoder.decodeSingularBytesField(value: &self.msg) }()
case 8: try { try decoder.decodeRepeatedMessageField(value: &self.funds) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.runAs.isEmpty {
try visitor.visitSingularStringField(value: self.runAs, fieldNumber: 3)
}
if !self.admin.isEmpty {
try visitor.visitSingularStringField(value: self.admin, fieldNumber: 4)
}
if self.codeID != 0 {
try visitor.visitSingularUInt64Field(value: self.codeID, fieldNumber: 5)
}
if !self.label.isEmpty {
try visitor.visitSingularStringField(value: self.label, fieldNumber: 6)
}
if !self.msg.isEmpty {
try visitor.visitSingularBytesField(value: self.msg, fieldNumber: 7)
}
if !self.funds.isEmpty {
try visitor.visitRepeatedMessageField(value: self.funds, fieldNumber: 8)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_InstantiateContractProposal, rhs: Cosmwasm_Wasm_V1_InstantiateContractProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.runAs != rhs.runAs {return false}
if lhs.admin != rhs.admin {return false}
if lhs.codeID != rhs.codeID {return false}
if lhs.label != rhs.label {return false}
if lhs.msg != rhs.msg {return false}
if lhs.funds != rhs.funds {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_MigrateContractProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".MigrateContractProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "run_as"),
4: .same(proto: "contract"),
5: .standard(proto: "code_id"),
6: .same(proto: "msg"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.runAs) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.contract) }()
case 5: try { try decoder.decodeSingularUInt64Field(value: &self.codeID) }()
case 6: try { try decoder.decodeSingularBytesField(value: &self.msg) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.runAs.isEmpty {
try visitor.visitSingularStringField(value: self.runAs, fieldNumber: 3)
}
if !self.contract.isEmpty {
try visitor.visitSingularStringField(value: self.contract, fieldNumber: 4)
}
if self.codeID != 0 {
try visitor.visitSingularUInt64Field(value: self.codeID, fieldNumber: 5)
}
if !self.msg.isEmpty {
try visitor.visitSingularBytesField(value: self.msg, fieldNumber: 6)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_MigrateContractProposal, rhs: Cosmwasm_Wasm_V1_MigrateContractProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.runAs != rhs.runAs {return false}
if lhs.contract != rhs.contract {return false}
if lhs.codeID != rhs.codeID {return false}
if lhs.msg != rhs.msg {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_UpdateAdminProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".UpdateAdminProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "new_admin"),
4: .same(proto: "contract"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.newAdmin) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.contract) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.newAdmin.isEmpty {
try visitor.visitSingularStringField(value: self.newAdmin, fieldNumber: 3)
}
if !self.contract.isEmpty {
try visitor.visitSingularStringField(value: self.contract, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_UpdateAdminProposal, rhs: Cosmwasm_Wasm_V1_UpdateAdminProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.newAdmin != rhs.newAdmin {return false}
if lhs.contract != rhs.contract {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_ClearAdminProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".ClearAdminProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .same(proto: "contract"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.contract) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.contract.isEmpty {
try visitor.visitSingularStringField(value: self.contract, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_ClearAdminProposal, rhs: Cosmwasm_Wasm_V1_ClearAdminProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.contract != rhs.contract {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_PinCodesProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".PinCodesProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "code_ids"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeRepeatedUInt64Field(value: &self.codeIds) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.codeIds.isEmpty {
try visitor.visitPackedUInt64Field(value: self.codeIds, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_PinCodesProposal, rhs: Cosmwasm_Wasm_V1_PinCodesProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.codeIds != rhs.codeIds {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmwasm_Wasm_V1_UnpinCodesProposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".UnpinCodesProposal"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "title"),
2: .same(proto: "description"),
3: .standard(proto: "code_ids"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.title) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.description_p) }()
case 3: try { try decoder.decodeRepeatedUInt64Field(value: &self.codeIds) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.title.isEmpty {
try visitor.visitSingularStringField(value: self.title, fieldNumber: 1)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 2)
}
if !self.codeIds.isEmpty {
try visitor.visitPackedUInt64Field(value: self.codeIds, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Cosmwasm_Wasm_V1_UnpinCodesProposal, rhs: Cosmwasm_Wasm_V1_UnpinCodesProposal) -> Bool {
if lhs.title != rhs.title {return false}
if lhs.description_p != rhs.description_p {return false}
if lhs.codeIds != rhs.codeIds {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 41.459044 | 156 | 0.725499 |
9cb58370d6413e51c48684e00c567ae0cc9ee919 | 92 | public enum Purpose: UInt32 {
case bip44 = 44
case bip49 = 49
case bip84 = 84
}
| 15.333333 | 29 | 0.608696 |
e977f522f4f65887efcd1e85d0089ce2f0e4f35f | 1,014 | /*
Copyright 2019 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class OpaqueType : TypeBase {
public let wrappedType: Type
public init(wrappedType: Type) {
self.wrappedType = wrappedType
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
// the concrete type is unknown at this point, so we just save it syntactically
return "Opaque<\(wrappedType.textDescription)>"
}
}
| 32.709677 | 85 | 0.744576 |
ab816ae9d2ba025d943fc73b1265682759945dc0 | 9,186 | import Swift2D
struct RectangleProcessor {
let rectangle: Rectangle
init(rectangle: Rectangle) {
self.rectangle = rectangle
}
func commands(clockwise: Bool) -> [Path.Command] {
var rx = rectangle.rx
var ry = rectangle.ry
if let _rx = rx, _rx > (rectangle.width / 2.0) {
rx = rectangle.width / 2.0
}
if let _ry = ry, _ry > (rectangle.height / 2.0) {
ry = rectangle.height / 2.0
}
var commands: [Path.Command] = []
switch (rx, ry) {
case (.some(let radiusX), .some(let radiusY)) where radiusX != radiusY:
// Use Cubic Bezier Curve to form rounded corners
// TODO: Verify that the control points are right
var cp1: Point = .zero
var cp2: Point = .zero
var point: Point = Point(x: rectangle.x + radiusX, y: rectangle.y)
commands.append(.moveTo(point: point))
if clockwise {
point = .init(x: rectangle.x + rectangle.width - radiusX, y: rectangle.y)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x + rectangle.width, y: rectangle.y)
cp2 = cp1
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + radiusY)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height - radiusY)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)
cp2 = cp1
point = .init(x: rectangle.x + rectangle.width - radiusX, y: rectangle.y + rectangle.height)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x + radiusX, y: rectangle.y + rectangle.height)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x, y: rectangle.y + rectangle.height)
cp2 = cp1
point = .init(x: rectangle.x, y: rectangle.y + rectangle.height - radiusY)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x, y: rectangle.y + radiusY)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x, y: rectangle.y)
cp2 = cp1
point = .init(x: rectangle.x + radiusX, y: rectangle.y)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
} else {
cp1 = .init(x: rectangle.x, y: rectangle.y)
cp2 = cp1
point = .init(x: rectangle.x, y: rectangle.y + radiusY)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x, y: rectangle.y + rectangle.height - radiusY)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x, y: rectangle.y + rectangle.height)
cp2 = cp1
point = .init(x: rectangle.x + radiusX, y: rectangle.y + rectangle.height)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x + rectangle.width - radiusX, y: rectangle.y + rectangle.height)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)
cp2 = cp1
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height - radiusY)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + radiusY)
commands.append(.lineTo(point: point))
cp1 = .init(x: rectangle.x + rectangle.width, y: rectangle.y)
cp2 = cp1
point = .init(x: rectangle.x + rectangle.width - radiusX, y: rectangle.y)
commands.append(.cubicBezierCurve(cp1: cp1, cp2: cp2, point: point))
}
case (.some(let radius), .none), (.none, .some(let radius)), (.some(let radius), _):
// use Quadratic Bezier Curve to form rounded corners
var cp: Point = .zero
var point: Point = Point(x: rectangle.x + radius, y: rectangle.y)
commands.append(.moveTo(point: point))
if clockwise {
point = .init(x: (rectangle.x + rectangle.width) - radius, y: rectangle.y)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x + rectangle.width, y: rectangle.y)
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + radius)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x + rectangle.width, y: (rectangle.y + rectangle.height) - radius)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)
point = .init(x: rectangle.x + rectangle.width - radius, y: rectangle.y + rectangle.height)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x + radius, y: rectangle.y + rectangle.height)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x, y: rectangle.y + rectangle.height)
point = .init(x: rectangle.x, y: rectangle.y + rectangle.height - radius)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x, y: rectangle.y + radius)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x, y: rectangle.y)
point = .init(x: rectangle.x + radius, y: rectangle.y)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
} else {
cp = .init(x: rectangle.x, y: rectangle.y)
point = .init(x: rectangle.x, y: rectangle.y + radius)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x, y: rectangle.y + rectangle.height - radius)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x, y: rectangle.y + rectangle.height)
point = .init(x: rectangle.x + radius, y: rectangle.y + rectangle.height)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x + rectangle.width - radius, y: rectangle.y + rectangle.height)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height - radius)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
point = .init(x: rectangle.x + rectangle.width, y: rectangle.y + radius)
commands.append(.lineTo(point: point))
cp = .init(x: rectangle.x + rectangle.width, y: rectangle.y)
point = .init(x: rectangle.x + rectangle.width - radius, y: rectangle.y)
commands.append(.quadraticBezierCurve(cp: cp, point: point))
}
case (.none, .none):
// draw three line segments.
commands.append(.moveTo(point: Point(x: rectangle.x, y: rectangle.y)))
if clockwise {
commands.append(.lineTo(point: Point(x: rectangle.x + rectangle.width, y: rectangle.y)))
commands.append(.lineTo(point: Point(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)))
commands.append(.lineTo(point: Point(x: rectangle.x, y: rectangle.y + rectangle.height)))
} else {
commands.append(.lineTo(point: Point(x: rectangle.x, y: rectangle.y + rectangle.height)))
commands.append(.lineTo(point: Point(x: rectangle.x + rectangle.width, y: rectangle.y + rectangle.height)))
commands.append(.lineTo(point: Point(x: rectangle.x + rectangle.width, y: rectangle.y)))
}
}
commands.append(.closePath)
return commands
}
}
| 51.033333 | 123 | 0.528848 |
28b26a0848373414693068cb76fa5f5bb19c769a | 532 | //
// Copyright © 2020 Jesús Alfredo Hernández Alarcón. All rights reserved.
//
import EssentialFeed
import XCTest
final class SharedLocalizationTests: XCTestCase {
func test_localizedStrings_haveKeysAndValuesForAllSupportedLocalizations() {
let table = "Shared"
let bundle = Bundle(for: LoadResourcePresenter<Any, DummyView>.self)
assertLocalizedKeysAndValuesExists(in: bundle, table)
}
// MARK: - Helpers
private class DummyView: ResourceView {
func display(_: Any) {}
}
}
| 25.333333 | 80 | 0.710526 |
239193d856471ea17044bce96b65cfe8eb886400 | 3,744 | import UIKit
var str = "Hello, playground"
//let driving = {
// print("I'm driving in my car")
//}
//
//driving()
//let driving = { (place: String) in
// print("I'm driving to \(place) in my car")
//}
//
//driving("London")
//
//let driving = { (place: String) -> String in
// return "I'm driving to \(place) in my car"
//}
//
//let message = driving("London")
//
//print(message)
//let driving = {
// print("I'm driving in my car")
//}
//
//func travel(action: () -> Void) {
// print("I'm getting ready to go.")
// action()
// print("I arrived")
//}
//travel(action: driving)
//let driving = {
// print("I'm driving in my car")
//}
//
//func travel(action: () -> Void) {
// print("I'm getting ready to go.")
// action()
// print("I arrived")
//}
//
//travel {
// print("I'm driving in my car")
//}
//
func goOnVacation(to destination: String, _ activities: () -> Void) {
print("Packing bags...")
print("Getting on plane to \(destination)...")
activities()
print("Time to go home!")
}
goOnVacation(to: "Mexico") {
print("Go sightseeing")
print("Relax in sun")
print("Go hiking")
}
func goCamping(then action: () -> Void) {
print("We're going camping!")
action()
}
goCamping {
print("Sing songs")
print("Put up tent")
print("Attempt to sleep")
}
//func travel(action: () -> String) {
// print("I'm getting ready to go.")
// print(action())
// print("I arrived")
//}
//
//travel {() -> String in
// return "I'm going in my car..."
//}
//func travel(action: (String) -> String) {
// print("I'm getting ready to go.")
// let msg = action("London")
// print(msg)
// print("I arrived")
//}
//
//travel {(place: String) -> String in
// return "I'm going to \(place) in my car"
//}
func loadData(input: () -> String) {
print("Loading...")
let str = input()
print("Loaded: \(str)")
}
loadData {
return "He thrusts his fists against the posts"
}
func manipulate(numbers: [Int], using algorithm: (Int) -> Int) {
for number in numbers {
let result = algorithm(number)
print("Manipulating \(number) produced \(result)")
}
}
manipulate(numbers: [1, 2, 3]) { (number: Int) in
return number * number
}
//func travel(action: () -> String) {
// print("I'm getting ready to go.")
// print(action())
// print("I arrived")
//}
//
//travel {
// "I'm going in my car..."
//}
//func travel(action: (String) -> String) {
// print("I'm getting ready to go.")
// let msg = action("London")
// print(msg)
// print("I arrived")
//}
//
//travel {
// "I'm going to \($0) in my car"
//}
//func travel(action: (String, Int) -> String) {
// print("I'm getting ready to go.")
// let description = action("London", 60)
// print(description)
// print("I arrived")
//}
//
//travel {
// "I'm goign to \($0) at \($1) miles per hour"
//}
//func travel() -> (String) -> Void {
// return {
// print("I'm goign to \($0)")
// }
//}
//
//let result = travel()
//
//result("London")
//
//
//func mealProducer() -> (Int) -> String {
// return {
// print("I'll make dinner for \($0) people.")
// }
//}
//let makeDinner = mealProducer()
//print(makeDinner(5))
func travel() -> (String) -> Void {
var counter = 1
return {
print("\(counter). I'm going to \($0)")
counter += 1
}
}
let result = travel()
result("London")
result("London")
result("London")
func visitPlaces() -> (String) -> Void {
var places = [String: Int]()
return {
places[$0, default: 0] += 1
let timesVisited = places[$0, default: 0]
print("Number of times I've visited \($0): \(timesVisited).")
}
}
let visit = visitPlaces()
visit("London")
visit("New York")
visit("London")
func handOutBusinessCards() -> () -> Void {
let number = 0
return {
number += 1
print("Number handed out: \(number)")
}
}
let handOut = handOutBusinessCards()
handOut()
handOut()
| 18.174757 | 69 | 0.59375 |
8f290f54dbdeafa8b582fcdc5cfd74dcebf2672f | 7,633 | //
// WBComment.swift
// Gzone_App
//
// Created by Lyes Atek on 19/06/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import Foundation
class WBComment: NSObject {
func addComment(userId : String,postId : String,text : String,accessToken : String,_ completion: @escaping (_ result: Bool) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments?access_token="+accessToken
let url: NSURL = NSURL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue("application/json", forHTTPHeaderField: "Content-type")
let params = ["userId":userId,"postId" : postId,"text" : text]
let options : JSONSerialization.WritingOptions = JSONSerialization.WritingOptions();
do{
let requestBody = try JSONSerialization.data(withJSONObject: params, options: options)
request.httpBody = requestBody
let session = URLSession.shared
_ = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
completion( false)
}
completion(true)
}).resume()
}
catch{
print("error")
completion(false)
}
}
func deleteComment(commentId : String,accessToken : String, _ completion: @escaping (_ result: Void) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "DELETE"
let session = URLSession.shared
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
})
task.resume()
}
func getCommentByUserId(userId : String,accessToken : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/user/"+userId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentByPostId(postId : String,accessToken : String ,offset : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/post/"+postId+"?access_token="+accessToken+"&offset="+offset
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentById(commentId : String,accessToken : String,_ completion: @escaping (_ result: Comment) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"&access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let comment : Comment = self.JSONToComment(json: jsonResult)!
completion(comment)
}
catch{
print("error")
}
})
task.resume()
}
func JSONToCommentArray(_ jsonEvents : NSArray) -> [Comment]{
print (jsonEvents)
var commentsTab : [Comment] = []
for object in jsonEvents{
let _id = (object as AnyObject).object(forKey: "_id") as! String
let userId = (object as AnyObject).object(forKey: "userId") as! String
let text = (object as AnyObject).object(forKey: "text") as! String
var video : String
if((object as AnyObject).object(forKey: "videos") != nil){
video = (object as AnyObject).object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = (object as AnyObject).object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
commentsTab.append(comment);
}
return commentsTab;
}
func JSONToComment(json : NSDictionary) ->Comment?{
let _id = json.object(forKey: "_id") as! String
let userId = json.object(forKey: "userId") as! String
let text = json.object(forKey: "text") as! String
var video : String
if(json.object(forKey: "videos") != nil){
video = json.object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = json.object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
return comment
}
}
| 38.356784 | 156 | 0.558627 |
e20ba9b713c1b35b2150584fa7f22d152ad1aef0 | 3,296 | //
// UIAlertController+OS.swift
// OSKit
//
// Created by Brody Robertson.
// Copyright © 2019 Outside Source. All rights reserved.
//
import UIKit
public typealias UIAlertActionHandler = ((UIAlertAction) -> ())
public extension UIAlertController {
static func successOkAlertController(message: String, handler: UIAlertActionHandler? = nil) -> UIAlertController {
let title = NSLocalizedString("Success", comment: "")
let okTitle = NSLocalizedString("OK", comment: "")
let alertController = self.alertController(title: title, message: message, actionTitles: [okTitle], handlers: [handler])
return alertController
}
static func errorOkAlertController(error: Error, handler: UIAlertActionHandler? = nil) -> UIAlertController {
let title = NSLocalizedString("Error", comment: "")
let message = error.localizedDescription
let okTitle = NSLocalizedString("OK", comment: "")
let alertController = self.alertController(title: title, message: message, actionTitles: [okTitle], handlers: [handler])
return alertController
}
static func errorCancelRetryAlertController(error: Error, cancelHandler: UIAlertActionHandler? = nil, retryHandler: UIAlertActionHandler? = nil) -> UIAlertController {
let title = NSLocalizedString("Error", comment: "")
let message = error.localizedDescription
let cancelTitle = NSLocalizedString("Cancel", comment: "")
let retryTitle = NSLocalizedString("Retry", comment: "")
let alertController = self.alertController(title: title, message: message, actionTitles: [cancelTitle, retryTitle], handlers: [cancelHandler, retryHandler])
return alertController
}
static func errorRetryAlertController(error: Error, handler: @escaping UIAlertActionHandler) -> UIAlertController {
let title = NSLocalizedString("Error", comment: "")
let message = error.localizedDescription
let retryTitle = NSLocalizedString("Retry", comment: "")
let alertController = self.alertController(title: title, message: message, actionTitles: [retryTitle], handlers: [handler])
return alertController
}
static func alertController(title: String, message: String, actionTitles: [String], handlers: [UIAlertActionHandler?]) -> UIAlertController {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (i, actionTitle) in actionTitles.enumerated() {
if let handler = handlers[safe: i] {
/// completionBlock is optional
let alertAction = UIAlertAction(title: actionTitle, style: .default, handler: handler)
alertController.addAction(alertAction)
} else {
let alertAction = UIAlertAction(title: actionTitle, style: .default, handler: nil)
alertController.addAction(alertAction)
}
}
return alertController
}
}
| 37.033708 | 171 | 0.627124 |
64ca06fdfd11c3fbb70ef1656fc0f359d45ea86b | 4,850 | // MIT License
//
// Copyright (c) 2021 Ian Cooper
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class CoolSwitchControls: UIView {
public weak var dataSource:CoolSwitchControlsDataSource?
public var selected:Int = 0
public var cornerRadius:CGFloat = 15
public var knobCornerRadius:CGFloat = 15
var parent:UIViewController?
public init(parent:UIViewController) {
super.init(frame: .zero)
self.parent = parent
self.initPage()
}
public init() {
super.init(frame: .zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func initPageWithStoryBoard(){
guard let parent = self.parentViewController else{return}
self.parent = parent
}
private func initPage(){
self.backgroundColor = .clear
self.translatesAutoresizingMaskIntoConstraints = false
}
}
extension CoolSwitchControls{
///Adding the correct switch type as a subview
///and initializing it
/// - Warning: you should not call this function unless CoolSwitchControls was initialized
public func CreateSwitch(){
self.CornerRadius(for: self.cornerRadius)
///remove all the subviews if any exist
for views in self.subviews{
views.removeFromSuperview()
}
do{
try addsubivews()
}catch let error as SwitchError{
switch error {
case .typeError:
print(SwitchError.typeError.localizedDescription)
case .configError:
print(SwitchError.configError.localizedDescription)
case .parentError:
print(SwitchError.parentError.localizedDescription)
}
}catch let error as NSError{
print(error.localizedDescription)
}
}
fileprivate func addsubivews()throws{
guard let type = dataSource?.SetSwitch(for: self).type else {throw SwitchError.typeError}
guard let configuration = dataSource?.SetSwitch(for: self).config else {throw SwitchError.configError}
if parent == nil{
self.initPageWithStoryBoard()
}
switch type {
case .One:
let view = One(frame: self.bounds, configuration: configuration)
view.selected = self.selected
view.cornerRadius = self.knobCornerRadius
view.delegate = parent as? CoolSwitchControlsDelegate
self.addSubview(view)
view.addsubviews()
case .Two:
let view = Two(frame: self.bounds, configuration: configuration)
view.selected = self.selected
view.cornerRadius = self.knobCornerRadius
view.delegate = parent as? CoolSwitchControlsDelegate
self.addSubview(view)
view.addsubviews()
case .Three:
let view = Three(frame: self.bounds, configuration: configuration)
view.selected = self.selected
view.cornerRadius = self.knobCornerRadius
view.delegate = parent as? CoolSwitchControlsDelegate
self.addSubview(view)
view.addsubviews()
}
}
}
private enum SwitchError: Error {
case typeError
case configError
case parentError
var localizedDescription: String {
switch self {
case .typeError:
return NSLocalizedString("No type was found", comment: "")
case .configError:
return NSLocalizedString("No config was set", comment: "")
case .parentError:
return NSLocalizedString("No parent was set", comment: "")
}
}
}
| 34.15493 | 110 | 0.647216 |
db072addbf653a3ddd23224a0c1557edeecf295a | 4,249 | /*
*
* TextBubbleView.swift
* ZDCChatAPI Sample App
*
* Created by Zendesk on 07/07/2016.
*
* Copyright (c) 2016 Zendesk. All rights reserved.
*
* By downloading or using the Zopim Chat SDK, You agree to the Zendesk Terms
* of Service https://www.zendesk.com/company/terms and Application Developer and API License
* Agreement https://www.zendesk.com/company/application-developer-and-api-license-agreement and
* acknowledge that such terms govern Your use of and access to the Chat SDK.
*
*/
import UIKit
import NSDate_TimeAgo
/// Bubble View State
enum BubbleState {
/// Confirmed: happens when the message is confirmed
case Confirmed
/// Confirmed: the message is sent but not yet confirmed
case NotConfirmed
/// Confirmed: the bubble is an agent bubble
case Hidden
var image: UIImage {
switch self {
case .Confirmed:
return UIImage(named: "check-mark")!
case .Hidden:
return UIImage()
case .NotConfirmed:
return UIImage(named: "refresh")!
}
}
}
/// Bubble View
@IBDesignable
final class BubbleView: UIView {
enum CellType: String {
case Agent = "agent", Visitor = "visitor"
}
@IBOutlet var contentView: UIView!
private var timeStampLabel: UILabel!
private var verifiedImage: UIImageView!
@IBInspectable var typeString: String? {
didSet {
updateType()
}
}
@IBInspectable var type: CellType = .Agent {
didSet {
let isAgent = type == .Agent
verifiedImage?.hidden = isAgent
backgroundColor = type.cellBackgroundColor
timeStampLabel?.textColor = type.timestampTextColor
additionalViewUpdate()
}
}
var bubbleState: BubbleState = .Confirmed {
didSet {
verifiedImage.image = bubbleState.image
}
}
var timestamp: NSDate = NSDate.init(timeIntervalSinceNow: -1000) {
didSet {
timeStampLabel.text = timestamp.dateTimeAgo()
}
}
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 4
createViews()
updateType()
}
func updateType() {
if
let typeString = typeString,
let newType = CellType(rawValue: typeString) {
type = newType
}
}
//MARK: - Layout
func createViews() {
timeStampLabel = UILabel()
timeStampLabel.translatesAutoresizingMaskIntoConstraints = false
timeStampLabel.font = UIFont.systemFontOfSize(11)
timeStampLabel.text = "Some time ago"
self.addSubview(timeStampLabel)
verifiedImage = UIImageView(image: UIImage.init(named: "check-mark"))
verifiedImage.contentMode = .ScaleAspectFit
verifiedImage.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(verifiedImage)
setupConstraints()
}
func setupConstraints() {
timeStampLabel.topAnchor.constraintEqualToAnchor(contentView.bottomAnchor, constant: 8).active = true
timeStampLabel.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -4).active = true
timeStampLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal)
timeStampLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
verifiedImage.widthAnchor.constraintEqualToConstant(10).active = true
verifiedImage.heightAnchor.constraintEqualToConstant(10).active = true
verifiedImage.centerYAnchor.constraintEqualToAnchor(timeStampLabel.centerYAnchor, constant: 0).active = true
verifiedImage.leadingAnchor.constraintEqualToAnchor(timeStampLabel.trailingAnchor, constant: 4).active = true
if type == .Agent {
timeStampLabel.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor).active = true
trailingAnchor.constraintGreaterThanOrEqualToAnchor(verifiedImage.trailingAnchor, constant: 10).active = true
} else {
timeStampLabel.leadingAnchor.constraintGreaterThanOrEqualToAnchor(leadingAnchor, constant: 10).active = true
trailingAnchor.constraintEqualToAnchor(verifiedImage.trailingAnchor, constant: 8).active = true
}
}
}
extension BubbleView {
func additionalViewUpdate() {
if let label = contentView as? UILabel {
label.textColor = type.messageTextColor
}
}
}
| 28.139073 | 115 | 0.714756 |
9b920e7d5728c30f594364bbd400d81d29623838 | 4,667 | //
// ReportBrokenSiteViewController.swift
// DuckDuckGo
//
// Copyright © 2020 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class ReportBrokenSiteViewController: UIViewController {
@IBOutlet var tableView: UITableView!
@IBOutlet var headerView: UIView!
@IBOutlet var headerLabel: UILabel!
@IBOutlet var submitButton: UIBarButtonItem!
public var brokenSiteInfo: BrokenSiteInfo?
private var selectedCategory: Int? {
didSet {
submitButton.isEnabled = true
}
}
private let categories: [BrokenSite.Category] = {
var categories = BrokenSite.Category.allCases
categories = categories.filter { $0 != .other }
categories = categories.shuffled()
categories.append(.other)
return categories
}()
override func viewDidLoad() {
super.viewDidLoad()
submitButton.isEnabled = false
headerLabel.setAttributedTextString(UserText.reportBrokenSiteHeader)
applyTheme(ThemeManager.shared.currentTheme)
DispatchQueue.main.async {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
@IBAction func onClosePressed(sender: Any) {
dismiss(animated: true)
}
@IBAction func onSubmitPressed(sender: Any) {
guard let selectedCategory = selectedCategory else {
fatalError("Category should be selected!")
}
brokenSiteInfo?.send(with: categories[selectedCategory].rawValue)
ActionMessageView.present(message: UserText.feedbackSumbittedConfirmation)
dismiss(animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let headerView = tableView.tableHeaderView else {
return
}
let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
if headerView.frame.size.height != size.height {
headerView.frame.size.height = size.height
tableView.tableHeaderView = headerView
tableView.layoutIfNeeded()
}
}
}
extension ReportBrokenSiteViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrokenSiteCategoryCell") else {
fatalError("Failed to dequeue cell")
}
let theme = ThemeManager.shared.currentTheme
cell.textLabel?.textColor = theme.tableCellTextColor
cell.backgroundColor = theme.tableCellBackgroundColor
cell.tintColor = theme.buttonTintColor
if let selectedIndex = selectedCategory, selectedIndex == indexPath.row {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
cell.textLabel?.text = categories[indexPath.row].categoryText
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return UserText.brokenSiteSectionTitle
}
}
extension ReportBrokenSiteViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCategory = indexPath.row
tableView.reloadData()
}
}
extension ReportBrokenSiteViewController: Themable {
func decorate(with theme: Theme) {
decorateNavigationBar(with: theme)
view.backgroundColor = theme.backgroundColor
headerView.backgroundColor = theme.backgroundColor
headerLabel.textColor = theme.homeRowSecondaryTextColor
tableView.separatorColor = theme.tableCellSeparatorColor
tableView.backgroundColor = theme.backgroundColor
tableView.reloadData()
}
}
| 32.186207 | 103 | 0.668738 |
48605f2f38f8d9836d36f3d909295f2d63d2f82a | 1,938 | //
// PipelineRunNode.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public struct PipelineRunNode: Codable, JSONEncodable, Hashable {
public var _class: String?
public var displayName: String?
public var durationInMillis: Int?
public var edges: [PipelineRunNodeedges]?
public var id: String?
public var result: String?
public var startTime: String?
public var state: String?
public init(_class: String? = nil, displayName: String? = nil, durationInMillis: Int? = nil, edges: [PipelineRunNodeedges]? = nil, id: String? = nil, result: String? = nil, startTime: String? = nil, state: String? = nil) {
self._class = _class
self.displayName = displayName
self.durationInMillis = durationInMillis
self.edges = edges
self.id = id
self.result = result
self.startTime = startTime
self.state = state
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case _class
case displayName
case durationInMillis
case edges
case id
case result
case startTime
case state
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(_class, forKey: ._class)
try container.encodeIfPresent(displayName, forKey: .displayName)
try container.encodeIfPresent(durationInMillis, forKey: .durationInMillis)
try container.encodeIfPresent(edges, forKey: .edges)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(result, forKey: .result)
try container.encodeIfPresent(startTime, forKey: .startTime)
try container.encodeIfPresent(state, forKey: .state)
}
}
| 31.770492 | 226 | 0.678535 |
4acb4dcd9d7b40b1795cbacdfba399beace73faf | 163 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(PKCSPMExampleTests.allTests),
]
}
#endif
| 16.3 | 46 | 0.680982 |
c1116a132eb4783140e749b5d45a1ae2e865540c | 987 | //
// URLSession+Stubbed.swift
// NetworkableTests
//
// Created by Duy Tran on 7/13/20.
//
import Foundation
extension URLSession {
static var stubbed: URLSession {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubbedURLProtocol.self]
return URLSession(configuration: configuration)
}
func set(stubbedResponse response: URLResponse?, for request: URLRequest) {
StubbedURLProtocol.stubbedResponse[request] = response
}
func set(stubbedResponseError error: Error?, for request: URLRequest) {
StubbedURLProtocol.stubbedResponseError[request] = error
}
func set(stubbedData data: Data?, for request: URLRequest) {
StubbedURLProtocol.stubbedData[request] = data
}
func tearDown() {
StubbedURLProtocol.stubbedResponse.removeAll()
StubbedURLProtocol.stubbedResponseError.removeAll()
StubbedURLProtocol.stubbedData.removeAll()
}
}
| 28.2 | 79 | 0.712259 |
acdea81d6bd555415418af71761171432999779c | 7,072 | //
// CEFCommandLine.swift
// cef
//
// Created by Tamas Lustyik on 2015. 07. 12..
//
//
import Foundation
public extension CEFCommandLine {
/// Returns the singleton global CefCommandLine object. The returned object
/// will be read-only.
public static var globalCommandLine: CEFCommandLine? {
return CEFCommandLine(ptr: cef_command_line_get_global())
}
/// Create a new CefCommandLine instance.
public convenience init?() {
self.init(ptr: cef_command_line_create())
}
/// Returns true if this object is valid. Do not call any other methods if this
/// function returns false.
public var isValid: Bool {
return cefObject.is_valid(cefObjectPtr) != 0
}
/// Returns true if the values of this object are read-only. Some APIs may
/// expose read-only objects.
public var isReadOnly: Bool {
return cefObject.is_read_only(cefObjectPtr) != 0
}
/// Returns a writable copy of this object.
public func copy() -> CEFCommandLine? {
let copiedObj = cefObject.copy(cefObjectPtr)
return CEFCommandLine.fromCEF(copiedObj)
}
/// Initialize the command line with the specified |argc| and |argv| values.
/// The first argument must be the name of the program. This method is only
/// supported on non-Windows platforms.
public func initFromArguments(arguments: [String]) {
let argv = CEFArgVFromArguments(arguments)
cefObject.init_from_argv(cefObjectPtr, Int32(arguments.count), argv)
argv.dealloc(arguments.count)
}
/// Initialize the command line with the string returned by calling
/// GetCommandLineW(). This method is only supported on Windows.
public func initFromString(commandLine: String) {
let cefCmdLinePtr = CEFStringPtrCreateFromSwiftString(commandLine)
defer { CEFStringPtrRelease(cefCmdLinePtr) }
cefObject.init_from_string(cefObjectPtr, cefCmdLinePtr)
}
/// Reset the command-line switches and arguments but leave the program
/// component unchanged.
public func reset() {
cefObject.reset(cefObjectPtr)
}
/// Retrieve the original command line string as a vector of strings.
/// The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
public var argv: [String] {
var argv = [String]()
let cefList = cef_string_list_alloc()
defer { cef_string_list_free(cefList) }
cefObject.get_argv(cefObjectPtr, cefList)
let count = cef_string_list_size(cefList)
var cefStr = cef_string_t()
for i in 0..<count {
cef_string_list_value(cefList, i, &cefStr)
argv.append(CEFStringToSwiftString(cefStr))
}
return argv
}
/// Constructs and returns the represented command line string. Use this method
/// cautiously because quoting behavior is unclear.
public var stringValue: String {
let cefCmdLinePtr = cefObject.get_command_line_string(cefObjectPtr)
defer { CEFStringPtrRelease(cefCmdLinePtr) }
return CEFStringToSwiftString(cefCmdLinePtr.memory)
}
/// The program part of the command line string (the first item).
public var program: String {
get {
let cefProgramPtr = cefObject.get_program(cefObjectPtr)
defer { CEFStringPtrRelease(cefProgramPtr) }
return CEFStringToSwiftString(cefProgramPtr.memory)
}
set {
let cefProgramPtr = CEFStringPtrCreateFromSwiftString(newValue)
defer { CEFStringPtrRelease(cefProgramPtr) }
cefObject.set_program(cefObjectPtr, cefProgramPtr)
}
}
/// Returns true if the command line has switches.
public var hasSwitches: Bool {
return cefObject.has_switches(cefObjectPtr) != 0
}
/// Returns true if the command line contains the given switch.
public func hasSwitch(name: String) -> Bool {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(name)
defer { CEFStringPtrRelease(cefStrPtr) }
return cefObject.has_switch(cefObjectPtr, cefStrPtr) != 0
}
/// Returns the value associated with the given switch. If the switch has no
/// value or isn't present this method returns the empty string.
public func valueForSwitch(name: String) -> String {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(name)
let cefValuePtr = cefObject.get_switch_value(cefObjectPtr, cefStrPtr)
defer {
CEFStringPtrRelease(cefStrPtr)
CEFStringPtrRelease(cefValuePtr)
}
return cefValuePtr != nil ? CEFStringToSwiftString(cefValuePtr.memory) : ""
}
/// Returns the map of switch names and values. If a switch has no value an
/// empty string is returned.
public var allSwitches: [String: String] {
let cefMap = cef_string_map_alloc()
defer { cef_string_map_free(cefMap) }
cefObject.get_switches(cefObjectPtr, cefMap)
return CEFStringMapToSwiftDictionary(cefMap)
}
/// Add a switch to the end of the command line. If the switch has no value
/// pass an empty value string.
public func appendSwitch(name: String) {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(name)
defer { CEFStringPtrRelease(cefStrPtr) }
cefObject.append_switch(cefObjectPtr, cefStrPtr)
}
/// Add a switch with the specified value to the end of the command line.
public func appendSwitch(name: String, value: String) {
let cefNamePtr = CEFStringPtrCreateFromSwiftString(name)
let cefValuePtr = CEFStringPtrCreateFromSwiftString(value)
defer {
CEFStringPtrRelease(cefNamePtr)
CEFStringPtrRelease(cefValuePtr)
}
cefObject.append_switch_with_value(cefObjectPtr, cefNamePtr, cefValuePtr)
}
/// True if there are remaining command line arguments.
public var hasArguments: Bool {
return cefObject.has_arguments(cefObjectPtr) != 0
}
/// Get the remaining command line arguments.
public var arguments: [String] {
let cefList = cef_string_list_alloc()
defer { cef_string_list_free(cefList) }
cefObject.get_arguments(cefObjectPtr, cefList)
return CEFStringListToSwiftArray(cefList)
}
/// Add an argument to the end of the command line.
public func appendArgument(arg: String) {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(arg)
defer { CEFStringPtrRelease(cefStrPtr) }
cefObject.append_argument(cefObjectPtr, cefStrPtr)
}
/// Insert a command before the current command.
/// Common for debuggers, like "valgrind" or "gdb --args".
public func prependWrapper(wrapper: String) {
let cefStrPtr = CEFStringPtrCreateFromSwiftString(wrapper)
defer { CEFStringPtrRelease(cefStrPtr) }
cefObject.prepend_wrapper(cefObjectPtr, cefStrPtr)
}
}
| 37.417989 | 83 | 0.668411 |
872868dfee7caac232fe961815c8e2fd0579545a | 2,023 | //
// JSONFixtureFactory.swift
// DataFixture
//
// Created by Andrea Del Fante on 31/10/2020.
//
import Foundation
/// This protocol defines the rules to create a JSON Object from an object.
public protocol JSONFixtureFactory: FixtureFactory, JSONFixtureMaker {
/// The default JSON model definition.
func jsonDefinition() -> JSONFixtureDefinition<Model>
}
extension JSONFixtureFactory {
/// Create a new JSON model fixture definition.
/// - Parameters:
/// - modelDefinition: the model definition to use for the JSON definition.
/// - definition: the JSON definition closure.
/// - Returns: a new JSON model fixture definition.
public func defineJSON(
_ modelDefinition: FixtureDefinition<Model>? = nil,
_ JSONDefinition: @escaping (Model) -> [String: Any]
) -> JSONFixtureDefinition<Model> {
return JSONFixtureDefinition(
fixtureDefinition: modelDefinition ?? self.definition(),
JSONDefinition: JSONDefinition
)
}
/// Edit the default JSON fixture definition.
/// - Parameters:
/// - redefinition: the redefinition closure.
/// - Returns: a new JSON model fixture definition with the specified edits.
public func redefine(_ redefinition: @escaping (Model) -> Model) -> JSONFixtureDefinition<Model> {
return JSONFixtureDefinition(
fixtureDefinition: redefine(redefinition),
JSONDefinition: jsonDefinition().JSONDefinition
)
}
}
// MARK: - JSONFixtureMaker
extension JSONFixtureFactory {
public func makeJSON(_ number: Int) -> [[String : Any]] {
return jsonDefinition().makeJSON(number)
}
public func makeJSON<S>(from objects: S) -> [[String : Any]] where S : Sequence, Model == S.Element {
return jsonDefinition().makeJSON(from: objects)
}
public func makeWithJSON(_ number: Int) -> [(object: Model, JSON: [String : Any])] {
return jsonDefinition().makeWithJSON(number)
}
}
| 33.163934 | 105 | 0.661888 |
7506168df1b517f407a0464ff4176f7f38ba4459 | 2,283 | //
// ColorExtensions.swift
// ObjectManager
//
// Created by Sky Morey on 6/5/18.
// Copyright © 2018 Sky Morey. All rights reserved.
//
import CoreGraphics
public struct Color32 {
public var red: UInt8
public var green: UInt8
public var blue: UInt8
public var alpha: UInt8
init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
init(color: Color) {
guard let comp = color.components else {
fatalError("color must have componets")
}
// debugPrint("\(comp[0]) \(comp[1]) \(comp[2]) \(comp[3])")
let r = UInt8(comp[0].clamped() * 0xFF)
let g = UInt8(comp[1].clamped() * 0xFF)
let b = UInt8(comp[2].clamped() * 0xFF)
let a = UInt8(comp[3].clamped() * 0xFF)
self.init(red: r, green: g, blue: b, alpha: a)
}
public var toColor: Color {
let r = CGFloat(self.red / 0xFF)
let g = CGFloat(self.green / 0xFF)
let b = CGFloat(self.blue / 0xFF)
let a = CGFloat(self.alpha / 0xFF)
return Color(red: r, green: g, blue: b, alpha: a)
}
}
public extension Color {
public static func color(b565: UInt16) -> Color {
let r5 = (b565 >> 11) & 31
let g6 = (b565 >> 5) & 63
let b5 = b565 & 31
return Color(red: CGFloat(r5) / 31, green: CGFloat(g6) / 63, blue: CGFloat(b5) / 31, alpha: 1.0)
}
public static func lerp(_ a: Color, _ b: Color, fraction: Float) -> Color? {
let f = CGFloat(fraction.clamped())
//let f = min(max(0, fraction), 1)
guard let c1 = a.components, let c2 = b.components else { return nil }
let r = CGFloat(c1[0] + (c2[0] - c1[0]) * f)
let g = CGFloat(c1[1] + (c2[1] - c1[1]) * f)
let b = CGFloat(c1[2] + (c2[2] - c1[2]) * f)
let a = CGFloat(c1[3] + (c2[3] - c1[3]) * f)
return CGColor(red: r, green: g, blue: b, alpha: a)
//let r = a.red + (b.red - a.red) * f
//let g = a.green + (b.green - a.green) * f
//let b = a.blue + (b.blue - a.blue) * f
//let a = a.alpha + (b.alpha - a.alpha) * f
//return CGColor(red: r, green: g, blue: b, alpha: a)
}
}
| 33.573529 | 104 | 0.532194 |
71b700e6d1ea076e98db8f9ec1f8fc9c073ab6a5 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d<f{
struct Q<T{protocol c{
class A class A{let a:d
let h=b> {
| 26.555556 | 87 | 0.74477 |
209a2199d7b41a793e108659917b2448d2a7a296 | 7,304 | //
// Log.swift
//
// Copyright (c) 2020 Daniel Murfin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Cocoa
/**
Log Delegate
Required methods for objects implementing this delegate.
*/
protocol LogDelegate: AnyObject {
/**
Called when a new log message has been received.
- Parameters:
- message: The log message received.
*/
func newLogMessage(_ message: String)
/**
Called when logs have been cleared.
*/
func clearLogs()
}
// MARK: -
// MARK: -
/**
Log
Responsible for storage and notification of log messages.
*/
public final class Log {
/**
MessageType
Enumerates the types of log messages.
*/
enum MessageType {
/// Used for informational messages.
case info
/// Used for socket errors.
case socket
/// Used for unknown errors
case unknown
/// Used for layer errors in the protocol.
case protocolLayer
/// Used for sequence errors in the protocol.
case protocolSequence
/// Used for unknown errors in the protocol.
case protocolUnknown
/// Used for debug errors.
case debug
}
/// The serial dispatch queue used for creating log messages.
private static let queue = DispatchQueue(label: "com.danielmurfin.OTPAnalyzer.logQueue")
/// Attributes used for log messages when displayed to a user.
static let attributes = [NSAttributedString.Key.font : NSFont(name: "Monaco", size: 11.0)!, NSAttributedString.Key.foregroundColor : NSColor.labelColor]
/// The maximum total size for log messages before they are cleared.
static let maxSize = 5000
/// The delegate to be notified when changes to the logs occur.
weak var delegate: LogDelegate?
/// Whether errors should be logged.
var logErrors: Bool {
get { Self.queue.sync { _logErrors } }
set (newValue) { return Self.queue.sync { _logErrors = newValue } }
}
/// Whether errors should be logged (internal).
private var _logErrors: Bool = false
/// Whether debug errors should be logged.
var logDebug: Bool {
get { Self.queue.sync { _logDebug } }
set (newValue) { return Self.queue.sync { _logDebug = newValue } }
}
/// Whether debug errors should be logged (internal).
private var _logDebug: Bool = false
/// Whether debug socket errors should be logged.
var logDebugSocket: Bool {
get { Self.queue.sync { _logDebugSocket } }
set (newValue) { return Self.queue.sync { _logDebugSocket = newValue } }
}
/// Whether debug socket errors should be logged (internal).
private var _logDebugSocket: Bool = false
/**
Adds a new message of the type specified to the logs.
- Parameters:
- message: The message to be logged.
- type: The `MessageType` of the message.
*/
func add(message: String, ofType type: MessageType) {
switch type {
case .info:
break
case .unknown, .protocolLayer, .protocolSequence, .protocolUnknown:
guard logErrors else { return }
case .debug:
guard logDebug else { return }
case .socket:
guard logDebug && logDebugSocket else { return }
}
Self.queue.async {
// get the formatted date string
let dateString = Date().logDateFormatter()
// create a message string
var newMessage = "[\(dateString)] "
switch type {
case .info:
newMessage += "[Info] "
case .socket:
newMessage += "[Socket] "
case .unknown:
newMessage += "[Error] "
case .protocolLayer:
newMessage += "[Protocol Layer] "
case .protocolSequence:
newMessage += "[Protocol Sequence] "
case .protocolUnknown:
newMessage += "[Protocol Unknown] "
case .debug:
newMessage += "[Debug] "
}
newMessage += message + "\n"
// notify the delegate of the new message
self.delegate?.newLogMessage(newMessage)
}
}
/**
Resets the logs back to a clean state.
*/
func reset() {
// notify the delegate that logs have been cleared
Self.queue.async {
self.delegate?.clearLogs()
}
// add the app and version information
addVersion()
}
/**
Adds the app name and version to the logs.
*/
func addVersion() {
// get the current version number
guard let currentVersionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return }
// get the build number
guard let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as? String else { return }
add(message: "OTPAnalyzer " + currentVersionNumber + " Build " + buildNumber, ofType: .info)
// create a date formatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
// get the date formatted
let date = formatter.string(from: Date())
// add copyright information
add(message: "Copyright \(date) Daniel Murfin. All rights reserved.", ofType: .info)
}
}
// MARK: -
// MARK: -
/**
Date Extension
Extensions to `Date` for log messages.
*/
extension Date {
func logDateFormatter() -> String {
return DateFormatter.LogDateFormatter.string(from: self)
}
}
// MARK: -
// MARK: -
/**
Date Formatter Extension
Extensions to `DateFormatter` for log messages.
*/
extension DateFormatter {
fileprivate static let LogDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
}
| 27.458647 | 156 | 0.597755 |
28c8ced2bac781fc697e74ca60b90a2e7023307e | 3,780 | //
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class UniqueValueRendererViewController: UIViewController {
@IBOutlet var mapView:AGSMapView!
private var featureLayer:AGSFeatureLayer!
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["UniqueValueRendererViewController"]
//instantiate map with basemap
let map = AGSMap(basemap: AGSBasemap.topographic())
//create feature layer
let featureTable = AGSServiceFeatureTable(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3")!)
self.featureLayer = AGSFeatureLayer(featureTable: featureTable)
//add the layer to the map as operational layer
map.operationalLayers.add(self.featureLayer)
//assign map to the map view
self.mapView.map = map
//set initial viewpoint
let center = AGSPoint(x: -12966000.5, y: 4441498.5, spatialReference: AGSSpatialReference.webMercator())
self.mapView.setViewpoint(AGSViewpoint(center: center, scale: 4e7))
//add unique value renderer
self.addUniqueValueRenderer()
}
private func addUniqueValueRenderer() {
//instantiate a new unique value renderer
let renderer = AGSUniqueValueRenderer()
//set the field to use for the unique values
//You can add multiple fields to be used for the renderer in the form of a list, in this case we are only adding a single field
renderer.fieldNames = ["STATE_ABBR"]
//create symbols to be used in the renderer
let defaultSymbol = AGSSimpleFillSymbol(style: .null, color: .clear, outline: AGSSimpleLineSymbol(style: .solid, color: .gray, width: 2))
let californiaSymbol = AGSSimpleFillSymbol(style: .solid, color: .red, outline: AGSSimpleLineSymbol(style: .solid, color: .red, width: 2))
let arizonaSymbol = AGSSimpleFillSymbol(style: .solid, color: .green, outline: AGSSimpleLineSymbol(style: .solid, color: .green, width: 2))
let nevadaSymbol = AGSSimpleFillSymbol(style: .solid, color: .blue, outline: AGSSimpleLineSymbol(style: .solid, color: .blue, width: 2))
//set the default symbol
renderer.defaultSymbol = defaultSymbol
renderer.defaultLabel = "Other"
//create unique values
let californiaValue = AGSUniqueValue(description: "State of California", label: "California", symbol: californiaSymbol, values: ["CA"])
let arizonaValue = AGSUniqueValue(description: "State of Arizona", label: "Arizona", symbol: arizonaSymbol, values: ["AZ"])
let nevadaValue = AGSUniqueValue(description: "State of Nevada", label: "Nevada", symbol: nevadaSymbol, values: ["NV"])
//add the values to the renderer
renderer.uniqueValues.append(contentsOf: [californiaValue, arizonaValue, nevadaValue])
//assign the renderer to the feature layer
self.featureLayer.renderer = renderer
}
}
| 46.097561 | 150 | 0.688889 |
2ff8b221fab8a6ab6e421647ecaa3fceddfa7413 | 1,530 | //
// MarginAdjustable.swift
// SwiftMessages
//
// Created by Timothy Moose on 8/5/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
/*
Message views that implement the `MarginAdjustable` protocol will have their
`layoutMargins` adjusted by SwiftMessages to account for the height of the
status bar (when displayed under the status bar) and a small amount of
overshoot in the bounce animation. `MessageView` implements this protocol
by way of its parent class `BaseMessageView`.
For the effect of this protocol to work, subviews should be pinned to the
message view's margins and the `layoutMargins` property should not be modified.
This protocol is optional. A message view that doesn't implement `MarginAdjustable`
is responsible for setting is own internal margins appropriately.
*/
public protocol MarginAdjustable {
/// The amount to add to the safe area insets in calculating
/// the layout margins.
var layoutMarginAdditions: UIEdgeInsets { get }
/// When `true`, SwiftMessages automatically collapses layout margin additions (topLayoutMarginAddition, etc.)
/// when the default layout margins are greater than zero. This is typically used when a margin addition is only
/// needed when the safe area inset is zero for a given edge. When the safe area inset for a given edge is non-zero,
/// the additional margin is not added.
var collapseLayoutMarginAdditions: Bool { get set }
var bounceAnimationOffset: CGFloat { get set }
}
| 39.230769 | 120 | 0.754902 |
266f4bf18ebbf0bc6b5704ca5b6e1c89793e2e38 | 1,523 | //
// DefaultsTests.swift
// CopyPasteTests
//
// Created by Garric Nahapetian on 1/26/18.
// Copyright © 2018 SwiftCoders. All rights reserved.
//
@testable import CopyPaste
import XCTest
class DefaultsTests: BaseTestCase {
private var subject: DataContext<Defaults>!
override func setUp() {
super.setUp()
let name = Globals.EnvironmentVariables.defaults
subject = DataContext<Defaults>.init(initialValue: .init(), store: DataStore.init(name: name))
subject.reset()
}
func testFoo() {
XCTAssertEqual(subject.data.showWelcome, true)
subject.save(Defaults(showWelcome: false))
XCTAssertEqual(subject.data.showWelcome, false)
}
func test_Defaults_Init() {
let defaults = Defaults()
XCTAssertTrue(defaults.showWelcome)
}
func test_Defaults_Init_With_Value() {
let defaults = Defaults(showWelcome: false)
XCTAssertFalse(defaults.showWelcome)
}
func test_DefaultsContext_Init() {
XCTAssertTrue(subject.data.showWelcome)
}
func test_Save() {
XCTAssertTrue(subject.data.showWelcome)
subject.save(Defaults(showWelcome: false))
XCTAssertFalse(subject.data.showWelcome)
}
func test_Reset() {
XCTAssertTrue(subject.data.showWelcome)
subject.save(Defaults(showWelcome: false))
XCTAssertFalse(subject.data.showWelcome)
subject.reset()
XCTAssertTrue(subject.data.showWelcome)
}
}
| 25.383333 | 102 | 0.663165 |
72e75b5ca03fcbea77399a5324bd0a48e74f9633 | 1,677 | //
// EditView-ViewModel.swift
// BucketList
//
// Created by Matt X on 3/6/22.
//
import Foundation
extension EditView {
@MainActor class ViewModel: ObservableObject {
enum LoadingState {
case loading, loaded, failed
}
var location: Location
@Published var name: String
@Published var description: String
@Published var loadingState: LoadingState = .loading
@Published var pages = [Page]()
init(location: Location) {
self.location = location
_name = Published(initialValue: location.name)
_description = Published(initialValue: location.description)
}
func fetchNearbyPlaces() async {
let urlString = "https://en.wikipedia.org/w/api.php?ggscoord=\(location.coordinate.latitude)%7C\(location.coordinate.longitude)&action=query&prop=coordinates%7Cpageimages%7Cpageterms&colimit=50&piprop=thumbnail&pithumbsize=500&pilimit=50&wbptterms=description&generator=geosearch&ggsradius=10000&ggslimit=50&format=json"
guard let url = URL(string: urlString) else {
print("Bad URL: \(urlString)")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
let items = try JSONDecoder().decode(Result.self, from: data)
pages = items.query.pages.values.sorted()
loadingState = .loaded
} catch {
loadingState = .failed
}
}
}
}
| 32.25 | 332 | 0.563506 |
e257d6c72224c1581a0c21ea8a54511fcc7ecef0 | 918 | //
// TimelineDraggingSession.swift
// TogglDesktop
//
// Created by Nghia Tran on 2/10/20.
// Copyright © 2020 Alari. All rights reserved.
//
import Foundation
struct TimelineDraggingSession {
// Selected indexpath for dragging item
var indexPath: IndexPath?
// The distance between the mouse and the Top of the TimeEntry pill
var mouseDistanceFromTop: Double?
// Start Time after dragging
private(set) var finalStartTime: TimeInterval?
private(set) var item: TimelineTimeEntry?
// Determine if the user is dragging
var isDragging: Bool {
return indexPath != nil
}
mutating func reset() {
indexPath = nil
mouseDistanceFromTop = nil
finalStartTime = nil
item = nil
}
mutating func acceptDrop(at time: TimeInterval, for timeEntry: TimelineTimeEntry) {
finalStartTime = time
item = timeEntry
}
}
| 22.95 | 87 | 0.668845 |
e03f6854ae8aee4e803294193f1e968a8b9865a2 | 977 | //
// UIImageDemoTests.swift
// UIImageDemoTests
//
// Created by apollo on 2016/11/18.
// Copyright © 2016年 projm. All rights reserved.
//
import XCTest
@testable import UIImageDemo
class UIImageDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.405405 | 111 | 0.636643 |
1ea04fb75505060bc787b09e333b6dfb23e07c7d | 2,036 | //
// AppListVC+elastic.swift
// App Love
//
// Created by Woodie Dovich on 2016-08-18.
// Copyright © 2016 Snowpunch. All rights reserved.
//
import Foundation
import ElasticTransition
// elastic extensions
extension AppListVC {
func initElasticTransitions(){
transition.stiffness = 0.7
transition.damping = 0.40
transition.stiffness = 1
transition.damping = 0.75
transition.transformType = .TranslateMid
}
func displayElasticOptions(viewControlerId:String) {
if let storyboard = self.storyboard {
let aboutVC = storyboard.instantiateViewControllerWithIdentifier(viewControlerId)
aboutVC.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
transition.edge = .Bottom
transition.startingPoint = CGPoint(x:30,y:70)
transition.stiffness = 1
transition.damping = 0.75
transition.showShadow = true
transition.transformType = .Rotate
aboutVC.transitioningDelegate = transition
aboutVC.modalPresentationStyle = .Custom
presentViewController(aboutVC, animated: true, completion: nil)
}
}
func elasticPresentViewController(storyBoardID:String) {
if let storyboard = self.storyboard {
let aboutVC = storyboard.instantiateViewControllerWithIdentifier(storyBoardID)
transition.edge = .Right
transition.startingPoint = CGPoint(x:30,y:70)
transition.stiffness = 1
transition.damping = 0.75
aboutVC.transitioningDelegate = transition
aboutVC.modalPresentationStyle = .Custom
presentViewController(aboutVC, animated: true, completion: nil)
}
}
func openElasticMenu() {
transition.edge = .Left
transition.startingPoint = CGPoint(x:30,y:70)
transition.showShadow = false
transition.transformType = .TranslateMid
performSegueWithIdentifier("menu", sender: self)
}
} | 34.508475 | 93 | 0.660118 |
5026f4041ec6e1d28c6dd16c82eb90cf4bbfcbda | 969 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Cyllene open source project
//
// Copyright (c) 2017 Chris Daley
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See http://www.apache.org/licenses/LICENSE-2.0 for license information
//
//===----------------------------------------------------------------------===//
typealias LogFunction = (String, CVaListPointer...) -> Int
final class Log {
static let sharedInstance = Log()
var logHandler: LogFunction?
var continueHandler: LogFunction?
private init() {}
func set_handler(log: @escaping LogFunction, cont: @escaping LogFunction) {
self.logHandler = log
self.continueHandler = cont
}
/*
func vlog(fmt:String, _ ap:CVarArg...) -> Int {
return withVaList(ap) {
logHandler(fmt, $0)
}
}*/
}
| 21.533333 | 80 | 0.555212 |
1a099d188ef9f1cee4e42a0094facd2bfa3167d2 | 2,054 | //
// IndicatorLayer.swift
// GeigerCounter
//
// Created by Pablo Caif on 11/2/18.
// Copyright © 2018 Pablo Caif. All rights reserved.
//
import UIKit
public class IndicatorLayer: CALayer {
var maxValue: CGFloat = 100.0
@objc var value: CGFloat = 0.0
@objc var indicatorColor = UIColor.green.cgColor
var greenLevel: CGFloat = 25
var orangeLevel: CGFloat = 65
public override class func needsDisplay(forKey key: String) -> Bool {
if key == "value" {
return true
}
return CALayer.needsDisplay(forKey: key)
}
public override func draw(in ctx: CGContext) {
ctx.setShouldAntialias(true)
let center = CGPoint(x: bounds.size.width / 2.0, y: bounds.size.height / 2.0)
let radius = frame.size.height / 2.0 * 0.94
let color = indicatorColor
//Lower left border
ctx.setStrokeColor(color)
ctx.setLineWidth(2.0)
ctx.move(to: center)
ctx.addLine(to: CGPoint(x: center.x - (bounds.size.width * 0.48), y: center.y))
//Arc
let angle = calculateAngle(for: value, maxValue: maxValue)
ctx.addArc(center: center, radius: radius, startAngle: CGFloat.pi, endAngle: angle, clockwise: false)
//Closing area
ctx.addLine(to: center)
ctx.setFillColor(color)
ctx.closePath()
ctx.fillPath()
ctx.strokePath()
let radialPoint = calculateRadialCoordinate(forAngle: angle, center: center, radius: radius * 0.94)
ctx.move(to: center)
ctx.addLine(to: radialPoint)
ctx.setLineWidth(5.0)
ctx.setStrokeColor(UIColor.white.cgColor)
ctx.setLineCap(CGLineCap.round)
ctx.strokePath()
}
public func colorForValue(_ value: CGFloat) -> CGColor {
if value <= greenLevel {
return UIColor.green.cgColor
} else if value > greenLevel && value <= orangeLevel {
return UIColor.orange.cgColor
}
return UIColor.red.cgColor
}
}
| 29.768116 | 109 | 0.61149 |
e2f470a78d607b52df9662fd7dd3860304dea7f9 | 1,478 | //
// RyeView.swift
// RyeExample
//
// Created by Andrei Hogea on 12/06/2019.
// Copyright © 2019 Nodes. All rights reserved.
//
import UIKit
class RyeView: UIView {
private var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
layer.cornerRadius = 25
backgroundColor = UIColor.red.withAlphaComponent(0.4)
makeMessageLabel(with: "An error occured",
font: UIFont.systemFont(ofSize: 16, weight: .semibold),
textColor: .white)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
// MARK: - Make Subview
private func makeMessageLabel(with text: String, font: UIFont, textColor: UIColor) {
label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.text = text
label.font = font
label.textColor = textColor
addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: topAnchor, constant: 16).isActive = true
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
}
}
| 28.980392 | 95 | 0.620433 |
298bdb184c34e3184d565139914fd151be247967 | 3,616 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public struct ConstraintViewDSL: ConstraintAttributesDSL {
@discardableResult
public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(item: self.view, closure: closure)
}
public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}
public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.remakeConstraints(item: self.view, closure: closure)
}
public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.updateConstraints(item: self.view, closure: closure)
}
public func removeConstraints() {
ConstraintMaker.removeConstraints(item: self.view)
}
public var contentHuggingHorizontalPriority: Float {
get {
return self.view.contentHuggingPriority(for: .horizontal).rawValue
}
set {
self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .horizontal)
}
}
public var contentHuggingVerticalPriority: Float {
get {
return self.view.contentHuggingPriority(for: .vertical).rawValue
}
set {
self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .vertical)
}
}
public var contentCompressionResistanceHorizontalPriority: Float {
get {
return self.view.contentCompressionResistancePriority(for: .horizontal).rawValue
}
set {
self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .horizontal)
}
}
public var contentCompressionResistanceVerticalPriority: Float {
get {
return self.view.contentCompressionResistancePriority(for: .vertical).rawValue
}
set {
self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .vertical)
}
}
public var target: AnyObject? {
return self.view
}
internal let view: ConstraintView
internal init(view: ConstraintView) {
self.view = view
}
}
| 35.45098 | 115 | 0.684181 |
c1dfa80823192ee02a63368bef781b73760cee2c | 3,043 | //
// FlatPageControl.swift
// FlatPageControl
//
// Created by Александр Чаусов on 02.10.2018.
// Copyright © 2018 Surf. All rights reserved.
//
import UIKit
/// Custom page control with a limited number of visible indicators
public class FlatPageControl: UIControl {
// MARK: - ColorConstants
private struct ColorConstants {
static let defaultPageIndicatorTintColor = UIColor.white.withAlphaComponent(0.2)
static let defaultCurrentPageIndicatorTintColor = UIColor.white
static let defaultExtraPageIndicatorTintColor = UIColor.white.withAlphaComponent(0.1)
}
// MARK: - IBOutlets
@IBOutlet var containerView: UIView!
// MARK: - Public Properties
public var view: UIView! {
return subviews.first
}
public var maxPagesNumber: Int = 16
public var numberOfPages: Int = 1 {
didSet {
layoutSubviews()
}
}
public var hidesForSinglePage: Bool = true {
didSet {
layoutSubviews()
}
}
public var pageIndicatorTintColor: UIColor = ColorConstants.defaultPageIndicatorTintColor {
didSet {
updatePageIndicatorsColor()
}
}
public var currentPageIndicatorTintColor: UIColor = ColorConstants.defaultCurrentPageIndicatorTintColor {
didSet {
updatePageIndicatorsColor()
}
}
public var extraPageIndicatorTintColor: UIColor = ColorConstants.defaultExtraPageIndicatorTintColor {
didSet {
updatePageIndicatorsColor()
}
}
// MARK: - Internal Properties
var viewsPool: ViewsPool = ViewsPool()
var currentPageIndicators: [FlatPageIndicator] = []
var offset: Int = 0
var currentPage: Int = 0
// MARK: - UIControl
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupControl()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupControl()
}
override public func layoutSubviews() {
super.layoutSubviews()
layoutPageIndicators()
updatePageIndicatorsColor()
}
// MARK: - Public Methods
/**
Method allows you to set the current page index and pass "animated" flag
- Note: it is recommended to set the current page with the animation only if the user changes the number of the visible page manually, without animation in other case (for example, on view setup)
*/
public func setCurrentPage(_ currentPage: Int, animated: Bool) {
guard currentPage < numberOfPages else {
return
}
if self.currentPage != currentPage {
let oldCurrentPage = self.currentPage
self.currentPage = currentPage
if animated && abs(currentPage - oldCurrentPage) == 1 {
refreshCurrentPageIndicator(oldCurrentPage: oldCurrentPage)
} else {
refreshOffset()
layoutSubviews()
}
}
}
}
| 28.707547 | 200 | 0.632271 |
f7c36bb540e6a1b4ccf6b95762bee8d454467758 | 4,143 | //
// String+File.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
public enum FileError: Error {
case error(Int32)
}
public class File {
internal let pointer: UnsafeMutablePointer<FILE>
public init(_ pointer: UnsafeMutablePointer<FILE>) {
self.pointer = pointer
}
public func close() -> Void {
fclose(pointer)
}
public func read(_ data: inout [UInt8]) throws -> Int {
if data.count <= 0 {
return data.count
}
let count = fread(&data, 1, data.count, self.pointer)
if count == data.count {
return count
}
if feof(self.pointer) != 0 {
return count
}
if ferror(self.pointer) != 0 {
throw FileError.error(errno)
}
throw FileError.error(0)
}
public func write(_ data: [UInt8]) throws -> Void {
if data.count <= 0 {
return
}
try data.withUnsafeBufferPointer {
if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
throw FileError.error(errno)
}
}
}
}
public static var PATH_SEPARATOR = "/"
public func openNewForWriting() throws -> File {
return try openFileForMode(self, "wb")
}
public func openForReading() throws -> File {
return try openFileForMode(self, "rb")
}
public func openForWritingAndReading() throws -> File {
return try openFileForMode(self, "r+b")
}
public func openFileForMode(_ path: String, _ mode: String) throws -> File {
guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
throw FileError.error(errno)
}
return File(file)
}
public func exists() throws -> Bool {
return try self.withStat {
if let _ = $0 {
return true
}
return false
}
}
public func directory() throws -> Bool {
return try self.withStat {
if let stat = $0 {
return stat.st_mode & S_IFMT == S_IFDIR
}
return false
}
}
public func files() throws -> [String] {
guard let dir = self.withCString({ opendir($0) }) else {
throw FileError.error(errno)
}
defer { closedir(dir) }
var results = [String]()
while let ent = readdir(dir) {
var name = ent.pointee.d_name
let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
#if os(Linux)
return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: 256)))
#else
var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, to: UnsafePointer<CChar>.self), count: Int(ent.pointee.d_namlen)))
buffer.append(0)
return String(validatingUTF8: buffer)
#endif
}
if let fileName = fileName {
results.append(fileName)
}
}
return results
}
public static func currentWorkingDirectory() throws -> String {
guard let path = getcwd(nil, 0) else {
throw FileError.error(errno)
}
return String(cString: path)
}
private func withStat<T>(_ closure: ((stat?) throws -> T)) throws -> T {
return try self.withCString({
var statBuffer = stat()
if stat($0, &statBuffer) == 0 {
return try closure(statBuffer)
}
if errno == ENOENT {
return try closure(nil)
}
throw FileError.error(errno)
})
}
}
| 29.592857 | 163 | 0.508327 |
76212e03df88ade7b821462b719b72ddc44d5a29 | 4,113 | //
// CollectionViewController.swift
// PhotoMap
//
// Created by Ivan Chen on 8/24/17.
//
//
import UIKit
class AlbumViewController: UIViewController
{
@IBOutlet weak var collectionView: UICollectionView!
fileprivate let reuseIdentifier = "cell"
fileprivate let sectionInsets = UIEdgeInsets(top: 20.0, left: 0.0, bottom: 20.0, right: 0.0)
fileprivate let itemsPerRow: CGFloat = 1
fileprivate var snapData: [SnapData] = []
weak var snapDataRepositoryDelegate: SnapDataRepository?
override func viewDidLoad()
{
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
collectionView.refreshControl = refreshControl
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadData()
}
private func reloadData()
{
guard let snapData = snapDataRepositoryDelegate?.getSnapData() else
{
return
}
self.snapData = snapData
collectionView.reloadData()
}
@objc
fileprivate func deleteCell(sender: UISwipeGestureRecognizer)
{
let cell = sender.view as? UICollectionViewCell ?? UICollectionViewCell()
let snap = snapData[snapData.count - (collectionView.indexPath(for: cell)!.row + 1)]
snapDataRepositoryDelegate?.removeSnap(snap: snap)
reloadData()
showToast(message: "Snap Deleted")
}
@objc
fileprivate func refresh(sender: UIRefreshControl)
{
reloadData()
sender.endRefreshing()
}
}
// MARK: - UICollectionViewDataSource
extension AlbumViewController: UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return snapData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? AlbumCardCell ?? AlbumCardCell()
let snap = snapData[snapData.count - (indexPath.item + 1)]
let imageAsData = snap.image as Data? ?? Data()
cell.cardData = (snap.address, UIImage(data: imageAsData, scale: 1.0)) as? (label: String, image: UIImage)
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(deleteCell))
swipeGesture.direction = UISwipeGestureRecognizerDirection.right
cell.addGestureRecognizer(swipeGesture)
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension AlbumViewController: UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath)
-> CGSize
{
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: 130)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int)
-> UIEdgeInsets
{
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int)
-> CGFloat
{
return 5.0
}
}
// MARK: - UICollectionViewDelegate
extension AlbumViewController: UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
| 32.132813 | 144 | 0.67858 |
8fb1a19aa096827eb30365bbc50f684686d36fb5 | 687 | //
// Created by Jake Lin on 12/25/15.
// Copyright © 2015 CBIban. All rights reserved.
//
import UIKit
public protocol RootWindowDesignable: class {
/**
Root window background color
*/
var rootWindowBackgroundColor: UIColor? { get set }
}
public extension RootWindowDesignable where Self: UIViewController {
public func configureRootWindowBackgroundColor() {
#if NS_EXTENSION_UNAVAILABLE_IOS
if let rootWindowBackgroundColor = rootWindowBackgroundColor,
let delegate = UIApplication.sharedApplication().delegate,
let rootWindow = delegate.window {
rootWindow?.backgroundColor = rootWindowBackgroundColor
}
#endif
}
}
| 22.9 | 68 | 0.72198 |
fbfc5ba684bb92910a0cba675cbe04998bda195b | 3,154 | //
// DevelopersTableViewCell.swift
// Revels-20
//
// Created by Rohit Kuber on 30/10/20.
// Copyright © 2020 Naman Jain. All rights reserved.
//
import UIKit
class DevelopersTableViewCell: UITableViewCell {
var homeViewController: HomeViewController?
lazy var developersButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(UIImage(named: "developer")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.contentMode = .scaleAspectFit
button.imageView?.contentMode = .scaleAspectFit
button.tintColor = .lightGray
button.backgroundColor = UIColor.CustomColors.Black.card
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(showDevelopersPage), for: .touchUpInside)
return button
}()
@objc func showDevelopersPage(){
self.homeViewController?.showDeveloper()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
addSubview(developersButton)
developersButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
_ = developersButton.anchor(top: topAnchor, left: nil, bottom: bottomAnchor, right: nil, topConstant: 16, leftConstant: 0, bottomConstant: 8, rightConstant: 0, widthConstant: 0, heightConstant: 0)
developersButton.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.45).isActive = true
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 14)
titleLabel.numberOfLines = 0
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.textColor = .white
titleLabel.textAlignment = .center
titleLabel.text = "Developers"
if UIViewController().isSmalliPhone(){
titleLabel.font = UIFont.boldSystemFont(ofSize: 10)
developersButton.addSubview(titleLabel)
_ = titleLabel.anchor(top: nil, left: developersButton.leftAnchor, bottom: developersButton.bottomAnchor, right: developersButton.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 4, rightConstant: 0, widthConstant: 0, heightConstant: 14)
developersButton.imageEdgeInsets = .init(top: 8, left: 0, bottom: 18, right: 0)
}else{
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
developersButton.addSubview(titleLabel)
_ = titleLabel.anchor(top: nil, left: developersButton.leftAnchor, bottom: developersButton.bottomAnchor, right: developersButton.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 8, rightConstant: 0, widthConstant: 0, heightConstant: 16)
developersButton.imageEdgeInsets = .init(top: 16, left: 0, bottom: 32, right: 0)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 38.938272 | 262 | 0.662651 |
5dcd5949e4c650f9737c8289440458901eeb6c3c | 2,978 | //
// CharacterDetailsViewController.swift
// MarvelAppIOS
//
// Created by Guilherme Silva on 07/08/21.
//
import UIKit
class CharacterDetailsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var favoriteBarButton: UIBarButtonItem!
var character: Character!
private var viewModel: CharacterDetailViewModel!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: CharacterDetailCell.IDENTIFIER, bundle: nil), forCellReuseIdentifier: CharacterDetailCell.IDENTIFIER)
self.tableView.register(UINib(nibName: CharacterAppearencesCell.IDENTIFIER, bundle: nil), forCellReuseIdentifier: CharacterAppearencesCell.IDENTIFIER)
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 200.0
self.viewModel = CharacterDetailViewModel(character: self.character)
setupFavoriteButton()
NotificationCenter.default.addObserver(self, selector: #selector(favoriteCharacterChanged(_:)), name: .favoriteCharacter, object: nil)
}
private func setupFavoriteButton() {
let icon = self.viewModel.isFavorite ? UIImage(systemName: "star.fill") : UIImage(systemName: "star")
let favoriteButton = UIBarButtonItem(image: icon, style: .plain, target: self, action: #selector(onFavoriteClicked))
self.navigationItem.rightBarButtonItem = favoriteButton
}
@objc func favoriteCharacterChanged(_ notification: Notification) {
setupFavoriteButton()
}
@objc func onFavoriteClicked(){
self.viewModel.saveFavorite()
}
}
extension CharacterDetailsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
if indexPath.row == 0 {
let itemCell = tableView.dequeueReusableCell(withIdentifier: CharacterDetailCell.IDENTIFIER, for: indexPath) as! CharacterDetailCell
itemCell.fillCell(character: character)
cell = itemCell
}
else {
let itemCell = tableView.dequeueReusableCell(withIdentifier: CharacterAppearencesCell.IDENTIFIER, for: indexPath) as! CharacterAppearencesCell
itemCell.fillCell(character: character)
cell = itemCell
}
return cell!
}
}
extension CharacterDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
}
| 35.452381 | 158 | 0.704835 |
21dec5f8c9b56db0efeeea9ca4a20b2a5d555dfb | 2,062 | //
// CertificateListTests.swift
//
//
// Created by Thomas Kuleßa on 23.02.22.
//
@testable import CovPassCommon
import Foundation
import XCTest
class CertificateListTests: XCTestCase {
func testCertificatePairs_empty() {
// Given
let sut = CertificateList(certificates: [])
// When
let pairs = sut.certificatePairs
// Then
XCTAssertTrue(pairs.isEmpty)
}
func testCertificatePairs_same() {
// Given
let certificates: [ExtendedCBORWebToken] = [
CBORWebToken.mockVaccinationCertificate.extended(),
CBORWebToken.mockTestCertificate.extended(),
CBORWebToken.mockRecoveryCertificate.extended(),
]
let sut = CertificateList(certificates: certificates)
// When
let pairs = sut.certificatePairs
// Then
XCTAssertEqual(pairs.count, 1)
}
func testCertificatePairs_different() {
// Given
let certificates: [ExtendedCBORWebToken] = [
CBORWebToken.mockVaccinationCertificate.extended(),
CBORWebToken.mockVaccinationCertificateWithOtherName.extended()
]
let sut = CertificateList(certificates: certificates)
// When
let pairs = sut.certificatePairs
// Then
XCTAssertEqual(pairs.count, 2)
}
func testNumberOfPersons() {
// Given
let certificates: [ExtendedCBORWebToken] = [
CBORWebToken.mockVaccinationCertificate.extended(),
CBORWebToken.mockVaccinationCertificate.extended(),
CBORWebToken.mockTestCertificate.extended(),
CBORWebToken.mockRecoveryCertificate.extended(),
CBORWebToken.mockVaccinationCertificateWithOtherName.extended(),
CBORWebToken.mockVaccinationCertificateWithOtherName.extended()
]
let sut = CertificateList(certificates: certificates)
// When
let numberOfPersons = sut.numberOfPersons
// Then
XCTAssertEqual(numberOfPersons, 2)
}
}
| 27.493333 | 76 | 0.645975 |
d708ee6a3e58508d2e4920816eee3f384b76b8cd | 1,109 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// ---- 闭包 Closures ----
/*
闭包是自包含的函数代码块,与Objective-C中的Blocks比较相似
闭包三种形式:
*全局函数是一个有名字但不会捕获任何值的闭包
*嵌套函数是一个有名字并可以捕获其封闭函数域内值得闭包
*闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值得匿名闭包
闭包语法优化:
*利用上下文推断参数和返回值类型
*隐式返回单表达式闭包,即单表达式闭包可以省略return关键字
*参数名称缩写
*尾随(Trailing)闭包语法
*/
// -- 闭包表达式 Closure Expressions
// -- sort 方法 The Sort Method
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
var reversed = names.sort(backwards) // sort(_:)方法可接受一个闭包作为参数以决定如何排序
// -- 闭包表达式语法 Closure Expression Syntax
/*
闭包表达式语法有如下一般形式:
{ (parameters) -> returnType in
statements
}
闭包表达式语法可以使用常量、变量和inout类型作为参数,不能提供默认值,也可以在参数列表的最后使用可变参数,元组也可以作为参数和返回值
*/
reversed = names.sort({ (s1: String, s2: String) -> Bool in
return s1 > s2
}) // backwards(_:_:)函数对应的闭包表达式版本代码
reversed = names.sort( { (s1: String, s2: String) -> Bool in return s1 > s2 } )
// -- 根据上下文推断类型 Inferring Type From Context | 18.79661 | 79 | 0.671776 |
e90174f4ec0b59e01a6da29acc7193ea83166af7 | 4,313 | //
// ViewController.swift
// WebViewScreenShot
//
// Created by Zmsky on 15/11/9.
// Copyright © 2015年 http://xloli.net . All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
var resultImage : UIImage!;
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.
}
func screenShot() -> UIImage{
UIGraphicsBeginImageContext(self.webView.bounds.size);
self.webView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let resultingImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return resultingImage
}
func addImage(image1:UIImage!,image2:UIImage!) -> UIImage{
let size = CGSizeMake(image2.size.width , image1.size.height + image2.size.height)
UIGraphicsBeginImageContext(size)
UIGraphicsGetCurrentContext()
// Draw iamge1
image1.drawInRect(CGRectMake(0, 0, image1.size.width, image1.size.height))
// Draw image2
image2.drawInRect(CGRectMake(0, image1.size.height, image2.size.width, image2.size.height))
let resultingImage : UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultingImage
}
func getSubImage(image:CGImageRef,rect:CGRect) -> UIImage{
let subImageRef = CGImageCreateWithImageInRect(image, rect)
let smallBounds = CGRectMake(0, 0, CGFloat(CGImageGetWidth(subImageRef)), CGFloat(CGImageGetHeight(subImageRef)))
UIGraphicsBeginImageContext(smallBounds.size)
let context = UIGraphicsGetCurrentContext()
CGContextDrawImage(context, smallBounds,subImageRef)
let smallImage = UIImage(CGImage: subImageRef!)
UIGraphicsEndImageContext()
return smallImage;
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let nextViewController = segue.destinationViewController as! ResultViewController
nextViewController.image = self.resultImage;
}
@IBAction func screenShotAction(sender: AnyObject) {
let viewHeight = Int(self.webView.bounds.size.height);
let pageHeight = Int(self.webView.scrollView.contentSize.height);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
var current = 0
let totalCount = Int(pageHeight / viewHeight) + 1
var screenShotImage : UIImage!
for(current = 0 ; current < totalCount ; current++ ){
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let y = current * viewHeight
self.webView.scrollView.setContentOffset(CGPoint(x: 0, y: y), animated: false)
})
NSThread.sleepForTimeInterval(0.3)
let image = self.screenShot()
if current == 0 {
screenShotImage = UIImage(CGImage:image.CGImage!)
continue
}else{
screenShotImage = self.addImage(screenShotImage, image2: image)
}
}
print(screenShotImage)
self.resultImage = self.getSubImage(screenShotImage.CGImage!, rect: CGRectMake(0,0,self.webView.frame.size.width,CGFloat(pageHeight)))//screenShotImage;
self.performSegueWithIdentifier("ShowResult", sender: screenShotImage)
}
}
@IBAction func openPageAction(sender: AnyObject) {
let url = NSURL(string:"http://xloli.net/comments")
let request = NSURLRequest(URL: url!)
self.webView.loadRequest(request)
}
}
| 32.428571 | 164 | 0.600974 |
726a874a881bd39cf37ea0176c1948a5ac0a2fac | 427 | import XCTest
@testable import TBEmptyDataSet
final class TBEmptyDataSetTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(TBEmptyDataSet().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 26.6875 | 87 | 0.662763 |
207712e18a1ca8577648c88c14f1616c1005b566 | 882 | //
// Intersection.swift
// Minigames
//
// Created by Tomer Israeli on 04/06/2021.
//
import Foundation
struct Intersection: BoardPosition {
var tile: Tile
var tileCorner: TileCorner
init(on tile: Tile, at corner: TileCorner, isHarbor: Bool = false) {
self.tile = tile
self.tileCorner = corner
}
}
extension Intersection: Hashable, Equatable {
// find the intersection relative position to middle tile of the board
// assuming the radius ot the blocking circle of the hexagon is 1
func boardPosition() -> SIMD2<Float> {
tile.boardPosition() + self.tileCorner.vector
}
static func == (lhs: Intersection, rhs: Intersection) -> Bool {
lhs.boardPosition() == rhs.boardPosition()
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.boardPosition())
}
}
| 23.210526 | 74 | 0.639456 |
e2f4781ab7bb7297fb266def5845245a703ab827 | 698 | //
// secondViewController.swift
// navegation
//
// Created by Douglas Nunes on 15/03/22.
//
import UIKit
class secondViewController: UIViewController {
var property: Data?
override func viewDidLoad() {
super.viewDidLoad()
if let property = property {
print("property: \(property.name)")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 19.942857 | 106 | 0.648997 |
222fbbaaf4f0df65a3bb5405a139217c1414ee74 | 1,050 | //
// ResultSet.swift
// SyntaxKit
//
// Stores a set of results generated by the parser.
//
// Created by Sam Soffes on 10/11/14.
// Copyright © 2014-2015 Sam Soffes. All rights reserved.
//
import Foundation
internal class ResultSet {
// MARK: - Properties
var results: [Result] { return _results }
/// Guaranteed to be larger or equal to the union of all the ranges
/// associated with the contained results.
var range: NSRange { return _range }
private var _results: [Result] = []
private var _range: NSRange
// MARK: - Initializers
init(startingRange range: NSRange) {
_range = range
}
// MARK: - Adding
func extend(with range: NSRange) {
_range = NSUnionRange(self.range, range)
}
func add(_ result: Result) {
extend(with: result.range)
_results.append(result)
}
func add(_ resultSet: ResultSet) {
extend(with: resultSet.range)
for result in resultSet.results {
_results.append(result)
}
}
}
| 21.428571 | 71 | 0.621905 |
293b58980399420af9b83fcead9cfff76584e62d | 1,552 |
import Foundation
class ContainerDelfault : Container {
let produccerStorage: FactoriesStorage
let instanceStorage: InstanceStorage
init(produccerStorage: FactoriesStorage, instanceStorage: InstanceStorage) {
self.produccerStorage = produccerStorage
self.instanceStorage = instanceStorage
}
func register<T, J:Injectable>(type: T.Type, with injectable: J.Type, name: String, scope: Scope) {
let produccer = Factory({ injector in
try injectable.init(injector: injector)
}, scope: scope)
produccerStorage.save(key: FactoryKey(type: type, name: name), value: produccer)
}
fileprivate func getInstance<T>(key: FactoryKey) throws -> T {
let produccer = try produccerStorage.findProduccerBy(key: key)
let injectable = try instanceStorage.retrieveInstanceOf(key: key, produccer: produccer, injector: self)
guard let instance = injectable as? T else {
throw NurseError(message: "The instance is not the type \(key.type)", code: 2)
}
return instance
}
func clear() {
produccerStorage.clear()
instanceStorage.clear()
}
func getInstance<T>(of type: T.Type) throws -> T {
let key = FactoryKey(type: type)
return try getInstance(key: key)
}
func getInstance<T>(of type: T.Type, name: String) throws -> T {
let key = FactoryKey(type: type, name: name)
return try getInstance(key: key)
}
}
| 31.673469 | 111 | 0.632732 |
0307e684ff963e6f0817e586e996f89b85bb7b06 | 20,891 | // Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import CoreLocation
import Crashlytics
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var sendImage: UIImageView!
@IBOutlet weak var signalImage: UIImageView!
@IBOutlet weak var gpsLabel: UILabel!
@IBOutlet weak var lineChart: LineChartCustom!
@IBOutlet weak var labelSignal: UILabel!
@IBOutlet weak var QueuedLabel: UILabel!
@IBOutlet weak var sentLabel: UILabel!
@IBOutlet weak var sensivityLabel: UILabel!
@IBOutlet weak var updateOfflineButton: UIButton!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var distanceFilterSlider: UISlider!
//@IBOutlet weak var tank: VNTankView!
let locationManager = CLLocationManager()
var lineValues = [CGFloat]()
//let databaseManager = SqliteManager()
let databaseManager = UnsentFeaturesManager()
let reachability = Reachability()!
var hasInternet = false
var editor: Editor? = nil
var timer: Timer? = nil
var privateTimer: Timer? = nil
var timerHeartbeat: Timer? = nil
var sentCounter = 0
var featureServiceError = 0
var offlineFeaturesSender: OfflineFeaturesSender?
// ------------ New feature service sync
// Not in used at this time, we are using Editor at this time
var bUseTrackingService = false
var trackingService: FeatureServiceEditor? {
didSet {
if trackingService == nil {
uploadTimer?.invalidate()
} else {
uploadTimer = Timer.scheduledTimer(withTimeInterval: uploadTimeInterval, repeats: true) { _ in
self.uploadIfNecessary()
}
}
}
}
var isUploading = false
let uploadTimeInterval: TimeInterval = 300
var uploadTimer: Timer?
var lastUploadTime: Date?
// ----------------------
override func viewDidLoad() {
super.viewDidLoad()
if let versionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] {
versionLabel.text = "Version \(versionNumber)"
}
lineChart.colors = [UIColor.black, UIColor.black]
databaseManager.viewController = self
//tank.percent = 0
// Start Location Manager and Motion
LocationManager(locationManager:locationManager).setup(distanceFilter: Double(distanceFilterSlider.value))
locationManager.delegate = self
sensivityLabel.text = "Location Filter: \(distanceFilterSlider.value)"
startReachability()
setupChart()
updateUnsentFeatures()
timerHeartbeat = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.checkForOfflineFeatures), userInfo: nil, repeats: true)
// Test the crash
//Crashlytics.sharedInstance().crash()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var signal = SignalStrength().getSignalStrength()
// Internet down, the UI could fail at reporting 0
if hasInternet == false {
signal = 0
}
lineValues.append(CGFloat(signal))
lineChart.clearAll()
lineChart.addLine(lineValues)
labelSignal.text = "Last Signal: \(signal)"
var signalObservation: SignalObservation? = nil
if let coordinate = locations.last?.coordinate {
gpsLabel.text = "\(coordinate.latitude) \(coordinate.longitude)"
let altitude = locations.last?.altitude ?? 0
// Create the observation
signalObservation = SignalObservation(coordinates: coordinate, signalStrength: Int(signal), altitude: altitude)
}
// Clear the lines to avoid the chart to get huge
if lineValues.count > 15 {
lineValues.remove(at: 0)
}
if hasInternet {
// Build the editor for the first time
loadEditor()
// Send observation to the feature service inmediatly
if let signalObservation = signalObservation {
sendObservation(signalObservation: signalObservation, databaseObservation: nil, completion: { success in
self.checkForOfflineFeatures()
})
}
} else {
// No internet, adding into the database for later.
if let signalObservation = signalObservation {
_ = databaseManager.addObservation(newObservation: signalObservation)
}
updateUnsentFeatures()
}
}
private func loadEditor() {
if editor == nil {
SettingsBundleHelper.registerSettingsBundle()
var urlString = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.FeatureService)
var username = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.Username)
var password = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.Password)
var webMap = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.WebMap)
var portalUrl = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.Portal)
if urlString == nil {
urlString = SettingsBundleHelper.featureServiceToUse
UserDefaults.standard.set(urlString, forKey: SettingsBundleHelper.SettingsBundleKeys.FeatureService)
}
if username == nil {
username = "apascual_apl"
UserDefaults.standard.set(username, forKey: SettingsBundleHelper.SettingsBundleKeys.Username)
}
if password == nil {
password = "blank"
UserDefaults.standard.set(password, forKey: SettingsBundleHelper.SettingsBundleKeys.Password)
}
if webMap == nil {
webMap = "insert-id-here"
UserDefaults.standard.set(webMap, forKey: SettingsBundleHelper.SettingsBundleKeys.WebMap)
}
if portalUrl == nil {
portalUrl = "https://arcgis.com/....."
UserDefaults.standard.set(portalUrl, forKey: SettingsBundleHelper.SettingsBundleKeys.Portal)
}
//USE the new tracking start the new service here
if bUseTrackingService {
if let urlString = urlString, let username = username, let password = password {
trackingService = FeatureServiceEditor(tracksUrl: URL(string: urlString)!, username: username, password: password)
}
}
if trackingService == nil {
if let urlString = urlString, let username = username, let password = password {
editor = Editor(urlString: urlString, username: username, password: password)
}
}
}
}
var privateTimerReschedule = 0
@objc private func checkForOfflineFeatures() {
// Update signal without GPS
var signal = SignalStrength().getSignalStrength()
// Internet down, the UI could fail at reporting 0
if hasInternet == false {
signal = 0
}
labelSignal.text = "Last Signal: \(signal)"
// Check if there are old observations to send to the feature service
if self.timer == nil && self.privateTimer == nil && hasInternet {
privateTimerReschedule = 0
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.CheckForObservations), userInfo: nil, repeats: false)
} else {
//Check the private timer as does not become nil when there are features waiting
if let databaseCount = databaseManager.fetchUnsentObservations()?.count {
if databaseCount > 1 {
privateTimerReschedule = privateTimerReschedule + 1
if privateTimerReschedule > 4 {
privateTimerReschedule = 0
self.privateTimer = nil
}
}
}
}
// Check if the feature service is having issues
if featureServiceError > 10 {
featureServiceError = 0
loadEditor()
print("loading editor again")
}
}
@objc func CheckForObservations() {
defer {
timer?.invalidate()
timer = nil
}
let unsent = databaseManager.fetchUnsentObservations()
if unsent == nil {
return
}
if unsent?.count == 0 {
return
}
if privateTimer == nil {
privateTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.SendOfflineObservations), userInfo: nil, repeats: false)
showSendingImage()
}
}
@objc func SendOfflineObservations() {
// Kill the timer
func closePrivateTimer() {
privateTimer?.invalidate()
privateTimer = nil
showSendingImage()
}
func rescheduleTimer(interval: Double) {
privateTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(self.SendOfflineObservations), userInfo: nil, repeats: false)
}
updateUnsentFeatures()
let unsent = databaseManager.fetchUnsentObservations()
if let unsent = unsent {
//Cannot send features too fast or will create duplicate, wait until
//we get the confirmation that is stored before sending next one
//we are using a timer that only fires after the confirmation happens
if let observation = unsent.first {
if let signalObservation = databaseManager.convertToSignalObservation(observation: observation) {
self.sendObservation(signalObservation: signalObservation, databaseObservation: observation, completion: { [weak self] success in
self?.databaseManager.deleteAllSent()
if success {
self?.updateUnsentFeatures()
} else {
// Store for later
if let mySelf = self {
mySelf.featureServiceError = mySelf.featureServiceError + 1
}
}
closePrivateTimer()
//rescheduleTimer(interval: 0.1)
return
})
}
}
if unsent.count == 0 {
closePrivateTimer()
} else if unsent.count > 1 {
print("Unsent feature waiting \(unsent.count)")
} else {
print("Unsent is less than interval \(unsent.count)")
}
// The private time won't be nil due the unsent only sends one at the time
// when there are a collection waiting the timer never becomes nil
} else {
closePrivateTimer()
}
}
func updateUnsentFeatures() {
let count = "\(databaseManager.fetchUnsentObservations()?.count ?? 0)"
//print("Unsent features count \(count)")
self.QueuedLabel.text = "\(count) features unsent"
// if let floatCount = Float(count) {
// if floatCount > 0 {
//
// self.tank.percent = floatCount / 100
// }
// }
}
func sendObservation(signalObservation: SignalObservation, databaseObservation: Any?, completion: @escaping (_ success:Bool) -> Void) {
// Otherwise send the observation to the server
// Update status of the observation inside the sql database.
// Should we avoid to change the status so many times?
func updateStatusObservation(databaseObservation: Any?, status: String) {
if let databaseObservation = databaseObservation as? Observation{
databaseObservation.status = status
self.databaseManager.updateObservation(databaseObservation: databaseObservation)
} else if let databaseObservation = databaseObservation as? MemoryObservation {
databaseObservation.status = status
self.databaseManager.updateObservation(databaseObservation: databaseObservation)
}
}
updateStatusObservation(databaseObservation: databaseObservation, status: "sending")
if trackingService == nil {
editor?.addObservationToFeatureService(signalObservation: signalObservation, counter: String(sentCounter), completion: { [weak self] success in
//print("Enter \(String(describing: self?.sentCounter))")
if success {
// Update the database only when is offline
updateStatusObservation(databaseObservation: databaseObservation, status: "sending")
// Update the counter
if var sentCounter = self?.sentCounter {
sentCounter = sentCounter + 1
self?.sentLabel.text = "\(sentCounter) features stored online"
self?.sentCounter = sentCounter
}
} else {
if let mySelf = self {
if let databaseObservation = databaseObservation {
print("failed changing observation status to new")
CustomNotification.show(parent: mySelf, title: "Error Feature Service Failed", description: "The request timed out reschedule")
updateStatusObservation(databaseObservation: databaseObservation, status: "new")
mySelf.updateUnsentFeatures()
} else {
// Update
print("failed queue observation for later")
CustomNotification.show(parent: mySelf, title: "Error Feature Service Failed", description: "The request timed out, adding...")
_ = self?.databaseManager.addObservation(newObservation: signalObservation)
mySelf.updateUnsentFeatures()
}
mySelf.loadEditor()
}
}
completion(success)
})
} else {
trackingService?.save(observation: signalObservation, completion: { (error) in
if let error = error {
print("error with tracking service \(error)")
} else {
updateStatusObservation(databaseObservation: databaseObservation, status: "sent")
// Update the counter
self.sentCounter = self.sentCounter + 1
self.sentLabel.text = "\(self.sentCounter) features stored online"
}
})
}
}
func setupChart() {
// Remove labels
lineChart.x.labels.visible = false
lineChart.y.labels.visible = true
lineChart.y.grid.count = 5
lineChart.y.labels.values = ["0", "1", "2", "3", "4"]
lineChart.hardMax = 4
lineChart.hardMin = 0
lineChart.labelsX = ["0", "1", "2", "3", "4"]
lineValues.append(CGFloat(0))
lineValues.append(CGFloat(0))
lineValues.append(CGFloat(0))
lineValues.append(CGFloat(0))
lineValues.append(CGFloat(0))
lineChart.addLine(lineValues)
}
@IBAction func sensivityChanged(_ sender: Any) {
let sensivityControl = sender as! UISlider
let sliderValue = round(sensivityControl.value)
sensivityLabel.text = "Location Filter: \(sliderValue)"
if locationManager.distanceFilter != Double(sliderValue) {
locationManager.stopUpdatingLocation()
locationManager.distanceFilter = Double(sliderValue)
locationManager.startUpdatingLocation()
}
}
func startReachability() {
reachability.whenReachable = { [weak self] reachability in
self?.hasInternet = true
self?.signalImage.isHidden = true
// Start the timer to check for offline features if needed.
self?.checkForOfflineFeatures()
self?.updateOfflineButton.isEnabled = true
if reachability.connection == .wifi {
// Disconnect from the WIFI notification
if let mySelf = self {
CustomNotification.show(parent: mySelf, title: "WIFI detected", description: "Disconnect from the current WIFI to get accurate reading.")
}
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
// TODO Make sure the data plan actually works
}
}
reachability.whenUnreachable = { [weak self] _ in
print("Not reachable")
self?.hasInternet = false
self?.signalImage.isHidden = false
self?.updateOfflineButton.isEnabled = false
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
func showSendingImage() {
if privateTimer == nil {
sendImage.isHidden = true
} else if hasInternet {
sendImage.isHidden = false
} else {
sendImage.isHidden = true
}
}
@IBAction func updateOfflinePressed(_ sender: Any) {
if let count = databaseManager.fetchUnsentObservations()?.count {
if count > 0 {
privateTimer?.invalidate()
privateTimer = nil
// Stop the internet for now
hasInternet = false
guard let editor = editor else {
CustomNotification.show(parent: self, title: "Cannot Sync Offline", description: "Feature Service Editor is not enabled.")
return
}
offlineFeaturesSender = OfflineFeaturesSender(editor: editor, databaseManager: databaseManager, sentCounter: sentCounter, sentLabel: sentLabel, QueuedLabel: self.QueuedLabel)
if let offlineFeaturesSender = offlineFeaturesSender {
offlineFeaturesSender.finishHandler = {
self.hasInternet = true
self.updateUnsentFeatures()
self.offlineFeaturesSender = nil
}
offlineFeaturesSender.sendAll()
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMapSegue" {
CustomNotification.show(parent: self, title: "Tracking Stopped", description: "While the map is open, the tracking of the GPS and Signal has paused.", checkForDuplicates: false)
}
}
}
| 39.944551 | 190 | 0.56565 |
675f0e01392a70a2befade5b34f6c81614a3f8db | 9,535 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Dispatch
import Basic
import PackageGraph
import SourceControl
import struct Utility.Version
public typealias MockDependencyResolver = DependencyResolver<MockPackagesProvider, MockResolverDelegate>
extension String: PackageContainerIdentifier { }
public typealias MockPackageConstraint = PackageContainerConstraint<String>
extension VersionSetSpecifier {
init(_ json: JSON) {
switch json {
case let .string(str):
switch str {
case "any": self = .any
case "empty": self = .empty
default: fatalError()
}
case let .array(arr):
switch arr.count {
case 1:
guard case let .string(str) = arr[0] else { fatalError() }
self = .exact(Version(string: str)!)
case 2:
let versions = arr.map({ json -> Version in
guard case let .string(str) = json else { fatalError() }
return Version(string: str)!
})
self = .range(versions[0] ..< versions[1])
default: fatalError()
}
default: fatalError()
}
}
}
extension PackageContainerConstraint where T == String {
public init(json: JSON) {
guard case let .dictionary(dict) = json else { fatalError() }
guard case let .string(identifier)? = dict["identifier"] else { fatalError() }
guard let requirement = dict["requirement"] else { fatalError() }
self.init(container: identifier, versionRequirement: VersionSetSpecifier(requirement))
}
}
extension PackageContainerProvider {
public func getContainer(
for identifier: Container.Identifier,
completion: @escaping (Result<Container, AnyError>) -> Void
) {
getContainer(for: identifier, skipUpdate: false, completion: completion)
}
}
public enum MockLoadingError: Error {
case unknownModule
}
public class MockPackageContainer: PackageContainer {
public typealias Identifier = String
public typealias Dependency = (container: Identifier, requirement: MockPackageConstraint.Requirement)
let name: Identifier
let dependencies: [String: [Dependency]]
public var unversionedDeps: [MockPackageConstraint] = []
/// Contains the versions for which the dependencies were requested by resolver using getDependencies().
public var requestedVersions: Set<Version> = []
public var identifier: Identifier {
return name
}
public let _versions: [Version]
public func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version> {
return AnySequence(_versions.filter(isIncluded))
}
public func getDependencies(at version: Version) -> [MockPackageConstraint] {
requestedVersions.insert(version)
return getDependencies(at: version.description)
}
public func getDependencies(at revision: String) -> [MockPackageConstraint] {
return dependencies[revision]!.map({ value in
let (name, requirement) = value
return MockPackageConstraint(container: name, requirement: requirement)
})
}
public func getUnversionedDependencies() -> [MockPackageConstraint] {
return unversionedDeps
}
public func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> String {
return name
}
public convenience init(
name: Identifier,
dependenciesByVersion: [Version: [(container: Identifier, versionRequirement: VersionSetSpecifier)]]
) {
var dependencies: [String: [Dependency]] = [:]
for (version, deps) in dependenciesByVersion {
dependencies[version.description] = deps.map({
($0.container, .versionSet($0.versionRequirement))
})
}
self.init(name: name, dependencies: dependencies)
}
public init(
name: Identifier,
dependencies: [String: [Dependency]] = [:]
) {
self.name = name
let versions = dependencies.keys.flatMap(Version.init(string:))
self._versions = versions.sorted().reversed()
self.dependencies = dependencies
}
}
public class MockPackageContainer2: MockPackageContainer {
public override func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> String {
return name + "-name"
}
}
extension MockPackageContainer {
public convenience init(json: JSON) {
guard case let .dictionary(dict) = json else { fatalError() }
guard case let .string(identifier)? = dict["identifier"] else { fatalError() }
guard case let .dictionary(versions)? = dict["versions"] else { fatalError() }
var depByVersion: [Version: [(container: Identifier, versionRequirement: VersionSetSpecifier)]] = [:]
for (version, deps) in versions {
guard case let .array(depArray) = deps else { fatalError() }
depByVersion[Version(string: version)!] = depArray
.map(PackageContainerConstraint.init(json:))
.map({ constraint in
switch constraint.requirement {
case .versionSet(let versionSet):
return (constraint.identifier, versionSet)
case .unversioned:
fatalError()
case .revision:
fatalError()
}
})
}
self.init(name: identifier, dependenciesByVersion: depByVersion)
}
}
public struct MockPackagesProvider: PackageContainerProvider {
public typealias Container = MockPackageContainer
public let containers: [Container]
public let containersByIdentifier: [Container.Identifier: Container]
public init(containers: [MockPackageContainer]) {
self.containers = containers
self.containersByIdentifier = Dictionary(items: containers.map({ ($0.identifier, $0) }))
}
public func getContainer(
for identifier: Container.Identifier,
skipUpdate: Bool,
completion: @escaping (Result<Container, AnyError>
) -> Void) {
DispatchQueue.global().async {
completion(self.containersByIdentifier[identifier].map(Result.init) ??
Result(MockLoadingError.unknownModule))
}
}
}
public class MockResolverDelegate: DependencyResolverDelegate {
public typealias Identifier = MockPackageContainer.Identifier
public init() {}
}
extension DependencyResolver where P == MockPackagesProvider, D == MockResolverDelegate {
/// Helper method which returns all the version binding out of resolver and assert failure for non version bindings.
public func resolveToVersion(
constraints: [MockPackageConstraint],
file: StaticString = #file,
line: UInt = #line
) throws -> [(container: String, version: Version)] {
return try resolve(constraints: constraints).flatMap({
guard case .version(let version) = $0.binding else {
XCTFail("Unexpected non version binding \($0.binding)", file: file, line: line)
return nil
}
return ($0.container, version)
})
}
}
public struct MockGraph {
public let name: String
public let constraints: [MockPackageConstraint]
public let containers: [MockPackageContainer]
public let result: [String: Version]
public init(_ json: JSON) {
guard case let .dictionary(dict) = json else { fatalError() }
guard case let .string(name)? = dict["name"] else { fatalError() }
guard case let .array(constraints)? = dict["constraints"] else { fatalError() }
guard case let .array(containers)? = dict["containers"] else { fatalError() }
guard case let .dictionary(result)? = dict["result"] else { fatalError() }
self.result = Dictionary(items: result.map({ value in
let (container, version) = value
guard case let .string(str) = version else { fatalError() }
return (container, Version(string: str)!)
}))
self.name = name
self.constraints = constraints.map(PackageContainerConstraint.init(json:))
self.containers = containers.map(MockPackageContainer.init(json:))
}
public func checkResult(
_ output: [(container: String, version: Version)],
file: StaticString = #file,
line: UInt = #line
) {
var result = self.result
for item in output {
XCTAssertEqual(result[item.container], item.version, file: file, line: line)
result[item.container] = nil
}
if !result.isEmpty {
XCTFail("Unchecked containers: \(result)", file: file, line: line)
}
}
}
public func XCTAssertEqual<I: PackageContainerIdentifier>(
_ assignment: [(container: I, version: Version)],
_ expected: [I: Version],
file: StaticString = #file, line: UInt = #line) {
var actual = [I: Version]()
for (identifier, binding) in assignment {
actual[identifier] = binding
}
XCTAssertEqual(actual, expected, file: file, line: line)
}
| 35.184502 | 120 | 0.639224 |
e4895a2d328e9bec3632d49c6282b75eeabd588e | 1,563 | // Copyright (c) 2020 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
final class LZMALenDecoder {
private var choice: Int = LZMAConstants.probInitValue
private var choice2: Int = LZMAConstants.probInitValue
private var lowCoder: [LZMABitTreeDecoder] = []
private var midCoder: [LZMABitTreeDecoder] = []
private var highCoder: LZMABitTreeDecoder
init() {
self.highCoder = LZMABitTreeDecoder(numBits: 8)
for _ in 0..<(1 << LZMAConstants.numPosBitsMax) {
self.lowCoder.append(LZMABitTreeDecoder(numBits: 3))
self.midCoder.append(LZMABitTreeDecoder(numBits: 3))
}
}
/// Decodes zero-based match length.
func decode(with rangeDecoder: LZMARangeDecoder, posState: Int) -> Int {
// There can be one of three options.
// We need one or two bits to find out which decoding scheme to use.
// `choice` is used to decode first bit.
// `choice2` is used to decode second bit.
// If binary sequence starts with 0 then:
if rangeDecoder.decode(bitWithProb: &self.choice) == 0 {
return self.lowCoder[posState].decode(with: rangeDecoder)
}
// If binary sequence starts with 1 0 then:
if rangeDecoder.decode(bitWithProb: &self.choice2) == 0 {
return 8 + self.midCoder[posState].decode(with: rangeDecoder)
}
// If binary sequence starts with 1 1 then:
return 16 + self.highCoder.decode(with: rangeDecoder)
}
}
| 36.348837 | 76 | 0.65643 |
6958b44585b31df02c719d2c5fbab7da90881402 | 1,563 | //
// AVIFImage.swift
// Nuke-AVIF-Plugin
//
// Created by delneg on 2021/12/05.
// Copyright © 2021 delneg. All rights reserved.
//
import Foundation
import Nuke
#if SWIFT_PACKAGE
import NukeAVIFPluginC
#endif
public class AVIFImageDecoder: Nuke.ImageDecoding {
private lazy var decoder: AVIFDataDecoder = AVIFDataDecoder()
public init() {
}
public func decode(_ data: Data) -> ImageContainer? {
guard data.isAVIFFormat else { return nil }
guard let image = _decode(data) else { return nil }
return ImageContainer(image: image)
}
public func decodePartiallyDownloadedData(_ data: Data) -> ImageContainer? {
guard data.isAVIFFormat else { return nil }
guard let image = decoder.incrementallyDecode(data) else { return nil }
return ImageContainer(image: image)
}
}
// MARK: - check avif format data.
extension AVIFImageDecoder {
public static func enable() {
Nuke.ImageDecoderRegistry.shared.register { (context) -> ImageDecoding? in
AVIFImageDecoder.enable(context: context)
}
}
public static func enable(context: Nuke.ImageDecodingContext) -> Nuke.ImageDecoding? {
return context.data.isAVIFFormat ? AVIFImageDecoder() : nil
}
}
// MARK: - private
private let _queue = DispatchQueue(label: "com.github.delneg.Nuke-AVIF-Plugin.DataDecoder")
extension AVIFImageDecoder {
private func _decode(_ data: Data) -> PlatformImage? {
return _queue.sync {
return decoder.decode(data)
}
}
}
| 24.809524 | 91 | 0.675624 |
61f134351360acd17b65f3ea741ef22cf2da433d | 4,811 | //
// Completable+AndThen.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/2/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Single<E>) -> Single<E> {
let completable = primitiveSequence.asObservable()
return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> {
let completable = primitiveSequence.asObservable()
return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen(_ second: Completable) -> Completable {
let completable = primitiveSequence.asObservable()
return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Observable<E>) -> Observable<E> {
let completable = primitiveSequence.asObservable()
return ConcatCompletable(completable: completable, second: second.asObservable())
}
}
private final class ConcatCompletable<Element>: Producer<Element> {
fileprivate let _completable: Observable<Never>
fileprivate let _second: Observable<Element>
init(completable: Observable<Never>, second: Observable<Element>) {
_completable = completable
_second = second
}
override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O: ObserverType, O.E == Element {
let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
private final class ConcatCompletableSink<O: ObserverType>:
Sink<O>,
ObserverType {
typealias E = Never
typealias Parent = ConcatCompletable<O.E>
private let _parent: Parent
private let _subscription = SerialDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case let .error(error):
forwardOn(.error(error))
dispose()
case .next:
break
case .completed:
let otherSink = ConcatCompletableSinkOther(parent: self)
_subscription.disposable = _parent._second.subscribe(otherSink)
}
}
func run() -> Disposable {
let subscription = SingleAssignmentDisposable()
_subscription.disposable = subscription
subscription.setDisposable(_parent._completable.subscribe(self))
return _subscription
}
}
private final class ConcatCompletableSinkOther<O: ObserverType>:
ObserverType {
typealias E = O.E
typealias Parent = ConcatCompletableSink<O>
private let _parent: Parent
init(parent: Parent) {
_parent = parent
}
func on(_ event: Event<O.E>) {
_parent.forwardOn(event)
if event.isStopEvent {
_parent.dispose()
}
}
}
| 36.172932 | 147 | 0.687383 |
e4d6f5b6fd1097abdf64b3d64fe1a3c40062e6d9 | 20,016 | //
// SevenSwitch.swift
//
// Created by Benjamin Vogelzang on 6/20/14.
// Copyright (c) 2014 Ben Vogelzang. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import QuartzCore
@IBDesignable @objc open class SevenSwitch: UIControl {
// public
/*
* Set (without animation) whether the switch is on or off
*/
@IBInspectable open var on: Bool {
get {
return switchValue
}
set {
switchValue = newValue
self.setOn(newValue, animated: false)
}
}
/*
* Sets the background color that shows when the switch off and actively being touched.
* Defaults to light gray.
*/
@IBInspectable open var activeColor: UIColor = UIColor(red: 0.89, green: 0.89, blue: 0.89, alpha: 1) {
willSet {
if self.on && !self.isTracking {
backgroundView.backgroundColor = newValue
}
}
}
/*
* Sets the background color when the switch is off.
* Defaults to clear color.
*/
@IBInspectable open var inactiveColor: UIColor = UIColor.clear {
willSet {
if !self.on && !self.isTracking {
backgroundView.backgroundColor = newValue
}
}
}
/*
* Sets the background color that shows when the switch is on.
* Defaults to green.
*/
@IBInspectable open var onTintColor: UIColor = UIColor(red: 0.3, green: 0.85, blue: 0.39, alpha: 1) {
willSet {
if self.on && !self.isTracking {
backgroundView.backgroundColor = newValue
backgroundView.layer.borderColor = newValue.cgColor
}
}
}
/*
* Sets the border color that shows when the switch is off. Defaults to light gray.
*/
@IBInspectable open var borderColor: UIColor = UIColor(red: 0.78, green: 0.78, blue: 0.8, alpha: 1) {
willSet {
if !self.on {
backgroundView.layer.borderColor = newValue.cgColor
}
}
}
/*
* Sets the knob color. Defaults to white.
*/
@IBInspectable open var thumbTintColor: UIColor = UIColor.white {
willSet {
if !userDidSpecifyOnThumbTintColor {
onThumbTintColor = newValue
}
if (!userDidSpecifyOnThumbTintColor || !self.on) && !self.isTracking {
thumbView.backgroundColor = newValue
}
}
}
/*
* Sets the knob color that shows when the switch is on. Defaults to white.
*/
@IBInspectable open var onThumbTintColor: UIColor = UIColor.white {
willSet {
userDidSpecifyOnThumbTintColor = true
if self.on && !self.isTracking {
thumbView.backgroundColor = newValue
}
}
}
/*
* Sets the shadow color of the knob. Defaults to gray.
*/
@IBInspectable open var shadowColor: UIColor = UIColor.gray {
willSet {
thumbView.layer.shadowColor = newValue.cgColor
}
}
/*
* Sets whether or not the switch edges are rounded.
* Set to NO to get a stylish square switch.
* Defaults to YES.
*/
@IBInspectable open var isRounded: Bool = true {
willSet {
if newValue {
backgroundView.layer.cornerRadius = self.frame.size.height * 0.5
thumbView.layer.cornerRadius = (self.frame.size.height * 0.5) - 1
}
else {
backgroundView.layer.cornerRadius = 2
thumbView.layer.cornerRadius = 2
}
thumbView.layer.shadowPath = UIBezierPath(roundedRect: thumbView.bounds, cornerRadius: thumbView.layer.cornerRadius).cgPath
}
}
/*
* Sets the image that shows on the switch thumb.
*/
@IBInspectable open var thumbImage: UIImage! {
willSet {
thumbImageView.image = newValue
}
}
/*
* Sets the image that shows when the switch is on.
* The image is centered in the area not covered by the knob.
* Make sure to size your images appropriately.
*/
@IBInspectable open var onImage: UIImage! {
willSet {
onImageView.image = newValue
}
}
/*
* Sets the image that shows when the switch is off.
* The image is centered in the area not covered by the knob.
* Make sure to size your images appropriately.
*/
@IBInspectable open var offImage: UIImage! {
willSet {
offImageView.image = newValue
}
}
/*
* Sets the text that shows when the switch is on.
* The text is centered in the area not covered by the knob.
*/
open var onLabel: UILabel!
/*
* Sets the text that shows when the switch is off.
* The text is centered in the area not covered by the knob.
*/
open var offLabel: UILabel!
// internal
internal var backgroundView: UIView!
internal var thumbView: UIView!
internal var onImageView: UIImageView!
internal var offImageView: UIImageView!
internal var thumbImageView: UIImageView!
// private
fileprivate var currentVisualValue: Bool = false
fileprivate var startTrackingValue: Bool = false
fileprivate var didChangeWhileTracking: Bool = false
fileprivate var isAnimating: Bool = false
fileprivate var userDidSpecifyOnThumbTintColor: Bool = false
fileprivate var switchValue: Bool = false
/*
* Initialization
*/
public convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
override public init(frame: CGRect) {
let initialFrame = frame.isEmpty ? CGRect(x: 0, y: 0, width: 50, height: 30) : frame
super.init(frame: initialFrame)
self.setup()
}
/*
* Setup the individual elements of the switch and set default values
*/
fileprivate func setup() {
// background
self.backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
backgroundView.backgroundColor = UIColor.clear
backgroundView.layer.cornerRadius = self.frame.size.height * 0.5
backgroundView.layer.borderColor = self.borderColor.cgColor
backgroundView.layer.borderWidth = 1.0
backgroundView.isUserInteractionEnabled = false
backgroundView.clipsToBounds = true
self.addSubview(backgroundView)
// on/off images
self.onImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width - self.frame.size.height, height: self.frame.size.height))
onImageView.alpha = 1.0
onImageView.contentMode = UIViewContentMode.center
backgroundView.addSubview(onImageView)
self.offImageView = UIImageView(frame: CGRect(x: self.frame.size.height, y: 0, width: self.frame.size.width - self.frame.size.height, height: self.frame.size.height))
offImageView.alpha = 1.0
offImageView.contentMode = UIViewContentMode.center
backgroundView.addSubview(offImageView)
// labels
self.onLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width - self.frame.size.height, height: self.frame.size.height))
onLabel.textAlignment = NSTextAlignment.center
onLabel.textColor = UIColor.lightGray
onLabel.font = UIFont.systemFont(ofSize: 12)
backgroundView.addSubview(onLabel)
self.offLabel = UILabel(frame: CGRect(x: self.frame.size.height, y: 0, width: self.frame.size.width - self.frame.size.height, height: self.frame.size.height))
offLabel.textAlignment = NSTextAlignment.center
offLabel.textColor = UIColor.lightGray
offLabel.font = UIFont.systemFont(ofSize: 12)
backgroundView.addSubview(offLabel)
// thumb
self.thumbView = UIView(frame: CGRect(x: 1, y: 1, width: self.frame.size.height - 2, height: self.frame.size.height - 2))
thumbView.backgroundColor = self.thumbTintColor
thumbView.layer.cornerRadius = (self.frame.size.height * 0.5) - 1
thumbView.layer.shadowColor = self.shadowColor.cgColor
thumbView.layer.shadowRadius = 2.0
thumbView.layer.shadowOpacity = 0.5
thumbView.layer.shadowOffset = CGSize(width: 0, height: 3)
thumbView.layer.shadowPath = UIBezierPath(roundedRect: thumbView.bounds, cornerRadius: thumbView.layer.cornerRadius).cgPath
thumbView.layer.masksToBounds = false
thumbView.isUserInteractionEnabled = false
self.addSubview(thumbView)
// thumb image
self.thumbImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: thumbView.frame.size.width, height: thumbView.frame.size.height))
thumbImageView.contentMode = UIViewContentMode.center
thumbImageView.autoresizingMask = UIViewAutoresizing.flexibleWidth
thumbView.addSubview(thumbImageView)
self.on = false
}
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.beginTracking(touch, with: event)
startTrackingValue = self.on
didChangeWhileTracking = false
let activeKnobWidth = self.bounds.size.height - 2 + 5
isAnimating = true
UIView.animate(withDuration: 0.3, delay: 0.0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.beginFromCurrentState], animations: {
if self.on {
self.thumbView.frame = CGRect(x: self.bounds.size.width - (activeKnobWidth + 1), y: self.thumbView.frame.origin.y, width: activeKnobWidth, height: self.thumbView.frame.size.height)
self.backgroundView.backgroundColor = self.onTintColor
self.thumbView.backgroundColor = self.onThumbTintColor
}
else {
self.thumbView.frame = CGRect(x: self.thumbView.frame.origin.x, y: self.thumbView.frame.origin.y, width: activeKnobWidth, height: self.thumbView.frame.size.height)
self.backgroundView.backgroundColor = self.activeColor
self.thumbView.backgroundColor = self.thumbTintColor
}
}, completion: { finished in
self.isAnimating = false
})
return true
}
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.continueTracking(touch, with: event)
// Get touch location
let lastPoint = touch.location(in: self)
// update the switch to the correct visuals depending on if
// they moved their touch to the right or left side of the switch
if lastPoint.x > self.bounds.size.width * 0.5 {
self.showOn(true)
if !startTrackingValue {
didChangeWhileTracking = true
}
}
else {
self.showOff(true)
if startTrackingValue {
didChangeWhileTracking = true
}
}
return true
}
override open func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
let previousValue = self.on
if didChangeWhileTracking {
self.setOn(currentVisualValue, animated: true)
}
else {
self.setOn(!self.on, animated: true)
}
if previousValue != self.on {
self.sendActions(for: UIControlEvents.valueChanged)
}
}
override open func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
// just animate back to the original value
if self.on {
self.showOn(true)
}
else {
self.showOff(true)
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if !isAnimating {
let frame = self.frame
// background
backgroundView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.5 : 2
// images
onImageView.frame = CGRect(x: 0, y: 0, width: frame.size.width - frame.size.height, height: frame.size.height)
offImageView.frame = CGRect(x: frame.size.height, y: 0, width: frame.size.width - frame.size.height, height: frame.size.height)
self.onLabel.frame = CGRect(x: 0, y: 0, width: frame.size.width - frame.size.height, height: frame.size.height)
self.offLabel.frame = CGRect(x: frame.size.height, y: 0, width: frame.size.width - frame.size.height, height: frame.size.height)
// thumb
let normalKnobWidth = frame.size.height - 2
if self.on {
thumbView.frame = CGRect(x: frame.size.width - (normalKnobWidth + 1), y: 1, width: frame.size.height - 2, height: normalKnobWidth)
}
else {
thumbView.frame = CGRect(x: 1, y: 1, width: normalKnobWidth, height: normalKnobWidth)
}
thumbView.layer.cornerRadius = self.isRounded ? (frame.size.height * 0.5) - 1 : 2
}
}
/*
* Set the state of the switch to on or off, optionally animating the transition.
*/
open func setOn(_ isOn: Bool, animated: Bool) {
switchValue = isOn
if on {
self.showOn(animated)
}
else {
self.showOff(animated)
}
}
/*
* Detects whether the switch is on or off
*
* @return BOOL YES if switch is on. NO if switch is off
*/
open func isOn() -> Bool {
return self.on
}
/*
* update the looks of the switch to be in the on position
* optionally make it animated
*/
fileprivate func showOn(_ animated: Bool) {
let normalKnobWidth = self.bounds.size.height - 2
let activeKnobWidth = normalKnobWidth + 5
if animated {
isAnimating = true
UIView.animate(withDuration: 0.3, delay: 0.0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.beginFromCurrentState], animations: {
if self.isTracking {
self.thumbView.frame = CGRect(x: self.bounds.size.width - (activeKnobWidth + 1), y: self.thumbView.frame.origin.y, width: activeKnobWidth, height: self.thumbView.frame.size.height)
}
else {
self.thumbView.frame = CGRect(x: self.bounds.size.width - (normalKnobWidth + 1), y: self.thumbView.frame.origin.y, width: normalKnobWidth, height: self.thumbView.frame.size.height)
}
self.backgroundView.backgroundColor = self.onTintColor
self.backgroundView.layer.borderColor = self.onTintColor.cgColor
self.thumbView.backgroundColor = self.onThumbTintColor
self.onImageView.alpha = 1.0
self.offImageView.alpha = 0
self.onLabel.alpha = 1.0
self.offLabel.alpha = 0
}, completion: { finished in
self.isAnimating = false
})
}
else {
if self.isTracking {
thumbView.frame = CGRect(x: self.bounds.size.width - (activeKnobWidth + 1), y: thumbView.frame.origin.y, width: activeKnobWidth, height: thumbView.frame.size.height)
}
else {
thumbView.frame = CGRect(x: self.bounds.size.width - (normalKnobWidth + 1), y: thumbView.frame.origin.y, width: normalKnobWidth, height: thumbView.frame.size.height)
}
backgroundView.backgroundColor = self.onTintColor
backgroundView.layer.borderColor = self.onTintColor.cgColor
thumbView.backgroundColor = self.onThumbTintColor
onImageView.alpha = 1.0
offImageView.alpha = 0
onLabel.alpha = 1.0
offLabel.alpha = 0
}
currentVisualValue = true
}
/*
* update the looks of the switch to be in the off position
* optionally make it animated
*/
fileprivate func showOff(_ animated: Bool) {
let normalKnobWidth = self.bounds.size.height - 2
let activeKnobWidth = normalKnobWidth + 5
if animated {
isAnimating = true
UIView.animate(withDuration: 0.3, delay: 0.0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.beginFromCurrentState], animations: {
if self.isTracking {
self.thumbView.frame = CGRect(x: 1, y: self.thumbView.frame.origin.y, width: activeKnobWidth, height: self.thumbView.frame.size.height);
self.backgroundView.backgroundColor = self.activeColor
}
else {
self.thumbView.frame = CGRect(x: 1, y: self.thumbView.frame.origin.y, width: normalKnobWidth, height: self.thumbView.frame.size.height);
self.backgroundView.backgroundColor = self.inactiveColor
}
self.backgroundView.layer.borderColor = self.borderColor.cgColor
self.thumbView.backgroundColor = self.thumbTintColor
self.onImageView.alpha = 0
self.offImageView.alpha = 1.0
self.onLabel.alpha = 0
self.offLabel.alpha = 1.0
}, completion: { finished in
self.isAnimating = false
})
}
else {
if (self.isTracking) {
thumbView.frame = CGRect(x: 1, y: thumbView.frame.origin.y, width: activeKnobWidth, height: thumbView.frame.size.height)
backgroundView.backgroundColor = self.activeColor
}
else {
thumbView.frame = CGRect(x: 1, y: thumbView.frame.origin.y, width: normalKnobWidth, height: thumbView.frame.size.height)
backgroundView.backgroundColor = self.inactiveColor
}
backgroundView.layer.borderColor = self.borderColor.cgColor
thumbView.backgroundColor = self.thumbTintColor
onImageView.alpha = 0
offImageView.alpha = 1.0
onLabel.alpha = 0
offLabel.alpha = 1.0
}
currentVisualValue = false
}
}
| 38.492308 | 200 | 0.604267 |
75c4a5c6f5dd6d17becfdc20cebe311e3eb51e19 | 985 | //
// CarouselDemoTests.swift
// CarouselDemoTests
//
// Created by Yang Yang on 10/18/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import XCTest
@testable import CarouselDemo
class CarouselDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.621622 | 111 | 0.637563 |
62710fc57896cfe1685384ebbba093a1e7372399 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct D : e
protocol e {
protocol P {
enum a<j : e
func a
typealias A : a
| 22.181818 | 87 | 0.737705 |
038c147e3541bd02c51f19da7651aef849a32963 | 2,665 | /*
* Copyright 2018 ICON Foundation
*
* 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 CryptoSwift
//import scrypt
// MARK: Wallet
open class Wallet {
public let key: KeyPair
public let address: String
public var keystore: Keystore?
private init(privateKey: PrivateKey) {
let publicKey = Cipher.createPublicKey(privateKey: privateKey)!
self.address = Cipher.makeAddress(privateKey, publicKey)
self.key = KeyPair(publicKey: publicKey, privateKey: privateKey)
}
}
extension Wallet {
public convenience init(privateKey prvKey: PrivateKey?) {
if let key = prvKey {
self.init(privateKey: key)
} else {
let prvKey = Wallet.generatePrivateKey()
self.init(privateKey: prvKey)
}
}
public convenience init(keystore: Keystore, password: String) throws {
let extracted = try keystore.extract(password: password)
guard let pubKey = Cipher.createPublicKey(privateKey: extracted) else { throw ICError.invalid(reason: .malformedKeystore) }
let address = Cipher.makeAddress(extracted, pubKey)
guard address == keystore.address else { throw ICError.invalid(reason: .wrongPassword) }
self.init(privateKey: extracted)
self.keystore = keystore
}
public class func generatePrivateKey() -> PrivateKey {
var key = ""
for _ in 0..<64 {
let code = arc4random() % 16
key += String(format: "%x", code)
}
let data = key.hexToData()!.sha3(.sha256)
let privateKey = PrivateKey(hex: data)
return privateKey
}
/// Signing
///
/// - Parameters:
/// - data: Data
/// - Returns: Signed.
/// - Throws: exceptions
public func getSignature(data: Data) throws -> String {
let hash = data.sha3(.sha256)
let sign = try Cipher.signECDSA(hashedMessage: hash, privateKey: key.privateKey)
return sign.base64EncodedString()
}
}
extension Wallet: Storable {
}
| 29.285714 | 131 | 0.633021 |
cc2e3a8e95e5a0a72ff9966336bdba2f944914a6 | 22,962 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import XCTest
import ArgumentParserTestHelpers
@testable import ArgumentParser
final class HelpGenerationTests: XCTestCase {
}
extension URL: ExpressibleByArgument {
public init?(argument: String) {
guard let url = URL(string: argument) else {
return nil
}
self = url
}
public var defaultValueDescription: String {
self.path == FileManager.default.currentDirectoryPath && self.isFileURL
? "current directory"
: String(describing: self)
}
}
// MARK: -
extension HelpGenerationTests {
struct A: ParsableArguments {
@Option(help: "Your name") var name: String
@Option(help: "Your title") var title: String?
}
func testHelp() {
AssertHelp(.default, for: A.self, equals: """
USAGE: a --name <name> [--title <title>]
OPTIONS:
--name <name> Your name
--title <title> Your title
-h, --help Show help information.
""")
}
struct B: ParsableArguments {
@Option(help: "Your name") var name: String
@Option(help: "Your title") var title: String?
@Argument(help: .hidden) var hiddenName: String?
@Option(help: .hidden) var hiddenTitle: String?
@Flag(help: .hidden) var hiddenFlag: Bool = false
@Flag(inversion: .prefixedNo, help: .hidden) var hiddenInvertedFlag: Bool = true
}
func testHelpWithHidden() {
AssertHelp(.default, for: B.self, equals: """
USAGE: b --name <name> [--title <title>]
OPTIONS:
--name <name> Your name
--title <title> Your title
-h, --help Show help information.
""")
AssertHelp(.hidden, for: B.self, equals: """
USAGE: b --name <name> [--title <title>] [<hidden-name>] [--hidden-title <hidden-title>] [--hidden-flag] [--hidden-inverted-flag] [--no-hidden-inverted-flag]
ARGUMENTS:
<hidden-name>
OPTIONS:
--name <name> Your name
--title <title> Your title
--hidden-title <hidden-title>
--hidden-flag
--hidden-inverted-flag/--no-hidden-inverted-flag
(default: true)
-h, --help Show help information.
""")
}
struct C: ParsableArguments {
@Option(help: ArgumentHelp("Your name.",
discussion: "Your name is used to greet you and say hello."))
var name: String
}
func testHelpWithDiscussion() {
AssertHelp(.default, for: C.self, equals: """
USAGE: c --name <name>
OPTIONS:
--name <name> Your name.
Your name is used to greet you and say hello.
-h, --help Show help information.
""")
}
struct Issue27: ParsableArguments {
@Option
var two: String = "42"
@Option(help: "The third option")
var three: String
@Option(help: "A fourth option")
var four: String?
@Option(help: "A fifth option")
var five: String = ""
}
func testHelpWithDefaultValueButNoDiscussion() {
AssertHelp(.default, for: Issue27.self, equals: """
USAGE: issue27 [--two <two>] --three <three> [--four <four>] [--five <five>]
OPTIONS:
--two <two> (default: 42)
--three <three> The third option
--four <four> A fourth option
--five <five> A fifth option
-h, --help Show help information.
""")
}
enum OptionFlags: String, EnumerableFlag { case optional, required }
enum Degree {
case bachelor, master, doctor
static func degreeTransform(_ string: String) throws -> Degree {
switch string {
case "bachelor":
return .bachelor
case "master":
return .master
case "doctor":
return .doctor
default:
throw ValidationError("Not a valid string for 'Degree'")
}
}
}
struct D: ParsableCommand {
@Argument(help: "Your occupation.")
var occupation: String = "--"
@Option(help: "Your name.")
var name: String = "John"
@Option(help: "Your age.")
var age: Int = 20
@Option(help: "Whether logging is enabled.")
var logging: Bool = false
@Option(parsing: .upToNextOption, help: ArgumentHelp("Your lucky numbers.", valueName: "numbers"))
var lucky: [Int] = [7, 14]
@Flag(help: "Vegan diet.")
var nda: OptionFlags = .optional
@Option(help: "Your degree.", transform: Degree.degreeTransform)
var degree: Degree = .bachelor
@Option(help: "Directory.")
var directory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
}
func testHelpWithDefaultValues() {
AssertHelp(.default, for: D.self, equals: """
USAGE: d [<occupation>] [--name <name>] [--age <age>] [--logging <logging>] [--lucky <numbers> ...] [--optional] [--required] [--degree <degree>] [--directory <directory>]
ARGUMENTS:
<occupation> Your occupation. (default: --)
OPTIONS:
--name <name> Your name. (default: John)
--age <age> Your age. (default: 20)
--logging <logging> Whether logging is enabled. (default: false)
--lucky <numbers> Your lucky numbers. (default: 7, 14)
--optional/--required Vegan diet. (default: optional)
--degree <degree> Your degree. (default: bachelor)
--directory <directory> Directory. (default: current directory)
-h, --help Show help information.
""")
}
struct E: ParsableCommand {
enum OutputBehaviour: String, EnumerableFlag {
case stats, count, list
static func name(for value: OutputBehaviour) -> NameSpecification {
.shortAndLong
}
}
@Flag(help: "Change the program output")
var behaviour: OutputBehaviour
}
struct F: ParsableCommand {
enum OutputBehaviour: String, EnumerableFlag {
case stats, count, list
static func name(for value: OutputBehaviour) -> NameSpecification {
.short
}
}
@Flag(help: "Change the program output")
var behaviour: OutputBehaviour = .list
}
struct G: ParsableCommand {
@Flag(inversion: .prefixedNo, help: "Whether to flag")
var flag: Bool = false
}
func testHelpWithMutuallyExclusiveFlags() {
AssertHelp(.default, for: E.self, equals: """
USAGE: e --stats --count --list
OPTIONS:
-s, --stats/-c, --count/-l, --list
Change the program output
-h, --help Show help information.
""")
AssertHelp(.default, for: F.self, equals: """
USAGE: f [-s] [-c] [-l]
OPTIONS:
-s/-c/-l Change the program output (default: list)
-h, --help Show help information.
""")
AssertHelp(.default, for: G.self, equals: """
USAGE: g [--flag] [--no-flag]
OPTIONS:
--flag/--no-flag Whether to flag (default: false)
-h, --help Show help information.
""")
}
struct H: ParsableCommand {
struct CommandWithVeryLongName: ParsableCommand {}
struct ShortCommand: ParsableCommand {
static var configuration: CommandConfiguration = CommandConfiguration(abstract: "Test short command name.")
}
struct AnotherCommandWithVeryLongName: ParsableCommand {
static var configuration: CommandConfiguration = CommandConfiguration(abstract: "Test long command name.")
}
struct AnotherCommand: ParsableCommand {
@Option()
var someOptionWithVeryLongName: String?
@Option()
var option: String?
@Argument(help: "This is an argument with a long name.")
var argumentWithVeryLongNameAndHelp: String = ""
@Argument
var argumentWithVeryLongName: String = ""
@Argument
var argument: String = ""
}
static var configuration = CommandConfiguration(subcommands: [CommandWithVeryLongName.self,ShortCommand.self,AnotherCommandWithVeryLongName.self,AnotherCommand.self])
}
func testHelpWithSubcommands() {
AssertHelp(.default, for: H.self, equals: """
USAGE: h <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
command-with-very-long-name
short-command Test short command name.
another-command-with-very-long-name
Test long command name.
another-command
See 'h help <subcommand>' for detailed help.
""")
AssertHelp(.default, for: H.AnotherCommand.self, root: H.self, equals: """
USAGE: h another-command [--some-option-with-very-long-name <some-option-with-very-long-name>] [--option <option>] [<argument-with-very-long-name-and-help>] [<argument-with-very-long-name>] [<argument>]
ARGUMENTS:
<argument-with-very-long-name-and-help>
This is an argument with a long name.
<argument-with-very-long-name>
<argument>
OPTIONS:
--some-option-with-very-long-name <some-option-with-very-long-name>
--option <option>
-h, --help Show help information.
""")
}
struct I: ParsableCommand {
static var configuration = CommandConfiguration(version: "1.0.0")
}
func testHelpWithVersion() {
AssertHelp(.default, for: I.self, equals: """
USAGE: i
OPTIONS:
--version Show the version.
-h, --help Show help information.
""")
}
struct J: ParsableCommand {
static var configuration = CommandConfiguration(discussion: "test")
}
func testOverviewButNoAbstractSpacing() {
let renderedHelp = HelpGenerator(J.self, visibility: .default)
.rendered()
AssertEqualStringsIgnoringTrailingWhitespace(renderedHelp, """
OVERVIEW:
test
USAGE: j
OPTIONS:
-h, --help Show help information.
""")
}
struct K: ParsableCommand {
@Argument(help: "A list of paths.")
var paths: [String] = []
func validate() throws {
if paths.isEmpty {
throw ValidationError("At least one path must be specified.")
}
}
}
func testHelpWithNoValueForArray() {
AssertHelp(.default, for: K.self, equals: """
USAGE: k [<paths> ...]
ARGUMENTS:
<paths> A list of paths.
OPTIONS:
-h, --help Show help information.
""")
}
struct L: ParsableArguments {
@Option(
name: [.short, .customLong("remote"), .customLong("remote"), .short, .customLong("when"), .long, .customLong("other", withSingleDash: true), .customLong("there"), .customShort("x"), .customShort("y")],
help: "Help Message")
var time: String?
}
func testHelpWithMultipleCustomNames() {
AssertHelp(.default, for: L.self, equals: """
USAGE: l [--remote <remote>]
OPTIONS:
-t, -x, -y, --remote, --when, --time, -other, --there <remote>
Help Message
-h, --help Show help information.
""")
}
struct M: ParsableCommand {
}
struct N: ParsableCommand {
static var configuration = CommandConfiguration(subcommands: [M.self], defaultSubcommand: M.self)
}
func testHelpWithDefaultCommand() {
AssertHelp(.default, for: N.self, equals: """
USAGE: n <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
m (default)
See 'n help <subcommand>' for detailed help.
""")
}
enum O: String, ExpressibleByArgument {
case small
case medium
case large
init?(argument: String) {
guard let result = Self(rawValue: argument) else {
return nil
}
self = result
}
}
struct P: ParsableArguments {
@Option(name: [.short], help: "Help Message")
var o: [O] = [.small, .medium]
@Argument(help: "Help Message")
var remainder: [O] = [.large]
}
func testHelpWithDefaultValueForArray() {
AssertHelp(.default, for: P.self, equals: """
USAGE: p [-o <o> ...] [<remainder> ...]
ARGUMENTS:
<remainder> Help Message (default: large)
OPTIONS:
-o <o> Help Message (default: small, medium)
-h, --help Show help information.
""")
}
struct Foo: ParsableCommand {
public static var configuration = CommandConfiguration(
commandName: "foo",
abstract: "Perform some foo",
subcommands: [
Bar.self
],
helpNames: [.short, .long, .customLong("help", withSingleDash: true)])
@Option(help: "Name for foo")
var fooName: String?
public init() {}
}
struct Bar: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "bar",
_superCommandName: "foo",
abstract: "Perform bar operations",
helpNames: [.short, .long, .customLong("help", withSingleDash: true)])
@Option(help: "Bar Strength")
var barStrength: String?
public init() {}
}
func testHelpExcludingSuperCommand() throws {
AssertHelp(.default, for: Bar.self, root: Foo.self, equals: """
OVERVIEW: Perform bar operations
USAGE: foo bar [--bar-strength <bar-strength>]
OPTIONS:
--bar-strength <bar-strength>
Bar Strength
-h, -help, --help Show help information.
""")
}
}
extension HelpGenerationTests {
private struct optionsToHide: ParsableArguments {
@Flag(help: "Verbose")
var verbose: Bool = false
@Option(help: "Custom Name")
var customName: String?
@Option(help: .hidden)
var hiddenOption: String?
@Argument(help: .private)
var privateArg: String?
}
@available(*, deprecated)
private struct HideOptionGroupLegacyDriver: ParsableCommand {
static let configuration = CommandConfiguration(commandName: "driver", abstract: "Demo hiding option groups")
@OptionGroup(_hiddenFromHelp: true)
var hideMe: optionsToHide
@Option(help: "Time to wait before timeout (in seconds)")
var timeout: Int?
}
private struct HideOptionGroupDriver: ParsableCommand {
static let configuration = CommandConfiguration(commandName: "driver", abstract: "Demo hiding option groups")
@OptionGroup(visibility: .hidden)
var hideMe: optionsToHide
@Option(help: "Time to wait before timeout (in seconds)")
var timeout: Int?
}
private struct PrivateOptionGroupDriver: ParsableCommand {
static let configuration = CommandConfiguration(commandName: "driver", abstract: "Demo hiding option groups")
@OptionGroup(visibility: .private)
var hideMe: optionsToHide
@Option(help: "Time to wait before timeout (in seconds)")
var timeout: Int?
}
private var helpMessage: String { """
OVERVIEW: Demo hiding option groups
USAGE: driver [--timeout <timeout>]
OPTIONS:
--timeout <timeout> Time to wait before timeout (in seconds)
-h, --help Show help information.
"""
}
private var helpHiddenMessage: String { """
OVERVIEW: Demo hiding option groups
USAGE: driver [--verbose] [--custom-name <custom-name>] [--hidden-option <hidden-option>] [--timeout <timeout>]
OPTIONS:
--verbose Verbose
--custom-name <custom-name>
Custom Name
--hidden-option <hidden-option>
--timeout <timeout> Time to wait before timeout (in seconds)
-h, --help Show help information.
"""
}
@available(*, deprecated)
func testHidingOptionGroup() throws {
AssertHelp(.default, for: HideOptionGroupLegacyDriver.self, equals: helpMessage)
AssertHelp(.default, for: HideOptionGroupDriver.self, equals: helpMessage)
AssertHelp(.default, for: PrivateOptionGroupDriver.self, equals: helpMessage)
}
@available(*, deprecated)
func testHelpHiddenShowsDefaultAndHidden() throws {
AssertHelp(.hidden, for: HideOptionGroupLegacyDriver.self, equals: helpHiddenMessage)
AssertHelp(.hidden, for: HideOptionGroupDriver.self, equals: helpHiddenMessage)
// Note: Private option groups are not visible at `.hidden` help level.
AssertHelp(.hidden, for: PrivateOptionGroupDriver.self, equals: helpMessage)
}
}
extension HelpGenerationTests {
struct AllValues: ParsableCommand {
enum Manual: Int, ExpressibleByArgument {
case foo
static var allValueStrings = ["bar"]
}
enum UnspecializedSynthesized: Int, CaseIterable, ExpressibleByArgument {
case one, two
}
enum SpecializedSynthesized: String, CaseIterable, ExpressibleByArgument {
case apple = "Apple", banana = "Banana"
}
@Argument var manualArgument: Manual
@Option var manualOption: Manual
@Argument var unspecializedSynthesizedArgument: UnspecializedSynthesized
@Option var unspecializedSynthesizedOption: UnspecializedSynthesized
@Argument var specializedSynthesizedArgument: SpecializedSynthesized
@Option var specializedSynthesizedOption: SpecializedSynthesized
}
func testAllValueStrings() throws {
XCTAssertEqual(AllValues.Manual.allValueStrings, ["bar"])
XCTAssertEqual(AllValues.UnspecializedSynthesized.allValueStrings, ["one", "two"])
XCTAssertEqual(AllValues.SpecializedSynthesized.allValueStrings, ["Apple", "Banana"])
}
func testAllValues() {
let opts = ArgumentSet(AllValues.self, visibility: .private)
XCTAssertEqual(AllValues.Manual.allValueStrings, opts[0].help.allValues)
XCTAssertEqual(AllValues.Manual.allValueStrings, opts[1].help.allValues)
XCTAssertEqual(AllValues.UnspecializedSynthesized.allValueStrings, opts[2].help.allValues)
XCTAssertEqual(AllValues.UnspecializedSynthesized.allValueStrings, opts[3].help.allValues)
XCTAssertEqual(AllValues.SpecializedSynthesized.allValueStrings, opts[4].help.allValues)
XCTAssertEqual(AllValues.SpecializedSynthesized.allValueStrings, opts[5].help.allValues)
}
struct Q: ParsableArguments {
@Option(help: "Your name") var name: String
@Option(help: "Your title") var title: String?
@Argument(help: .private) var privateName: String?
@Option(help: .private) var privateTitle: String?
@Flag(help: .private) var privateFlag: Bool = false
@Flag(inversion: .prefixedNo, help: .private) var privateInvertedFlag: Bool = true
}
func testHelpWithPrivate() {
AssertHelp(.default, for: Q.self, equals: """
USAGE: q --name <name> [--title <title>]
OPTIONS:
--name <name> Your name
--title <title> Your title
-h, --help Show help information.
""")
}
}
// MARK: - Issue #278 https://github.com/apple/swift-argument-parser/issues/278
extension HelpGenerationTests {
private struct ParserBug: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "parserBug",
subcommands: [Sub.self])
struct CommonOptions: ParsableCommand {
@Flag(help: "example flag")
var example: Bool = false
}
struct Sub: ParsableCommand {
@OptionGroup()
var commonOptions: CommonOptions
@Argument(help: "Non-mandatory argument")
var argument: String?
}
}
func testIssue278() {
AssertHelp(.default, for: ParserBug.Sub.self, root: ParserBug.self, equals: """
USAGE: parserBug sub [--example] [<argument>]
ARGUMENTS:
<argument> Non-mandatory argument
OPTIONS:
--example example flag
-h, --help Show help information.
""")
}
struct CustomUsageShort: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(usage: """
example [--verbose] <file-name>
""")
}
@Argument var file: String
@Flag var verboseMode = false
}
struct CustomUsageLong: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(usage: """
example <file-name>
example --verbose <file-name>
example --help
""")
}
@Argument var file: String
@Flag var verboseMode = false
}
struct CustomUsageHidden: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(usage: "")
}
@Argument var file: String
@Flag var verboseMode = false
}
func testCustomUsageHelp() {
XCTAssertEqual(CustomUsageShort.helpMessage(columns: 80), """
USAGE: example [--verbose] <file-name>
ARGUMENTS:
<file>
OPTIONS:
--verbose-mode
-h, --help Show help information.
""")
XCTAssertEqual(CustomUsageLong.helpMessage(columns: 80), """
USAGE: example <file-name>
example --verbose <file-name>
example --help
ARGUMENTS:
<file>
OPTIONS:
--verbose-mode
-h, --help Show help information.
""")
XCTAssertEqual(CustomUsageHidden.helpMessage(columns: 80), """
ARGUMENTS:
<file>
OPTIONS:
--verbose-mode
-h, --help Show help information.
""")
}
func testCustomUsageError() {
XCTAssertEqual(CustomUsageShort.fullMessage(for: ValidationError("Test")), """
Error: Test
Usage: example [--verbose] <file-name>
See 'custom-usage-short --help' for more information.
""")
XCTAssertEqual(CustomUsageLong.fullMessage(for: ValidationError("Test")), """
Error: Test
Usage: example <file-name>
example --verbose <file-name>
example --help
See 'custom-usage-long --help' for more information.
""")
XCTAssertEqual(CustomUsageHidden.fullMessage(for: ValidationError("Test")), """
Error: Test
See 'custom-usage-hidden --help' for more information.
""")
}
}
| 29.476252 | 207 | 0.601298 |
e607edad1b70e10124b3832edd3197a11a63a5e6 | 1,873 | //
// AppDelegate.swift
// ClickCounter
//
// Created by juan ocampo on 4/4/20.
// Copyright © 2020 juan ocampo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
checkIfFirstLaunch()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func checkIfFirstLaunch() {
if UserDefaults.standard.bool(forKey: "HasLaunchedBefore") {
print("App has launched before")
} else {
print("This is the first launch ever!")
UserDefaults.standard.set(true, forKey: "HasLaunchedBefore")
UserDefaults.standard.set(0.0, forKey: "Slider Value Key")
UserDefaults.standard.synchronize()
}
}
}
| 38.22449 | 179 | 0.711159 |
721c4f0a59a3f85387d3945fb0bd462537474a2b | 20,787 | //
// UIButton+Extension.swift
// SDBaseClassLib
//
// Created by Liu Sida on 2021/4/3.
//
import UIKit
// MARK:- 带有样式的button
private enum LineType {
case none
case color(_: UIColor)
}
// MARK:- 一、基本的扩展
public extension SDPOP where Base: UIButton {
enum SmallButtonType {
case red
case pink
}
// MARK: 1.1、创建一个带颜色的 Button
/// 创建一个带颜色的 Button
/// - Parameters:
/// - type: 类型
/// - height: 高度
/// - Returns: 返回自身
@discardableResult
static func small(type: SmallButtonType = .red, height: CGFloat = 45) -> UIButton {
let normalColor: UIColor
let disabledColor: UIColor
let lineTypeNormal: LineType
let lineTypeDisable: LineType
let titleColorNormal: UIColor
let titleColorDisable: UIColor
switch type {
case .red:
normalColor = .hexStringColor(hexString: "#E54749")
disabledColor = .hexStringColor(hexString: "#CCCCCC")
lineTypeNormal = .none
lineTypeDisable = .none
titleColorNormal = .white
titleColorDisable = .white
case .pink:
normalColor = .hexStringColor(hexString: "#FFE8E8")
disabledColor = .hexStringColor(hexString: "#CCCCCC")
lineTypeNormal = .color(.hexStringColor(hexString: "#F6CDCD"))
lineTypeDisable = .color(.hexStringColor(hexString: "#9C9C9C"))
titleColorNormal = .hexStringColor(hexString: "#E54749")
titleColorDisable = .white
}
let btn = UIButton(type: .custom).font(.systemFont(ofSize: 16))
btn.setTitleColor(titleColorNormal, for: .normal)
btn.setTitleColor(titleColorDisable, for: .disabled)
btn.setBackgroundImage(drawSmallBtn(color: normalColor, height: height, lineType: lineTypeNormal), for: .normal)
btn.setBackgroundImage(drawSmallBtn(color: disabledColor, height: height, lineType: lineTypeDisable), for: .disabled)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 13, right: 0)
return btn
}
// MARK: 1.2、创建一个常规的 Button
/// 创建一个常规的 Button
/// - Returns: 返回自身
static func normal() -> UIButton {
let btn = UIButton(type: .custom).font(.boldSystemFont(ofSize: 18))
btn.setTitleColor(.white, for: .normal)
btn.setTitleColor(.white, for: .disabled)
btn.setBackgroundImage(drawNormalBtn(color: .hexStringColor(hexString: "#E54749"))?.resizableImage(withCapInsets: UIEdgeInsets(top: 10, left: 15, bottom: 15, right: 15)), for: .normal)
btn.setBackgroundImage(drawNormalBtn(color: .hexStringColor(hexString: "#CCCCCC"))?.resizableImage(withCapInsets: UIEdgeInsets(top: 10, left: 15, bottom: 15, right: 15)), for: .disabled)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 4, right: 0)
return btn
}
private static func drawSmallBtn(color: UIColor, height: CGFloat, lineType: LineType) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 200, height: height + 20)
let path = UIBezierPath(roundedRect: CGRect(x: 10, y: 3, width: 180, height: height), cornerRadius: height / 2)
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.addPath(path.cgPath)
context?.setShadow(offset: CGSize(width: 1, height: 4), blur: 10, color: color.withAlphaComponent(0.5).cgColor)
context?.fillPath()
switch lineType {
case let .color(color):
color.setStroke()
path.lineWidth = kPixel
path.stroke()
default:
break
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
private static func drawNormalBtn(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 260, height: 50)
let path = UIBezierPath(roundedRect: CGRect(x: 10, y: 3, width: 240, height: 40), cornerRadius: 3)
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.addPath(path.cgPath)
context?.setShadow(offset: CGSize(width: 1, height: 2), blur: 6, color: color.withAlphaComponent(0.5).cgColor)
context?.fillPath()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
// MARK:- 二、链式调用
public extension UIButton {
// MARK: 2.1、设置title
/// 设置title
/// - Parameters:
/// - text: 文字
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func title(_ text: String, _ state: UIControl.State = .normal) -> Self {
setTitle(text, for: state)
return self
}
// MARK: 2.2、设置文字颜色
/// 设置文字颜色
/// - Parameters:
/// - color: 文字颜色
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func textColor(_ color: UIColor, _ state: UIControl.State = .normal) -> Self {
setTitleColor(color, for: state)
return self
}
// MARK: 2.3、设置字体大小(UIFont)
/// 设置字体大小
/// - Parameter font: 字体 UIFont
/// - Returns: 返回自身
@discardableResult
func font(_ font: UIFont) -> Self {
titleLabel?.font = font
return self
}
// MARK: 2.4、设置字体大小(CGFloat)
/// 设置字体大小(CGFloat)
/// - Parameter fontSize: 字体的大小
/// - Returns: 返回自身
@discardableResult
func font(_ fontSize: CGFloat) -> Self {
titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
return self
}
// MARK: 2.5、设置字体粗体
/// 设置粗体
/// - Parameter fontSize: 设置字体粗体
/// - Returns: 返回自身
@discardableResult
func boldFont(_ fontSize: CGFloat) -> Self {
titleLabel?.font = UIFont.boldSystemFont(ofSize: fontSize)
return self
}
// MARK: 2.6、设置图片
/// 设置图片
/// - Parameters:
/// - image: 图片
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func image(_ image: UIImage?, _ state: UIControl.State = .normal) -> Self {
setImage(image, for: state)
return self
}
// MARK: 2.7、设置图片(通过Bundle加载)
/// 设置图片(通过Bundle加载)
/// - Parameters:
/// - bundle: Bundle
/// - imageName: 图片名字
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func image(in bundle: Bundle? = nil, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
setImage(image, for: state)
return self
}
// MARK: 2.8、设置图片(通过Bundle加载)
/// 设置图片(通过Bundle加载)
/// - Parameters:
/// - aClass: className bundle所在的类的类名
/// - bundleName: bundle 的名字
/// - imageName: 图片的名字
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func image(forParent aClass: AnyClass, bundleName: String, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
guard let path = Bundle(for: aClass).path(forResource: bundleName, ofType: "bundle") else {
return self
}
let image = UIImage(named: imageName, in: Bundle(path: path), compatibleWith: nil)
setImage(image, for: state)
return self
}
// MARK: 2.9、设置图片(纯颜色的图片)
/// 设置图片(纯颜色的图片)
/// - Parameters:
/// - color: 图片颜色
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func image(_ color: UIColor, _ size: CGSize = CGSize(width: 20.0, height: 20.0), _ state: UIControl.State = .normal) -> Self {
let image = UIImage.sd.image(color: color, size: size)
setImage(image, for: state)
return self
}
// MARK: 2.10、设置背景图片
/// 设置背景图片
/// - Parameters:
/// - image: 图片
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func bgImage(_ image: UIImage?, _ state: UIControl.State = .normal) -> Self {
setBackgroundImage(image, for: state)
return self
}
// MARK: 2.11、设置背景图片(通过Bundle加载)
/// 设置背景图片(通过Bundle加载)
/// - Parameters:
/// - aClass: className bundle所在的类的类名
/// - bundleName: bundle 的名字
/// - imageName: 图片的名字
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func bgImage(forParent aClass: AnyClass, bundleName: String, _ imageName: String, _: UIControl.State = .normal) -> Self {
guard let path = Bundle(for: aClass).path(forResource: bundleName, ofType: "bundle") else {
return self
}
let image = UIImage(named: imageName, in: Bundle(path: path), compatibleWith: nil)
setBackgroundImage(image, for: state)
return self
}
// MARK: 2.12、设置背景图片(通过Bundle加载)
/// 设置背景图片(通过Bundle加载)
/// - Parameters:
/// - bundle: Bundle
/// - imageName: 图片的名字
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func bgImage(in bundle: Bundle? = nil, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
setBackgroundImage(image, for: state)
return self
}
// MARK: 2.13、设置背景图片(纯颜色的图片)
/// 设置背景图片(纯颜色的图片)
/// - Parameters:
/// - color: 背景色
/// - state: 状态
/// - Returns: 返回自身
@discardableResult
func bgImage(_ color: UIColor, _ state: UIControl.State = .normal) -> Self {
let image = UIImage.sd.image(color: color)
setBackgroundImage(image, for: state)
return self
}
// MARK: 2.14、按钮点击的变化
/// 按钮点击的变化
/// - Returns: 返回自身
@discardableResult
func confirmButton() -> Self {
let normalImage = UIImage.sd.image(color: UIColor.hexStringColor(hexString: "#E54749"), size: CGSize(width: 10, height: 10), corners: .allCorners, radius: 4)?.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
let disableImg = UIImage.sd.image(color: UIColor.hexStringColor(hexString: "#E6E6E6"), size: CGSize(width: 10, height: 10), corners: .allCorners, radius: 4)?.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
setBackgroundImage(normalImage, for: .normal)
setBackgroundImage(disableImg, for: .disabled)
return self
}
}
// MARK:- 三、UIButton 图片 与 title 位置关系
/// UIButton 图片与title位置关系 https://www.jianshu.com/p/0f34c1b52604
public extension SDPOP where Base: UIButton {
/// 图片 和 title 的布局样式
enum ImageTitleLayout {
case imgTop
case imgBottom
case imgLeft
case imgRight
}
// MARK: 3.1、设置图片和 title 的位置关系(提示:title和image要在设置布局关系之前设置)
/// 设置图片和 title 的位置关系(提示:title和image要在设置布局关系之前设置)
/// - Parameters:
/// - layout: 布局
/// - spacing: 间距
/// - Returns: 返回自身
@discardableResult
func setImageTitleLayout(_ layout: ImageTitleLayout, spacing: CGFloat = 0) -> UIButton {
switch layout {
case .imgLeft:
alignHorizontal(spacing: spacing, imageFirst: true)
case .imgRight:
alignHorizontal(spacing: spacing, imageFirst: false)
case .imgTop:
alignVertical(spacing: spacing, imageTop: true)
case .imgBottom:
alignVertical(spacing: spacing, imageTop: false)
}
return self.base
}
/// 水平方向
/// - Parameters:
/// - spacing: 间距
/// - imageFirst: 图片是否优先
private func alignHorizontal(spacing: CGFloat, imageFirst: Bool) {
let edgeOffset = spacing / 2
base.imageEdgeInsets = UIEdgeInsets(top: 0,
left: -edgeOffset,
bottom: 0,
right: edgeOffset)
base.titleEdgeInsets = UIEdgeInsets(top: 0,
left: edgeOffset,
bottom: 0,
right: -edgeOffset)
if !imageFirst {
base.transform = CGAffineTransform(scaleX: -1, y: 1)
base.imageView?.transform = CGAffineTransform(scaleX: -1, y: 1)
base.titleLabel?.transform = CGAffineTransform(scaleX: -1, y: 1)
}
base.contentEdgeInsets = UIEdgeInsets(top: 0, left: edgeOffset, bottom: 0, right: edgeOffset)
}
/// 垂直方向
/// - Parameters:
/// - spacing: 间距
/// - imageTop: 图片是不是在顶部
private func alignVertical(spacing: CGFloat, imageTop: Bool) {
guard let imageSize = self.base.imageView?.image?.size,
let text = self.base.titleLabel?.text,
let font = self.base.titleLabel?.font
else {
return
}
let labelString = NSString(string: text)
let titleSize = labelString.size(withAttributes: [NSAttributedString.Key.font: font])
let imageVerticalOffset = (titleSize.height + spacing) / 2
let titleVerticalOffset = (imageSize.height + spacing) / 2
let imageHorizontalOffset = (titleSize.width) / 2
let titleHorizontalOffset = (imageSize.width) / 2
let sign: CGFloat = imageTop ? 1 : -1
base.imageEdgeInsets = UIEdgeInsets(top: -imageVerticalOffset * sign,
left: imageHorizontalOffset,
bottom: imageVerticalOffset * sign,
right: -imageHorizontalOffset)
base.titleEdgeInsets = UIEdgeInsets(top: titleVerticalOffset * sign,
left: -titleHorizontalOffset,
bottom: -titleVerticalOffset * sign,
right: titleHorizontalOffset)
// increase content height to avoid clipping
let edgeOffset = (min(imageSize.height, titleSize.height) + spacing) / 2
base.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0, bottom: edgeOffset, right: 0)
}
}
// MARK:- 四、自带倒计时功能的 Button(有待改进)
/// 自带倒计时功能的Button
/// - 状态分为 [倒计时中,倒计时完成],分别提供回调
/// - 需要和业务结合时,后期再考虑
public extension UIButton {
// MARK: 4.1、设置 Button 倒计时
/// 设置 Button 倒计时
/// - Parameters:
/// - count: 最初的倒计时数字
/// - timering: 倒计时中的 Block
/// - complete: 倒计时完成的 Block
/// - timeringPrefix: 倒计时文字的:前缀
/// - completeText: 倒计时完成后的文字
func countDown(_ count: Int, timering: TimeringBlock? = nil, complete: CompletionBlock? = nil, timeringPrefix: String = "再次获取", completeText: String = "重新获取") {
isEnabled = false
let begin = ProcessInfo().systemUptime
let c_default = UIColor.hexStringColor(hexString: "#2798fd")
let c_default_disable = UIColor.hexStringColor(hexString: "#999999")
self.textColor(titleColor(for: .normal) ?? c_default)
self.textColor(titleColor(for: .disabled) ?? c_default_disable, .disabled)
var remainingCount: Int = count {
willSet {
setTitle(timeringPrefix + "(\(newValue)s)", for: .normal)
if newValue <= 0 {
setTitle(completeText, for: .normal)
}
}
}
self.invalidate()
self.timer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
self.timer?.schedule(deadline: .now(), repeating: .seconds(1))
self.isTiming = true
self.timer?.setEventHandler(handler: {
DispatchQueue.main.async {
remainingCount = count - Int(ProcessInfo().systemUptime - begin)
if remainingCount <= 0 {
if let cb = complete {
cb()
}
// 计时结束后,enable的条件
self.isEnabled = self.reEnableCond ?? true
self.isTiming = false
self.invalidate()
} else {
if let tb = timering {
tb(remainingCount)
}
}
}
})
self.timer?.resume()
}
// MARK: 4.2、是否可以点击
/// 是否可以点击
var reEnableCond: Bool? {
get {
if let value = objc_getAssociatedObject(self, &TimerKey.reEnableCond_key) {
return value as? Bool
}
return nil
}
set {
objc_setAssociatedObject(self, &TimerKey.reEnableCond_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: 4.3、是否正在倒计时
/// 是否正在倒计时
var isTiming: Bool {
get {
if let value = objc_getAssociatedObject(self, &TimerKey.running_key) {
return value as! Bool
}
// 默认状态
return false
}
set {
objc_setAssociatedObject(self, &TimerKey.running_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: 4.3、处于倒计时时,前缀文案,如:「再次获取」 + (xxxs)
/// 处于倒计时时,前缀文案,如:「再次获取」 + (xxxs)
var timeringPrefix: String? {
get {
if let value = objc_getAssociatedObject(self, &TimerKey.timeringPrefix_key) {
return value as? String
}
return nil
}
set {
objc_setAssociatedObject(self, &TimerKey.timeringPrefix_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: 销毁定时器
/// 销毁定时器
func invalidate() {
if self.timer != nil {
self.timer?.cancel()
self.timer = nil
}
}
// MARK: 时间对象
/// 时间对象
var timer: DispatchSourceTimer? {
get {
if let value = objc_getAssociatedObject(self, &TimerKey.timer_key) {
return value as? DispatchSourceTimer
}
return nil
}
set {
objc_setAssociatedObject(self, &TimerKey.timer_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
typealias TimeringBlock = (Int) -> ()
typealias CompletionBlock = () -> ()
private struct TimerKey {
static var timer_key = "timer_key"
static var running_key = "running_key"
static var timeringPrefix_key = "timering_prefix_key"
static var reEnableCond_key = "re_enable_cond_key"
}
}
// MARK:- 五、Button的基本事件
private var buttonCallBackKey: Void?
extension UIButton: SDSwiftPropertyCompatible {
internal typealias T = UIButton
internal var swiftCallBack: SwiftCallBack? {
get { return sd_getAssociatedObject(self, &buttonCallBackKey) }
set { sd_setRetainedAssociatedObject(self, &buttonCallBackKey, newValue) }
}
@objc internal func swiftButtonAction(_ button: UIButton) {
self.swiftCallBack?(button)
}
}
public extension SDPOP where Base: UIButton {
// MARK: 5.1、button的事件
/// button的事件
/// - Parameters:
/// - controlEvents: 事件类型,默认是 valueChanged
/// - buttonCallBack: 事件
/// - Returns: 闭包事件
func setHandleClick(controlEvents: UIControl.Event = .touchUpInside, buttonCallBack: ((_ button: UIButton?) -> ())?){
base.swiftCallBack = buttonCallBack
base.addTarget(base, action: #selector(base.swiftButtonAction), for: controlEvents)
}
}
// MARK:- 六、Button扩大点击事件
private var SDUIButtonExpandSizeKey = "SDUIButtonExpandSizeKey"
public extension UIButton {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let buttonRect = self.sd.expandRect()
if (buttonRect.equalTo(bounds)) {
return super.point(inside: point, with: event)
}else{
return buttonRect.contains(point)
}
}
}
public extension SDPOP where Base: UIButton {
// MARK: 6.1、扩大UIButton的点击区域,向四周扩展10像素的点击范围
/// 扩大UIButton的点击区域,向四周扩展10像素的点击范围
/// - Parameter size: 向四周扩展像素的点击范围
func expandSize(size: CGFloat) {
objc_setAssociatedObject(self.base, &SDUIButtonExpandSizeKey, size, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
fileprivate func expandRect() -> CGRect {
let expandSize = objc_getAssociatedObject(self.base, &SDUIButtonExpandSizeKey)
if (expandSize != nil) {
return CGRect(x: self.base.bounds.origin.x - (expandSize as! CGFloat), y: self.base.bounds.origin.y - (expandSize as! CGFloat), width: self.base.bounds.size.width + 2 * (expandSize as! CGFloat), height: self.base.bounds.size.height + 2 * (expandSize as! CGFloat))
} else {
return self.base.bounds
}
}
}
| 35.901554 | 275 | 0.590128 |
39e90295203a52cb655b29e2a72e7207760e7de6 | 5,373 | //
// ViewController2.swift
// mobilizer
//
// Created by Connor on 6/13/16.
// Copyright © 2016 Connor Kirk. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController2 : UIViewController, AVCaptureMetadataOutputObjectsDelegate{
@IBOutlet weak var messageLabel: UILabel!
var captureSession:AVCaptureSession?
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
var qrCodeFrameView:UIView?
// Added to support different barcodes
let supportedBarCodes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeUPCECode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeAztecCode]
override func viewDidLoad() {
super.viewDidLoad()
// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
// as the media type parameter.
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice)
// Initialize the captureSession object.
captureSession = AVCaptureSession()
// Set the input device on the capture session.
captureSession?.addInput(input)
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
// Detect all the supported bar code
captureMetadataOutput.metadataObjectTypes = supportedBarCodes
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture
captureSession?.startRunning()
// Move the message label to the top view
view.bringSubviewToFront(messageLabel)
// Initialize QR Code Frame to highlight the QR code
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
//qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor
qrCodeFrameView.layer.borderColor = UIColor(red:0.64, green:0.82, blue:0.77, alpha:1.0).CGColor
qrCodeFrameView.layer.borderWidth = 2
view.addSubview(qrCodeFrameView)
view.bringSubviewToFront(qrCodeFrameView)
}
} catch {
// If any error occurs, simply print it out and don't continue any more.
print(error)
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
// Check if the metadataObjects array is not nil and it contains at least one object.
if metadataObjects == nil || metadataObjects.count == 0 {
qrCodeFrameView?.frame = CGRectZero
messageLabel.text = "No barcode/QR code is detected"
return
}
// Get the metadata object.
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
// Here we use filter method to check if the type of metadataObj is supported
// Instead of hardcoding the AVMetadataObjectTypeQRCode, we check if the type
// can be found in the array of supported bar codes.
if supportedBarCodes.contains(metadataObj.type) {
// if metadataObj.type == AVMetadataObjectTypeQRCode {
// If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj)
qrCodeFrameView?.frame = barCodeObject!.bounds
if metadataObj.stringValue != nil {
messageLabel.text = metadataObj.stringValue
self.performSegueWithIdentifier("segue2to3", sender: nil)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let dest : ViewController3 = segue.destinationViewController as! ViewController3
dest.id = messageLabel.text!
captureSession?.stopRunning()
}
} | 44.404959 | 277 | 0.656803 |
9bdfe658cf039a83261e647002d7dcbe6ae8a0d5 | 3,029 | /**
* Copyright (c) 2016 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.
*
* 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
final class SlideInPresentationAnimator: NSObject {
// MARK: - Properties
let direction: PresentationDirection
let isPresentation: Bool
// MARK: - Initializers
init(direction: PresentationDirection, isPresentation: Bool) {
self.direction = direction
self.isPresentation = isPresentation
super.init()
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension SlideInPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from
let controller = transitionContext.viewController(forKey: key)!
if isPresentation {
transitionContext.containerView.addSubview(controller.view)
}
let presentedFrame = transitionContext.finalFrame(for: controller)
var dismissedFrame = presentedFrame
switch direction {
case .left:
dismissedFrame.origin.x = -presentedFrame.width
case .right:
dismissedFrame.origin.x = transitionContext.containerView.frame.size.width
case .top:
dismissedFrame.origin.y = -presentedFrame.height
case .bottom:
dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
}
let initialFrame = isPresentation ? dismissedFrame : presentedFrame
let finalFrame = isPresentation ? presentedFrame : dismissedFrame
let animationDuration = transitionDuration(using: transitionContext)
controller.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, animations: {
controller.view.frame = finalFrame
}) { finished in
transitionContext.completeTransition(finished)
}
}
}
| 38.341772 | 114 | 0.761307 |
f7d4f7f2460a3a1fa771d55b17f543012d561074 | 8,305 | //
// APIStub.swift
// TRON
//
// Created by Denys Telezhkin on 11.12.15.
// Copyright © 2015 - present MLSDev. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
// This protocol is only needed to work around bogus warning message when casting Alamofire.Request below.
// For example this line
// if let stubbedRequest = self as? UploadRequest
// produces a warning "Cast from `Self` to unrelated type `UploadRequest` always fails".
// This is wrong as the cast actually succeeds at runtime, and the only reason why it exists
// apparently is returning Self from method, which somehow affects this warning.
protocol DataRequestResponseSerialization {}
extension DataRequest: DataRequestResponseSerialization {}
extension DataRequestResponseSerialization {
func performResponseSerialization<Serializer>(queue: DispatchQueue,
responseSerializer: Serializer,
completionHandler: @escaping (DataResponse<Serializer.SerializedObject>) -> Void) -> Self
where Serializer: DataResponseSerializerProtocol {
if let stubbedRequest = self as? DataRequest, let stub = stubbedRequest.tron_apiStub, stub.isEnabled {
let start = CFAbsoluteTimeGetCurrent()
let result = Result {
try responseSerializer.serialize(request: stub.request, response: stub.response, data: stub.data, error: stub.error)
}
let end = CFAbsoluteTimeGetCurrent()
let response = DataResponse(request: stub.request,
response: stub.response,
data: stub.data,
metrics: nil,
serializationDuration: (end - start),
result: result)
queue.asyncAfter(deadline: .now() + stub.stubDelay) {
completionHandler(response)
}
return self
} else if let uploadRequest = self as? UploadRequest {
//swiftlint:disable:next force_cast
return uploadRequest.response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) as! Self
} else if let dataRequest = self as? DataRequest {
//swiftlint:disable:next force_cast
return dataRequest.response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) as! Self
} else {
fatalError("\(type(of: self)) is not supported")
}
}
}
extension DownloadRequest {
func performResponseSerialization<Serializer>(queue: DispatchQueue,
responseSerializer: Serializer,
completionHandler: @escaping (DownloadResponse<Serializer.SerializedObject>) -> Void) -> Self
where Serializer: DownloadResponseSerializerProtocol {
if let stub = tron_apiStub, stub.isEnabled {
let start = CFAbsoluteTimeGetCurrent()
let result = Result {
try responseSerializer.serializeDownload(request: stub.request, response: stub.response, fileURL: stub.fileURL, error: stub.error)
}
let end = CFAbsoluteTimeGetCurrent()
let response = DownloadResponse(request: stub.request,
response: stub.response,
fileURL: stub.fileURL,
resumeData: resumeData,
metrics: nil,
serializationDuration: (end - start),
result: result)
queue.asyncAfter(deadline: .now() + stub.stubDelay) {
completionHandler(response)
}
return self
} else {
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
}
private var TRONAPIStubAssociatedKey = "TRON APIStub Associated Key"
extension Request {
var tron_apiStub: APIStub? {
get {
return objc_getAssociatedObject(self, &TRONAPIStubAssociatedKey) as? APIStub
}
set {
if let stub = newValue {
objc_setAssociatedObject(self, &TRONAPIStubAssociatedKey, stub, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
/**
`APIStub` instance that is used to represent stubbed response. Any properties of this class is presented to serialization classes as if they would be received by URL loading system.
*/
open class APIStub {
/// `URLRequest` object to use when request is being stubbed.
open var request: URLRequest?
/// `HTTPURLResponse` to use when request is being stubbed.
open var response: HTTPURLResponse?
/// `Data` to use when request is being stubbed. This property is ignored for `DownloadAPIRequest`.
open var data: Data?
/// Error to use when request is being stubbed.
open var error: Error?
/// File URL to use when stubbing `DownloadAPIRequest`. This property is ignored for `APIRequest` and `UploadAPIRequest`.
open var fileURL: URL?
/// Delay before stub is executed
open var stubDelay: Double = 0
/// When this property is set to true, stub will be activated. Defaults to false.
open var isEnabled: Bool = false
/// Creates `APIStub` instance for `APIRequest` and `UploadAPIRequest`.
///
/// - Parameters:
/// - request: `URLRequest` object ot use when request is being stubbed. Defaults to nil.
/// - response: `HTTPURLResponse` object to use when request is being stubbed. Defaults to nil.
/// - data: `Data` object to use when request is being stubbed. Defaults to nil.
/// - error: `Error` to use when request is being stubbed. Defaults to nil.
public init(request: URLRequest? = nil,
response: HTTPURLResponse? = nil,
data: Data? = nil,
error: Error? = nil) {
self.request = request
self.response = response
self.data = data
self.error = error
}
/// Creates `APIStub` instance for `DownloadAPIRequest`.
///
/// - Parameters:
/// - request: `URLRequest` object ot use when request is being stubbed. Defaults to nil.
/// - response: `HTTPURLResponse` object to use when request is being stubbed. Defaults to nil.
/// - fileURL: File URL of downloaded file to use when request is being stubbed. Defaults to nil.
/// - error: `Error` to use when request is being stubbed. Defaults to nil.
public init(request: URLRequest? = nil,
response: HTTPURLResponse? = nil,
fileURL: URL? = nil,
error: Error? = nil) {
self.request = request
self.response = response
self.fileURL = fileURL
self.error = error
}
}
| 48.00578 | 182 | 0.624202 |
616cf873d62248214e81a3d75e13ae90c47927de | 1,572 | //
// DZMReadViewStatusTopView.swift
// DZMeBookRead
//
// Created by dengzemiao on 2019/4/17.
// Copyright © 2019年 DZM. All rights reserved.
//
import UIKit
/// topView 高度
let DZM_READ_STATUS_TOP_VIEW_HEIGHT:CGFloat = DZM_SPACE_SA_40
class DZMReadViewStatusTopView: UIView {
/// 书名
private(set) var bookName:UILabel!
/// 章节名
private(set) var chapterName:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
addSubviews()
}
private func addSubviews() {
// 书名
bookName = UILabel()
bookName.font = DZM_FONT_SA_10
bookName.textColor = DZMReadConfigure.shared().statusTextColor
bookName.textAlignment = .left
addSubview(bookName)
// 章节名
chapterName = UILabel()
chapterName.font = DZM_FONT_SA_10
chapterName.textColor = DZMReadConfigure.shared().statusTextColor
chapterName.textAlignment = .right
addSubview(chapterName)
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.size.width
let h = frame.size.height
let labelW = (w - DZM_SPACE_SA_15) / 2
// 书名
bookName.frame = CGRect(x: 0, y: 0, width: labelW, height: h)
// 章节名
chapterName.frame = CGRect(x: w - labelW, y: 0, width: labelW, height: h)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 23.818182 | 81 | 0.589059 |
7921f53f6787c7e5a9c222c28cc31de95b77d326 | 384 | // Copyright © Fleuronic LLC. All rights reserved.
#if swift(>=5.5)
public extension Request where Response: Decodable {
var returnedResource: Resource {
get async throws {
try await returnedResult.get()
}
}
}
public extension Request where Response: DataDecodable {
var returnedResource: Resource {
get async throws {
try await returnedResult.get()
}
}
}
#endif
| 18.285714 | 56 | 0.71875 |
89de5f60228dc5cf5cf463f96e917d60ec06b82a | 730 | //
// AppContext+TestRuner.swift
// Thali
//
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE.txt file in the project root for full license information.
//
import Foundation
import SwiftXCTest
import ThaliCore
extension AppContext: TestRunnerProtocol {
func runNativeTests() -> String {
let rootTestSuite = XCTestSuite(name: "All tests")
let currentTestSuite = XCTestSuite(
name: "All tests",
testCases: [
[testCase(AppContextTests.allTests)]
].flatMap { $0 }
)
rootTestSuite.addTest(currentTestSuite)
let runner = TestRunner(testSuite: rootTestSuite)
runner.runTest()
return runner.resultDescription ?? ""
}
}
| 22.121212 | 74 | 0.693151 |
62c1831615494e9036af1e35072a7957e7d63f90 | 2,997 | //
// MIBadgeButton.swift
// MIBadgeButton
//
// Created by Yosemite on 8/27/14.
// Copyright (c) 2014 Youxel Technology. All rights reserved.
//
import UIKit
class MIBadgeButton: UIButton {
var calculationTextView: UITextView
var badgeLabel: UILabel
var badgeString: NSString? {
didSet {
self.setupBadgeViewWithString(badgeText: badgeString)
}
}
var badgeEdgeInsets: UIEdgeInsets? {
didSet {
self.setupBadgeViewWithString(badgeText: badgeString)
}
}
override init(frame: CGRect) {
calculationTextView = UITextView()
badgeLabel = MIBadgeLabel(frame: CGRectMake(0, 0, 10, 10))
super.init(frame: frame)
// Initialization code
self.setupBadgeViewWithString(badgeText: "")
}
required init(coder aDecoder: NSCoder) {
calculationTextView = UITextView()
badgeLabel = MIBadgeLabel(frame: CGRectMake(0, 0, 10, 10))
super.init(coder: aDecoder)!
self.setupBadgeViewWithString(badgeText: "")
}
func initWithFrame(frame frame: CGRect, withBadgeString badgeString: NSString, withBadgeInsets badgeInsets: UIEdgeInsets) -> AnyObject {
self.calculationTextView = UITextView()
self.badgeLabel = MIBadgeLabel(frame: CGRectMake(0, 0, 10, 10))
self.badgeEdgeInsets = badgeInsets
self.setupBadgeViewWithString(badgeText: badgeString)
return self
}
func setupBadgeViewWithString(badgeText badgeText: NSString?) {
badgeLabel.clipsToBounds = true
badgeLabel.text = badgeText as NSString? as? String
var badgeSize: CGSize = badgeLabel.sizeThatFits(CGSize(width: 320, height: CGFloat(FLT_MAX)))
badgeSize.width = badgeSize.width < 20 ? 25 : badgeSize.width + 5
var vertical: Double?, horizontal: Double?
if let badgeInset = self.badgeEdgeInsets {
vertical = Double(badgeInset.top) - Double(badgeInset.bottom)
horizontal = Double(badgeInset.left) - Double(badgeInset.right)
let x = (Double(bounds.size.width) - 5 + horizontal!)
let y = -(Double(badgeSize.height) / 2) - 5 + vertical!
let width = Double(badgeSize.width)
let height = Double(badgeSize.height)
badgeLabel.frame = CGRect(x: x, y: y, width: width, height: height)
} else {
badgeLabel.frame = CGRectMake(self.bounds.size.width - 5, -(badgeSize.height / 2) - 5, badgeSize.width, badgeSize.height)
}
self.setupBadgeStyle()
self.addSubview(badgeLabel)
badgeLabel.hidden = badgeText != nil ? false : true
}
func setupBadgeStyle()
{
badgeLabel.textAlignment = .Center
badgeLabel.backgroundColor = UIColor(red: 33/255, green: 192/255, blue: 100/255, alpha: 1.0)
badgeLabel.textColor = UIColor.blackColor()
badgeLabel.layer.cornerRadius = 10.0
}
}
| 34.848837 | 140 | 0.636637 |
337e353edf1e2b85ac775d9248becca8b6e216f1 | 971 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Hummingbird
extension HBResponse {
/// Set cookie on response
public func setCookie(_ cookie: HBCookie) {
self.headers.add(name: "Set-Cookie", value: cookie.description)
}
}
extension HBRequest.ResponsePatch {
/// Set cookie on reponse patch
///
/// Can be accessed via `request.response.setCookie(myCookie)`
public func setCookie(_ cookie: HBCookie) {
self.headers.add(name: "Set-Cookie", value: cookie.description)
}
}
| 30.34375 | 80 | 0.588054 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.