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
|
---|---|---|---|---|---|
abb3aa3d1470f240a680cef85cfa7b620f923d15
| 3,181 |
import UIKit
class UserCell: SeparatorCell {
@IBOutlet weak var followButton: LoaderButton!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var sentBadgeLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var verifiedBadgeImageView: UIImageView!
@IBOutlet weak var voteCountLabel: UILabel!
@IBOutlet weak var rankLabel: UILabel!
@IBOutlet weak var rankLabelWidth: NSLayoutConstraint!
var user: Account? {
didSet {
if let name = self.user?.username {
self.titleLabel.text = name
}
if let url = self.user?.imageURL {
self.profileImageView.af_setImage(withURL: url)
}
if let verified = self.user?.isVerified {
self.verifiedBadgeImageView.isHidden = !verified
}
if let user = self.user as? AccountWithFollowState, !user.isCurrentUser {
self.updateFollowButton(state: user.isFollowing)
} else {
self.updateFollowButton(state: nil)
}
}
}
var rank: Int? {
didSet {
guard let rank = self.rank else {
self.rankLabel.text = nil
self.rankLabelWidth.constant = 0
return
}
self.rankLabel.text = "\(rank)."
self.rankLabelWidth.constant = 28
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.followButton.loader.activityIndicatorViewStyle = .white
let highlightView = UIView()
highlightView.backgroundColor = UIColor(white: 0.15, alpha: 1)
self.selectedBackgroundView = highlightView
}
override func prepareForReuse() {
super.prepareForReuse()
self.followButton.isLoading = false
self.profileImageView.image = #imageLiteral(resourceName: "single")
self.sentBadgeLabel.text = ""
self.titleLabel.text = nil
self.verifiedBadgeImageView.isHidden = true
self.voteCountLabel.text = nil
}
// MARK: - Actions
@IBAction func followButtonTapped(_ sender: LoaderButton) {
guard let user = self.user as? AccountWithFollowState else {
return
}
self.followButton.isLoading = true
user.toggleFollowing {
self.followButton.isLoading = false
self.updateFollowButton(state: $0)
}
}
// MARK: - Private
private func updateFollowButton(state: Bool?) {
guard let isFollowing = state else {
self.followButton.setTitle("", for: .normal)
self.followButton.isUserInteractionEnabled = false
return
}
if isFollowing {
self.followButton.setTitleColor(.white, for: .normal)
self.followButton.setTitle("check", for: .normal)
self.followButton.isUserInteractionEnabled = false
} else {
self.followButton.setTitleColor(.uiYellow, for: .normal)
self.followButton.setTitle("add", for: .normal)
self.followButton.isUserInteractionEnabled = true
}
}
}
| 33.484211 | 85 | 0.603898 |
f540352cb93e4aff1949bfd752df3b6b1d5e9f66
| 2,261 |
//
// GlucoseRxMessage.swift
// xDrip5
//
// Created by Nathan Racklyeft on 11/23/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import Foundation
public struct GlucoseSubMessage: TransmitterRxMessage {
static let size = 8
public let timestamp: UInt32
public let glucoseIsDisplayOnly: Bool
public let glucose: UInt16
public let state: UInt8
public let trend: Int8
init?(data: Data) {
guard data.count == GlucoseSubMessage.size else {
return nil
}
var start = data.startIndex
var end = start.advanced(by: 4)
timestamp = data[start..<end].toInt()
start = end
end = start.advanced(by: 2)
let glucoseBytes = data[start..<end].to(UInt16.self)
glucoseIsDisplayOnly = (glucoseBytes & 0xf000) > 0
glucose = glucoseBytes & 0xfff
start = end
end = start.advanced(by: 1)
state = data[start]
start = end
end = start.advanced(by: 1)
trend = Int8(bitPattern: data[start])
}
}
public struct GlucoseRxMessage: TransmitterRxMessage {
public let status: UInt8
public let sequence: UInt32
public let glucose: GlucoseSubMessage
init?(data: Data) {
guard data.count == 16 && data.isCRCValid else {
return nil
}
guard data.starts(with: .glucoseRx) else {
return nil
}
status = data[1]
sequence = data[2..<6].toInt()
guard let glucose = GlucoseSubMessage(data: data[6..<14]) else {
return nil
}
self.glucose = glucose
}
}
extension GlucoseSubMessage: Equatable {
public static func ==(lhs: GlucoseSubMessage, rhs: GlucoseSubMessage) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.glucoseIsDisplayOnly == rhs.glucoseIsDisplayOnly &&
lhs.glucose == rhs.glucose &&
lhs.state == rhs.state &&
lhs.trend == rhs.trend
}
}
extension GlucoseRxMessage: Equatable {
public static func ==(lhs: GlucoseRxMessage, rhs: GlucoseRxMessage) -> Bool {
return lhs.status == rhs.status &&
lhs.sequence == rhs.sequence &&
lhs.glucose == rhs.glucose
}
}
| 25.404494 | 83 | 0.601061 |
6a27c1804d9abaee81f767699f6b702282d931c3
| 2,959 |
//
// ViewController.swift
// EnglistWords
//
// Created by Alexluan on 2019/9/29.
// Copyright © 2019 Alexluan. All rights reserved.
//
import UIKit
import SnapKit
//新1 词汇2900 水平小学到初中 对应考试剑桥少儿英语2级
//
//新2 词汇3000 水平高考 对应考试剑桥通用英语证书PET 雅思3.5
//
//新3 词汇4500 水平大学四级 对应考试剑桥通用英语证书PCE 雅思6.5
//
//新4 词汇6000 水平大学六级 对应考试新托福100分 雅思7.5
class ViewController: UIViewController {
private var voiceList = [String]()
private let tableView = UITableView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
title = "雅思词汇"
view.backgroundColor = .systemBackground
createUI()
createData()
let link = "http://download.dogwood.com.cn/online/yschlx/WordList41.mp3"
LYSDownloadHelper.instance.registCallBack(url: URL(string: link)!) { (process, uurl) in
print(".........::\(process)")
}
}
private func createUI() {
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview()
make.top.equalToSuperview().offset(view.safeAreaInsets.top)
make.bottom.equalTo(view.snp.bottomMargin)
}
}
private func createData() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.rowHeight = 45
tableView.delegate = self
tableView.dataSource = self
for i in 0..<45 {
let index = i + 1
var indexStr = ""
if index < 10 {
indexStr = "0\(String(index))"
} else {
indexStr = String(index)
}
let link = "http://download.dogwood.com.cn/online/yschlx/WordList\(indexStr).mp3"
voiceList.append(link)
}
tableView.reloadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return voiceList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.selectionStyle = .none
cell?.textLabel?.textColor = .label
cell?.textLabel?.text = getIdentifier(index: indexPath.row)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let url = voiceList[indexPath.row]
navigationController?.pushViewController(VoiceDetailController(url: url, title: getIdentifier(index: indexPath.row)), animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
private func getIdentifier(index: Int) -> String{
return "WordList\(index + 1)"
}
}
| 30.505155 | 141 | 0.639743 |
6417df8c12d76b9702e4216d159b7dbef9c71359
| 1,915 |
//
// SlackRequest.swift
// Kitura-Starter
//
// Created by B Gay on 8/16/17.
//
//
import Foundation
import SwiftyJSON
public enum SlackItem: String
{
case token
case teamID = "team_id"
case teamDomain = "team_domain"
case channelID = "channel_id"
case channelName = "channel_name"
case userID = "user_id"
case userName = "user_name"
case command
case text
case responseURL = "response_url"
}
public struct SlackRequest
{
public var token: String?
public var teamID: String?
public var teamDomain: String?
public var channelID: String?
public var channelName: String?
public var userID: String?
public var userName: String?
public var command: String?
public var text: String?
public var responseURL: URL?
public init(payload: String)
{
let elementPairs = payload.components(separatedBy: "&")
for element in elementPairs
{
let elementItem = element.components(separatedBy: "=")
guard let slackItem = SlackItem(rawValue: elementItem[0]) else { continue }
switch slackItem
{
case .token:
token = elementItem[1]
case .teamID:
teamID = elementItem[1]
case .teamDomain:
teamDomain = elementItem[1]
case .channelID:
channelID = elementItem[1]
case .channelName:
channelName = elementItem[1]
case .userID:
userID = elementItem[1]
case .userName:
userName = elementItem[1]
case .command:
command = elementItem[1]
case .text:
text = elementItem[1]
case .responseURL:
responseURL = URL(string: elementItem[1].removingPercentEncoding ?? "")
}
}
}
}
| 26.232877 | 87 | 0.569713 |
f5a38c5037b3963221642d92afcfdcc7c2975e9a
| 17,289 |
import UIKit
import Then
class AuctionViewController: UIViewController {
@objc let saleID: String
@objc var saleViewModel: SaleViewModel!
var appeared = false
var headerStack: ORStackView?
var stickyHeader: ScrollingStickyHeaderView!
var titleView: AuctionTitleView?
var lotStandingsView: LotStandingsView?
var buyNowView: AuctionBuyNowView?
var allowAnimations = true
fileprivate var showLiveInterfaceWhenAuctionOpensTimer: Timer?
/// Variable for storing lazily-computed default refine settings.
/// Should not be accessed directly, call defaultRefineSettings() instead.
fileprivate var _defaultRefineSettings: AuctionRefineSettings?
fileprivate var saleArtworksViewController: ARModelInfiniteScrollViewController!
fileprivate var activeModule: ARSaleArtworkItemWidthDependentModule?
/// Current refine settings.
/// Our refine settings are (by default) the defaultRefineSettings().
lazy var refineSettings: AuctionRefineSettings = {
return self.defaultRefineSettings()
}()
lazy var networkModel: AuctionNetworkModelType = {
return AuctionNetworkModel(saleID: self.saleID)
}()
@objc init(saleID: String) {
self.saleID = saleID
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
return nil
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.ARAuctionArtworkRegistrationUpdated, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if appeared && saleViewModel.isNotEmpty {
// Re-appearing, so: check if Live has launched, and if not, re-fetch lot standings and update.
if saleViewModel.shouldShowLiveInterface {
setupLiveInterfaceAndPop()
} else {
fetchLotStandingsAndUpdate()
}
}
guard appeared == false else { return }
appeared = true
self.ar_presentIndeterminateLoadingIndicator(animated: animated)
self.networkModel
.fetch()
.next { [weak self] saleViewModel in
if saleViewModel.shouldShowLiveInterface {
self?.setupLiveInterfaceAndPop()
} else if saleViewModel.isUpcomingAndHasNoLots {
self?.setupForUpcomingSale(saleViewModel)
} else {
self?.setupForSale(saleViewModel)
}
if let timeToLiveStart = saleViewModel.timeToLiveStart {
self?.setupForUpcomingLiveInterface(timeToLiveStart)
}
saleViewModel.registerSaleAsActiveActivity(self)
}.error { error in
// TODO: Error-handling somehow
}
NotificationCenter.default.addObserver(self, selector: #selector(AuctionViewController.registrationUpdated(_:)), name: NSNotification.Name.ARAuctionArtworkRegistrationUpdated, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
userActivity?.invalidate()
showLiveInterfaceWhenAuctionOpensTimer?.invalidate()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// titleView being nil indicates this is an upcoming sale with no lots, so we shouldn't displayCurrentItems()
guard saleViewModel != nil && titleView != nil else {
// We can't set up our current saleArtworksViewController if it has no models.
return
}
displayCurrentItems()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
activeModule?.setWidth(size.width - sideSpacing)
}
override var shouldAutorotate : Bool {
return traitDependentAutorotateSupport
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return traitDependentSupportedInterfaceOrientations
}
enum ViewTags: Int {
case banner = 0, title, lotStandings, buyNow
case whitespaceGobbler
}
}
extension AuctionViewController {
var isCompactSize: Bool {
return traitCollection.horizontalSizeClass == .compact
}
var buyNowSegmentWillBeShown: Bool {
guard let promotedSaleArtworks = self.saleViewModel.promotedSaleArtworks , promotedSaleArtworks.count > 0 else {
return false
}
return true
}
// Fetches new lot standings, updates the model, removes the old standings view, and adds a fresh one.
func fetchLotStandingsAndUpdate() {
guard let saleViewModel = saleViewModel else { return }
self.networkModel.fetchLotStanding(self.saleID).next { [weak self] lotStandings in
saleViewModel.updateLotStandings(lotStandings)
if let existingLotStandingsView = self?.headerStack?.viewWithTag(ViewTags.lotStandings.rawValue) {
self?.headerStack?.removeSubview(existingLotStandingsView)
}
self?.addLotStandings()
// Needs to dispatch because of UIKit ¯\_(ツ)_/¯
DispatchQueue.main.async {
self?.view.setNeedsUpdateConstraints()
}
}
}
func addTitleView() {
let bannerView = AuctionBannerView(viewModel: saleViewModel)
bannerView.tag = ViewTags.banner.rawValue
headerStack?.addSubview(bannerView, withTopMargin: "0", sideMargin: "0")
let topSpacing = isCompactSize ? 20 : 30
let sideSpacing = isCompactSize ? 40 : 80
let titleView = AuctionTitleView(
viewModel: saleViewModel,
delegate: self,
fullWidth: isCompactSize,
showAdditionalInformation: true,
titleTextAlignment: isCompactSize ? .left : .center
)
titleView.tag = ViewTags.title.rawValue
headerStack?.addSubview(titleView, withTopMargin: "\(topSpacing)", sideMargin: "\(sideSpacing)")
self.titleView = titleView
}
func addLotStandings() {
guard !saleViewModel.saleIsClosed else {
return
}
let lotStandingsView = LotStandingsView(
saleViewModel: saleViewModel,
isCompact: isCompactSize,
lotStandingTappedClosure: { [weak self] index in
guard let lotStanding = self?.saleViewModel?.lotStanding(at: index) else { return }
let artworkViewController = ARArtworkComponentViewController(artworkID: lotStanding.saleArtwork.artwork.artworkID)
self?.navigationController?.pushViewController(artworkViewController, animated: true)
},
isFinalHeaderElement: !self.buyNowSegmentWillBeShown
)
lotStandingsView.tag = ViewTags.lotStandings.rawValue
headerStack?.addSubview(lotStandingsView, withTopMargin: "0", sideMargin: "0")
self.lotStandingsView = lotStandingsView
}
func maybeAddBuyNow() {
guard let promotedSaleArtworks = self.saleViewModel.promotedSaleArtworks, promotedSaleArtworks.count > 0, self.buyNowView == nil else {
return
}
let buyNowView = AuctionBuyNowView()
buyNowView.tag = ViewTags.buyNow.rawValue
headerStack?.addSubview(buyNowView, withTopMargin: "0", sideMargin: "0")
self.buyNowView = buyNowView
// Needs to dispatch because of UIKit ¯\_(ツ)_/¯
DispatchQueue.main.async {
buyNowView.setup(isCompact: self.isCompactSize, promotedSaleArtworks: promotedSaleArtworks, viewController: self.saleArtworksViewController.children.first!, delegate:self)
buyNowView.setNeedsUpdateConstraints()
self.headerStack?.setNeedsUpdateConstraints()
self.headerStack?.updateConstraintsIfNeeded()
self.saleArtworksViewController.invalidateHeaderHeight()
}
}
func setupForUpcomingSale(_ saleViewModel: SaleViewModel) {
self.saleViewModel = saleViewModel
let auctionInfoVC = AuctionInformationViewController(saleViewModel: saleViewModel)
auctionInfoVC.titleViewDelegate = self
ar_addAlignedModernChildViewController(auctionInfoVC)
let bannerView = AuctionBannerView(viewModel: saleViewModel)
bannerView.tag = ViewTags.banner.rawValue
auctionInfoVC.scrollView.stackView.insertSubview(bannerView, at: 0, withTopMargin: "0", sideMargin: "0")
}
func setupForSale(_ saleViewModel: SaleViewModel) {
// TODO: Recreate everything from scratch when size class changes.
let headerStack = ORTagBasedAutoStackView()
self.headerStack = headerStack
saleArtworksViewController = ARModelInfiniteScrollViewController()
ar_addAlignedModernChildViewController(saleArtworksViewController)
saleArtworksViewController.view.backgroundColor = .black
// Disable the vertical offset for status bar.
automaticallyAdjustsScrollViewInsets = false
saleArtworksViewController.automaticallyAdjustsScrollViewInsets = false
saleArtworksViewController.headerStackView = headerStack
saleArtworksViewController.showTrailingLoadingIndicator = false
saleArtworksViewController.delegate = self
self.saleViewModel = saleViewModel
stickyHeader = ScrollingStickyHeaderView().then {
$0.toggleAttatched(false, animated: false)
$0.button.setTitle("Refine", for: .normal)
$0.titleLabel.text = saleViewModel.displayName
$0.button.addTarget(self, action: #selector(AuctionViewController.showRefineTapped), for: .touchUpInside)
}
saleArtworksViewController.stickyHeaderView = stickyHeader
saleArtworksViewController.invalidateHeaderHeight()
addTitleView()
addLotStandings()
maybeAddBuyNow()
displayCurrentItems()
saleArtworksViewController.invalidateHeaderHeight()
ar_removeIndeterminateLoadingIndicator(animated: allowAnimations)
}
func setupForUpcomingLiveInterface(_ timeToLiveStart: TimeInterval) {
guard timeToLiveStart > 0 else { return }
self.showLiveInterfaceWhenAuctionOpensTimer = Timer.scheduledTimer(timeInterval: timeToLiveStart, target: self, selector: #selector(AuctionViewController.setupLiveInterfaceAndPop), userInfo: nil, repeats: false)
}
@objc func setupLiveInterfaceAndPop() {
let liveCV = ARSwitchBoard.sharedInstance().loadLiveAuction(saleID)
ARTopMenuViewController.shared().push(liveCV!, animated: true) {
_ = self.navigationController?.popViewController(animated: false)
}
}
func defaultRefineSettings() -> AuctionRefineSettings {
guard let defaultSettings = _defaultRefineSettings else {
let defaultSettings = AuctionRefineSettings(ordering: AuctionOrderingSwitchValue.LotNumber, priceRange:self.saleViewModel.lowEstimateRange, saleViewModel:saleViewModel)
_defaultRefineSettings = defaultSettings
return defaultSettings
}
return defaultSettings
}
func showRefineTappedAnimated(_ animated: Bool) {
let refineViewController = RefinementOptionsViewController<AuctionRefineSettings>(defaultSettings: defaultRefineSettings(),
initialSettings: refineSettings,
currencySymbol: saleViewModel.currencySymbol,
userDidCancelClosure: { _ in
self.dismiss(animated: animated, completion: nil)
},
userDidApplyClosure: { (settings: AuctionRefineSettings) in
self.refineSettings = settings
self.displayCurrentItems()
self.dismiss(animated: animated, completion: nil)
})
refineViewController.modalPresentationStyle = .formSheet
var properties = [String: Any]()
properties["auction_slug"] = saleViewModel.saleID
properties["context_type"] = "sale"
properties["slug"] = NSString(format:"/auction/%@/refine", saleViewModel.saleID)
refineViewController.applyButtonPressedAnalyticsOption = RefinementAnalyticsOption(name: ARAnalyticsTappedApplyRefine, properties: properties)
properties = [String: Any]()
properties["context"] = "auction"
properties["slub"] = "/auction/\(saleViewModel.saleID)/refine"
refineViewController.viewDidAppearAnalyticsOption = RefinementAnalyticsOption(name: "Sale Information", properties: properties)
refineViewController.statusBarHidden = (self.traitCollection.horizontalSizeClass == .compact)
present(refineViewController, animated: animated, completion: nil)
}
@objc func showRefineTapped() {
self.showRefineTappedAnimated(true)
}
var sideSpacing: CGFloat {
let compactSize = traitCollection.horizontalSizeClass == .compact
return compactSize ? 40 : 80
}
/// Displays the current items, sorted/filtered through the current refine settings.
func displayCurrentItems() {
let items = saleViewModel.refinedSaleArtworks(refineSettings)
let viewWidth = self.view.bounds.size.width
let newModule: ARModelCollectionViewModule
switch refineSettings.ordering.layoutType {
case .grid:
newModule = ARSaleArtworkItemMasonryModule(traitCollection: traitCollection, width: viewWidth - sideSpacing)
case .list:
newModule = ARSaleArtworkItemFlowModule(traitCollection: traitCollection, width: viewWidth - sideSpacing)
}
saleArtworksViewController.activeModule = newModule
activeModule = newModule as? ARSaleArtworkItemWidthDependentModule // Conditional cast always succeeds, but the compiler will complain otherwise.
saleArtworksViewController.items = items
stickyHeader.subtitleLabel.text = saleViewModel.subtitleForRefineSettings(refineSettings, defaultRefineSettings: defaultRefineSettings())
}
}
fileprivate typealias NotificationCenterObservers = AuctionViewController
extension NotificationCenterObservers {
@objc func registrationUpdated(_ notification: Notification) {
networkModel.fetchBidders(self.saleID).next { [weak self] bidders in
self?.saleViewModel.bidders = bidders
self?.titleView?.updateRegistrationStatus()
}
}
}
fileprivate typealias TitleCallbacks = AuctionViewController
extension TitleCallbacks: AuctionTitleViewDelegate {
func userDidPressInfo(_ titleView: AuctionTitleView) {
let auctionInforVC = AuctionInformationViewController(saleViewModel: saleViewModel)
auctionInforVC.titleViewDelegate = self
let controller = ARSerifNavigationViewController(rootViewController: auctionInforVC)
present(controller, animated: true, completion: nil)
}
func userDidPressRegister(_ titleView: AuctionTitleView) {
let showRegister = {
let registrationPath = "/auction-registration/\(self.saleID)"
let viewController = ARSwitchBoard.sharedInstance().loadPath(registrationPath)
self.ar_TopMenuViewController()?.push(viewController, animated: true)
}
if let _ = presentedViewController {
dismiss(animated: true, completion: showRegister)
} else {
showRegister()
}
}
func userDidPressIdentityFAQ(_ titleView: AuctionTitleView) {
let showIdentityFAQ = {
let identityFAQPath = "/identity-verification-faq"
let viewController = ARSwitchBoard.sharedInstance().loadPath(identityFAQPath)
self.ar_TopMenuViewController()?.push(viewController, animated: true)
}
if let _ = presentedViewController {
dismiss(animated: true, completion: showIdentityFAQ)
} else {
showIdentityFAQ()
}
}
}
fileprivate typealias EmbeddedModelCallbacks = AuctionViewController
extension EmbeddedModelCallbacks: ARModelInfiniteScrollViewControllerDelegate {
func embeddedModelsViewController(_ controller: AREmbeddedModelsViewController!, didTapItemAt index: UInt) {
guard let saleArtwork = controller.items?[Int(index)] as? SaleArtworkViewModel else {
return
}
let viewController = ARArtworkComponentViewController(artworkID: saleArtwork.artworkID)
navigationController?.pushViewController(viewController, animated: allowAnimations)
}
func embeddedModelsViewController(_ controller: AREmbeddedModelsViewController!, shouldPresent viewController: UIViewController!) {
navigationController?.pushViewController(viewController, animated: true)
}
func embeddedModelsViewController(_ controller: AREmbeddedModelsViewController!, stickyHeaderDidChangeStickyness isAttachedToLeadingEdge: Bool) {
stickyHeader.stickyHeaderHeight.constant = isAttachedToLeadingEdge ? 120 : 60
stickyHeader.toggleAttatched(isAttachedToLeadingEdge, animated: true)
}
}
| 40.969194 | 219 | 0.699115 |
486e4d4f1655bfe870616e49aa4efd0eec1f14d4
| 687 |
//
// ViewController.swift
// Example
//
// Created by zhiyuan wang on 17/3/9.
// Copyright © 2017年 l9y. All rights reserved.
//
import UIKit
import SwiftEvent
class ViewController: UIViewController {
let clickEventObserver = Observer<ClickEvent>()
override func viewDidLoad() {
super.viewDidLoad()
clickEventObserver.receive = {[weak self] clickEvent in
self?.onReceiveClickEvent(clickEvent)
}
}
@IBAction func sendClickEvent(_ sender: AnyObject) {
Event.instance.post(ClickEvent())
}
func onReceiveClickEvent(_ clickEvent: ClickEvent) {
print("click \(clickEvent)")
}
}
| 19.083333 | 63 | 0.636099 |
11eb4a7fb0e88b56f37a92f7e08dd364ada64796
| 8,500 |
//
// ChannelInfoViewController.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 09/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
fileprivate typealias ListSegueData = (title: String, query: String?)
class ChannelInfoViewController: BaseViewController {
var tableViewData: [[Any]] = [] {
didSet {
tableView?.reloadData()
}
}
var subscription: Subscription? {
didSet {
guard let subscription = self.subscription else { return }
let channelInfoData = [
ChannelInfoDetailCellData(title: localized("chat.info.item.members"), detail: "", action: showMembersList),
ChannelInfoDetailCellData(title: localized("chat.info.item.pinned"), detail: "", action: showPinnedList),
ChannelInfoDetailCellData(title: localized("chat.info.item.starred"), detail: "", action: showStarredList)
]
if subscription.type == .directMessage {
tableViewData = [[
ChannelInfoUserCellData(user: subscription.directMessageUser)
], channelInfoData]
} else {
let topic = subscription.roomTopic?.characters.count ?? 0 == 0 ? localized("chat.info.item.no_topic") : subscription.roomTopic
let description = subscription.roomDescription?.characters.count ?? 0 == 0 ? localized("chat.info.item.no_description") : subscription.roomDescription
tableViewData = [[
ChannelInfoBasicCellData(title: "#\(subscription.displayName())"),
ChannelInfoDescriptionCellData(
title: localized("chat.info.item.topic"),
description: topic
),
ChannelInfoDescriptionCellData(
title: localized("chat.info.item.description"),
description: description
)
], channelInfoData]
}
}
}
@IBOutlet weak var tableView: UITableView!
weak var buttonFavorite: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
title = localized("chat.info.title")
if let settings = AuthSettingsManager.settings {
if settings.favoriteRooms {
let defaultImage = UIImage(named: "Star")?.imageWithTint(UIColor.RCGray()).withRenderingMode(.alwaysOriginal)
let buttonFavorite = UIBarButtonItem(image: defaultImage, style: .plain, target: self, action: #selector(buttonFavoriteDidPressed))
navigationItem.rightBarButtonItem = buttonFavorite
self.buttonFavorite = buttonFavorite
updateButtonFavoriteImage()
}
}
}
func updateButtonFavoriteImage(_ force: Bool = false, value: Bool = false) {
guard let buttonFavorite = self.buttonFavorite else { return }
let favorite = force ? value : subscription?.favorite ?? false
var image: UIImage?
if favorite {
image = UIImage(named: "Star-Filled")?.imageWithTint(UIColor.RCFavoriteMark())
} else {
image = UIImage(named: "Star")?.imageWithTint(UIColor.RCGray())
}
buttonFavorite.image = image?.withRenderingMode(.alwaysOriginal)
}
func showMembersList() {
self.performSegue(withIdentifier: "toMembersList", sender: self)
}
func showPinnedList() {
let data = ListSegueData(title: localized("chat.messages.pinned.list.title"), query: "{\"pinned\":true}")
self.performSegue(withIdentifier: "toMessagesList", sender: data)
}
func showStarredList() {
guard let userId = AuthManager.currentUser()?.identifier else {
alert(title: localized("error.socket.default_error_title"), message: "error.socket.default_error_message")
return
}
let data = ListSegueData(title: localized("chat.messages.starred.list.title"), query: "{\"starred._id\":{\"$in\":[\"\(userId)\"]}}")
self.performSegue(withIdentifier: "toMessagesList", sender: data)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let membersList = segue.destination as? MembersListViewController {
membersList.data.subscription = self.subscription
}
if let messagesList = segue.destination as? MessagesListViewController {
messagesList.data.subscription = self.subscription
if let segueData = sender as? ListSegueData {
messagesList.data.title = segueData.title
messagesList.data.query = segueData.query
}
}
}
// MARK: IBAction
@objc func buttonFavoriteDidPressed(_ sender: Any) {
guard let subscription = self.subscription else { return }
SubscriptionManager.toggleFavorite(subscription) { [unowned self] (response) in
if response.isError() {
subscription.updateFavorite(!subscription.favorite)
}
self.updateButtonFavoriteImage()
}
self.subscription?.updateFavorite(!subscription.favorite)
updateButtonFavoriteImage()
}
@IBAction func buttonCloseDidPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
// MARK: UITableViewDelegate
extension ChannelInfoViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = tableViewData[indexPath.section][indexPath.row]
if let data = data as? ChannelInfoBasicCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoBasicCell.identifier) as? ChannelInfoBasicCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoDetailCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoDetailCell.identifier) as? ChannelInfoDetailCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoUserCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoUserCell.identifier) as? ChannelInfoUserCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoDescriptionCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoDescriptionCell.identifier) as? ChannelInfoDescriptionCell {
cell.data = data
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let data = tableViewData[indexPath.section][indexPath.row]
if data as? ChannelInfoBasicCellData != nil {
return CGFloat(ChannelInfoBasicCell.defaultHeight)
}
if data as? ChannelInfoDetailCellData != nil {
return CGFloat(ChannelInfoDetailCell.defaultHeight)
}
if data as? ChannelInfoUserCellData != nil {
return CGFloat(ChannelInfoUserCell.defaultHeight)
}
if data as? ChannelInfoDescriptionCellData != nil {
return CGFloat(ChannelInfoDescriptionCell.defaultHeight)
}
return CGFloat(0)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let data = tableViewData[indexPath.section][indexPath.row]
if let data = data as? ChannelInfoDetailCellData {
guard let action = data.action else {
alert(title: localized("alert.feature.wip.title"), message: localized("alert.feature.wip.message"))
return
}
action()
if let selectedIndex = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndex, animated: true)
}
}
}
}
// MARK: UITableViewDataSource
extension ChannelInfoViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData[section].count
}
}
| 36.170213 | 166 | 0.627294 |
618f6dea3e90ecc3d0f105fa490650d97a6d3e3e
| 1,792 |
import XCTest
@testable import Aspen
class AspenTests: AspenTestCase
{
override func setUp()
{
super.setUp()
super.registerLoggers()
}
override func tearDown()
{
super.tearDown()
}
// MARK: - Verbose mode
func testVerbosePasses()
{
Aspen.setLoggingLevel(.verbose)
self.expectLog { aspenVerbose(passVerbose) }
self.expectLog { aspenInfo(passInfo) }
self.expectLog { aspenWarn(passWarn) }
self.expectLog { aspenError(passError) }
}
// MARK: - Info mode
func testInfoPasses()
{
Aspen.setLoggingLevel(.info)
self.expectLog { aspenInfo(passInfo) }
self.expectLog { aspenWarn(passWarn) }
self.expectLog { aspenError(passError) }
}
func testInfoFailures()
{
Aspen.setLoggingLevel(.info)
self.expectNoLog { aspenVerbose(failVerbose) }
}
// MARK: - Warn mode
func testWarnPasses()
{
Aspen.setLoggingLevel(.warning)
self.expectLog { aspenWarn(passWarn) }
self.expectLog { aspenError(passError) }
}
func testWarnFailures()
{
Aspen.setLoggingLevel(.warning)
self.expectNoLog { aspenInfo(failInfo) }
self.expectNoLog { aspenVerbose(failVerbose) }
}
// MARK: - Error mode
func testErrorPasses()
{
Aspen.setLoggingLevel(.error)
self.expectLog { aspenError(passError) }
}
func testErrorFailures()
{
Aspen.setLoggingLevel(.error)
self.expectNoLog { aspenVerbose(failVerbose) }
self.expectNoLog { aspenInfo(failInfo) }
self.expectNoLog { aspenWarn(failWarn) }
}
}
let passVerbose = "Verbose; should pass"
let passInfo = "Info; should pass"
let passWarn = "Warn; should pass"
let passError = "Error; should pass"
let failVerbose = "Verbose; should fail"
let failInfo = "Info; should fail"
let failWarn = "Warn; should fail"
let failError = "Error; should fail"
| 20.597701 | 48 | 0.695871 |
8fa33f943a52ed4693a877772015aff6c50c9f82
| 5,561 |
/*
* Copyright IBM Corporation 2016
*
* 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 LoggerAPI
// MARK: ContentType
/// A set of APIs to work with Content-Type headers, whether to generate the value
/// or to determine if it's an acceptable value.
public class ContentType {
/// A dictionary of extensions to MIME type descriptions
private var extToContentType = [String:String]()
/// Shared singleton instance.
public static let sharedInstance = ContentType()
/// The following function loads the MIME types from an external file
private init () {
let contentTypesData = contentTypesString.data(using: .utf8)
guard contentTypesData != nil else {
Log.error("Error parsing \(contentTypesString)")
return
}
let jsonParseOptions = JSONSerialization.ReadingOptions.mutableContainers
let parsedObject = try? JSONSerialization.jsonObject(with: contentTypesData!,
options: jsonParseOptions)
// MARK: Linux Foundation will return an Any instead of an AnyObject
// Need to test if this breaks the Linux build.
guard parsedObject != nil,
let jsonData = parsedObject as? [String : [String]] else {
Log.error("JSON could not be parsed")
return
}
for (contentType, exts) in jsonData {
for ext in exts {
extToContentType[ext] = contentType
}
}
}
/// Get the content type for the given file extension.
///
/// - Parameter forExtension: the file extension.
/// - Returns: an Optional String for the content type.
public func getContentType(forExtension ext: String) -> String? {
return extToContentType[ext]
}
/// Get the content type for the given file based on its extension.
///
/// - Parameter forFileName: the file name.
/// - Returns: an Optional String for the content type.
public func getContentType(forFileName fileName: String) -> String? {
let lastPathElemRange: Range<String.Index>
let extRange: Range<String.Index>
let backwards = String.CompareOptions.backwards
if let lastSlash = fileName.range(of: "/", options: backwards) {
lastPathElemRange = fileName.index(after: lastSlash.lowerBound)..<fileName.characters.endIndex
} else {
lastPathElemRange = fileName.characters.startIndex..<fileName.characters.endIndex
}
if let lastDot = fileName.range(of: ".", options: backwards, range: lastPathElemRange) {
extRange = fileName.index(after: lastDot.lowerBound)..<fileName.characters.endIndex
} else {
// No "extension", use the entire last path element as the "extension"
extRange = lastPathElemRange
}
return getContentType(forExtension: fileName.substring(with: extRange))
}
/// Check if the message content type matches the type descriptor.
///
/// - Parameter messageContentType: the content type.
/// - Parameter ofType: the description of the type.
/// - Returns: true if the types matched.
public func isContentType(_ messageContentType: String, ofType typeDescriptor: String) -> Bool {
let type = typeDescriptor.lowercased()
let typeAndSubtype = messageContentType.components(separatedBy: ";")[0].lowercased()
if typeAndSubtype == type {
return true
}
// typeDescriptor is file extension
if typeAndSubtype == extToContentType[type] {
return true
}
// typeDescriptor is a shortcut
let normalizedType = normalize(type: type)
if typeAndSubtype == normalizedType {
return true
}
// the types match and the subtype in typeDescriptor is "*"
let messageTypePair = typeAndSubtype.components(separatedBy: "/")
let normalizedTypePair = normalizedType.components(separatedBy: "/")
if messageTypePair.count == 2 && normalizedTypePair.count == 2
&& messageTypePair[0] == normalizedTypePair[0] && normalizedTypePair[1] == "*" {
return true
}
return false
}
/// Normalize the type
///
/// - Parameter type: the content type
///
/// - Returns: the normalized String
private func normalize(type: String) -> String {
switch type {
case "urlencoded":
return "application/x-www-form-urlencoded"
case "multipart":
return "multipart/*"
case "json":
return "application/json"
// swiftlint:disable todo
// TODO: +json?
// if (type[0] === '+') {
// // "+json" -> "*/*+json" expando
// type = '*/*' + type
// }
// swiftlint:enable todo
default:
return type
}
}
}
| 36.11039 | 106 | 0.617155 |
f8ce7c97d7efc12c5e159abe059d6bfa4e104d84
| 277 |
//
// BaseViewController.swift
// StatusBarNotification
//
// Created by Shannon Wu on 9/17/15.
// Copyright © 2015 Shannon Wu. All rights reserved.
//
import UIKit
/// The view controller object of the notification window
class BaseViewController: UIViewController {
}
| 18.466667 | 57 | 0.736462 |
75c2bff77c3fe05fea670b8697647ae45f7523a1
| 2,037 |
//
// Atom.swift
// AntsColony
//
// Created by rhishikesh on 24/04/20.
// Copyright © 2020 Helpshift. All rights reserved.
//
import Foundation
struct Atom<T: Hashable>: Hashable {
var value: T
private let lock: UnsafeMutablePointer<pthread_mutex_t>
init(withValue v: T) {
value = v
lock = UnsafeMutablePointer.allocate(capacity: MemoryLayout<pthread_mutex_t>.size)
pthread_mutex_init(lock, nil)
}
public mutating func swap(usingFn fn: (T) -> T) -> T {
// capture the current value
let v1 = value
// run fn to update the value
let v2 = fn(v1)
// compare to see if someone changed the value
pthread_mutex_lock(lock)
if v1 != value {
// unlock and try again
pthread_mutex_unlock(lock)
return swap(usingFn: fn)
} else {
value = v2
pthread_mutex_unlock(lock)
}
return value
}
public func deref() -> T {
return value
}
static func == (lhs: Atom<T>, rhs: Atom<T>) -> Bool {
lhs.deref() == rhs.deref()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(lock)
}
}
struct Atomic<T: Hashable>: Hashable {
var reference: AtomicReference<T>
init(withValue v: T) {
reference = AtomicReference(initialValue: v)
}
public mutating func swap(usingFn fn: (T) -> T) -> T {
while true {
let oldValue = reference.value
if reference.compareAndSet(expect: oldValue, newValue: fn(oldValue)) {
break
} else {
return swap(usingFn: fn)
}
}
return reference.value
}
public func deref() -> T {
return reference.value
}
static func == (lhs: Atomic<T>, rhs: Atomic<T>) -> Bool {
lhs.deref() == rhs.deref()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(reference.value)
}
}
| 23.686047 | 90 | 0.56161 |
9bc9f08e3ea6ccb5fc8ccc5f41972b6a657ef538
| 40,019 |
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_any -Xllvm -sil-print-debuginfo -enable-sil-ownership %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import objc_generics
protocol P {}
protocol CP: class {}
struct KnownUnbridged {}
// CHECK-LABEL: sil hidden @$S17objc_bridging_any11passingToId{{.*}}F
func passingToId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optionalA: String?,
optionalB: NSString?,
optionalC: Any?) {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $NSIdLover,
// CHECK: debug_value [[STRING:%.*]] : $String
// CHECK: debug_value [[NSSTRING:%.*]] : $NSString
// CHECK: debug_value [[OBJECT:%.*]] : $AnyObject
// CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T
// CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: debug_value_addr [[GENERIC:%.*]] : $*U
// CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P
// CHECK: debug_value [[ERROR:%.*]] : $Error
// CHECK: debug_value_addr [[ANY:%.*]] : $*Any
// CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged
// CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String>
// CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(string)
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(nsString)
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(classGeneric)
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[OBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[SELF]])
// CHECK: destroy_value [[OBJECT_COPY]]
receiver.takesId(object)
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(classExistential)
// These cases perform a universal bridging conversion.
// CHECK: [[COPY:%.*]] = alloc_stack $U
// CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(generic)
// CHECK: [[COPY:%.*]] = alloc_stack $P
// CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(existential)
// CHECK: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] : $Error
// CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @$Ss27_bridgeAnythingToObjectiveCyyXlxlF
// CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: destroy_value [[ERROR_COPY]] : $Error
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[SELF]])
// CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject
receiver.takesId(error)
// CHECK: [[COPY:%.*]] = alloc_stack $Any
// CHECK: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
receiver.takesId(any)
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(knownUnbridged)
// These cases bridge using Optional's _ObjectiveCBridgeable conformance.
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<String>
// CHECK: [[BORROWED_OPT_STRING_COPY:%.*]] = begin_borrow [[OPT_STRING_COPY]]
// CHECK: store_borrow [[BORROWED_OPT_STRING_COPY]] to [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_STRING_COPY]] from [[OPT_STRING_COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalA)
// CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[OPT_NSSTRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString>
// CHECK: [[BORROWED_OPT_NSSTRING_COPY:%.*]] = begin_borrow [[OPT_NSSTRING_COPY]]
// CHECK: store_borrow [[BORROWED_OPT_NSSTRING_COPY]] to [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_NSSTRING_COPY]] from [[OPT_NSSTRING]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalB)
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]])
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalC)
// TODO: Property and subscript setters
}
// Once upon a time, as a workaround for rdar://problem/28318984, we had
// to skip the peephole for types with nontrivial SIL lowerings because we
// didn't correctly form the substitutions for a generic
// _bridgeAnythingToObjectiveC call. That's not true anymore.
func zim() {}
struct Zang {}
// CHECK-LABEL: sil hidden @$S17objc_bridging_any27typesWithNontrivialLowering8receiverySo9NSIdLoverC_tF
func typesWithNontrivialLowering(receiver: NSIdLover) {
// CHECK: apply {{.*}}<() -> ()>
receiver.takesId(zim)
// CHECK: apply {{.*}}<Zang.Type>
receiver.takesId(Zang.self)
// CHECK: apply {{.*}}<(() -> (), Zang.Type)>
receiver.takesId((zim, Zang.self))
// CHECK: apply {{%.*}}<(Int, String)>
receiver.takesId((0, "one"))
}
// CHECK-LABEL: sil hidden @$S17objc_bridging_any19passingToNullableId{{.*}}F
func passingToNullableId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optString: String?,
optNSString: NSString?,
optObject: AnyObject?,
optClassGeneric: T?,
optClassExistential: CP?,
optGeneric: U?,
optExistential: P?,
optAny: Any?,
optKnownUnbridged: KnownUnbridged?,
optOptA: String??,
optOptB: NSString??,
optOptC: Any??)
{
// CHECK: bb0([[SELF:%.*]] : @guaranteed $NSIdLover,
// CHECK: [[STRING:%.*]] : $String,
// CHECK: [[NSSTRING:%.*]] : $NSString
// CHECK: [[OBJECT:%.*]] : $AnyObject
// CHECK: [[CLASS_GENERIC:%.*]] : $T
// CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: [[GENERIC:%.*]] : $*U
// CHECK: [[EXISTENTIAL:%.*]] : $*P
// CHECK: [[ERROR:%.*]] : $Error
// CHECK: [[ANY:%.*]] : $*Any,
// CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged,
// CHECK: [[OPT_STRING:%.*]] : $Optional<String>,
// CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject>
// CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T>
// CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP>
// CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U>
// CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P>
// CHECK: [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged>
// CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>>
// CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>>
// CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>>
// CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[OPT_ANYOBJECT]]
receiver.takesNullableId(string)
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
receiver.takesNullableId(nsString)
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[OBJECT]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
receiver.takesNullableId(object)
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
receiver.takesNullableId(classGeneric)
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
// CHECK: destroy_value [[OPT_ANYOBJECT]]
receiver.takesNullableId(classExistential)
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U
// CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
receiver.takesNullableId(generic)
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P
// CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
receiver.takesNullableId(existential)
// CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] : $Error
// CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @$Ss27_bridgeAnythingToObjectiveCyyXlxlF
// CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject
// CHECK-NEXT: destroy_addr [[ERROR_STACK]]
// CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[SELF]])
// CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]]
receiver.takesNullableId(error)
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
receiver.takesNullableId(any)
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover,
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]])
receiver.takesNullableId(knownUnbridged)
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]]
// CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : @owned $String):
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]]
// CHECK: destroy_value [[STRING_DATA]]
// CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]]
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt
// CHECK: br [[JOIN]]([[OPT_NONE]]
//
// CHECK: [[JOIN]]([[PHI:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]]
// CHECK: apply [[METHOD]]([[PHI]], [[SELF]])
// CHECK: destroy_value [[PHI]]
receiver.takesNullableId(optString)
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]]
receiver.takesNullableId(optNSString)
// CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[OPT_OBJECT]]
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]]
// CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[SELF]])
receiver.takesNullableId(optObject)
receiver.takesNullableId(optClassGeneric)
receiver.takesNullableId(optClassExistential)
receiver.takesNullableId(optGeneric)
receiver.takesNullableId(optExistential)
receiver.takesNullableId(optAny)
receiver.takesNullableId(optKnownUnbridged)
receiver.takesNullableId(optOptA)
receiver.takesNullableId(optOptB)
receiver.takesNullableId(optOptC)
}
protocol Anyable {
init(any: Any)
init(anyMaybe: Any?)
var anyProperty: Any { get }
var maybeAnyProperty: Any? { get }
}
// Make sure we generate correct bridging thunks
class SwiftIdLover : NSObject, Anyable {
func methodReturningAny() -> Any { fatalError() }
// SEMANTIC ARC TODO: This is another case of pattern matching the body of one
// function in a different function... Just pattern match the unreachable case
// to preserve behavior. We should check if it is correct.
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any
// CHECK: unreachable
// CHECK: } // end sil function '$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF'
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject {
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftIdLover):
// CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_IMP:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF
// CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPEN_RESULT]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[TMP]])
// CHECK: return [[OBJC_RESULT]]
// CHECK: } // end sil function '$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo'
func methodReturningOptionalAny() -> Any? { fatalError() }
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo
// CHECK: function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F
@objc func methodTakingAny(a: Any) { fatalError() }
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[ARG:%.*]] : @unowned $AnyObject, [[SELF:%.*]] : @unowned $SwiftIdLover):
// CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY:@\$Ss018_bridgeAnyObjectToB0yypyXlSgF]] : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @out Any
// CHECK: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tF
// CHECK-NEXT: apply [[METHOD]]([[RESULT:%.*]], [[BORROWED_SELF_COPY:%.*]]) :
func methodTakingOptionalAny(a: Any?) { fatalError() }
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tF
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tFTo
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEF : $@convention(method) (@noescape @callee_guaranteed (@in_guaranteed Any) -> (), @guaranteed SwiftIdLover) -> ()
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEFTo : $@convention(objc_method) (@convention(block) @noescape (AnyObject) -> (), SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (AnyObject) -> (), [[SELF:%.*]] : @unowned $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SyXlIyBy_ypIegn_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[THUNK]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[THUNK]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SyXlIyBy_ypIegn_TR
// CHECK: bb0([[ANY:%.*]] : @trivial $*Any, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape (AnyObject) -> ()):
// CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPENED_ANY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]])
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: destroy_value [[BRIDGED]]
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: return [[VOID]]
@objc func methodTakingBlockTakingAny(_: (Any) -> ()) { fatalError() }
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_guaranteed (@in_guaranteed Any) -> ()
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> ()
// CHECK: bb0([[SELF:%.*]] : @unowned $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed (@in_guaranteed Any) -> ()
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SypIegn_yXlIeyBy_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed (@in_guaranteed Any) -> (), invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypIegn_yXlIeyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@in_guaranteed Any) -> (), AnyObject) -> ()
// CHECK: bb0([[BLOCK_STORAGE:%.*]] : @trivial $*@block_storage @callee_guaranteed (@in_guaranteed Any) -> (), [[ANY:%.*]] : @unowned $AnyObject):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY_COPY]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[INIT:%.*]] = init_existential_addr [[RESULT]] : $*Any
// CHECK-NEXT: store [[OPENED_ANY]] to [init] [[INIT]]
// CHECK-NEXT: [[BORROW_FUN:%.*]] = begin_borrow [[FUNCTION]]
// CHECK-NEXT: apply [[BORROW_FUN]]([[RESULT]])
// CHECK-NEXT: end_borrow [[BORROW_FUN]] from [[FUNCTION]]
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: destroy_addr [[RESULT]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[FUNCTION]]
// CHECK-NEXT: return [[VOID]] : $()
@objc func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) { fatalError() }
@objc func methodReturningBlockTakingAny() -> ((Any) -> ()) { fatalError() }
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEF : $@convention(method) (@noescape @callee_guaranteed () -> @out Any, @guaranteed SwiftIdLover) -> () {
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEFTo : $@convention(objc_method) (@convention(block) @noescape () -> @autoreleased AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape () -> @autoreleased AnyObject, [[ANY:%.*]] : @unowned $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @$SyXlIyBa_ypIegr_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[THUNK]]
// CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_ANY_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]]
// CHECK-NEXT: destroy_value [[THUNK]]
// CHECK-NEXT: destroy_value [[ANY_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SyXlIyBa_ypIegr_TR : $@convention(thin) (@guaranteed @convention(block) @noescape () -> @autoreleased AnyObject) -> @out Any
// CHECK: bb0([[ANY_ADDR:%.*]] : @trivial $*Any, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape () -> @autoreleased AnyObject):
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]()
// CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] :
// CHECK-NEXT: [[BORROWED_OPTIONAL:%.*]] = begin_borrow [[OPTIONAL]]
// CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[ANY_ADDR]], [[BORROWED_OPTIONAL]])
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: end_borrow [[BORROWED_OPTIONAL]]
// CHECK-NEXT: destroy_value [[OPTIONAL]]
// CHECK-NEXT: return [[EMPTY]]
@objc func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) { fatalError() }
@objc func methodTakingBlockReturningAny(_: () -> Any) { fatalError() }
// CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_guaranteed () -> @out Any
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject
// CHECK: bb0([[SELF:%.*]] : @unowned $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF
// CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> @out Any
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @$SypIegr_yXlIeyBa_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> @out Any, invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypIegr_yXlIeyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> @out Any) -> @autoreleased AnyObject
// CHECK: bb0(%0 : @trivial $*@block_storage @callee_guaranteed () -> @out Any):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[BORROW_FUN:%.*]] = begin_borrow [[FUNCTION]]
// CHECK-NEXT: apply [[BORROW_FUN]]([[RESULT]])
// CHECK-NEXT: end_borrow [[BORROW_FUN]] from [[FUNCTION]]
// CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[RESULT]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[FUNCTION]]
// CHECK-NEXT: return [[BRIDGED]]
@objc func methodTakingBlockReturningOptionalAny(_: () -> Any?) { fatalError() }
@objc func methodReturningBlockReturningAny() -> (() -> Any) { fatalError() }
@objc func methodReturningBlockReturningOptionalAny() -> (() -> Any?) { fatalError() }
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypSgIegr_yXlSgIeyBa_TR
// CHECK: function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F
override init() { fatalError() }
@objc dynamic required convenience init(any: Any) { fatalError() }
@objc dynamic required convenience init(anyMaybe: Any?) { fatalError() }
@objc dynamic var anyProperty: Any
@objc dynamic var maybeAnyProperty: Any?
subscript(_: IndexForAnySubscript) -> Any { get { fatalError() } set { fatalError() } }
@objc func methodReturningAnyOrError() throws -> Any { fatalError() }
}
class IndexForAnySubscript { }
func dynamicLookup(x: AnyObject) {
_ = x.anyProperty
_ = x[IndexForAnySubscript()]
}
extension GenericClass {
// CHECK-LABEL: sil hidden @$SSo12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF :
func pseudogenericAnyErasure(x: T) -> Any {
// CHECK: bb0([[ANY_OUT:%.*]] : @trivial $*Any, [[ARG:%.*]] : @guaranteed $T, [[SELF:%.*]] : @guaranteed $GenericClass<T>
// CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject
// CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]]
return x
}
// CHECK: } // end sil function '$SSo12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF'
}
// Make sure AnyHashable erasure marks Hashable conformance as used
class AnyHashableClass : NSObject {
// CHECK-LABEL: sil hidden @$S17objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF
// CHECK: [[FN:%.*]] = function_ref @$Ss21_convertToAnyHashableys0cD0Vxs0D0RzlF
// CHECK: apply [[FN]]<GenericOption>({{.*}})
func returnsAnyHashable() -> AnyHashable {
return GenericOption.multithreaded
}
}
// CHECK-LABEL: sil hidden @$S17objc_bridging_any33bridgeOptionalFunctionToAnyObject2fnyXlyycSg_tF : $@convention(thin) (@guaranteed Optional<@callee_guaranteed () -> ()>) -> @owned AnyObject
// CHECK: [[BRIDGE:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF
// CHECK: [[FN:%.*]] = function_ref @$SIeg_ytytIegnr_TR
// CHECK: partial_apply [callee_guaranteed] [[FN]]
// CHECK: [[SELF:%.*]] = alloc_stack $Optional<@callee_guaranteed (@in_guaranteed ()) -> @out ()>
// CHECK: apply [[BRIDGE]]<() -> ()>([[SELF]])
func bridgeOptionalFunctionToAnyObject(fn: (() -> ())?) -> AnyObject {
return fn as AnyObject
}
// When bridging `id _Nonnull` values incoming from unknown ObjC code,
// turn them into `Any` using a runtime call that defends against the
// possibility they still may be nil.
// CHECK-LABEL: sil hidden @$S17objc_bridging_any22bridgeIncomingAnyValueyypSo9NSIdLoverCF
func bridgeIncomingAnyValue(_ receiver: NSIdLover) -> Any {
// CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]]
return receiver.makesId()
}
class SwiftAnyEnjoyer: NSIdLover, NSIdLoving {
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any15SwiftAnyEnjoyerC7takesIdyyypFTo
// CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]]
override func takesId(_ x: Any) { }
// CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any15SwiftAnyEnjoyerC7takesId11viaProtocolyyp_tFTo
// CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]]
func takesId(viaProtocol x: Any) { }
}
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics
// CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @$SSo13GenericOptionas8HashableSCsACP9hashValueSivgTW
// CHECK-NEXT: method #Hashable.hash!1: {{.*}} : @$SSo13GenericOptionas8HashableSCsACP4hash4intoys6HasherVz_tFTW
// CHECK-NEXT: method #Hashable._rawHashValue!1: {{.*}} : @$SSo13GenericOptionas8HashableSCsACP13_rawHashValue4seedSis6UInt64V_AHt_tFTW
// CHECK-NEXT: }
| 56.926031 | 224 | 0.64197 |
6a8a6b01cbe0835617fe0a4dc297ce78e59b6795
| 477 |
//
// LocalFeedImage.swift
// EssentialFeed
//
// Created by Breno Valadão on 12/01/22.
//
import Foundation
public struct LocalFeedImage: Equatable {
public let id: UUID
public let description: String?
public let location: String?
public let url: URL
public init(id: UUID, description: String?, location: String?, url: URL) {
self.id = id
self.description = description
self.location = location
self.url = url
}
}
| 20.73913 | 78 | 0.645702 |
18ed5f5b441332f363a096f43f795c7c57e8ce3b
| 684 |
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let layoutName = "ListCollectionLayout"
let package = Package(
name: layoutName,
platforms: [.iOS(.v11)],
products: [
.library(
name: layoutName,
targets: [layoutName]
)
],
dependencies: [],
targets: [
.target(
name: layoutName
),
.target(
name: "ListCollectionView",
dependencies: ["ListCollectionLayout"],
path: "Sources/ListCollectionView"
)
],
swiftLanguageVersions: [.v5]
)
| 22.8 | 96 | 0.580409 |
18b90ea6e8d441641ebb4cce56ef3a47c0c72369
| 26,707 |
//
// WalletManager+Auth.swift
// breadwallet
//
// Created by Aaron Voisine on 11/7/16.
// Copyright (c) 2016 breadwallet 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 Foundation
import UIKit
import LocalAuthentication
import BRCore
import sqlite3
private let WalletSecAttrService = "com.breadwalet.new"
private let BIP39CreationTime = TimeInterval(BIP39_CREATION_TIME) - NSTimeIntervalSince1970
/// WalletAuthenticator is a protocol whose implementors are able to interact with wallet authentication
public protocol WalletAuthenticator {
var noWallet: Bool { get }
var apiAuthKey: String? { get }
var userAccount: Dictionary<AnyHashable, Any>? { get set }
}
struct NoAuthAuthenticator : WalletAuthenticator {
let noWallet = true
let apiAuthKey: String? = nil
var userAccount: Dictionary<AnyHashable, Any>? = nil
}
enum TouchIdResult {
case success
case cancel
case fallback
case failure
}
extension WalletManager : WalletAuthenticator {
static private var failedPins = [String]()
convenience init(store: Store, dbPath: String? = nil) throws {
if !UIApplication.shared.isProtectedDataAvailable {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecNotAvailable))
}
if try keychainItem(key: KeychainKey.seed) as Data? != nil { // upgrade from old keychain scheme
let seedPhrase: String? = try keychainItem(key: KeychainKey.mnemonic)
var seed = UInt512()
print("upgrading to authenticated keychain scheme")
BRBIP39DeriveKey(&seed, seedPhrase, nil)
let mpk = BRBIP32MasterPubKey(&seed, MemoryLayout<UInt512>.size)
seed = UInt512() // clear seed
try setKeychainItem(key: KeychainKey.mnemonic, item: seedPhrase, authenticated: true)
try setKeychainItem(key: KeychainKey.masterPubKey, item: Data(masterPubKey: mpk))
try setKeychainItem(key: KeychainKey.seed, item: nil as Data?)
}
let mpkData: Data? = try keychainItem(key: KeychainKey.masterPubKey)
guard let masterPubKey = mpkData?.masterPubKey else {
try self.init(masterPubKey: BRMasterPubKey(), earliestKeyTime: 0, dbPath: dbPath, store: store)
return
}
var earliestKeyTime = BIP39CreationTime
if let creationTime: Data = try keychainItem(key: KeychainKey.creationTime),
creationTime.count == MemoryLayout<TimeInterval>.stride {
creationTime.withUnsafeBytes { earliestKeyTime = $0.pointee }
}
try self.init(masterPubKey: masterPubKey, earliestKeyTime: earliestKeyTime, dbPath: dbPath, store: store)
}
// true if keychain is available and we know that no wallet exists on it
var noWallet: Bool {
if didInitWallet { return false }
return WalletManager.staticNoWallet
}
static var staticNoWallet: Bool {
do {
if try keychainItem(key: KeychainKey.masterPubKey) as Data? != nil { return false }
if try keychainItem(key: KeychainKey.seed) as Data? != nil { return false } // check for old keychain scheme
return true
}
catch { return false }
}
//Login with pin should be required if the pin hasn't been used within a week
var pinLoginRequired: Bool {
let pinUnlockTime = UserDefaults.standard.double(forKey: DefaultsKey.pinUnlockTime)
let now = Date.timeIntervalSinceReferenceDate
let secondsInWeek = 60.0*60.0*24.0*7.0
return now - pinUnlockTime > secondsInWeek
}
// true if the given transaction can be signed with touch ID authentication
func canUseTouchID(forTx: BRTxRef) -> Bool {
guard LAContext.canUseTouchID else { return false }
do {
let spendLimit: Int64 = try keychainItem(key: KeychainKey.spendLimit) ?? 0
guard let wallet = wallet else { assert(false, "No wallet!"); return false }
return wallet.amountSentByTx(forTx) - wallet.amountReceivedFromTx(forTx) + wallet.totalSent <= UInt64(spendLimit)
}
catch { return false }
}
var spendingLimit: UInt64 {
get {
guard UserDefaults.standard.object(forKey: DefaultsKey.spendLimitAmount) != nil else {
return 0
}
return UInt64(UserDefaults.standard.double(forKey: DefaultsKey.spendLimitAmount))
}
set {
guard let wallet = self.wallet else { assert(false, "No wallet!"); return }
do {
try setKeychainItem(key: KeychainKey.spendLimit, item: Int64(wallet.totalSent + newValue))
UserDefaults.standard.set(newValue, forKey: DefaultsKey.spendLimitAmount)
} catch let error {
print("Set spending limit error: \(error)")
}
}
}
// number of unique failed pin attempts remaining before wallet is wiped
var pinAttemptsRemaining: Int {
do {
let failCount: Int64 = try keychainItem(key: KeychainKey.pinFailCount) ?? 0
return Int(8 - failCount)
}
catch { return -1 }
}
// after 3 or more failed pin attempts, authentication is disabled until this time (interval since reference date)
var walletDisabledUntil: TimeInterval {
do {
let failCount: Int64 = try keychainItem(key: KeychainKey.pinFailCount) ?? 0
guard failCount >= 3 else { return 0 }
let failTime: Int64 = try keychainItem(key: KeychainKey.pinFailTime) ?? 0
return Double(failTime) + pow(6, Double(failCount - 3))*60
}
catch let error {
assert(false, "Error: \(error)")
return 0
}
}
//Can be expensive...result should be cached
var pinLength: Int {
do {
if let pin: String = try keychainItem(key: KeychainKey.pin) {
return pin.utf8.count
} else {
return 6
}
} catch let error {
print("Pin keychain error: \(error)")
return 6
}
}
// true if pin is correct
func authenticate(pin: String) -> Bool {
do {
let secureTime = Date().timeIntervalSince1970 // TODO: XXX use secure time from https request
var failCount: Int64 = try keychainItem(key: KeychainKey.pinFailCount) ?? 0
if failCount >= 3 {
let failTime: Int64 = try keychainItem(key: KeychainKey.pinFailTime) ?? 0
if secureTime < Double(failTime) + pow(6, Double(failCount - 3))*60 { // locked out
return false
}
}
if !WalletManager.failedPins.contains(pin) { // count unique attempts before checking success
failCount += 1
try setKeychainItem(key: KeychainKey.pinFailCount, item: failCount)
}
if try pin == keychainItem(key: KeychainKey.pin) { // successful pin attempt
try authenticationSuccess()
return true
}
else if !WalletManager.failedPins.contains(pin) { // unique failed attempt
WalletManager.failedPins.append(pin)
if (failCount >= 8) { // wipe wallet after 8 failed pin attempts and 24+ hours of lockout
if !wipeWallet() { return false }
return false
}
let pinFailTime: Int64 = try keychainItem(key: KeychainKey.pinFailTime) ?? 0
if secureTime > Double(pinFailTime) {
try setKeychainItem(key: KeychainKey.pinFailTime, item: Int64(secureTime))
}
}
return false
}
catch let error {
assert(false, "Error: \(error)")
return false
}
}
//true if phrase is correct
func authenticate(phrase: String) -> Bool {
do {
var seed = UInt512()
guard let nfkdPhrase = CFStringCreateMutableCopy(secureAllocator, 0, phrase as CFString)
else { return false }
CFStringNormalize(nfkdPhrase, .KD)
BRBIP39DeriveKey(&seed, nfkdPhrase as String, nil)
let mpk = BRBIP32MasterPubKey(&seed, MemoryLayout<UInt512>.size)
seed = UInt512() // clear seed
let mpkData: Data? = try keychainItem(key: KeychainKey.masterPubKey)
guard mpkData?.masterPubKey == mpk else { return false }
return true
} catch {
return false
}
}
private func authenticationSuccess() throws {
let limit = Int64(UserDefaults.standard.double(forKey: DefaultsKey.spendLimitAmount))
WalletManager.failedPins.removeAll()
UserDefaults.standard.set(Date.timeIntervalSinceReferenceDate, forKey: DefaultsKey.pinUnlockTime)
try setKeychainItem(key: KeychainKey.pinFailTime, item: Int64(0))
try setKeychainItem(key: KeychainKey.pinFailCount, item: Int64(0))
if let wallet = wallet, limit > 0 {
try setKeychainItem(key: KeychainKey.spendLimit,
item: Int64(wallet.totalSent) + limit)
}
}
// show touch ID dialog and call completion block with success or failure
func authenticate(touchIDPrompt: String, completion: @escaping (TouchIdResult) -> ()) {
let policy = LAPolicy.deviceOwnerAuthenticationWithBiometrics
LAContext().evaluatePolicy(policy, localizedReason: touchIDPrompt,
reply: { success, error in
DispatchQueue.main.async {
if success { return completion(.success) }
guard let error = error else { return completion(.failure) }
if error._code == Int(kLAErrorUserCancel) {
return completion (.cancel)
} else if error._code == Int(kLAErrorUserFallback) {
return completion (.fallback)
}
completion(.failure)
} })
}
// sign the given transaction using pin authentication
func signTransaction(_ tx: BRTxRef, forkId: Int = 0, pin: String) -> Bool {
guard authenticate(pin: pin) else { return false }
return signTx(tx, forkId: forkId)
}
// sign the given transaction using touch ID authentication
func signTransaction(_ tx: BRTxRef, touchIDPrompt: String, completion: @escaping (TouchIdResult) -> ()) {
do {
let spendLimit: Int64 = try keychainItem(key: KeychainKey.spendLimit) ?? 0
guard let wallet = wallet, wallet.amountSentByTx(tx) - wallet.amountReceivedFromTx(tx) + wallet.totalSent <= UInt64(spendLimit) else {
return completion(.failure)
}
}
catch { return completion(.failure) }
store.perform(action: TouchIdActions.setIsPrompting(true))
authenticate(touchIDPrompt: touchIDPrompt) { result in
self.store.perform(action: TouchIdActions.setIsPrompting(false))
guard result == .success else { return completion(result) }
completion(self.signTx(tx) == true ? .success : .failure)
}
}
func buildBitIdKey(url: String, index: Int) -> BRKey? {
return autoreleasepool {
do {
guard let phrase: String = try keychainItem(key: KeychainKey.mnemonic) else { return nil }
var key = BRKey()
var seed = UInt512()
BRBIP39DeriveKey(&seed, phrase, nil)
BRBIP32BitIDKey(&key, &seed, MemoryLayout<UInt512>.size, UInt32(index), url)
seed = UInt512()
return key
} catch {
return nil
}
}
}
// the 12 word wallet recovery phrase
func seedPhrase(pin: String) -> String? {
guard authenticate(pin: pin) else { return nil }
do {
return try keychainItem(key: KeychainKey.mnemonic)
}
catch { return nil }
}
// recover an existing wallet using 12 word wallet recovery phrase
// will fail if a wallet already exists on the keychain
func setSeedPhrase(_ phrase: String) -> Bool {
guard noWallet else { return false }
do {
guard let nfkdPhrase = CFStringCreateMutableCopy(secureAllocator, 0, phrase as CFString)
else { return false }
CFStringNormalize(nfkdPhrase, .KD)
var seed = UInt512()
try setKeychainItem(key: KeychainKey.mnemonic, item: nfkdPhrase as String?, authenticated: true)
BRBIP39DeriveKey(&seed, nfkdPhrase as String, nil)
self.masterPubKey = BRBIP32MasterPubKey(&seed, MemoryLayout<UInt512>.size)
seed = UInt512() // clear seed
if self.earliestKeyTime < BIP39CreationTime { self.earliestKeyTime = BIP39CreationTime }
try setKeychainItem(key: KeychainKey.masterPubKey, item: Data(masterPubKey: self.masterPubKey))
return true
}
catch { return false }
}
// create a new wallet and return the 12 word wallet recovery phrase
// will fail if a wallet already exists on the keychain
func setRandomSeedPhrase() -> String? {
guard noWallet else { return nil }
guard var words = rawWordList else { return nil }
let time = Date.timeIntervalSinceReferenceDate
// we store the wallet creation time on the keychain because keychain data persists even when app is deleted
do {
try setKeychainItem(key: KeychainKey.creationTime,
item: [time].withUnsafeBufferPointer { Data(buffer: $0) })
self.earliestKeyTime = time
}
catch { return nil }
// wrapping in an autorelease pool ensures sensitive memory is wiped and released immediately
return autoreleasepool {
var entropy = UInt128()
let entropyRef = UnsafeMutableRawPointer(mutating: &entropy).assumingMemoryBound(to: UInt8.self)
guard SecRandomCopyBytes(kSecRandomDefault, MemoryLayout<UInt128>.size, entropyRef) == 0
else { return nil }
let phraseLen = BRBIP39Encode(nil, 0, &words, entropyRef, MemoryLayout<UInt128>.size)
var phraseData = CFDataCreateMutable(secureAllocator, phraseLen) as Data
phraseData.count = phraseLen
guard phraseData.withUnsafeMutableBytes({
BRBIP39Encode($0, phraseData.count, &words, entropyRef, MemoryLayout<UInt128>.size)
}) == phraseData.count else { return nil }
entropy = UInt128()
let phrase = CFStringCreateFromExternalRepresentation(secureAllocator, phraseData as CFData,
CFStringBuiltInEncodings.UTF8.rawValue) as String
guard setSeedPhrase(phrase) else { return nil }
return phrase
}
}
// change wallet authentication pin
func changePin(newPin: String, pin: String) -> Bool {
guard authenticate(pin: pin) else { return false }
do {
store.perform(action: PinLength.set(newPin.utf8.count))
try setKeychainItem(key: KeychainKey.pin, item: newPin)
return true
}
catch { return false }
}
// change wallet authentication pin using the wallet recovery phrase
// recovery phrase is optional if no pin is currently set
func forceSetPin(newPin: String, seedPhrase: String? = nil) -> Bool {
do {
if let phrase = seedPhrase {
var seed = UInt512()
guard let nfkdPhrase = CFStringCreateMutableCopy(secureAllocator, 0, phrase as CFString)
else { return false }
CFStringNormalize(nfkdPhrase, .KD)
BRBIP39DeriveKey(&seed, nfkdPhrase as String, nil)
let mpk = BRBIP32MasterPubKey(&seed, MemoryLayout<UInt512>.size)
seed = UInt512() // clear seed
let mpkData: Data? = try keychainItem(key: KeychainKey.masterPubKey)
guard mpkData?.masterPubKey == mpk else { return false }
}
else if try keychainItem(key: KeychainKey.pin) as String? != nil {
return authenticate(pin: newPin)
}
store.perform(action: PinLength.set(newPin.utf8.count))
try setKeychainItem(key: KeychainKey.pin, item: newPin)
try authenticationSuccess()
return true
}
catch { return false }
}
// wipe the existing wallet from the keychain
func wipeWallet(pin: String = "forceWipe") -> Bool {
guard pin == "forceWipe" || authenticate(pin: pin) else { return false }
do {
lazyWallet = nil
lazyPeerManager = nil
if db != nil { sqlite3_close(db) }
db = nil
masterPubKey = BRMasterPubKey()
didInitWallet = false
earliestKeyTime = 0
if let bundleId = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleId)
}
try BRAPIClient(authenticator: self).kv?.rmdb()
try? FileManager.default.removeItem(atPath: dbPath)
try? FileManager.default.removeItem(at: BRReplicatedKVStore.dbPath)
try setKeychainItem(key: KeychainKey.apiAuthKey, item: nil as Data?)
try setKeychainItem(key: KeychainKey.spendLimit, item: nil as Int64?)
try setKeychainItem(key: KeychainKey.creationTime, item: nil as Data?)
try setKeychainItem(key: KeychainKey.pinFailTime, item: nil as Int64?)
try setKeychainItem(key: KeychainKey.pinFailCount, item: nil as Int64?)
try setKeychainItem(key: KeychainKey.pin, item: nil as String?)
try setKeychainItem(key: KeychainKey.masterPubKey, item: nil as Data?)
try setKeychainItem(key: KeychainKey.seed, item: nil as Data?)
try setKeychainItem(key: KeychainKey.mnemonic, item: nil as String?, authenticated: true)
NotificationCenter.default.post(name: .WalletDidWipe, object: nil)
return true
}
catch let error {
print("Wipe wallet error: \(error)")
return false
}
}
// key used for authenticated API calls
var apiAuthKey: String? {
return autoreleasepool {
do {
if let apiKey: String? = try? keychainItem(key: KeychainKey.apiAuthKey) {
if apiKey != nil {
return apiKey
}
}
var key = BRKey()
var seed = UInt512()
guard let phrase: String = try keychainItem(key: KeychainKey.mnemonic) else { return nil }
BRBIP39DeriveKey(&seed, phrase, nil)
BRBIP32APIAuthKey(&key, &seed, MemoryLayout<UInt512>.size)
seed = UInt512() // clear seed
let pkLen = BRKeyPrivKey(&key, nil, 0)
var pkData = CFDataCreateMutable(secureAllocator, pkLen) as Data
pkData.count = pkLen
guard pkData.withUnsafeMutableBytes({ BRKeyPrivKey(&key, $0, pkLen) }) == pkLen else { return nil }
let privKey = CFStringCreateFromExternalRepresentation(secureAllocator, pkData as CFData,
CFStringBuiltInEncodings.UTF8.rawValue) as String
try setKeychainItem(key: KeychainKey.apiAuthKey, item: privKey)
return privKey
}
catch let error {
print("apiAuthKey error: \(error)")
return nil
}
}
}
// sensitive user information stored on the keychain
var userAccount: Dictionary<AnyHashable, Any>? {
get {
do {
return try keychainItem(key: KeychainKey.userAccount)
}
catch { return nil }
}
set (value) {
do {
try setKeychainItem(key: KeychainKey.userAccount, item: value)
}
catch { }
}
}
private struct KeychainKey {
public static let mnemonic = "mnemonic"
public static let creationTime = "creationtime"
public static let masterPubKey = "masterpubkey"
public static let spendLimit = "spendlimit"
public static let pin = "pin"
public static let pinFailCount = "pinfailcount"
public static let pinFailTime = "pinfailheight"
public static let apiAuthKey = "authprivkey"
public static let userAccount = "https://api.breadwallet.com"
public static let seed = "seed" // deprecated
}
private struct DefaultsKey {
public static let spendLimitAmount = "SPEND_LIMIT_AMOUNT"
public static let pinUnlockTime = "PIN_UNLOCK_TIME"
}
private func signTx(_ tx: BRTxRef, forkId: Int = 0) -> Bool {
return autoreleasepool {
do {
var seed = UInt512()
defer { seed = UInt512() }
guard let wallet = wallet else { return false }
guard let phrase: String = try keychainItem(key: KeychainKey.mnemonic) else { return false }
BRBIP39DeriveKey(&seed, phrase, nil)
return wallet.signTransaction(tx, forkId: forkId, seed: &seed)
}
catch { return false }
}
}
}
private func keychainItem<T>(key: String) throws -> T? {
let query = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrService as String : WalletSecAttrService,
kSecAttrAccount as String : key,
kSecReturnData as String : true as Any]
var result: CFTypeRef? = nil
let status = SecItemCopyMatching(query as CFDictionary, &result);
guard status == noErr || status == errSecItemNotFound else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
guard let data = result as? Data else { return nil }
switch T.self {
case is Data.Type:
return data as? T
case is String.Type:
return CFStringCreateFromExternalRepresentation(secureAllocator, data as CFData,
CFStringBuiltInEncodings.UTF8.rawValue) as? T
case is Int64.Type:
guard data.count == MemoryLayout<T>.stride else { return nil }
return data.withUnsafeBytes { $0.pointee }
case is Dictionary<AnyHashable, Any>.Type:
return NSKeyedUnarchiver.unarchiveObject(with: data) as? T
default:
throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam))
}
}
private func setKeychainItem<T>(key: String, item: T?, authenticated: Bool = false) throws {
let accessible = (authenticated) ? kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String
: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String
let query = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrService as String : WalletSecAttrService,
kSecAttrAccount as String : key]
var status = noErr
var data: Data? = nil
if let item = item {
switch T.self {
case is Data.Type:
data = item as? Data
case is String.Type:
data = CFStringCreateExternalRepresentation(secureAllocator, item as! CFString,
CFStringBuiltInEncodings.UTF8.rawValue, 0) as Data
case is Int64.Type:
data = CFDataCreateMutable(secureAllocator, MemoryLayout<T>.stride) as Data
[item].withUnsafeBufferPointer { data?.append($0) }
case is Dictionary<AnyHashable, Any>.Type:
data = NSKeyedArchiver.archivedData(withRootObject: item)
default:
throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam))
}
}
if data == nil { // delete item
if SecItemCopyMatching(query as CFDictionary, nil) != errSecItemNotFound {
status = SecItemDelete(query as CFDictionary)
}
}
else if SecItemCopyMatching(query as CFDictionary, nil) != errSecItemNotFound { // update existing item
let update = [kSecAttrAccessible as String : accessible,
kSecValueData as String : data as Any]
status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
}
else { // add new item
let item = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrService as String : WalletSecAttrService,
kSecAttrAccount as String : key,
kSecAttrAccessible as String : accessible,
kSecValueData as String : data as Any]
status = SecItemAdd(item as CFDictionary, nil)
}
guard status == noErr else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
}
| 43.853859 | 146 | 0.604635 |
9c13b7742bb0e7b80a32df5a2eaa3eb91fba6ba5
| 520 |
//
// Repo.swift
// Clima
//
// Created by mohammad mugish on 28/01/21.
//
import Foundation
import Combine
class Repo : ObservableObject {
var weatherInfoStore : WeatherInformationStore
var api_handler : API_Handler
private var cancellables = Set<AnyCancellable>()
init(weatherInfoStore : WeatherInformationStore, api_handler : API_Handler){
print("Repo Init")
self.weatherInfoStore = weatherInfoStore
self.api_handler = api_handler
}
}
| 17.333333 | 80 | 0.663462 |
91c6a560639f3df78eeb07457f5c1dc434ff1dbe
| 760 |
import App
import Vapor
import PostgreSQLProvider
/// We have isolated all of our App's logic into
/// the App module because it makes our app
/// more testable.
///
/// In general, the executable portion of our App
/// shouldn't include much more code than is presented
/// here.
///
/// We simply initialize our Droplet, optionally
/// passing in values if necessary
/// Then, we pass it to our App's setup function
/// this should setup all the routes and special
/// features of our app
///
/// .run() runs the Droplet's commands,
/// if no command is given, it will default to "serve"
let config = try Config()
try config.addProvider(PostgreSQLProvider.Provider.self)
try config.setup()
let drop = try Droplet(config)
try drop.setup()
try drop.run()
| 25.333333 | 56 | 0.721053 |
291c0fe8542e9aad70b51bc32a15c71073a3dd47
| 4,423 |
//
// SpinnerView.swift
// SpinerViewiOS
//
// Created by SumitKumar on 01/06/18.
// Copyright © 2018 SumitKumar. All rights reserved.
//
import UIKit
import Foundation
protocol SpinnerViewDelegate {
func didSelectOptionFromList(SpinnerView : SpinnerView, index : Int, slectedValue : String)
func didTapBackGround()
}
class SpinnerView: UIView, UITableViewDelegate, UITableViewDataSource {
//MARK: Variables
private var btnBackGround = UIButton()
private var arroptionList = NSMutableArray()
private let TABLEVIEW_CELL_HEIGHT : CGFloat = 44.0
private let vwConatiner = UIView()
private let maximumConatainerHeight : CGFloat = 220.0
private let tblOption = UITableView()
var maxHeight : CGFloat = 0.0
var delegate : SpinnerViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
}
//below override method is required when a view doesn't have an nib file
required init?(coder aDecoder: NSCoder) {
print("requiered Method Fired")
fatalError("init(coder:) has not been implemented")
}
func setupViewComponents(frame: CGRect, arrOptions : [String], isShowListUpside : Bool) {
btnBackGround.frame = CGRect.init(x: 0, y: 0, width: GLOBAL_CONSTANT.SCREEN_WIDTH.width, height: GLOBAL_CONSTANT.SCREEN_WIDTH.height)
btnBackGround.backgroundColor = UIColor.black.withAlphaComponent(0.1)
btnBackGround.addTarget(self, action: #selector(btnBAckgroundAction), for: .touchUpInside)
//GLOBAL_CONSTANT.APP_DELEGATE.window?.addSubview(btnBackGround)
self.addSubview(btnBackGround)
if arroptionList.count > 0 {
arroptionList.removeAllObjects()
}
arroptionList.addObjects(from: arrOptions)
var containerHeight : CGFloat = CGFloat(Double(arrOptions.count) * Double(TABLEVIEW_CELL_HEIGHT))
if arrOptions.count > 5 {
containerHeight = (maxHeight == 0.0) ? maximumConatainerHeight : maxHeight
}
let containerPosY : CGFloat!
if isShowListUpside{
containerPosY = frame.origin.y - containerHeight
}else{
containerPosY = frame.origin.y + frame.size.height
}
vwConatiner.removeFromSuperview()
vwConatiner.frame = CGRect.init(x: frame.origin.x, y: containerPosY, width: frame.size.width, height: containerHeight)
vwConatiner.dropShadow(scale: true)
self.addSubview(vwConatiner)
self.bringSubview(toFront: vwConatiner)
tblOption.frame = CGRect.init(x: 0, y: 0, width: vwConatiner.frame.size.width, height: vwConatiner.frame.size.height)
tblOption.dataSource = self
tblOption.delegate = self
tblOption.isScrollEnabled = (arrOptions.count <= 5) ? false : true
//tblOption.registerCellClass(CustomTableViewCell.self)
tblOption.separatorColor = UIColor.clear
tblOption.separatorStyle = .none
vwConatiner.addSubview(tblOption)
}
//MARK: Button Actions
@objc func btnBAckgroundAction() {
delegate?.didTapBackGround()
tblOption.removeFromSuperview()
vwConatiner.removeFromSuperview()
btnBackGround.removeFromSuperview()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arroptionList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = CustomTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "CustomTableViewCell")
cell.textLabel?.font = UIFont.italicSystemFont(ofSize: 18)
cell.textLabel?.text = arroptionList[indexPath.row] as? String
cell.selectionStyle = .none
tableView.separatorColor = UIColor.clear
tableView.separatorStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
delegate?.didSelectOptionFromList(SpinnerView: self, index: indexPath.row, slectedValue: arroptionList[indexPath.row] as! String)
tblOption.removeFromSuperview()
vwConatiner.removeFromSuperview()
btnBackGround.removeFromSuperview()
}
}
| 36.553719 | 141 | 0.677368 |
fe79d9dab90af7ebf17444564225637d50129aff
| 3,437 |
//
// Wikipedia+Article.swift
// WikipediaKit
//
// Created by Frank Rausch on 2020-09-01.
// Copyright © 2020 Raureif GmbH / Frank Rausch
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// “Software”), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension Wikipedia {
public func requestArticle(language: WikipediaLanguage,
title: String,
fragment: String? = nil,
imageWidth: Int,
completion: @escaping (Result<WikipediaArticle, WikipediaError>)->())
-> URLSessionDataTask? {
if let cachedArticle = self.articleCache.get(language: language, title: title) {
DispatchQueue.main.async {
completion(.success(cachedArticle))
}
return nil
}
let title = title.wikipediaURLEncodedString(encodeSlashes: true)
let urlString = "https://\(language.code).wikipedia.org/api/rest_v1/page/mobile-sections/\(title)"
guard let url = URL(string: urlString)
else {
DispatchQueue.main.async {
completion(.failure(.other(nil)))
}
return nil
}
let request = URLRequest(url: url)
return WikipediaNetworking.shared.loadJSON(urlRequest: request) { jsonDictionary, error in
guard error == nil else {
DispatchQueue.main.async {
completion (.failure(error!))
}
return
}
guard let jsonDictionary = jsonDictionary else {
DispatchQueue.main.async {
completion (.failure(.decodingError))
}
return
}
if let article = WikipediaArticle(jsonDictionary: jsonDictionary, language: language, title: title, fragment: fragment, imageWidth: imageWidth) {
self.articleCache.add(article)
DispatchQueue.main.async {
completion(.success(article))
}
} else {
DispatchQueue.main.async {
completion(.failure(.decodingError))
}
}
}
}
}
| 36.178947 | 157 | 0.595868 |
20877ed0cb890f6302cfb271bdaef1d1fef97187
| 11,978 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
#if os(macOS)
private let ε: CGFloat = 2.22045e-16
public struct AffineTransform : ReferenceConvertible, Hashable, CustomStringConvertible {
public var m11, m12, m21, m22, tX, tY: CGFloat
public typealias ReferenceType = NSAffineTransform
/**
Creates an affine transformation.
*/
public init(m11: CGFloat, m12: CGFloat, m21: CGFloat, m22: CGFloat, tX: CGFloat, tY: CGFloat) {
self.m11 = m11
self.m12 = m12
self.m21 = m21
self.m22 = m22
self.tX = tX
self.tY = tY
}
private init(reference: __shared NSAffineTransform) {
m11 = reference.transformStruct.m11
m12 = reference.transformStruct.m12
m21 = reference.transformStruct.m21
m22 = reference.transformStruct.m22
tX = reference.transformStruct.tX
tY = reference.transformStruct.tY
}
private var reference: NSAffineTransform {
let ref = NSAffineTransform()
ref.transformStruct = NSAffineTransformStruct(m11: m11, m12: m12, m21: m21, m22: m22, tX: tX, tY: tY)
return ref
}
/**
Creates an affine transformation matrix with identity values.
- seealso: identity
*/
public init() {
self.init(m11: CGFloat(1.0), m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: CGFloat(1.0),
tX: CGFloat(0.0), tY: CGFloat(0.0))
}
/**
Creates an affine transformation matrix from translation values.
The matrix takes the following form:
[ 1 0 0 ]
[ 0 1 0 ]
[ x y 1 ]
*/
public init(translationByX x: CGFloat, byY y: CGFloat) {
self.init(m11: CGFloat(1.0), m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: CGFloat(1.0),
tX: x, tY: y)
}
/**
Creates an affine transformation matrix from scaling values.
The matrix takes the following form:
[ x 0 0 ]
[ 0 y 0 ]
[ 0 0 1 ]
*/
public init(scaleByX x: CGFloat, byY y: CGFloat) {
self.init(m11: x, m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: y,
tX: CGFloat(0.0), tY: CGFloat(0.0))
}
/**
Creates an affine transformation matrix from scaling a single value.
The matrix takes the following form:
[ f 0 0 ]
[ 0 f 0 ]
[ 0 0 1 ]
*/
public init(scale factor: CGFloat) {
self.init(scaleByX: factor, byY: factor)
}
/**
Creates an affine transformation matrix from rotation value (angle in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByRadians angle: CGFloat) {
let α = Double(angle)
let sine = CGFloat(sin(α))
let cosine = CGFloat(cos(α))
self.init(m11: cosine, m12: sine, m21: -sine, m22: cosine, tX: 0, tY: 0)
}
/**
Creates an affine transformation matrix from a rotation value (angle in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByDegrees angle: CGFloat) {
let α = angle * .pi / 180.0
self.init(rotationByRadians: α)
}
/**
An identity affine transformation matrix
[ 1 0 0 ]
[ 0 1 0 ]
[ 0 0 1 ]
*/
public static let identity = AffineTransform(m11: 1, m12: 0, m21: 0, m22: 1, tX: 0, tY: 0)
// Translating
public mutating func translate(x: CGFloat, y: CGFloat) {
tX += m11 * x + m21 * y
tY += m12 * x + m22 * y
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byDegrees angle: CGFloat) {
let α = angle * .pi / 180.0
return rotate(byRadians: α)
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byRadians angle: CGFloat) {
let t2 = self
let t1 = AffineTransform(rotationByRadians: angle)
var t = AffineTransform.identity
t.m11 = t1.m11 * t2.m11 + t1.m12 * t2.m21
t.m12 = t1.m11 * t2.m12 + t1.m12 * t2.m22
t.m21 = t1.m21 * t2.m11 + t1.m22 * t2.m21
t.m22 = t1.m21 * t2.m12 + t1.m22 * t2.m22
t.tX = t1.tX * t2.m11 + t1.tY * t2.m21 + t2.tX
t.tY = t1.tX * t2.m12 + t1.tY * t2.m22 + t2.tY
self = t
}
/**
Creates an affine transformation matrix by combining the receiver with `transformStruct`.
That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is
the `transformStruct`'s affine transformation matrix.
The resulting matrix takes the following form:
[ m11_T m12_T 0 ] [ m11_M m12_M 0 ]
T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ]
[ tX_T tY_T 1 ] [ tX_M tY_M 1 ]
[ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ]
= [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ]
[ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ]
*/
private func concatenated(_ other: AffineTransform) -> AffineTransform {
let (t, m) = (self, other)
// this could be optimized with a vector version
return AffineTransform(
m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22),
m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22),
tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX,
tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY
)
}
// Scaling
public mutating func scale(_ scale: CGFloat) {
self.scale(x: scale, y: scale)
}
public mutating func scale(x: CGFloat, y: CGFloat) {
m11 *= x
m12 *= x
m21 *= y
m22 *= y
}
/**
Inverts the transformation matrix if possible. Matrices with a determinant that is less than
the smallest valid representation of a double value greater than zero are considered to be
invalid for representing as an inverse. If the input AffineTransform can potentially fall into
this case then the inverted() method is suggested to be used instead since that will return
an optional value that will be nil in the case that the matrix cannot be inverted.
D = (m11 * m22) - (m12 * m21)
D < ε the inverse is undefined and will be nil
*/
public mutating func invert() {
guard let inverse = inverted() else {
fatalError("Transform has no inverse")
}
self = inverse
}
public func inverted() -> AffineTransform? {
let determinant = (m11 * m22) - (m12 * m21)
if abs(determinant) <= ε {
return nil
}
var inverse = AffineTransform()
inverse.m11 = m22 / determinant
inverse.m12 = -m12 / determinant
inverse.m21 = -m21 / determinant
inverse.m22 = m11 / determinant
inverse.tX = (m21 * tY - m22 * tX) / determinant
inverse.tY = (m12 * tX - m11 * tY) / determinant
return inverse
}
// Transforming with transform
public mutating func append(_ transform: AffineTransform) {
self = concatenated(transform)
}
public mutating func prepend(_ transform: AffineTransform) {
self = transform.concatenated(self)
}
// Transforming points and sizes
public func transform(_ point: NSPoint) -> NSPoint {
var newPoint = NSPoint()
newPoint.x = (m11 * point.x) + (m21 * point.y) + tX
newPoint.y = (m12 * point.x) + (m22 * point.y) + tY
return newPoint
}
public func transform(_ size: NSSize) -> NSSize {
var newSize = NSSize()
newSize.width = (m11 * size.width) + (m21 * size.height)
newSize.height = (m12 * size.width) + (m22 * size.height)
return newSize
}
public func hash(into hasher: inout Hasher) {
hasher.combine(m11)
hasher.combine(m12)
hasher.combine(m21)
hasher.combine(m22)
hasher.combine(tX)
hasher.combine(tY)
}
public var description: String {
return "{m11:\(m11), m12:\(m12), m21:\(m21), m22:\(m22), tX:\(tX), tY:\(tY)}"
}
public var debugDescription: String {
return description
}
public static func ==(lhs: AffineTransform, rhs: AffineTransform) -> Bool {
return lhs.m11 == rhs.m11 && lhs.m12 == rhs.m12 &&
lhs.m21 == rhs.m21 && lhs.m22 == rhs.m22 &&
lhs.tX == rhs.tX && lhs.tY == rhs.tY
}
}
extension AffineTransform : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSAffineTransform.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSAffineTransform {
return self.reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge type")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) -> Bool {
result = AffineTransform(reference: x)
return true // Can't fail
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ x: NSAffineTransform?) -> AffineTransform {
guard let src = x else { return AffineTransform.identity }
return AffineTransform(reference: src)
}
}
extension NSAffineTransform : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as AffineTransform)
}
}
extension AffineTransform : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
m11 = try container.decode(CGFloat.self)
m12 = try container.decode(CGFloat.self)
m21 = try container.decode(CGFloat.self)
m22 = try container.decode(CGFloat.self)
tX = try container.decode(CGFloat.self)
tY = try container.decode(CGFloat.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.m11)
try container.encode(self.m12)
try container.encode(self.m21)
try container.encode(self.m22)
try container.encode(self.tX)
try container.encode(self.tY)
}
}
#endif
| 32.997245 | 123 | 0.565119 |
23789012287494f7816c0d244ef378adc920656a
| 532 |
//
// URLSessionType.swift
// LoadIt
//
// Created by Luciano Marisi on 25/06/2016.
// Copyright © 2016 Luciano Marisi. All rights reserved.
//
import Foundation
protocol URLSessionType {
func perform(request request: NSURLRequest, completion: (NSData?, NSURLResponse?, NSError?) -> Void)
}
extension NSURLSession: URLSessionType {
public func perform(request request: NSURLRequest, completion: (NSData?, NSURLResponse?, NSError?) -> Void) {
dataTaskWithRequest(request, completionHandler: completion).resume()
}
}
| 26.6 | 111 | 0.736842 |
619cfdccae8c355f1ab49025e61a9a9624f72608
| 30,678 |
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
#if GRDBCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE
import SQLite3
#else
import SQLite3
#endif
import GRDB
#endif
// A type that adopts DatabaseValueConvertible and StatementColumnConvertible
private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible {
let int: Int
let fast: Bool
init(int: Int, fast: Bool) {
self.int = int
self.fast = fast
}
init(sqliteStatement: SQLiteStatement, index: Int32) {
self.init(int: Int(sqlite3_column_int64(sqliteStatement, index)), fast: true)
}
var databaseValue: DatabaseValue {
return int.databaseValue
}
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Fetched? {
guard let int = Int.fromDatabaseValue(dbValue) else {
return nil
}
return Fetched(int: int, fast: false)
}
}
class StatementColumnConvertibleFetchTests: GRDBTestCase {
func testSlowConversion() {
let slow = Fetched.fromDatabaseValue(0.databaseValue)!
XCTAssertEqual(slow.int, 0)
XCTAssertEqual(slow.fast, false)
}
func testRowExtraction() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var rows = try Row.fetchCursor(db, sql: "SELECT NULL")
while let row = try rows.next() {
let one: Fetched? = row[0]
XCTAssertTrue(one == nil)
}
rows = try Row.fetchCursor(db, sql: "SELECT 1")
while let row = try rows.next() {
let one: Fetched? = row[0]
XCTAssertEqual(one!.int, 1)
XCTAssertEqual(one!.fast, true)
}
rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int")
while let row = try rows.next() {
let one: Fetched? = row["int"]
XCTAssertEqual(one!.int, 1)
XCTAssertEqual(one!.fast, true)
}
rows = try Row.fetchCursor(db, sql: "SELECT 1")
while let row = try rows.next() {
let one: Fetched = row[0]
XCTAssertEqual(one.int, 1)
XCTAssertEqual(one.fast, true)
}
rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int")
while let row = try rows.next() {
let one: Fetched = row["int"]
XCTAssertEqual(one.int, 1)
XCTAssertEqual(one.fast, true)
}
}
}
// MARK: - StatementColumnConvertible.fetch
func testFetchCursor() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ cursor: FastDatabaseValueCursor<Fetched>) throws {
var i = try cursor.next()!
XCTAssertEqual(i.int, 1)
XCTAssertTrue(i.fast)
i = try cursor.next()!
XCTAssertEqual(i.int, 2)
XCTAssertTrue(i.fast)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let sql = "SELECT 1 UNION ALL SELECT 2"
let statement = try db.makeSelectStatement(sql: sql)
try test(Fetched.fetchCursor(db, sql: sql))
try test(Fetched.fetchCursor(statement))
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched>(sql: sql).fetchCursor(db))
}
do {
let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter))
try test(Fetched.fetchCursor(statement, adapter: adapter))
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchCursor(db))
}
}
}
#if swift(>=5.0)
func testFetchCursorWithInterpolation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: SQLRequest<Fetched> = "SELECT \(42)"
let cursor = try request.fetchCursor(db)
let fetched = try cursor.next()!
XCTAssertEqual(fetched.int, 42)
XCTAssertTrue(fetched.fast)
}
}
#endif
func testFetchCursorStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
let customError = NSError(domain: "Custom", code: 0xDEAD)
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
func test(_ cursor: FastDatabaseValueCursor<Fetched>, sql: String) throws {
do {
_ = try cursor.next()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "\(customError)")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: \(customError)")
}
do {
_ = try cursor.next()
XCTFail()
} catch is DatabaseError {
// Various SQLite and SQLCipher versions don't emit the same
// error. What we care about is that there is an error.
}
}
do {
let sql = "SELECT throw()"
try test(Fetched.fetchCursor(db, sql: sql), sql: sql)
try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchCursor(db), sql: sql)
}
do {
let sql = "SELECT 0, throw()"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchCursor(db), sql: sql)
}
}
}
func testFetchCursorCompilationFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ cursor: @autoclosure () throws -> FastDatabaseValueCursor<Fetched>, sql: String) throws {
do {
_ = try cursor()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: nonExistingTable")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: no such table: nonExistingTable")
}
}
do {
let sql = "SELECT * FROM nonExistingTable"
try test(Fetched.fetchCursor(db, sql: sql), sql: sql)
try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchCursor(db), sql: sql)
}
do {
let sql = "SELECT * FROM nonExistingTable"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchCursor(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchCursor(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchCursor(db), sql: sql)
}
}
}
func testFetchAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ array: [Fetched]) {
XCTAssertEqual(array.map { $0.int }, [1,2])
XCTAssertEqual(array.map { $0.fast }, [true, true])
}
do {
let sql = "SELECT 1 UNION ALL SELECT 2"
let statement = try db.makeSelectStatement(sql: sql)
try test(Fetched.fetchAll(db, sql: sql))
try test(Fetched.fetchAll(statement))
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched>(sql: sql).fetchAll(db))
}
do {
let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchAll(db, sql: sql, adapter: adapter))
try test(Fetched.fetchAll(statement, adapter: adapter))
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchAll(db))
}
}
}
#if swift(>=5.0)
func testFetchAllWithInterpolation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: SQLRequest<Fetched> = "SELECT \(42)"
let array = try request.fetchAll(db)
XCTAssertEqual(array[0].int, 42)
XCTAssertTrue(array[0].fast)
}
}
#endif
func testFetchAllStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
let customError = NSError(domain: "Custom", code: 0xDEAD)
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
func test(_ array: @autoclosure () throws -> [Fetched], sql: String) throws {
do {
_ = try array()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "\(customError)")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: \(customError)")
}
}
do {
let sql = "SELECT throw()"
try test(Fetched.fetchAll(db, sql: sql), sql: sql)
try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchAll(db), sql: sql)
}
do {
let sql = "SELECT 0, throw()"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchAll(db), sql: sql)
}
}
}
func testFetchAllCompilationFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ array: @autoclosure () throws -> [Fetched], sql: String) throws {
do {
_ = try array()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: nonExistingTable")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: no such table: nonExistingTable")
}
}
do {
let sql = "SELECT * FROM nonExistingTable"
try test(Fetched.fetchAll(db, sql: sql), sql: sql)
try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchAll(db), sql: sql)
}
do {
let sql = "SELECT * FROM nonExistingTable"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchAll(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchAll(db), sql: sql)
}
}
}
func testFetchOne() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
func test(_ nilBecauseMissingRow: Fetched?) {
XCTAssertTrue(nilBecauseMissingRow == nil)
}
do {
let sql = "SELECT 1 WHERE 0"
let statement = try db.makeSelectStatement(sql: sql)
try test(Fetched.fetchOne(db, sql: sql))
try test(Fetched.fetchOne(statement))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched>(sql: sql).fetchOne(db))
}
do {
let sql = "SELECT 0, 1 WHERE 0"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchOne(db, sql: sql, adapter: adapter))
try test(Fetched.fetchOne(statement, adapter: adapter))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchOne(db))
}
}
do {
func test(_ nilBecauseNull: Fetched?) {
XCTAssertTrue(nilBecauseNull == nil)
}
do {
let sql = "SELECT NULL"
let statement = try db.makeSelectStatement(sql: sql)
try test(Fetched.fetchOne(db, sql: sql))
try test(Fetched.fetchOne(statement))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched>(sql: sql).fetchOne(db))
}
do {
let sql = "SELECT 0, NULL"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchOne(db, sql: sql, adapter: adapter))
try test(Fetched.fetchOne(statement, adapter: adapter))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchOne(db))
}
}
do {
func test(_ value: Fetched?) {
XCTAssertEqual(value!.int, 1)
}
do {
let sql = "SELECT 1"
let statement = try db.makeSelectStatement(sql: sql)
try test(Fetched.fetchOne(db, sql: sql))
try test(Fetched.fetchOne(statement))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched>(sql: sql).fetchOne(db))
}
do {
let sql = "SELECT 0, 1"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchOne(db, sql: sql, adapter: adapter))
try test(Fetched.fetchOne(statement, adapter: adapter))
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchOne(db))
}
}
}
}
#if swift(>=5.0)
func testFetchOneWithInterpolation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: SQLRequest<Fetched> = "SELECT \(42)"
let fetched = try request.fetchOne(db)
XCTAssertEqual(fetched!.int, 42)
XCTAssertTrue(fetched!.fast)
}
}
#endif
func testFetchOneStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
let customError = NSError(domain: "Custom", code: 0xDEAD)
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
func test(_ value: @autoclosure () throws -> Fetched?, sql: String) throws {
do {
_ = try value()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "\(customError)")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: \(customError)")
}
}
do {
let sql = "SELECT throw()"
try test(Fetched.fetchOne(db, sql: sql), sql: sql)
try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchOne(db), sql: sql)
}
do {
let sql = "SELECT 0, throw()"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchOne(db), sql: sql)
}
}
}
func testFetchOneCompilationFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ value: @autoclosure () throws -> Fetched?, sql: String) throws {
do {
_ = try value()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: nonExistingTable")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: no such table: nonExistingTable")
}
}
do {
let sql = "SELECT * FROM nonExistingTable"
try test(Fetched.fetchOne(db, sql: sql), sql: sql)
try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql).fetchOne(db), sql: sql)
}
do {
let sql = "SELECT * FROM nonExistingTable"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Fetched.fetchOne(db, sql: sql, adapter: adapter), sql: sql)
try test(Fetched.fetchOne(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Fetched.fetchOne(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched>(sql: sql, adapter: adapter).fetchOne(db), sql: sql)
}
}
}
// MARK: - Optional<StatementColumnConvertible>.fetch
func testOptionalFetchCursor() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ cursor: FastNullableDatabaseValueCursor<Fetched>) throws {
let i = try cursor.next()!
XCTAssertEqual(i!.int, 1)
XCTAssertTrue(i!.fast)
XCTAssertTrue(try cursor.next()! == nil)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let sql = "SELECT 1 UNION ALL SELECT NULL"
let statement = try db.makeSelectStatement(sql: sql)
try test(Optional<Fetched>.fetchCursor(db, sql: sql))
try test(Optional<Fetched>.fetchCursor(statement))
try test(Optional<Fetched>.fetchCursor(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched?>(sql: sql).fetchCursor(db))
}
do {
let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Optional<Fetched>.fetchCursor(db, sql: sql, adapter: adapter))
try test(Optional<Fetched>.fetchCursor(statement, adapter: adapter))
try test(Optional<Fetched>.fetchCursor(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched?>(sql: sql, adapter: adapter).fetchCursor(db))
}
}
}
#if swift(>=5.0)
func testOptionalFetchCursorWithInterpolation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: SQLRequest<Fetched?> = "SELECT \(42)"
let cursor = try request.fetchCursor(db)
let fetched = try cursor.next()!
XCTAssertEqual(fetched!.int, 42)
XCTAssert(fetched!.fast)
}
}
#endif
func testOptionalFetchCursorCompilationFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ cursor: @autoclosure () throws -> FastNullableDatabaseValueCursor<Fetched>, sql: String) throws {
do {
_ = try cursor()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: nonExistingTable")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: no such table: nonExistingTable")
}
}
do {
let sql = "SELECT * FROM nonExistingTable"
try test(Optional<Fetched>.fetchCursor(db, sql: sql), sql: sql)
try test(Optional<Fetched>.fetchCursor(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Optional<Fetched>.fetchCursor(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql).fetchCursor(db), sql: sql)
}
do {
let sql = "SELECT * FROM nonExistingTable"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Optional<Fetched>.fetchCursor(db, sql: sql, adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchCursor(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchCursor(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql, adapter: adapter).fetchCursor(db), sql: sql)
}
}
}
func testOptionalFetchAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ array: [Fetched?]) {
XCTAssertEqual(array.count, 2)
XCTAssertEqual(array[0]!.int, 1)
XCTAssertTrue(array[0]!.fast)
XCTAssertTrue(array[1] == nil)
}
do {
let sql = "SELECT 1 UNION ALL SELECT NULL"
let statement = try db.makeSelectStatement(sql: sql)
try test(Optional<Fetched>.fetchAll(db, sql: sql))
try test(Optional<Fetched>.fetchAll(statement))
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql)))
try test(SQLRequest<Fetched?>(sql: sql).fetchAll(db))
}
do {
let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL"
let statement = try db.makeSelectStatement(sql: sql)
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Optional<Fetched>.fetchAll(db, sql: sql, adapter: adapter))
try test(Optional<Fetched>.fetchAll(statement, adapter: adapter))
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)))
try test(SQLRequest<Fetched?>(sql: sql, adapter: adapter).fetchAll(db))
}
}
}
#if swift(>=5.0)
func testOptionalFetchAllWithInterpolation() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: SQLRequest<Fetched?> = "SELECT \(42)"
let array = try request.fetchAll(db)
XCTAssertEqual(array[0]!.int, 42)
XCTAssert(array[0]!.fast)
}
}
#endif
func testOptionalFetchAllStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
let customError = NSError(domain: "Custom", code: 0xDEAD)
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
func test(_ array: @autoclosure () throws -> [Fetched?], sql: String) throws {
do {
_ = try array()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "\(customError)")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: \(customError)")
}
}
do {
let sql = "SELECT throw()"
try test(Optional<Fetched>.fetchAll(db, sql: sql), sql: sql)
try test(Optional<Fetched>.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql).fetchAll(db), sql: sql)
}
do {
let sql = "SELECT 0, throw()"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Optional<Fetched>.fetchAll(db, sql: sql, adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql, adapter: adapter).fetchAll(db), sql: sql)
}
}
}
func testOptionalFetchAllCompilationFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
func test(_ array: @autoclosure () throws -> [Fetched?], sql: String) throws {
do {
_ = try array()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: nonExistingTable")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: no such table: nonExistingTable")
}
}
do {
let sql = "SELECT * FROM nonExistingTable"
try test(Optional<Fetched>.fetchAll(db, sql: sql), sql: sql)
try test(Optional<Fetched>.fetchAll(db.makeSelectStatement(sql: sql)), sql: sql)
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql).fetchAll(db), sql: sql)
}
do {
let sql = "SELECT * FROM nonExistingTable"
let adapter = SuffixRowAdapter(fromIndex: 1)
try test(Optional<Fetched>.fetchAll(db, sql: sql, adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchAll(db.makeSelectStatement(sql: sql), adapter: adapter), sql: sql)
try test(Optional<Fetched>.fetchAll(db, SQLRequest<Void>(sql: sql, adapter: adapter)), sql: sql)
try test(SQLRequest<Fetched?>(sql: sql, adapter: adapter).fetchAll(db), sql: sql)
}
}
}
}
| 47.562791 | 128 | 0.546548 |
28c25a2e8f6a80fba7d7b7cf4796502a915ee49d
| 4,687 |
//
// YMMonthDayCollectionCell.swift
// YMCalendar
//
// Created by Yuma Matsune on 2017/02/21.
// Copyright © 2017年 Yuma Matsune. All rights reserved.
//
import Foundation
import UIKit
final class YMMonthDayCollectionCell: UICollectionViewCell {
typealias YMMonthDayAnimationCompletion = (Bool) -> Void
let dayLabel = UILabel()
var dayLabelColor: UIColor = .black {
didSet {
dayLabel.textColor = dayLabelColor
}
}
var dayLabelBackgroundColor: UIColor = .clear {
didSet {
dayLabel.backgroundColor = dayLabelBackgroundColor
}
}
var dayLabelSelectedColor: UIColor = .white
var dayLabelSelectedBackgroundColor: UIColor = .black
var day: Int = 1 {
didSet {
dayLabel.text = "\(day)"
}
}
var dayLabelAlignment: YMDayLabelAlignment = .left
var dayLabelHeight: CGFloat = 15
let dayLabelMargin: CGFloat = 2.0
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
backgroundColor = .clear
dayLabel.numberOfLines = 1
dayLabel.adjustsFontSizeToFitWidth = true
dayLabel.font = UIFont.systemFont(ofSize: 12.0)
dayLabel.textColor = dayLabelColor
dayLabel.layer.masksToBounds = true
dayLabel.textAlignment = .center
contentView.addSubview(dayLabel)
}
override func prepareForReuse() {
super.prepareForReuse()
deselect(withAnimation: .none)
}
override public func layoutSubviews() {
super.layoutSubviews()
let x: CGFloat
switch dayLabelAlignment {
case .left:
x = dayLabelMargin
dayLabel.frame = CGRect(x: dayLabelMargin, y: dayLabelMargin, width: dayLabelHeight, height: dayLabelHeight)
case .center:
x = (bounds.width - dayLabelHeight)/2
case .right:
x = bounds.width - dayLabelMargin - dayLabelHeight
}
dayLabel.frame = CGRect(x: x, y: dayLabelMargin, width: dayLabelHeight, height: dayLabelHeight)
dayLabel.layer.cornerRadius = dayLabelHeight / 2
}
public func select(withAnimation animation: YMSelectAnimation, completion: YMMonthDayAnimationCompletion? = nil) {
switch animation {
case .none:
animationWithNone(true, completion: completion)
case .bounce:
animationWithBounce(true, completion: completion)
case .fade:
animationWithFade(true, completion: completion)
}
}
public func deselect(withAnimation animation: YMSelectAnimation, completion: YMMonthDayAnimationCompletion? = nil) {
switch animation {
case .none:
animationWithNone(false, completion: completion)
case .bounce:
animationWithBounce(false, completion: completion)
case .fade:
animationWithFade(false, completion: completion)
}
}
// - MARK: Animation None
private func animationWithNone(_ isSelected: Bool, completion: YMMonthDayAnimationCompletion?=nil) {
if isSelected {
dayLabel.textColor = dayLabelSelectedColor
dayLabel.backgroundColor = dayLabelSelectedBackgroundColor
} else {
dayLabel.textColor = dayLabelColor
dayLabel.backgroundColor = dayLabelBackgroundColor
}
completion?(true)
}
// - MARK: Animation Bounce
private func animationWithBounce(_ isSelected: Bool, completion: YMMonthDayAnimationCompletion?) {
dayLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.1,
options: .beginFromCurrentState,
animations: {
self.dayLabel.transform = CGAffineTransform(scaleX: 1, y: 1)
self.animationWithNone(isSelected)
}, completion: completion)
}
// - MARK: Animation Fade
private func animationWithFade(_ isSelected: Bool, completion: YMMonthDayAnimationCompletion?) {
UIView.transition(with: dayLabel,
duration: 0.2,
options: .transitionCrossDissolve,
animations: {
self.animationWithNone(isSelected)
}, completion: completion)
}
}
| 31.668919 | 120 | 0.615106 |
72db752c40e8604a84f576f22b124fdcbd6630b0
| 2,120 |
//
// AppDelegate.swift
// DemoiOS
//
// Created by toshi0383 on 2016/10/23.
//
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}
}
| 45.106383 | 285 | 0.754717 |
ebb267bdde874e8b1d0ed869cabcfe007519842a
| 481 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 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 the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func b<Int) {
let start = 1))
struct A {
func f<T, a)(T, c) -> {
return self.init() -> a
| 34.357143 | 78 | 0.713098 |
9c50b9411498784815b3d612b1a963856b91315d
| 3,750 |
//
// The MIT License
//
// Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
// HMLinkDelegate.swift
// HMKit
//
// Created by Mikk Rätsep on 11/12/2018.
//
import Foundation
import Foundation
/// `HMLinkDelegated` is used to dispatch `HMLink` events.
/// All callbacks are executed on the **main** thread.
public protocol HMLinkDelegate {
typealias Approve = () throws -> Void
/// Callback for when the `HMLink` received an authorisation request.
///
/// - parameters:
/// - link: `HMLink` that sent the *authorisation* request.
/// - serialNumber: Serial number of the `HMLink` trying to authorise.
/// - approve: Block to be called after the user has approved the authorisation (ignore if the user disallowed or ignored the request). Throws a `.timeout` when the block is called after the timeout period.
/// - timeout: Amount of seconds it takes for the authorisation to time out.
/// - warning: If the *approve*-block is *not* called before the timeout interval elapses (starting after this method is invoked), the authorisation fails.
func link(_ link: HMLink, authorisationRequestedBy serialNumber: [UInt8], approve: @escaping Approve, timeout: TimeInterval)
/// Callback for when a command has been received from the `HMLink`.
///
/// - parameters:
/// - link: `HMLink` that sent the command.
/// - bytes: Bytes-array representing the received command.
/// - contentType: Type of the data received.
/// - requestID: Bytes denoting the *requestID* (could be empty, if wansn't set in sending).
func link(_ link: HMLink, commandReceived bytes: [UInt8], contentType: HMContainerContentType, requestID: [UInt8])
/// Callback for when `revoke` was completed on the other device and data was received back.
///
/// - Parameters:
/// - link: `HMLink` that was revoked.
/// - bytes: Bytes-array of the data sent back.
func link(_ link: HMLink, revokeCompleted bytes: [UInt8])
/// Callback for when the `HMLink`'s state has changed.
///
/// - parameters:
/// - link: The `HMLink` in question.
/// - newState: The new state of the `HMLink`.
/// - previousState: Previous state of the `HMLink`.
func link(_ link: HMLink, stateChanged newState: HMLinkState, previousState: HMLinkState)
/// Callback for when the `HMLink`'s encountered an error.
///
/// - parameters:
/// - link: The `HMLink` in question.
/// - error: The error received by the `HMLink`.
func link(_ link: HMLink, receivedError error: HMProtocolError)
}
| 44.117647 | 214 | 0.688267 |
20baaeed94c46d133d84bbf2c3115513df09cc08
| 2,082 |
//
// WeatherLocationViewControl.swift
// watchClock
//
// Created by [email protected] on 2018/11/15.
// Copyright © 2018 [email protected]. All rights reserved.
//
import Foundation
import UIKit
class WeatherLocationViewControl: UITableViewController, WeatherLocationDelegate {
func onFinishedGetData(data: [WeatherXMLItem]) {
self.xml = data
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
public var Location : String = ""
public var CityName : String = ""
private var xml: [WeatherXMLItem] = []
private var weather: WeatherLocation = WeatherLocation()
override func viewDidLoad() {
self.weather.delegate = self
self.weather.loadRootXML()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(self.xml.count)
return self.xml.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.backgroundColor = UIColor.black
cell.textLabel?.textColor = UIColor.white
let item = self.xml[indexPath.row]
if (item.mode == 0) {
cell.textLabel?.text = item.quName
cell.accessoryType = .disclosureIndicator
} else {
cell.textLabel?.text = item.cityname
if (item.pyName != "") {
cell.accessoryType = .disclosureIndicator
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.xml[indexPath.row]
if (item.mode != 0 && item.pyName == "" && item.location != "") {
self.CityName = item.cityname
self.Location = item.location
self.performSegue(withIdentifier: "unwindToSetup", sender: self)
}
self.weather.loadNextXML(item.pyName)
}
}
| 30.173913 | 109 | 0.62488 |
3847bc841772127eb531460da2507fe7edf687cc
| 7,936 |
//
// Point.swift
// PtahRenderer
//
// Created by Simon Rodriguez on 14/02/2016.
// Copyright © 2016 Simon Rodriguez. All rights reserved.
//
import Foundation
#if os(macOS)
import simd
#endif
#if os(macOS)
public typealias Point4 = float4
public typealias Point3 = float3
public typealias Point2 = float2
#else
public typealias Point4 = internal_float4
public typealias Point3 = internal_float3
public typealias Point2 = internal_float2
#endif
public typealias Scalar = Float
public typealias Vertex = Point3
public typealias Normal = Point3
public typealias UV = Point2
public func ==(lhs: Point2, rhs: Point2) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public func !=(lhs: Point2, rhs: Point2) -> Bool {
return lhs.x != rhs.x || lhs.y != rhs.y
}
public func ==(lhs: Point3, rhs: Point3) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
public func !=(lhs: Point3, rhs: Point3) -> Bool {
return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z
}
public func ==(lhs: Point4, rhs: Point4) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w
}
public func !=(lhs: Point4, rhs: Point4) -> Bool {
return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w
}
public func clamp(_ x: Scalar, _ a: Scalar, _ b: Scalar) -> Scalar {
return min(b, max(a, x))
}
public func clamp(_ x: UInt8, _ a: UInt8, _ b: UInt8) -> UInt8 {
return min(b, max(a, x))
}
public func clamp(_ x: Int, _ a: Int, _ b: Int) -> Int {
return min(b, max(a, x))
}
public extension Point3 {
public init(_ v: Point4) {
self.init(v.x, v.y, v.z)
}
}
public extension Point4 {
public init(_ v: Point3, _ wval: Float) {
self.init()
x = v.x
y = v.y
z = v.z
w = wval
}
}
/// MARK: Internal fallback
#if os(macOS)
// Rely on simd
#else
public struct internal_float2 {
public var x: Scalar = 0.0
public var y: Scalar = 0.0
public init() {
}
public init(_ val: Scalar){
x = val
y = val
}
public init(_ _x: Scalar, _ _y: Scalar) {
x = _x
y = _y
}
}
public func +(lhs: internal_float2, rhs: internal_float2) -> internal_float2 {
return internal_float2(lhs.x + rhs.x, lhs.y + rhs.y)
}
public func -(lhs: internal_float2, rhs: internal_float2) -> internal_float2 {
return internal_float2(lhs.x - rhs.x, lhs.y-rhs.y)
}
public prefix func -(rhs: internal_float2) -> internal_float2 {
return internal_float2(-rhs.x, -rhs.y)
}
public func *(lhs: Scalar, rhs: internal_float2) -> internal_float2 {
return internal_float2(lhs*rhs.x, lhs*rhs.y)
}
public func *(rhs: internal_float2, lhs: Scalar) -> internal_float2 {
return internal_float2(lhs*rhs.x, lhs*rhs.y)
}
public func min(_ lhs: internal_float2, _ rhs: internal_float2) -> internal_float2 {
return internal_float2(min(lhs.x, rhs.x), min(lhs.y, rhs.y))
}
public func max(_ lhs: internal_float2, _ rhs: internal_float2) -> internal_float2 {
return internal_float2(max(lhs.x, rhs.x), max(lhs.y, rhs.y))
}
public func abs(_ lhs: internal_float2) -> internal_float2 {
return internal_float2(abs(lhs.x), abs(lhs.y))
}
public func clamp(_ lhs: internal_float2, min mini: internal_float2, max maxi: internal_float2) -> internal_float2 {
return min(maxi, max(mini, lhs))
}
public func clamp(_ lhs: internal_float2, min mini: Scalar, max maxi: Scalar) -> internal_float2 {
return internal_float2(min(maxi, max(mini, lhs.x)), min(maxi, max(mini, lhs.y)))
}
public struct internal_float3 {
public var x: Scalar = 0.0
public var y: Scalar = 0.0
public var z: Scalar = 0.0
public init() {
}
public init(_ val: Scalar){
x = val
y = val
z = val
}
public init(_ _x: Scalar, _ _y: Scalar, _ _z: Scalar) {
x = _x
y = _y
z = _z
}
}
public func +(lhs: internal_float3, rhs: internal_float3) -> internal_float3 {
return internal_float3(lhs.x + rhs.x, lhs.y+rhs.y, lhs.z+rhs.z)
}
public func -(lhs: internal_float3, rhs: internal_float3) -> internal_float3 {
return internal_float3(lhs.x - rhs.x, lhs.y-rhs.y, lhs.z-rhs.z)
}
public prefix func -(rhs: internal_float3) -> internal_float3 {
return internal_float3(-rhs.x, -rhs.y, -rhs.z)
}
public func *(lhs: Scalar, rhs: internal_float3) -> internal_float3 {
return internal_float3(lhs*rhs.x, lhs*rhs.y, lhs*rhs.z)
}
public func *(rhs: internal_float3, lhs: Scalar) -> internal_float3 {
return internal_float3(lhs*rhs.x, lhs*rhs.y, lhs*rhs.z)
}
public func min(_ lhs: internal_float3, _ rhs: internal_float3) -> internal_float3 {
return internal_float3(min(lhs.x, rhs.x), min(lhs.y, rhs.y), min(lhs.z, rhs.z))
}
public func max(_ lhs: internal_float3, _ rhs: internal_float3) -> internal_float3 {
return internal_float3(max(lhs.x, rhs.x), max(lhs.y, rhs.y), max(lhs.z, rhs.z))
}
public func abs(_ lhs: internal_float3) -> internal_float3 {
return internal_float3(abs(lhs.x), abs(lhs.y), abs(lhs.z))
}
public func clamp(_ lhs: internal_float3, min mini: internal_float3, max maxi: internal_float3) -> internal_float3 {
return min(maxi, max(mini, lhs))
}
public func clamp(_ lhs: internal_float3, min mini: Scalar, max maxi: Scalar) -> internal_float3 {
return internal_float3(min(maxi, max(mini, lhs.x)), min(maxi, max(mini, lhs.y)), min(maxi, max(mini, lhs.z)))
}
public func cross(_ lhs: internal_float3, _ rhs: internal_float3) -> internal_float3 {
return internal_float3(lhs.y*rhs.z - lhs.z*rhs.y, lhs.z*rhs.x - lhs.x*rhs.z, lhs.x*rhs.y - lhs.y*rhs.x)
}
public func dot(_ lhs: internal_float3, _ rhs: internal_float3) -> Scalar {
return lhs.x*rhs.x+lhs.y*rhs.y+lhs.z*rhs.z
}
public func normalize(_ n: internal_float3) -> internal_float3 {
let norm = sqrt(dot(n, n))
if(norm==0.0){
return n
}
return (1.0/norm)*n
}
public func reflect(_ lhs: internal_float3, n rhs: internal_float3) -> internal_float3 {
return lhs - 2.0 * dot(rhs, lhs) * rhs
}
public struct internal_float4 {
public var x: Scalar = 0.0
public var y: Scalar = 0.0
public var z: Scalar = 0.0
public var w: Scalar = 0.0
public init() {
}
public init(_ val: Scalar){
x = val
y = val
z = val
w = val
}
public init(_ _x: Scalar, _ _y: Scalar, _ _z: Scalar, _ _w: Scalar) {
x = _x
y = _y
z = _z
w = _w
}
}
public func +(lhs: internal_float4, rhs: internal_float4) -> internal_float4 {
return internal_float4(lhs.x + rhs.x, lhs.y+rhs.y, lhs.z+rhs.z, lhs.w+rhs.w)
}
public func -(lhs: internal_float4, rhs: internal_float4) -> internal_float4 {
return internal_float4(lhs.x - rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w)
}
public prefix func -(rhs: internal_float4) -> internal_float4 {
return internal_float4(-rhs.x, -rhs.y, -rhs.z, -rhs.w)
}
public func *(lhs: Scalar, rhs: internal_float4) -> internal_float4 {
return internal_float4(lhs*rhs.x, lhs*rhs.y, lhs*rhs.z, lhs*rhs.w)
}
public func *(rhs: internal_float4, lhs: Scalar) -> internal_float4 {
return internal_float4(lhs*rhs.x, lhs*rhs.y, lhs*rhs.z, lhs*rhs.w)
}
public func min(_ lhs: internal_float4, _ rhs: internal_float4) -> internal_float4 {
return internal_float4(min(lhs.x, rhs.x), min(lhs.y, rhs.y), min(lhs.z, rhs.z), min(lhs.w, rhs.w))
}
public func max(_ lhs: internal_float4, _ rhs: internal_float4) -> internal_float4 {
return internal_float4(max(lhs.x, rhs.x), max(lhs.y, rhs.y), max(lhs.z, rhs.z), max(lhs.w, rhs.w))
}
public func abs(_ lhs: internal_float4) -> internal_float4 {
return internal_float4(abs(lhs.x), abs(lhs.y), abs(lhs.z), abs(lhs.w))
}
public func clamp(_ lhs: internal_float4, min mini: internal_float4, max maxi: internal_float4) -> internal_float4 {
return min(maxi, max(mini, lhs))
}
public func clamp(_ lhs: internal_float4, min mini: Scalar, max maxi: Scalar) -> internal_float4 {
return internal_float4(min(maxi, max(mini, lhs.x)), min(maxi, max(mini, lhs.y)), min(maxi, max(mini, lhs.z)), min(maxi, max(mini, lhs.w)))
}
#endif
| 21.862259 | 139 | 0.668725 |
b928ac308eb03cd02d6ce4cbf924d6a19ec3cc89
| 67 |
protocol AddToOrderDelegate {
func added(menuItem: MenuItem)
}
| 16.75 | 34 | 0.761194 |
fe30e97c49a865a45014f0800cdc96f25b0544c7
| 1,700 |
//
// LSLSheetTransitionAnim.swift
// TransitionAnimDemo
//
// Created by lisilong on 2017/11/27.
// Copyright © 2017年 LongShaoDream. All rights reserved.
//
import UIKit
class LSLSheetTransitionAnim: NSObject {
var duration = 0.5
}
extension LSLSheetTransitionAnim: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let toVC: UIViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let contentFrame = transitionContext.containerView.bounds
let maskView = UIView()
maskView.backgroundColor = UIColor.darkGray.withAlphaComponent(0.2)
maskView.frame = contentFrame
maskView.alpha = 0
maskView.tag = 999 // 方便在dismiss动画中查找到当前的maskView
let toView: UIView = toVC.view
toView.frame = CGRect.init(x: 0,
y: contentFrame.size.height * 2,
width: contentFrame.size.width,
height: contentFrame.size.height)
transitionContext.containerView.addSubview(maskView)
transitionContext.containerView.addSubview(toView)
UIView.animate(withDuration: self.duration, animations: {
toView.frame = contentFrame
toView.alpha = 1
maskView.alpha = 1
}) { (Bool) in
transitionContext.completeTransition(true)
}
}
}
| 34 | 119 | 0.644118 |
9c9a19b30c4c98490a9ef305c1e9d9c41e424e53
| 2,460 |
//
// ControlEvent.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 8/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
#endif
/// Protocol that enables extension of `ControlEvent`.
public protocol ControlEventType : ObservableType {
/// - returns: `ControlEvent` interface
func asControlEvent() -> ControlEvent<E>
}
/**
Unit for `Observable`/`ObservableType` that represents event on UI element.
It's properties are:
- it never fails
- it won't send any initial value on subscription
- it will `Complete` sequence on control being deallocated
- it never errors out
- it delivers events on `MainScheduler.instance`
**The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler
(`subscribeOn(ConcurrentMainScheduler.instance)` behavior).**
**It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.**
**If they aren't, then using this unit communicates wrong properties and could potentially break someone's code.**
**In case `events` observable sequence that is being passed into initializer doesn't satisfy all enumerated
properties, please don't use this unit.**
*/
public struct ControlEvent<PropertyType> : ControlEventType {
public typealias E = PropertyType
let _events: Observable<PropertyType>
/// Initializes control event with a observable sequence that represents events.
///
/// - parameter events: Observable sequence that represents events.
/// - returns: Control event created with a observable sequence of events.
public init<Ev: ObservableType>(events: Ev) where Ev.E == E {
_events = events.subscribeOn(ConcurrentMainScheduler.instance)
}
/// Subscribes an observer to control events.
///
/// - parameter observer: Observer to subscribe to events.
/// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events.
public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
return _events.subscribe(observer)
}
/// - returns: `Observable` interface.
public func asObservable() -> Observable<E> {
return _events
}
/// - returns: `ControlEvent` interface.
public func asControlEvent() -> ControlEvent<E> {
return self
}
}
| 34.166667 | 118 | 0.706911 |
18fe653f065e846b0eca30293f9d1391ba666659
| 8,473 |
//
// AnimatedTransitioner.swift
// Copyright (c) 2014 Todd Kramer.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class AnimatedTransitioner: NSObject, UIViewControllerTransitioningDelegate {
let style: PresentationStyle
init(style: PresentationStyle) {
self.style = style
super.init()
}
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController) -> UIPresentationController? {
return AnimatedPresentationController(presentedViewController: presented, presentingViewController: presenting, style: style)
}
func animatedTransitionController() -> ControllerAnimatedTransitioning {
let animationController = ControllerAnimatedTransitioning()
return animationController
}
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController: ControllerAnimatedTransitioning = animatedTransitionController()
animationController.isPresentation = true
animationController.style = style
return animationController
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController: ControllerAnimatedTransitioning = animatedTransitionController()
animationController.isPresentation = false
animationController.style = style
return animationController
}
}
class ControllerAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
var isPresentation = true
var style: PresentationStyle = .Drawer(side: .Right, phoneWantsFullScreen: false, screenRatio: 0.5)
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let containerView = transitionContext.containerView()
if isPresentation {
containerView.addSubview(toVC!.view)
}
let animatingVC = isPresentation ? toVC! : fromVC!
switch style {
case .Drawer(let side, let phoneWantsFullScreen, let screenRatio):
let presentedFrame = transitionContext.finalFrameForViewController(animatingVC)
var dismissedFrame = presentedFrame
switch side {
case .Left:
dismissedFrame.origin.x -= dismissedFrame.width
case .Right:
dismissedFrame.origin.x += dismissedFrame.width
case .Top:
dismissedFrame.origin.y -= dismissedFrame.height
case .Bottom:
dismissedFrame.origin.y += dismissedFrame.height
}
let initialFrame = isPresentation ? dismissedFrame : presentedFrame
let finalFrame = isPresentation ? presentedFrame : dismissedFrame
animatingVC.view.frame = initialFrame
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 300, initialSpringVelocity: 5, options: .AllowUserInteraction | .BeginFromCurrentState, animations: { () -> Void in
animatingVC.view.frame = finalFrame
}) { (finished) -> Void in
if !self.isPresentation {
fromVC!.view.removeFromSuperview()
}
transitionContext.completeTransition(true)
}
case .FormSheet(let horizontalRatio, let verticalRatio, let animationStyle):
switch animationStyle {
case .ExpandFromCenter:
animatingVC.view.frame = transitionContext.finalFrameForViewController(animatingVC)
let presentationTransform = CGAffineTransformIdentity
let dismissalTransform = CGAffineTransformConcat(CGAffineTransformMakeScale(0.001, 0.001), CGAffineTransformMakeRotation(CGFloat(8 * M_PI)))
animatingVC.view.transform = isPresentation ? dismissalTransform : presentationTransform
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 300, initialSpringVelocity: 5, options: .AllowUserInteraction | .BeginFromCurrentState, animations: { () -> Void in
animatingVC.view.transform = self.isPresentation ? presentationTransform : dismissalTransform
}) { (finished) -> Void in
if !self.isPresentation {
fromVC!.view.removeFromSuperview()
}
transitionContext.completeTransition(true)
}
case .Slide(let dismissOpposite, let side):
let presentedFrame = transitionContext.finalFrameForViewController(animatingVC)
var dismissedFrame = presentedFrame
var oppositeFrame = presentedFrame
var addedWidth = CGFloat(0)
var addedHeight = CGFloat(0)
switch side {
case .Left:
addedWidth = -(dismissedFrame.width / CGFloat(adjustRatio(horizontalRatio)))
case .Right:
addedWidth = dismissedFrame.width / CGFloat(adjustRatio(horizontalRatio))
case .Top:
addedHeight = -(dismissedFrame.height / CGFloat(adjustRatio(verticalRatio)))
case .Bottom:
addedHeight = dismissedFrame.height / CGFloat(adjustRatio(verticalRatio))
}
dismissedFrame.origin.x += addedWidth
dismissedFrame.origin.y += addedHeight
oppositeFrame.origin.x -= addedWidth
oppositeFrame.origin.y -= addedHeight
let initialFrame = isPresentation ? dismissedFrame : presentedFrame
let finalFrame = isPresentation ? presentedFrame : (dismissOpposite ? oppositeFrame : dismissedFrame)
animatingVC.view.frame = initialFrame
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 300, initialSpringVelocity: 5, options: .AllowUserInteraction | .BeginFromCurrentState, animations: { () -> Void in
animatingVC.view.frame = finalFrame
}) { (finished) -> Void in
if !self.isPresentation {
fromVC!.view.removeFromSuperview()
}
transitionContext.completeTransition(true)
}
}
}
}
func adjustRatio(ratio: Float) -> Float {
return ratio > 1.0 ? 1.0 : (ratio < 0.1 ? 0.1 : ratio)
}
}
| 49.841176 | 231 | 0.65455 |
d6a15ff4b09f949ddc9434afe35466c6e166c767
| 4,633 |
//
// PageContentView.swift
// DYZB
//
// Created by linxiaoyu on 2018/5/6.
// Copyright © 2018年 yi. All rights reserved.
//
import UIKit
let kReuseIdentifier = "cell"
protocol PageContentViewDelegate:class {
func pageContetnView(pageContentView:PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
class PageContentView: UIView {
private var childrenVcs:[UIViewController]
private var parentViewController:UIViewController
private var startContentOffsetX:CGFloat = 0
private var isForbidScrollDelegate : Bool = false
weak var delegate:PageContentViewDelegate?
init(frame: CGRect,childrenVcs:[UIViewController],parentViewController:UIViewController) {
self.childrenVcs = childrenVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("PageContentView init(coder:) has not been implemented")
}
private lazy var collectView:UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = bounds.size
// 行间距
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
collectView.isPagingEnabled = true
collectView.bounces = false
collectView.frame = bounds
collectView.delegate = self
collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:kReuseIdentifier)
collectView.dataSource = self
return collectView;
}()
}
extension PageContentView {
private func setupUI() {
for children in childrenVcs {
self.parentViewController.addChildViewController(children)
}
addSubview(collectView)
}
}
extension PageContentView:UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startContentOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isForbidScrollDelegate {return}
var progress:CGFloat = 0
var sourceIndex:Int = 0
var targetIndex:Int = 0
let scrollviewW = scrollView.bounds.width
var currentOffset = scrollView.contentOffset.x
//you
if currentOffset > startContentOffsetX {
progress = currentOffset/scrollviewW - floor(currentOffset/scrollviewW)
sourceIndex = Int(currentOffset/scrollviewW)
targetIndex = sourceIndex + 1
if targetIndex >= childrenVcs.count {
targetIndex = childrenVcs.count - 1
}
if currentOffset - startContentOffsetX == scrollviewW {
progress = 1
targetIndex = sourceIndex
}
} else {
progress = 1 - (currentOffset/scrollviewW-floor(currentOffset/scrollviewW))
targetIndex = Int(currentOffset/scrollviewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childrenVcs.count {
sourceIndex = childrenVcs.count-1
}
}
// print("progress \(progress) sourec \(sourceIndex) targetIndex \(targetIndex)")
delegate?.pageContetnView(pageContentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
extension PageContentView:UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childrenVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseIdentifier, for: indexPath)
for view in cell.contentView.subviews {
view .removeFromSuperview()
}
let childVc = childrenVcs[indexPath.row]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
extension PageContentView {
func setContentIndex(index:Int) {
let offsetX = CGFloat(index)*collectView.frame.width
isForbidScrollDelegate = true
collectView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| 32.858156 | 128 | 0.664148 |
ef72a848d375e040734a24edbb43a4dad0dc617b
| 2,280 |
//
// Extensions.swift
// UBottomSheet
//
// Created by ugur on 19.09.2019.
// Copyright © 2019 otw. All rights reserved.
//
import UIKit
extension UIViewController {
func ub_add(_ child: UIViewController, in _view: UIView? = nil, setupConstraints: ((UIView)->Void)? = nil){
addChild(child)
if let v = _view{
view.addSubview(v)
setupConstraints?(v)
v.addSubview(child.view)
}else{
view.addSubview(child.view)
}
child.didMove(toParent: self)
}
func ub_remove() {
// Just to be safe, we check that this view controller
// is actually added to a parent before removing it.
guard parent != nil else {
return
}
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
extension UIView {
func ub_firstSubView<T: UIView>(ofType type: T.Type) -> T? {
var resultView: T?
for view in subviews {
if let view = view as? T {
resultView = view
break
}
else {
if let foundView = view.ub_firstSubView(ofType: T.self) {
resultView = foundView
break
}
}
}
return resultView
}
}
extension UIView {
func edges(_ edges: UIRectEdge, to view: UIView, offset: UIEdgeInsets) {
self.translatesAutoresizingMaskIntoConstraints = false
if edges.contains(.top) || edges.contains(.all) {
self.topAnchor.constraint(equalTo: view.topAnchor, constant: offset.top).isActive = true
}
if edges.contains(.bottom) || edges.contains(.all) {
self.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: offset.bottom).isActive = true
}
if edges.contains(.left) || edges.contains(.all) {
self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: offset.left).isActive = true
}
if edges.contains(.right) || edges.contains(.all) {
self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: offset.right).isActive = true
}
}
}
| 28.860759 | 112 | 0.565789 |
23c4781e0440af0a8e610e404d16e2a0b0e8e7e9
| 206 |
import Foundation
extension URL {
/**
Returns the path file name without file extension.
*/
var fileName: String {
return self.deletingPathExtension().lastPathComponent
}
}
| 15.846154 | 61 | 0.65534 |
3abfa82345ec4f998da22c9cbc72263cc7ec9055
| 2,073 |
/*
RelativeDate.swift
This source file is part of the SDGCornerstone open source project.
https://sdggiesbrecht.github.io/SDGCornerstone
Copyright ©2017–2020 Jeremy David Giesbrecht and the SDGCornerstone project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import SDGControlFlow
import SDGMathematics
import SDGText
import SDGCornerstoneLocalizations
internal struct RelativeDate: DateDefinition, TextualPlaygroundDisplay {
// MARK: - Initialization
internal init(_ interval: CalendarInterval<FloatMax>, after date: CalendarDate) {
baseDate = date
intervalSince = interval
intervalSinceReferenceDate = (date − RelativeDate.referenceDate) + interval
}
// MARK: - Properties
internal let baseDate: CalendarDate
internal let intervalSince: CalendarInterval<FloatMax>
// MARK: - CustomStringConvertible
public var description: String {
return "(" + String(describing: baseDate) + ") + " + String(describing: intervalSince)
}
// MARK: - DateDefinition
internal static let identifier: StrictString = "Δ"
internal static let referenceDate: CalendarDate = CalendarDate.epoch
internal let intervalSinceReferenceDate: CalendarInterval<FloatMax>
internal init(intervalSinceReferenceDate: CalendarInterval<FloatMax>) {
self.intervalSinceReferenceDate = intervalSinceReferenceDate
self.baseDate = RelativeDate.referenceDate
self.intervalSince = intervalSinceReferenceDate
}
// MARK: - Decodable
internal init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let interval = try container.decode(CalendarInterval<FloatMax>.self)
let baseDate = try container.decode(CalendarDate.self)
self = RelativeDate(interval, after: baseDate)
}
// MARK: - Encodable
internal func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(intervalSince)
try container.encode(baseDate)
}
}
| 28.013514 | 90 | 0.76218 |
dd27b1023d50e55d541862f2f579897a31962449
| 7,348 |
//
// CountryPickerWithSectionViewController.swift
// CountryCodeInSwift3
//
// Created by SuryaKant Sharma on 16/12/17.
// Copyright © 2017 Suryakant. All rights reserved.
//
import UIKit
open class CountryPickerWithSectionViewController: CountryPickerController {
// MARK: - Variables
var sections: [Character] = []
var sectionCoutries = [Character: [Country]]()
var searchHeaderTitle: Character = "A"
// MARK: - View Life Cycle
override open func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = nil
tableView.delegate = nil
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchSectionCountries()
tableView.dataSource = self
tableView.delegate = self
}
open override func viewDidAppear(_ animated: Bool) {
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = true
}
/// Request for previous country and automatically scroll table view to item
if let previousCountry = CountryManager.shared.lastCountrySelected {
let previousCountryFirstCharacter = previousCountry.countryName.first!
scrollToCountry(previousCountry, withSection: previousCountryFirstCharacter)
}
}
@discardableResult
open override class func presentController(on viewController: UIViewController, callBack:@escaping (_ chosenCountry: Country) -> Void) -> CountryPickerWithSectionViewController {
let controller = CountryPickerWithSectionViewController()
controller.presentingVC = viewController
controller.callBack = callBack
let navigationController = UINavigationController(rootViewController: controller)
controller.presentingVC?.present(navigationController, animated: true, completion: nil)
return controller
}
}
// MARK: - Internal Methods
internal extension CountryPickerWithSectionViewController {
///
/// Automatically scrolls the `TableView` to a particular section on expected chosen country.
///
/// Under the hood, it tries to find several indexes for section title and expectd chosen country otherwise execution stops.
/// Then constructs an `IndexPath` and scrolls the rows to that particular path with animation (If enabled).
///
/// - Parameter country: Expected chosen country
/// - Parameter sectionTitle: Character value as table section title.
/// - Parameter animated: Scrolling animation state and by default its set to `False`.
func scrollToCountry(_ country: Country, withSection sectionTitle: Character, animated: Bool = false) {
// Find country index
let countryMatchIndex = sectionCoutries[sectionTitle]?.firstIndex(where: { $0.countryCode == country.countryCode})
// Find section title index
let countrySectionKeyIndexes = sectionCoutries.keys.map { $0 }.sorted()
let countryMatchSectionIndex = countrySectionKeyIndexes.firstIndex(of: sectionTitle)
if let itemIndexPath = countryMatchIndex, let sectionIndexPath = countryMatchSectionIndex {
let previousCountryIndex = IndexPath(item: itemIndexPath, section: sectionIndexPath)
tableView.scrollToRow(at: previousCountryIndex, at: .middle, animated: animated)
}
}
func fetchSectionCountries() {
sections = countries.map({ String($0.countryName.prefix(1)).first! }).removeDuplicates()
for section in sections {
let sectionCountries = countries.filter({ $0.countryName.first! == section })
sectionCoutries[section] = sectionCountries
}
}
}
// MARK: - TableView DataSource
extension CountryPickerWithSectionViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return applySearch ? 1 : sections.count
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return applySearch ? filterCountries.count : numberOfRowFor(section: section)
}
func numberOfRowFor(section: Int) -> Int {
let character = sections[section]
return sectionCoutries[character]!.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return applySearch ? String(searchHeaderTitle) : sections[section].description
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CountryCell.reuseIdentifier) as? CountryCell else {
fatalError("Cell with Identifier CountryTableViewCell cann't dequed")
}
cell.accessoryType = .none
cell.checkMarkImageView.isHidden = true
cell.checkMarkImageView.image = checkMarkImage
var country: Country
if applySearch {
country = filterCountries[indexPath.row]
} else {
let character = sections[indexPath.section]
country = sectionCoutries[character]![indexPath.row]
}
if let alreadySelectedCountry = CountryManager.shared.lastCountrySelected {
cell.checkMarkImageView.isHidden = country.countryCode == alreadySelectedCountry.countryCode ? false : true
}
cell.country = country
setUpCellProperties(cell: cell)
return cell
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sections.map {String($0)}
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return sections.firstIndex(of: Character(title))!
}
}
// MARK: - Override SearchBar Delegate
extension CountryPickerWithSectionViewController {
public override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
super.searchBar(searchBar, textDidChange: searchText)
if !searchText.isEmpty {
searchHeaderTitle = searchText.first ?? "A"
}
}
}
// MARK: - TableViewDelegate
extension CountryPickerWithSectionViewController {
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch applySearch {
case true:
let country = filterCountries[indexPath.row]
self.callBack?(country)
CountryManager.shared.lastCountrySelected = country
self.dismiss(animated: false, completion: nil)
case false:
let character = sections[indexPath.section]
let country = sectionCoutries[character]![indexPath.row]
self.callBack?(country)
CountryManager.shared.lastCountrySelected = country
}
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Array Extenstion
extension Array where Element: Equatable {
func removeDuplicates() -> [Element] {
var uniqueValues = [Element]()
forEach {
if !uniqueValues.contains($0) {
uniqueValues.append($0)
}
}
return uniqueValues
}
}
| 36.74 | 182 | 0.674469 |
20db92d25d77b92a317fc84641b254a71d1a8639
| 2,968 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import SotoCore
/// Error enum for ServerlessApplicationRepository
public struct ServerlessApplicationRepositoryErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case forbiddenException = "ForbiddenException"
case internalServerErrorException = "InternalServerErrorException"
case notFoundException = "NotFoundException"
case tooManyRequestsException = "TooManyRequestsException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ServerlessApplicationRepository
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// One of the parameters in the request is invalid.
public static var badRequestException: Self { .init(.badRequestException) }
/// The resource already exists.
public static var conflictException: Self { .init(.conflictException) }
/// The client is not authenticated.
public static var forbiddenException: Self { .init(.forbiddenException) }
/// The AWS Serverless Application Repository service encountered an internal error.
public static var internalServerErrorException: Self { .init(.internalServerErrorException) }
/// The resource (for example, an access policy statement) specified in the request doesn't exist.
public static var notFoundException: Self { .init(.notFoundException) }
/// The client is sending more than the allowed number of requests per unit of time.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
}
extension ServerlessApplicationRepositoryErrorType: Equatable {
public static func == (lhs: ServerlessApplicationRepositoryErrorType, rhs: ServerlessApplicationRepositoryErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ServerlessApplicationRepositoryErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 40.108108 | 130 | 0.68969 |
21e017c47356a3ef219674d6b065b04eea4e2a92
| 19,572 |
//
// SendTokensViewController.swift
// TestDemoApp
//
// Created by aniket ayachit on 04/05/19.
// Copyright © 2019 aniket ayachit. All rights reserved.
//
import UIKit
import OstWalletSdk
import MaterialComponents
class SendTokensViewController: BaseSettingOptionsSVViewController, UITextFieldDelegate {
//MAKR: - Components
let sendTokensLable: UILabel = {
let label = UILabel()
label.numberOfLines = 1
label.font = OstTheme.fontProvider.get(size: 15).bold()
label.textColor = UIColor.black.withAlphaComponent(0.4)
label.text = "Send Tokens To"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let balanceLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 1
label.font = OstTheme.fontProvider.get(size: 15)
label.textColor = UIColor.color(89, 122, 132)
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var userInfoView: UsersTableViewCell = {
let view = UsersTableViewCell()
view.sendButton?.isHidden = true
view.sendButton?.setTitle("", for: .normal)
view.translatesAutoresizingMaskIntoConstraints = false
view.seperatorLine?.isHidden = true
view.backgroundColor = UIColor.color(231, 243, 248)
view.layer.cornerRadius = 6
view.clipsToBounds = true
return view
}()
var sendButton: UIButton = {
let button = OstUIKit.primaryButton()
button.setTitle("Send Tokens", for: .normal)
return button
}()
// var cancelButton: UIButton = {
// let button = OstUIKit.linkButton()
// button.setTitle("Cancel", for: .normal)
// return button
// }()
var tokenAmountTextField: MDCTextField = {
let textField = MDCTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clearButtonMode = .never
textField.keyboardType = .decimalPad
textField.placeholderLabel.text = "Amount"
textField.font = OstTheme.fontProvider.get(size: 15)
textField.text = "1";
return textField
}()
var tokenAmountTextFieldController: MDCTextInputControllerOutlined? = nil
var tokenSpendingUnitTextField: MDCTextField = {
let textField = MDCTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clearButtonMode = .never
textField.placeholderLabel.text = "Unit"
textField.text = CurrentEconomy.getInstance.tokenSymbol ?? "";
textField.font = OstTheme.fontProvider.get(size: 15)
return textField
}()
var tokenSpendingUnitTextFieldController: MDCTextInputControllerOutlined? = nil
var usdAmountTextField: MDCTextField = {
let textField = MDCTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clearButtonMode = .never
textField.keyboardType = .decimalPad
textField.placeholderLabel.text = "Amount"
textField.font = OstTheme.fontProvider.get(size: 15)
return textField
}()
var usdAmountTextFieldController: MDCTextInputControllerOutlined? = nil
var usdSpendingUnitTextField: MDCTextField = {
let textField = MDCTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clearButtonMode = .never
textField.placeholderLabel.text = "Unit"
textField.text = "USD";
textField.font = OstTheme.fontProvider.get(size: 15)
return textField
}()
var usdSpendingUnitTextFieldController: MDCTextInputControllerOutlined? = nil
//MARK: - Variables
weak var tabbarController: TabBarViewController? = nil
var token: OstToken? = nil
var isShowingActionSheet = false;
var isUsdTx = false
var isBalanceApiInprogress = false
var didUserTapSendTokens = false
var userDetails: [String: Any]! {
didSet {
userInfoView.userData = userDetails
// userInfoView.balanceLabel?.text = userDetails["token_holder_address"] as? String ?? ""
userInfoView.sendButton?.isHidden = true
}
}
//MARK: - View LC
override func getNavBarTitle() -> String {
return "Send Tokens"
}
override func viewDidLoad() {
super.viewDidLoad()
getUserBalanceFromServer()
tokenAmountTextField.addTarget(self,
action: #selector(textFieldDidChange(textField:)),
for: UIControl.Event.editingChanged)
usdAmountTextField.addTarget(self,
action: #selector(textFieldDidChange(textField:)),
for: UIControl.Event.editingChanged)
}
func getUserBalanceFromServer() {
if isBalanceApiInprogress {
return
}
isBalanceApiInprogress = true
CurrentUserModel.getInstance.fetchUserBalance {[weak self] (isSuccess, _, _) in
self?.onRequestComplete()
}
}
@objc func onRequestComplete() {
updateUserBalanceUI()
isBalanceApiInprogress = false
if didUserTapSendTokens {
didUserTapSendTokens = false
self.perform(#selector(sendTokenButtonTapped(_ :)), with: nil, afterDelay: 0.3)
}
}
func updateUserBalanceUI() {
let currentUse = CurrentUserModel.getInstance
let currentEconomy = CurrentEconomy.getInstance
if isUsdTx {
let usdBalance = self.getUserUSDBalance()
balanceLabel.text = "Balance: $ \(usdBalance.toDisplayTxValue())"
}else {
balanceLabel.text = "Balance: \(currentUse.balance) \(currentEconomy.tokenSymbol ?? "")"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUserBalanceUI()
let usdAmount = CurrentUserModel.getInstance.toUSD(value: tokenAmountTextField.text ?? "0") ?? "0.00"
usdAmountTextField.text = usdAmount.toRoundUpTxValue()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tokenAmountTextField.becomeFirstResponder()
}
//MAKR: - Add Subview
override func addSubviews() {
super.addSubviews()
setupComponents()
addSubview(sendTokensLable)
addSubview(balanceLabel)
addSubview(userInfoView)
addSubview(tokenAmountTextField)
addSubview(tokenSpendingUnitTextField)
addSubview(usdAmountTextField)
addSubview(usdSpendingUnitTextField)
addSubview(sendButton)
// addSubview(cancelButton)
}
func setupComponents() {
progressIndicator?.progressText = "Executing Transaction..."
tokenAmountTextField.delegate = self
tokenSpendingUnitTextField.delegate = self
usdAmountTextField.delegate = self
usdSpendingUnitTextField.delegate = self
self.tokenAmountTextFieldController = MDCTextInputControllerOutlined(textInput: self.tokenAmountTextField)
self.tokenSpendingUnitTextFieldController = MDCTextInputControllerOutlined(textInput: self.tokenSpendingUnitTextField);
self.usdAmountTextFieldController = MDCTextInputControllerOutlined(textInput: self.usdAmountTextField)
self.usdSpendingUnitTextFieldController = MDCTextInputControllerOutlined(textInput: self.usdSpendingUnitTextField);
weak var weakSelf = self
sendButton.addTarget(weakSelf, action: #selector(weakSelf!.sendTokenButtonTapped(_ :)), for: .touchUpInside)
// cancelButton.addTarget(weakSelf, action: #selector(weakSelf!.cancelButtonTapped(_ :)), for: .touchUpInside)
}
//MAKR: - Add Constraints
override func addLayoutConstraints() {
super.addLayoutConstraints()
addSendTokenLabelConstraints()
addBalanceLabelConstraints()
addUserInfoConstraints()
addTokenAmountTextFieldConstraints()
addTokenUnitTextFiledConstraints()
addUsdAmountTextFieldConstraints()
addUsdUnitTextFiledConstraints()
addSendButtonConstraints()
// addCancelButtonConstraints()
sendButton.bottomAlignWithParent()
}
func addSendTokenLabelConstraints() {
sendTokensLable.topAlignWithParent(multiplier: 1, constant: 20)
sendTokensLable.leftAlignWithParent(multiplier: 1, constant: 20)
}
func addBalanceLabelConstraints() {
balanceLabel.topAlignWithParent(multiplier: 1, constant: 20)
balanceLabel.rightAlignWithParent(multiplier: 1, constant: -20)
balanceLabel.leftWithRightAlign(toItem: sendTokensLable, constant: 8)
}
func addUserInfoConstraints() {
userInfoView.placeBelow(toItem: sendTokensLable)
userInfoView.applyBlockElementConstraints()
userInfoView.heightAnchor.constraint(equalToConstant: 70).isActive = true
}
func addTokenAmountTextFieldConstraints() {
tokenAmountTextField.placeBelow(toItem: userInfoView)
tokenAmountTextField.leftAlignWithParent(multiplier: 1, constant: 20)
tokenAmountTextField.setW375Width(width: 238)
}
func addTokenUnitTextFiledConstraints() {
tokenSpendingUnitTextField.placeBelow(toItem: userInfoView)
tokenSpendingUnitTextField.rightAlignWithParent(multiplier: 1, constant: -20)
tokenSpendingUnitTextField.setW375Width(width: 90)
}
func addUsdAmountTextFieldConstraints() {
usdAmountTextField.placeBelow(toItem: tokenAmountTextField, constant: 0)
usdAmountTextField.leftAlignWithParent(multiplier: 1, constant: 20)
usdAmountTextField.setW375Width(width: 238)
}
func addUsdUnitTextFiledConstraints() {
usdSpendingUnitTextField.placeBelow(toItem: tokenSpendingUnitTextField, constant: 0)
usdSpendingUnitTextField.rightAlignWithParent(multiplier: 1, constant: -20)
usdSpendingUnitTextField.setW375Width(width: 90)
}
func addSendButtonConstraints() {
sendButton.placeBelow(toItem: usdSpendingUnitTextField)
sendButton.applyBlockElementConstraints()
}
// func addCancelButtonConstraints() {
// cancelButton.placeBelow(toItem: sendButton)
// cancelButton.applyBlockElementConstraints()
// }
//MARK: - Actions
@objc func sendTokenButtonTapped(_ sender: Any?) {
if isBalanceApiInprogress && isUsdTx {
didUserTapSendTokens = true
progressIndicator = OstProgressIndicator(textCode: .fetchingUserBalance)
progressIndicator?.show()
return
}
progressIndicator?.hide()
progressIndicator = nil
if !isValidInputPassed() {
return
}
var amountToTransferStr = self.tokenAmountTextField.text!
let receiverName = userDetails["username"] as? String ?? ""
let ruleType:OstExecuteTransactionType
let progressText: String
// if ( isUsdTx ) {
// //Multiply value with 10^18. Since we have string.
// //So: we can simply add 18 0s. [Not the best way to do it. Use BigInt]
// ruleType = .Pay
// progressText = "Sending $\(amountToTransferStr) to \(receiverName)"
// }else {
ruleType = .DirectTransfer
progressText = "Sending \(amountToTransferStr) \(CurrentEconomy.getInstance.tokenSymbol ?? "") to \(receiverName)"
// }
amountToTransferStr = amountToTransferStr.toSmallestUnit(isUSDTx: false)
progressIndicator = OstProgressIndicator(progressText: progressText)
getApplicationWindow()?.addSubview(progressIndicator!)
progressIndicator?.show()
var txMeta: [String: String] = [:];
txMeta["type"] = "user_to_user";
txMeta["name"] = "Tokens sent from iOS";
//Let's build some json. Not the best way do it, but, works here.
txMeta["details"] = "Received from \(CurrentUserModel.getInstance.userName ?? "")";
let tokenHolderAddress = userDetails["token_holder_address"] as! String
OstWalletSdk.executeTransaction(userId: CurrentUserModel.getInstance.ostUserId!,
tokenHolderAddresses: [tokenHolderAddress],
amounts: [amountToTransferStr],
transactionType: ruleType,
meta: txMeta,
delegate: self.workflowDelegate)
}
func isValidInputPassed() -> Bool {
var isValidInput: Bool = true
if self.tokenAmountTextField.text!.isEmpty {
isValidInput = false
}
if isValidInput,
var userBalance: Double = Double(CurrentUserModel.getInstance.balance),
let enteredAmount: Double = Double(self.tokenAmountTextField.text!) {
if isUsdTx {
let usdBalance = getUserUSDBalance()
userBalance = Double(usdBalance)!
}
if enteredAmount > userBalance {
isValidInput = false
}
}
if isValidInput {
tokenAmountTextFieldController?.setErrorText(nil,errorAccessibilityValue: nil);
} else {
tokenAmountTextFieldController?.setErrorText("Low balance to make this transaction",
errorAccessibilityValue: nil);
}
return isValidInput
}
@objc func cancelButtonTapped(_ sender: Any?) {
self.navigationController?.popViewController(animated: true)
}
//MARK: - TextField Delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if ( tokenSpendingUnitTextField == textField
|| usdSpendingUnitTextField == textField) {
// if !isShowingActionSheet {
// showUnitActionSheet();
// }
return false;
}
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
tokenAmountTextFieldController?.setErrorText(nil,errorAccessibilityValue: nil);
if (string == "." || string == ",")
&& ((textField.text ?? "").contains(".")
|| (textField.text ?? "").contains(",")) {
return false
}
return true
}
@objc func textFieldDidChange(textField: UITextField) {
var text = textField.text ?? "0"
text = text.replacingOccurrences(of: ",", with: ".")
textField.text = text
let values = text.components(separatedBy: ".")
if values.count == 2
&& values[1].count > 0{
textField.text = text.toDisplayTxValue()
}
if textField == tokenAmountTextField {
let usdAmount = CurrentUserModel.getInstance.toUSD(value: text) ?? "0.00"
usdAmountTextField.text = usdAmount.toRoundUpTxValue()
}
else if textField == usdAmountTextField {
let transferVal = text.toSmallestUnit(isUSDTx: true)
let finalVal = CurrentUserModel.getInstance.toBt(value: transferVal)
tokenAmountTextField.text = finalVal?.toRedableFormat().toRoundUpTxValue()
}
}
func showUnitActionSheet() {
if ( isShowingActionSheet ) {
//return;
}
isShowingActionSheet = true;
let actionSheet = UIAlertController(title: "Select Transfer Currency", message: "Please choose the currency to price transaction. Choosing USD will mean that the chosen number of USD worth of tokens will be transferred.", preferredStyle: UIAlertController.Style.actionSheet);
let directTransafer = UIAlertAction(title: CurrentEconomy.getInstance.tokenSymbol ?? "BT", style: .default, handler: {[weak self] (UIAlertAction) in
self?.isShowingActionSheet = false;
self?.tokenSpendingUnitTextField.text = CurrentEconomy.getInstance.tokenSymbol ?? "";
self?.isUsdTx = false
self?.updateUserBalanceUI()
});
actionSheet.addAction(directTransafer);
let pricer = UIAlertAction(title: "USD", style: .default, handler: {[weak self] (UIAlertAction) in
self?.isShowingActionSheet = false;
self?.tokenSpendingUnitTextField.text = "USD";
self?.isUsdTx = true
self?.updateUserBalanceUI()
});
actionSheet.addAction(pricer);
self.present(actionSheet, animated: true, completion: {
self.isShowingActionSheet = false;
});
}
//MARK: - Workflow Delegate
override func requestAcknowledged(workflowId: String, workflowContext: OstWorkflowContext, contextEntity: OstContextEntity) {
super.requestAcknowledged(workflowId: workflowId, workflowContext: workflowContext, contextEntity: contextEntity)
showSuccessAlert(workflowId: workflowId, workflowContext: workflowContext, contextEntity: contextEntity)
}
override func flowComplete(workflowId: String, workflowContext: OstWorkflowContext, contextEntity: OstContextEntity) {
super.flowComplete(workflowId: workflowId, workflowContext: workflowContext, contextEntity: contextEntity)
}
override func showSuccessAlert(workflowId: String, workflowContext: OstWorkflowContext, contextEntity: OstContextEntity) {
if workflowContext.workflowType == .executeTransaction {
progressIndicator?.showSuccessAlert(forWorkflowType: workflowContext.workflowType,
onCompletion: {[weak self] (_) in
self?.onFlowComplete(workflowId: workflowId, workflowContext: workflowContext, contextEntity: contextEntity)
})
}
}
override func onFlowComplete(workflowId: String, workflowContext: OstWorkflowContext, contextEntity: OstContextEntity) {
super.onFlowComplete(workflowId: workflowId,
workflowContext: workflowContext,
contextEntity: contextEntity)
self.navigationController?.popViewController(animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
self.tabbarController?.jumpToWalletVC(withWorkflowId: workflowId)
})
}
override func showFailureAlert(workflowId: String, workflowContext: OstWorkflowContext, error: OstError) {
progressIndicator?.hide()
progressIndicator = nil
}
func showWebViewForTransaction() {
progressIndicator = nil
CurrentUserModel.getInstance.showTokenHolderInView()
}
func getUserUSDBalance() -> String {
let currentUser = CurrentUserModel.getInstance
let usdBalance = currentUser.toUSD(value: currentUser.balance) ?? "0.00"
return usdBalance
}
}
| 38.910537 | 283 | 0.640149 |
39ce654c4c6bac19452230a260a92d6826ab651b
| 1,448 |
import Foundation
protocol TwitterAPISessionDelegatedTask {
var taskIdentifier: Int { get }
func append(chunk: Data)
func complete(error: Error?)
}
class TwitterAPISessionDelegate: NSObject, URLSessionDataDelegate {
private var tasks = [Int /* taskIdentifier */: TwitterAPISessionDelegatedTask]()
func appendAndResume(task: URLSessionTask) -> TwitterAPISessionJSONTask {
let twTask = TwitterAPISessionDelegatedJSONTask(task: task)
twTask.delegate = self
tasks[task.taskIdentifier] = twTask
task.resume()
return twTask
}
func appendAndResumeStream(task: URLSessionTask) -> TwitterAPISessionDelegatedStreamTask {
let twTask = TwitterAPISessionDelegatedStreamTask(task: task)
tasks[task.taskIdentifier] = twTask
task.resume()
return twTask
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
tasks[dataTask.taskIdentifier]?.append(chunk: data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let task = tasks[task.taskIdentifier] else { return }
task.complete(error: error)
}
}
extension TwitterAPISessionDelegate: TwitterAPISessionDelegatedJSONTaskDelegate {
func didFinishQueueInJsonTask(task: TwitterAPISessionDelegatedJSONTask) {
tasks[task.taskIdentifier] = nil
}
}
| 27.846154 | 102 | 0.716851 |
4b854d35025dc755224be4cd2e8b8a4e1ddb9c2f
| 2,976 |
//
// LoggedOutViewController.swift
// TicTacToe
//
// Created by Dinh, Nhat on 2019/03/11.
// Copyright © 2019 Uber. All rights reserved.
//
import RIBs
import RxSwift
import UIKit
import SnapKit
protocol LoggedOutPresentableListener: class {
// TODO: Declare properties and methods that the view controller can invoke to perform
// business logic, such as signIn(). This protocol is implemented by the corresponding
// interactor class.
func login(withPlayer1Name player1Name: String?, player2Name: String?)
}
final class LoggedOutViewController: UIViewController, LoggedOutPresentable, LoggedOutViewControllable {
weak var listener: LoggedOutPresentableListener?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let playerFields = buildPlayerFields()
buildLoginButton(withPlayer1Field: playerFields.player1Field, player2Field: playerFields.player2Field)
}
// MARK: - Private
private var player1Field: UITextField?
private var player2Field: UITextField?
private func buildPlayerFields() -> (player1Field: UITextField, player2Field: UITextField) {
let player1Field = UITextField()
self.player1Field = player1Field
player1Field.borderStyle = UITextBorderStyle.line
view.addSubview(player1Field)
player1Field.placeholder = "Player 1 name"
player1Field.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(self.view).offset(100)
maker.leading.trailing.equalTo(self.view).inset(40)
maker.height.equalTo(40)
}
let player2Field = UITextField()
self.player2Field = player2Field
player2Field.borderStyle = UITextBorderStyle.line
view.addSubview(player2Field)
player2Field.placeholder = "Player 2 name"
player2Field.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(player1Field.snp.bottom).offset(20)
maker.left.right.height.equalTo(player1Field)
}
return (player1Field, player2Field)
}
private func buildLoginButton(withPlayer1Field player1Field: UITextField, player2Field: UITextField) {
let loginButton = UIButton()
view.addSubview(loginButton)
loginButton.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(player2Field.snp.bottom).offset(20)
maker.left.right.height.equalTo(player1Field)
}
loginButton.setTitle("Login", for: .normal)
loginButton.setTitleColor(UIColor.white, for: .normal)
loginButton.backgroundColor = UIColor.black
loginButton.addTarget(self, action: #selector(didTapLoginButton), for: .touchUpInside)
}
@objc private func didTapLoginButton() {
listener?.login(withPlayer1Name: player1Field?.text, player2Name: player2Field?.text)
}
}
| 37.2 | 110 | 0.69422 |
64106f4812460a0198759e43ed0942a50a6a4d81
| 905 |
//
// AuthService.swift
// naver-music-for-mac
//
// Created by sonny on 2018. 5. 18..
// Copyright © 2018년 Kimjisoo. All rights reserved.
//
import Foundation
import RxSwift
class AuthService {
static let instance = AuthService()
private init() {
refresh()
}
public static func shared() -> AuthService {
return instance
}
public var changedAuthorizedState = BehaviorSubject<Bool>(value: false)
public func refresh() {
var isAuthorized = false
if let url = URL(string: "http://naver.com"),
let cookies = HTTPCookieStorage.shared.cookies(for: url) {
isAuthorized = cookies.contains(where: {$0.name == "NID_AUT"})
}
self.changedAuthorizedState.onNext(isAuthorized)
}
public func signout() {
for cookie in (HTTPCookieStorage.shared.cookies ?? []) {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
self.refresh()
}
}
| 22.625 | 73 | 0.665193 |
1cc51dd41f8918a1ed1edab359746509fdada460
| 3,618 |
//
// AppDelegate.swift
// twitter_alamofire_demo
//
// Created by Charles Hieger on 4/4/17.
// Copyright © 2017 Charles Hieger. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// MARK: TODO: Check for logged in user
NotificationCenter.default.addObserver(forName: Notification.Name("didLogout"), object: nil, queue: OperationQueue.main) { (Notification) in
print("Logout notification received")
// TODO: Load and show the login view controller
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
self.window?.rootViewController = loginViewController
}
if User.current == nil{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
self.window?.rootViewController = loginViewController
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let homeTimelineViewController = storyboard.instantiateViewController(withIdentifier: "TweetsNavigationController")
window?.rootViewController = homeTimelineViewController
}
return true
}
// MARK: TODO: Open URL
// OAuth step 2
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
// Handle urlcallback sent from Twitter
APIManager.shared.handle(url: url)
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:.
}
}
| 48.891892 | 285 | 0.71089 |
69380cad7dcd0975dc0cf1d0c636549e66c58495
| 1,878 |
/* Copyright © 2019 Mastercard. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
=============================================================================*/
import Foundation
/// Card view cell used in the settings list
class SettingsCardViewCell: UITableViewCell {
@IBOutlet weak var card1: UIImageView!
@IBOutlet weak var card2: UIImageView!
@IBOutlet weak var card3: UIImageView!
@IBOutlet weak var card4: UIImageView!
@IBOutlet weak var card5: UIImageView!
@IBOutlet weak var card6: UIImageView!
func setupCards(cards: [CardConfiguration]){
self.card1?.isHidden = true
self.card2?.isHidden = true
self.card3?.isHidden = true
self.card4?.isHidden = true
self.card5?.isHidden = true
self.card6?.isHidden = true
let cardImagesArray:[UIImageView] = [self.card1, self.card2, self.card3, self.card4, self.card5, self.card6]
var cardsIndex = 0
var imagesIndex = 0
repeat {
if cards[cardsIndex].isSelected{
cardImagesArray[imagesIndex].image = UIImage(named: cards[cardsIndex].image)
cardImagesArray[imagesIndex].isHidden = false
imagesIndex = imagesIndex + 1
}
cardsIndex = cardsIndex + 1
} while cardsIndex < cards.count
}
}
| 39.125 | 116 | 0.64377 |
69fe5aebc2e2da7f91a844b848cc3db57365d208
| 17,661 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import SKSupport
import Basic
import POSIX
final class SupportTests: XCTestCase {
func testResultEquality() {
enum MyError: Error, Equatable {
case err1, err2
}
typealias MyResult<T> = Result<T, MyError>
XCTAssertEqual(MyResult(1), .success(1))
XCTAssertNotEqual(MyResult(2), .success(1))
XCTAssertNotEqual(MyResult(.err1), .success(1))
XCTAssertEqual(MyResult(.err1), MyResult<Int>.failure(.err1))
XCTAssertNotEqual(MyResult(.err1), MyResult<Int>.failure(.err2))
}
func testResultProjection() {
enum MyError: Error, Equatable {
case err1, err2
}
typealias MyResult<T> = Result<T, MyError>
XCTAssertEqual(MyResult(1).success, 1)
XCTAssertNil(MyResult(.err1).success)
XCTAssertNil(MyResult(1).failure)
XCTAssertEqual(MyResult<Int>.failure(.err1).failure, .err1)
}
func testIntFromAscii() {
XCTAssertNil(Int(ascii: ""))
XCTAssertNil(Int(ascii: "a"))
XCTAssertNil(Int(ascii: "0x1"))
XCTAssertNil(Int(ascii: " "))
XCTAssertNil(Int(ascii: "+"))
XCTAssertNil(Int(ascii: "-"))
XCTAssertNil(Int(ascii: "+ "))
XCTAssertNil(Int(ascii: "- "))
XCTAssertNil(Int(ascii: "1 1"))
XCTAssertNil(Int(ascii: "1a1"))
XCTAssertNil(Int(ascii: "1a"))
XCTAssertNil(Int(ascii: "1+"))
XCTAssertNil(Int(ascii: "+ 1"))
XCTAssertNil(Int(ascii: "- 1"))
XCTAssertNil(Int(ascii: "1-1"))
XCTAssertEqual(Int(ascii: "0"), 0)
XCTAssertEqual(Int(ascii: "1"), 1)
XCTAssertEqual(Int(ascii: "45"), 45)
XCTAssertEqual(Int(ascii: " 45 "), 45)
XCTAssertEqual(Int(ascii: "\(Int.max)"), Int.max)
XCTAssertEqual(Int(ascii: "\(Int.max-1)"), Int.max-1)
XCTAssertEqual(Int(ascii: "\(Int.min)"), Int.min)
XCTAssertEqual(Int(ascii: "\(Int.min+1)"), Int.min+1)
XCTAssertEqual(Int(ascii: "+0"), 0)
XCTAssertEqual(Int(ascii: "+1"), 1)
XCTAssertEqual(Int(ascii: "+45"), 45)
XCTAssertEqual(Int(ascii: " +45 "), 45)
XCTAssertEqual(Int(ascii: "-0"), 0)
XCTAssertEqual(Int(ascii: "-1"), -1)
XCTAssertEqual(Int(ascii: "-45"), -45)
XCTAssertEqual(Int(ascii: " -45 "), -45)
XCTAssertEqual(Int(ascii: "+\(Int.max)"), Int.max)
XCTAssertEqual(Int(ascii: "+\(Int.max-1)"), Int.max-1)
XCTAssertEqual(Int(ascii: "\(Int.min)"), Int.min)
XCTAssertEqual(Int(ascii: "\(Int.min+1)"), Int.min+1)
}
func testFindSubsequence() {
XCTAssertNil([0, 1, 2].firstIndex(of: [3]))
XCTAssertNil([].firstIndex(of: [3]))
XCTAssertNil([0, 1, 2].firstIndex(of: [1, 3]))
XCTAssertNil([0, 1, 2].firstIndex(of: [0, 2]))
XCTAssertNil([0, 1, 2].firstIndex(of: [2, 3]))
XCTAssertNil([0, 1].firstIndex(of: [1, 0]))
XCTAssertNil([0].firstIndex(of: [0, 1]))
XCTAssertEqual([Int]().firstIndex(of: []), 0)
XCTAssertEqual([0].firstIndex(of: []), 0)
XCTAssertEqual([0].firstIndex(of: [0]), 0)
XCTAssertEqual([0, 1].firstIndex(of: [0]), 0)
XCTAssertEqual([0, 1].firstIndex(of: [1]), 1)
XCTAssertEqual([0, 1].firstIndex(of: [0, 1]), 0)
XCTAssertEqual([0, 1, 2, 3].firstIndex(of: [0, 1]), 0)
XCTAssertEqual([0, 1, 2, 3].firstIndex(of: [0, 1, 2]), 0)
XCTAssertEqual([0, 1, 2, 3].firstIndex(of: [1, 2]), 1)
XCTAssertEqual([0, 1, 2, 3].firstIndex(of: [3]), 3)
}
func testLogging() {
let orig = Logger.shared
defer { Logger.shared = orig }
let testLogger = Logger()
Logger.shared = testLogger
testLogger.disableNSLog = true
testLogger.disableOSLog = true
var messages: [(String, LogLevel)] = []
let obj = testLogger.addLogHandler { message, level in
messages.append((message, level))
}
func check(_ messages: inout [(String, LogLevel)], expected: [(String, LogLevel)], file: StaticString = #file, line: UInt = #line) {
testLogger.logQueue.sync {}
XCTAssert(messages == expected, "\(messages) does not match expected \(expected)", file: file, line: line)
messages.removeAll()
}
testLogger.currentLevel = .default
log("a")
check(&messages, expected: [("a", .default)])
check(&messages, expected: [])
log("b\n\nc")
check(&messages, expected: [("b\n\nc", .default)])
enum MyError: Error { case one }
func throw1(_ x: Int) throws -> Int {
if x == 1 { throw MyError.one }
return x
}
XCTAssertEqual(orLog { try throw1(0) }, 0)
check(&messages, expected: [])
XCTAssertNil(orLog { try throw1(1) })
check(&messages, expected: [("one", .default)])
XCTAssertNil(orLog("hi") { try throw1(1) })
check(&messages, expected: [("hi one", .default)])
logAsync { (currentLevel) -> String? in
return "\(currentLevel)"
}
check(&messages, expected: [("info", .default)])
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
("e", .warning),
("f", .info),
])
testLogger.currentLevel = .warning
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
("e", .warning),
])
testLogger.currentLevel = .error
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
])
testLogger.currentLevel = .default
try! setenv("TEST_ENV_LOGGGING_1", value: "1")
try! setenv("TEST_ENV_LOGGGING_0", value: "0")
// .warning
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_1")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
("e", .warning),
])
// .error
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_0")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
])
// missing - no change
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_err")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
])
// invalid - no change
try! setenv("TEST_ENV_LOGGGING_err", value: "")
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_err")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
])
// invalid - no change
try! setenv("TEST_ENV_LOGGGING_err", value: "a3")
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_err")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
])
// too high - max out at .debyg
try! setenv("TEST_ENV_LOGGGING_err", value: "1000")
testLogger.setLogLevel(environmentVariable: "TEST_ENV_LOGGGING_err")
log("d", level: .error)
log("e", level: .warning)
log("f", level: .info)
log("g", level: .debug)
check(&messages, expected: [
("d", .error),
("e", .warning),
("f", .info),
("g", .debug),
])
testLogger.currentLevel = .default
testLogger.addLogHandler(obj)
log("a")
check(&messages, expected: [
("a", .default),
("a", .default),
])
testLogger.removeLogHandler(obj)
log("a")
check(&messages, expected: [])
}
func checkLines(_ string: String, _ expected: [String], file: StaticString = #file, line: UInt = #line) {
let table = LineTable(string)
XCTAssertEqual(table.map { String($0) }, expected, file: file, line: line)
}
func checkOffsets(_ string: String, _ expected: [Int], file: StaticString = #file, line: UInt = #line) {
let table = LineTable(string)
XCTAssertEqual(table.map { string.utf8.distance(from: string.startIndex, to: $0.startIndex) }, expected, file: file, line: line)
}
func testLineTable() {
checkLines("", [""])
checkLines("a", ["a"])
checkLines("abc", ["abc"])
checkLines("abc\n", ["abc\n", ""])
checkLines("\n", ["\n", ""])
checkLines("\n\n", ["\n", "\n", ""])
checkLines("\r\n", ["\r\n", ""])
checkLines("\r\r", ["\r", "\r", ""])
checkLines("a\nb", ["a\n", "b"])
checkLines("a\nb\n", ["a\n", "b\n", ""])
checkLines("a\nb\nccccc", ["a\n", "b\n", "ccccc"])
checkLines("\u{1}\nb", ["\u{1}\n", "b"])
checkLines("\u{10000}\nb", ["\u{10000}\n", "b"])
checkLines("\n\u{10000}", ["\n", "\u{10000}"])
checkLines("\n\u{10000}b", ["\n", "\u{10000}b"])
checkLines("\n\u{10000}\nc", ["\n", "\u{10000}\n", "c"])
checkLines("\n\u{10000}b\nc", ["\n", "\u{10000}b\n", "c"])
checkOffsets("a", [0])
checkOffsets("abc", [0])
checkOffsets("\n", [0, 1])
checkOffsets("\n\n", [0, 1, 2])
checkOffsets("\n\r\n\n", [0, 1, 3, 4])
checkOffsets("a\nb", [0, 2])
checkOffsets("a\nb\n", [0, 2, 4])
checkOffsets("a\nbbb\nccccc", [0, 2, 6])
checkOffsets("a\nbbb\nccccc", [0, 2, 6])
checkOffsets("\u{1}\nb", [0, 2])
checkOffsets("\u{100}\nb", [0, 3])
checkOffsets("\u{1000}\nb", [0, 4])
checkOffsets("\u{10000}\nb", [0, 5])
checkOffsets("\n\u{10000}", [0, 1])
checkOffsets("\n\u{10000}b", [0, 1])
checkOffsets("\n\u{10000}b\nc", [0, 1, 7])
XCTAssertEqual(LineTable("")[0], "")
XCTAssertEqual(LineTable("\n")[1], "")
}
func checkLineAndColumns(_ table: LineTable, _ utf8Offset: Int, _ expected: (line: Int, utf16Column: Int)?, file: StaticString = #file, line: UInt = #line) {
switch (table.lineAndUTF16ColumnOf(utf8Offset: utf8Offset), expected) {
case (nil, nil):
break
case (let result?, let _expected?):
XCTAssertTrue(result == _expected, "\(result) != \(_expected)", file: file, line: line)
case (let result, let _expected):
XCTFail("\(String(describing: result)) != \(String(describing: _expected))", file: file, line: line)
}
}
func checkUTF8OffsetOf(_ table: LineTable, _ query: (line: Int, utf16Column: Int), _ expected: Int?, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(table.utf8OffsetOf(line: query.line, utf16Column: query.utf16Column), expected, file: file, line: line)
}
func checkUTF16ColumnAt(_ table: LineTable, _ query: (line: Int, utf8Column: Int), _ expected: Int?, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(table.utf16ColumnAt(line: query.line, utf8Column: query.utf8Column), expected, file: file, line: line)
}
func testLineTableLinePositionTranslation() {
let t1 = LineTable("""
0123
5678
abcd
""")
checkLineAndColumns(t1, 0, (line: 0, utf16Column: 0))
checkLineAndColumns(t1, 2, (line: 0, utf16Column: 2))
checkLineAndColumns(t1, 4, (line: 0, utf16Column: 4))
checkLineAndColumns(t1, 5, (line: 1, utf16Column: 0))
checkLineAndColumns(t1, 9, (line: 1, utf16Column: 4))
checkLineAndColumns(t1, 10, (line: 2, utf16Column: 0))
checkLineAndColumns(t1, 14, (line: 2, utf16Column: 4))
checkLineAndColumns(t1, 15, nil)
checkUTF8OffsetOf(t1, (line: 0, utf16Column: 0), 0)
checkUTF8OffsetOf(t1, (line: 0, utf16Column: 2), 2)
checkUTF8OffsetOf(t1, (line: 0, utf16Column: 4), 4)
checkUTF8OffsetOf(t1, (line: 0, utf16Column: 5), 5)
checkUTF8OffsetOf(t1, (line: 0, utf16Column: 6), nil)
checkUTF8OffsetOf(t1, (line: 1, utf16Column: 0), 5)
checkUTF8OffsetOf(t1, (line: 1, utf16Column: 4), 9)
checkUTF8OffsetOf(t1, (line: 2, utf16Column: 0), 10)
checkUTF8OffsetOf(t1, (line: 2, utf16Column: 4), 14)
checkUTF8OffsetOf(t1, (line: 2, utf16Column: 5), nil)
checkUTF8OffsetOf(t1, (line: 3, utf16Column: 0), nil)
checkUTF16ColumnAt(t1, (line: 0, utf8Column: 4), 4)
checkUTF16ColumnAt(t1, (line: 0, utf8Column: 5), 5)
checkUTF16ColumnAt(t1, (line: 0, utf8Column: 6), nil)
checkUTF16ColumnAt(t1, (line: 2, utf8Column: 0), 0)
checkUTF16ColumnAt(t1, (line: 3, utf8Column: 0), nil)
let t2 = LineTable("""
こんにちは
안녕하세요
\u{1F600}\u{1F648}
""")
checkLineAndColumns(t2, 0, (line: 0, utf16Column: 0))
checkLineAndColumns(t2, 15, (line: 0, utf16Column: 5))
checkLineAndColumns(t2, 19, (line: 1, utf16Column: 1))
checkLineAndColumns(t2, 32, (line: 2, utf16Column: 0))
checkLineAndColumns(t2, 36, (line: 2, utf16Column: 2))
checkLineAndColumns(t2, 40, (line: 2, utf16Column: 4))
checkUTF8OffsetOf(t2, (line: 0, utf16Column: 0), 0)
checkUTF8OffsetOf(t2, (line: 0, utf16Column: 5), 15)
checkUTF8OffsetOf(t2, (line: 0, utf16Column: 6), 16)
checkUTF8OffsetOf(t2, (line: 1, utf16Column: 1), 19)
checkUTF8OffsetOf(t2, (line: 1, utf16Column: 6), 32)
checkUTF8OffsetOf(t2, (line: 1, utf16Column: 7), nil)
checkUTF8OffsetOf(t2, (line: 2, utf16Column: 0), 32)
checkUTF8OffsetOf(t2, (line: 2, utf16Column: 2), 36)
checkUTF8OffsetOf(t2, (line: 2, utf16Column: 4), 40)
checkUTF8OffsetOf(t2, (line: 2, utf16Column: 5), nil)
checkUTF16ColumnAt(t2, (line: 0, utf8Column: 3), 1)
checkUTF16ColumnAt(t2, (line: 0, utf8Column: 15), 5)
checkUTF16ColumnAt(t2, (line: 2, utf8Column: 4), 2)
}
func testLineTableEditing() {
var t = LineTable("")
t.replace(fromLine: 0, utf16Offset: 0, utf16Length: 0, with: "a")
XCTAssertEqual(t, LineTable("a"))
t.replace(fromLine: 0, utf16Offset: 0, utf16Length: 0, with: "cb")
XCTAssertEqual(t, LineTable("cba"))
t.replace(fromLine: 0, utf16Offset: 1, utf16Length: 1, with: "d")
XCTAssertEqual(t, LineTable("cda"))
t.replace(fromLine: 0, utf16Offset: 3, utf16Length: 0, with: "e")
XCTAssertEqual(t, LineTable("cdae"))
t.replace(fromLine: 0, utf16Offset: 3, utf16Length: 1, with: "")
XCTAssertEqual(t, LineTable("cda"))
t = LineTable("a")
t.replace(fromLine: 0, utf16Offset: 0, utf16Length: 0, with: "\n")
XCTAssertEqual(t, LineTable("\na"))
t.replace(fromLine: 1, utf16Offset: 0, utf16Length: 0, with: "\n")
XCTAssertEqual(t, LineTable("\n\na"))
t.replace(fromLine: 2, utf16Offset: 1, utf16Length: 0, with: "\n")
XCTAssertEqual(t, LineTable("\n\na\n"))
t = LineTable("""
abcd
efgh
""")
t.replace(fromLine: 0, utf16Offset: 2, toLine: 1, utf16Offset: 1, with: "x")
XCTAssertEqual(t, LineTable("abxfgh"))
t.replace(fromLine: 0, utf16Offset: 2, toLine: 0, utf16Offset: 4, with: "p\nq\n")
XCTAssertEqual(t, LineTable("abp\nq\ngh"))
}
func testLineTableAppendPerf() {
let characters: [Character] = [
"\t", "\n"
] + (32...126).map { Character(UnicodeScalar($0)) }
// The debug performance is shockingly bad.
#if DEBUG
let iterations = 1_000
#else
let iterations = 10_000
#endif
self.measure {
var lcg = SimpleLCG(seed: 1)
var t = LineTable("")
var line = 0
var col = 0
for _ in 1...iterations {
let c = characters.randomElement(using: &lcg)!
t.replace(fromLine: line, utf16Offset: col, toLine: line, utf16Offset: col, with: String(c))
col += 1
if c == "\n" {
line += 1
col = 0
}
}
}
}
func testLineTableSingleCharEditPerf() {
let characters: [Character] = [
"\t", "\n"
] + (32...126).map { Character(UnicodeScalar($0)) }
// The debug performance is shockingly bad.
#if DEBUG
let iterations = 1_000
let size = 1_000
#else
let iterations = 10_000
let size = 10_000
#endif
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: false) {
var lcg = SimpleLCG(seed: 1)
var str = ""
for _ in 1...size {
str += String(characters.randomElement(using: &lcg)!)
}
var t = LineTable(str)
self.startMeasuring()
for _ in 1...iterations {
let line = (0..<(t.count-1)).randomElement(using: &lcg)!
let col = (0 ..< t[line].utf16.count).randomElement(using: &lcg)!
let len = Bool.random() ? 1 : 0
var newText = String(characters.randomElement(using: &lcg)!)
if len == 1 && Bool.random(using: &lcg) {
newText = "" // deletion
}
t.replace(fromLine: line, utf16Offset: col, utf16Length: len, with: newText)
}
self.stopMeasuring()
}
}
func testByteStringWithUnsafeData() {
ByteString(encodingAsUTF8: "").withUnsafeData { data in
XCTAssertEqual(data.count, 0)
}
ByteString(encodingAsUTF8: "abc").withUnsafeData { data in
XCTAssertEqual(data.count, 3)
}
}
func testExpandingTilde() {
XCTAssertEqual(AbsolutePath(expandingTilde: "~/foo").basename, "foo")
XCTAssertNotEqual(AbsolutePath(expandingTilde: "~/foo").parentDirectory, .root)
XCTAssertEqual(AbsolutePath(expandingTilde: "/foo"), AbsolutePath("/foo"))
}
}
| 33.385633 | 159 | 0.602457 |
f9d5b6f3c0e8eb4d4e27850a62a4a24b4a833bd0
| 7,968 |
/*
This source file is part of the Swift.org open source project
Copyright (c) 2020-2021 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 struct Foundation.Date
import struct Foundation.URL
import PackageModel
import SourceControl
import TSCBasic
import TSCUtility
public enum PackageCollectionsModel {}
// make things less verbose internally
internal typealias Model = PackageCollectionsModel
extension PackageCollectionsModel {
/// A `Collection` is a collection of packages.
public struct Collection: Equatable, Codable {
public typealias Identifier = CollectionIdentifier
public typealias Source = CollectionSource
/// The identifier of the collection
public let identifier: Identifier
/// Where the collection and its contents are obtained
public internal(set) var source: Source
/// The name of the collection
public let name: String
/// The description of the collection
public let overview: String?
/// Keywords for the collection
public let keywords: [String]?
/// Metadata of packages belonging to the collection
public let packages: [Package]
/// When this collection was created/published by the source
public let createdAt: Date
/// Who authored this collection
public let createdBy: Author?
/// When this collection was last processed locally
public let lastProcessedAt: Date
/// The collection's signature metadata
public let signature: SignatureData?
/// Indicates if the collection is signed
public var isSigned: Bool {
self.signature != nil
}
/// Initializes a `Collection`
init(
source: Source,
name: String,
overview: String?,
keywords: [String]?,
packages: [Package],
createdAt: Date,
createdBy: Author?,
signature: SignatureData?,
lastProcessedAt: Date = Date()
) {
self.identifier = .init(from: source)
self.source = source
self.name = name
self.overview = overview
self.keywords = keywords
self.packages = packages
self.createdAt = createdAt
self.createdBy = createdBy
self.signature = signature
self.lastProcessedAt = lastProcessedAt
}
}
}
extension PackageCollectionsModel {
/// Represents the source of a `Collection`
public struct CollectionSource: Equatable, Hashable, Codable {
/// Source type
public let type: CollectionSourceType
/// URL of the source file
public let url: URL
/// Indicates if the source is explicitly trusted or untrusted by the user
public var isTrusted: Bool?
/// Indicates if the source can skip signature validation
public var skipSignatureCheck: Bool
/// The source's absolute file system path, if its URL is of 'file' scheme.
let absolutePath: AbsolutePath?
public init(type: CollectionSourceType, url: URL, isTrusted: Bool? = nil, skipSignatureCheck: Bool = false) {
self.type = type
self.url = url
self.isTrusted = isTrusted
self.skipSignatureCheck = skipSignatureCheck
if url.scheme?.lowercased() == "file", let absolutePath = try? AbsolutePath(validating: url.path) {
self.absolutePath = absolutePath
} else {
self.absolutePath = nil
}
}
public static func == (lhs: CollectionSource, rhs: CollectionSource) -> Bool {
lhs.type == rhs.type && lhs.url == rhs.url
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.type)
hasher.combine(self.url)
}
}
/// Represents the source type of a `Collection`
public enum CollectionSourceType: String, Codable, CaseIterable {
case json
}
}
extension PackageCollectionsModel {
/// Represents the identifier of a `Collection`
public enum CollectionIdentifier: Hashable, Comparable {
/// JSON based package collection at URL
case json(URL)
/// Creates an `Identifier` from `Source`
init(from source: CollectionSource) {
switch source.type {
case .json:
self = .json(source.url)
}
}
public static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.json(let lhs), .json(let rhs)):
return lhs.absoluteString < rhs.absoluteString
}
}
}
}
extension PackageCollectionsModel.CollectionIdentifier: Codable {
public enum DiscriminatorKeys: String, Codable {
case json
}
public enum CodingKeys: CodingKey {
case _case
case url
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(DiscriminatorKeys.self, forKey: ._case) {
case .json:
let url = try container.decode(URL.self, forKey: .url)
self = .json(url)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .json(let url):
try container.encode(DiscriminatorKeys.json, forKey: ._case)
try container.encode(url, forKey: .url)
}
}
}
extension PackageCollectionsModel.Collection {
/// Represents the author of a `Collection`
public struct Author: Equatable, Codable {
/// The name of the author
public let name: String
}
}
extension PackageCollectionsModel {
/// Package collection signature metadata
public struct SignatureData: Equatable, Codable {
/// Details about the certificate used to generate the signature
public let certificate: Certificate
/// Indicates if the signature has been validated. This is set to false if signature check didn't take place.
public let isVerified: Bool
public init(certificate: Certificate, isVerified: Bool) {
self.certificate = certificate
self.isVerified = isVerified
}
public struct Certificate: Equatable, Codable {
/// Subject of the certificate
public let subject: Name
/// Issuer of the certificate
public let issuer: Name
/// Creates a `Certificate`
public init(subject: Name, issuer: Name) {
self.subject = subject
self.issuer = issuer
}
/// Generic certificate name (e.g., subject, issuer)
public struct Name: Equatable, Codable {
/// User ID
public let userID: String?
/// Common name
public let commonName: String?
/// Organizational unit
public let organizationalUnit: String?
/// Organization
public let organization: String?
/// Creates a `Name`
public init(userID: String?,
commonName: String?,
organizationalUnit: String?,
organization: String?) {
self.userID = userID
self.commonName = commonName
self.organizationalUnit = organizationalUnit
self.organization = organization
}
}
}
}
}
| 31.494071 | 117 | 0.597892 |
f5fe9fde1ee3e67705094098bcfebbdf09560530
| 3,945 |
//
// PersonalInformationTableViewController.swift
// iCampus
//
// Created by Yuchen Cheng on 2018/4/25.
// Copyright © 2018年 Yuchen Cheng. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class PersonalInformationTableViewController: UITableViewController {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var avatarButton: UIButton!
@IBOutlet weak var userIdLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var classIdLabel: UILabel!
private let memberViewModel = MemberViewModel()
private let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorColor = self.tableView.backgroundColor
avatarImageView.layer.cornerRadius = 10.0
avatarImageView.layer.masksToBounds = true
if let member = iCampusPersistence().getMember() {
memberViewModel
.getAvatar(id: member.id)
.bind(to: avatarImageView.rx.image)
.disposed(by: bag)
}
avatarButton.rx.tap
.bind { [unowned self] in self.showSheet() }
.disposed(by: bag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let member = iCampusPersistence().getMember() {
self.userIdLabel.text = member.userId ?? ""
self.nameLabel.text = member.name ?? "未填写"
self.phoneLabel.text = member.phone ?? ""
self.classIdLabel.text = member.classId ?? "未填写"
}
}
fileprivate func showSheet() {
let sheet = UIAlertController(title: "修改头像", message: nil, preferredStyle: .actionSheet)
sheet.addAction(UIAlertAction(title: "相机胶卷", style: .default) { [unowned self] _ in self.pickImage(sourceType: .photoLibrary) })
sheet.addAction(UIAlertAction(title: "拍照", style: .default) { [unowned self] _ in self.pickImage(sourceType: .camera) })
sheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
self.present(sheet, animated: true, completion: nil)
}
func pickImage(sourceType: UIImagePickerControllerSourceType) {
if UIImagePickerController.isSourceTypeAvailable(sourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? UITableViewCell {
let editTableViewController = segue.destination as! EditTableViewController
editTableViewController.editText = cell.detailTextLabel?.text
editTableViewController.index = tableView.indexPathForSelectedRow?.row
editTableViewController.navigationItem.title = "修改\(cell.textLabel?.text ?? "")"
}
}
}
extension PersonalInformationTableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage, let member = iCampusPersistence().getMember() {
memberViewModel
.uploadAvatar(id: member.id, image: image)
.subscribe(onNext: { [unowned self] _ in
self.dismiss(animated: true, completion: nil)
})
.disposed(by: bag)
}
}
}
| 38.676471 | 136 | 0.650951 |
e4a44fc474b2ba708460a16ef34b9c83ce69fd15
| 2,196 |
//
// ViewController.swift
// WhereUAt
//
// Created by Angel Xiao on 2/25/16.
// Copyright © 2016 WhereUAt. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController, HolderViewDelegate {
var holderView = HolderView(frame:CGRectZero)
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addHolderView()
if(FBSDKAccessToken.currentAccessToken() == nil){
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "toLoginViewTransition",
userInfo: nil, repeats: false)
} else {
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "toMapViewTransition",
userInfo: nil, repeats: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addHolderView() {
let boxSize: CGFloat = 100.0
holderView.frame = CGRect(x: view.bounds.width / 2 - boxSize / 2,
y: view.bounds.height / 2 - boxSize / 2,
width: boxSize,
height: boxSize)
holderView.parentFrame = view.frame
holderView.delegate = self
view.addSubview(holderView)
holderView.addOval()
}
func backgroundLabel() {
}
func toMapViewTransition(){
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyBoard.instantiateViewControllerWithIdentifier("MapViewController") as! MapViewController
self.presentViewController(secondViewController, animated: true, completion: nil)
}
func toLoginViewTransition(){
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyBoard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.presentViewController(loginViewController, animated: true, completion: nil)
}
}
| 32.294118 | 131 | 0.660291 |
6a6389b40f5feba4c97c45d44a5a77c1c3e1b7d0
| 7,822 |
//
// URFilter.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 6. 16..
// Copyright © 2017년 zigbang. All rights reserved.
//
import Foundation
open class URFilter: CIFilter, URFilterBootLoading {
open var inputImage: CIImage?
var customKernel: CIKernel?
var customAttributes: [Any]?
var extent: CGRect = .zero
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public init() {
super.init()
}
/**
Initialize CIFilter with **CGImage** and CIKernel shader params
- parameters:
- frame: The frame rectangle for the input image, measured in points.
- cgImage: Core Image of the input image
- inputValues: attributes for CIKernel
*/
required public init(frame: CGRect, cgImage: CGImage, inputValues: [Any]) {
super.init()
self.extent = frame
self.extractInputImage(cgImage: cgImage)
}
/**
Initialize CIFilter with **CGImage** and CIKernel shader params
- parameters:
- frame: The frame rectangle for the input image, measured in points.
- imageView: The UIImageView of the input image
- inputValues: attributes for CIKernel
*/
required public init(frame: CGRect, imageView: UIImageView, inputValues: [Any]) {
super.init()
self.extent = frame
self.extractInputImage(imageView: imageView)
}
override open var outputImage: CIImage? {
return self.applyFilter()
}
open var outputCGImage: CGImage? {
let context = CIContext(options: nil)
guard let output = self.outputImage, let resultCGImage = context.createCGImage(output, from: output.extent) else { return nil }
return resultCGImage
}
func applyFilter() -> CIImage {
return CIImage()
}
// MARK: - shaders
open static let colorKernelForRGB: CIColorKernel = CIColorKernel(string:
"kernel vec4 combineRGBChannel(__sample rgb) {" +
" return vec4(rgb.rgb, 1.0);" +
"}")!
open static let colorKernel: CIColorKernel = CIColorKernel(string:
"kernel vec4 combineRGBChannel(__sample red, __sample green, __sample blue, __sample rgb) {" +
" vec4 result = vec4(red.r, green.g, blue.b, rgb.a);" +
" bool isTransparency = true;" +
" if (red.r == 0.0 && red.g == 0.0 && red.b == 0.0 && red.a == 0.0) {" +
" result.r = 0.0;" +
" } else {" +
" isTransparency = false;" +
" }" +
" if (green.r == 0.0 && green.g == 0.0 && green.b == 0.0 && green.a == 0.0) {" +
" result.g = 0.0;" +
" } else {" +
" isTransparency = false;" +
" }" +
" if (blue.r == 0.0 && blue.g == 0.0 && blue.b == 0.0 && blue.a == 0.0) {" +
" result.b = 0.0;" +
" } else {" +
" isTransparency = false;" +
" }" +
" if (isTransparency) {" +
" result.a = 0.0;" +
" }" +
" return result;" +
"}")!
open static let brightenKernel: CIKernel = CIKernel(string:
"kernel vec4 brightenEffect (sampler src, float k)\n" +
"{\n" +
" vec4 currentSource = sample (src, samplerCoord (src)); // 1\n" +
" currentSource.rgb = currentSource.rgb + k * currentSource.a; // 2\n" +
" return currentSource; // 3\n" +
"}")!
open static let holeDistortionKernel: CIKernel = CIKernel(string:
"kernel vec4 hole (sampler src, vec2 center, vec2 params) // 1\n" +
"{\n" +
" vec2 t1;\n" +
" float distance0, distance1;\n" +
"\n" +
" t1 = destCoord () - center; // 2\n" +
" distance0 = dot (t1, t1); // 3\n" +
" t1 = t1 * inversesqrt (distance0); // 4\n" +
" distance0 = distance0 * inversesqrt (distance0) * params.x; // 5\n" +
" distance1 = distance0 - (1.0 / distance0); // 6\n" +
" distance0 = (distance0 < 1.0 ? 0.0 : distance1) * params.y; // 7\n" +
" t1 = t1 * distance0 + center; // 8\n" +
"\n" +
" return sample (src, samplerTransform (src, t1)); // 9\n" +
"}"
)!
open static let multiplyKernel: CIKernel = CIKernel(string:
"kernel vec4 multiplyEffect (sampler src, __color mul)\n" +
"{\n" +
" return sample (src, samplerCoord (src)) * mul;\n" +
"}"
)!
open static let swirlKernel: CIKernel = CIKernel(string:
"kernel vec4 swirl(sampler src, vec2 center, float radius, float angle, float time)\n" +
"{\n" +
"vec2 texSize = samplerSize(src);\n" +
"vec2 texure2D = samplerCoord(src) * texSize;\n" +
"texure2D -= center;\n" +
"float distance = length(texure2D);\n" +
"if (distance < radius)\n" +
"{\n" +
"float percent = (radius - distance) / radius;\n" +
"float theta = percent * percent * angle * 8.0;\n" +
"float s = sin(theta);\n" +
"float c = cos(theta);\n" +
"texure2D = vec2(dot(texure2D, vec2(c, -s)), dot(texure2D, vec2(s, c)));\n" +
"}\n" +
"texure2D += center;\n" +
"vec3 color = sample(src, texure2D / texSize).rgb;\n" +
"return vec4(color, 1.0);" +
"}"
)!
/// Shock Wave Effect
///
/// - Parameters:
/// - sampler: CISampler
/// - center: CIVertor(vec2)
open static let shockWaveKernel: CIKernel = CIKernel(string:
"kernel vec4 shockWave(sampler src, vec2 center, vec3 shockParams, float time)\n" +
"{\n" +
"vec2 texture2D = samplerCoord(src);\n" +
"float distance = length(texture2D - center);\n" +
"if ( (distance <= (time + shockParams.z)) && (distance >= (time - shockParams.z)) )\n" +
"{\n" +
"float diff = (distance - time);\n" +
"float powDiff = 1.0 - pow(abs(diff * shockParams.x), shockParams.y);\n" +
"float diffTime = diff * powDiff;\n" +
"vec2 diffUV = normalize(texture2D - center);\n" +
"texture2D = texture2D + (diffUV * diffTime);\n" +
"}\n" +
"return vec4(sample(src, texture2D).rgba);" +
"}"
)!
/// Wave Warp Effect
///
/// - Parameters:
/// - sampler: CISampler
/// - center: CIVertor(vec2)
open static let waveWarpKernel: CIKernel = CIKernel(string:
"kernel vec4 waveWarp(sampler src, vec2 center, vec3 shockParams, float time)\n" +
"{\n" +
"vec2 texture2D = samplerCoord(src);\n" +
"float distance = length(texture2D - center);\n" +
"if ( (distance <= (time + shockParams.z)) && (distance >= (time - shockParams.z)) )\n" +
"{\n" +
"float diff = (distance - time);\n" +
"float powDiff = 1.0 - pow(abs(diff * shockParams.x), shockParams.y);\n" +
"float diffTime = diff * powDiff;\n" +
"vec2 diffUV = normalize(texture2D - center);\n" +
"texture2D = texture2D + (diffUV * diffTime);\n" +
"}\n" +
"return vec4(sample(src, texture2D).rgba);" +
"}"
)!
}
| 39.11 | 135 | 0.495909 |
87ab9c11afbca4c6c941faa5b1713d6b99e5fac9
| 3,412 |
@testable import KsApi
import Prelude
import XCTest
final class UserTests: XCTestCase {
func testEquatable() {
XCTAssertEqual(User.template, User.template)
XCTAssertNotEqual(User.template, User.template |> \.id %~ { $0 + 1 })
}
func testDescription() {
XCTAssertNotEqual("", User.template.debugDescription)
}
func testJsonParsing() {
let json: [String: Any] = [
"id": 1,
"name": "Blob",
"avatar": [
"medium": "http://www.kickstarter.com/medium.jpg",
"small": "http://www.kickstarter.com/small.jpg"
],
"backed_projects_count": 2,
"weekly_newsletter": false,
"promo_newsletter": false,
"happening_newsletter": false,
"games_newsletter": false,
"notify_of_comment_replies": false,
"facebook_connected": false,
"location": [
"country": "US",
"id": 12,
"displayable_name": "Brooklyn, NY",
"localized_name": "Brooklyn, NY",
"name": "Brooklyn"
],
"is_admin": false,
"is_email_verified": false,
"is_friend": false,
"opted_out_of_recommendations": true,
"show_public_profile": false,
"social": true
]
let user: User? = tryDecode(json)
XCTAssertEqual(1, user?.id)
XCTAssertEqual(false, user?.isAdmin)
XCTAssertEqual("http://www.kickstarter.com/small.jpg", user?.avatar.small)
XCTAssertEqual(2, user?.stats.backedProjectsCount)
XCTAssertEqual(false, user?.newsletters.weekly)
XCTAssertEqual(false, user?.newsletters.promo)
XCTAssertEqual(false, user?.newsletters.happening)
XCTAssertEqual(false, user?.newsletters.games)
XCTAssertEqual(false, user?.notifications.commentReplies)
XCTAssertEqual(false, user?.facebookConnected)
XCTAssertEqual(false, user?.isEmailVerified)
XCTAssertEqual(false, user?.isFriend)
XCTAssertNotNil(user?.location)
XCTAssertEqual(json as NSDictionary?, user?.encode() as NSDictionary?)
}
func testJsonEncoding() {
let json: [String: Any] = [
"id": 1,
"name": "Blob",
"avatar": [
"medium": "http://www.kickstarter.com/medium.jpg",
"small": "http://www.kickstarter.com/small.jpg",
"large": "http://www.kickstarter.com/large.jpg"
],
"backed_projects_count": 2,
"games_newsletter": false,
"happening_newsletter": false,
"promo_newsletter": false,
"weekly_newsletter": false,
"notify_of_comment_replies": false,
"facebook_connected": false,
"location": [
"country": "US",
"id": 12,
"displayable_name": "Brooklyn, NY",
"localized_name": "Brooklyn, NY",
"name": "Brooklyn"
],
"is_admin": false,
"is_email_verified": false,
"is_friend": false,
"opted_out_of_recommendations": true,
"show_public_profile": false,
"social": true
]
let user: User? = User.decodeJSONDictionary(json)
XCTAssertEqual(user?.encode() as NSDictionary?, json as NSDictionary?)
}
func testIsRepeatCreator() {
let user = User.template
let creator = User.template
|> User.lens.stats.createdProjectsCount .~ 1
let repeatCreator = User.template
|> User.lens.stats.createdProjectsCount .~ 2
XCTAssertEqual(true, repeatCreator.isRepeatCreator)
XCTAssertEqual(false, creator.isRepeatCreator)
XCTAssertNil(user.isRepeatCreator)
}
}
| 31.018182 | 78 | 0.642438 |
21538349282be021b49ad2dfb637f31082c22ebd
| 2,949 |
//
// AnimationSelectionTableViewCell.swift
// Core-Sample
//
// Created by Elias Abel on 4/26/18.
// Copyright (c) 2018 Meniny Lab. All rights reserved.
//
import Pow
class AnimationSelectionTableViewCell: SelectionTableViewCell {
enum Action: String {
case entrance
case exit
case pop
var isOut: Bool {
return Set([.exit, .pop]).contains(self)
}
}
var action: Action = .entrance
var animation: PowAttributes.Animation {
set {
switch action {
case .entrance:
attributesWrapper.attributes.entranceAnimation = newValue
case .exit:
attributesWrapper.attributes.exitAnimation = newValue
case .pop:
attributesWrapper.attributes.popBehavior = PowAttributes.PopBehavior.animated(animation: newValue)
}
}
get {
switch action {
case .entrance:
return attributesWrapper.attributes.entranceAnimation
case .exit:
return attributesWrapper.attributes.exitAnimation
case .pop:
if case PowAttributes.PopBehavior.animated(animation: let animation) = attributesWrapper.attributes.popBehavior {
return animation
} else {
fatalError()
}
}
}
}
func configure(attributesWrapper: PowAttributeWrapper, action: Action) {
self.action = action
configure(attributesWrapper: attributesWrapper)
}
override func configure(attributesWrapper: PowAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "\(action.rawValue.capitalized) Animation"
descriptionValue = "Describes the \(action.rawValue) animation of the pow"
insertSegments(by: ["Translate", "Scale", "Fade"])
selectSegment()
}
private func selectSegment() {
if animation.containsTranslation {
segmentedControl.selectedSegmentIndex = 0
} else if animation.containsScale {
segmentedControl.selectedSegmentIndex = 1
} else if animation.containsFade {
segmentedControl.selectedSegmentIndex = 2
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
animation = .translation
case 1 where action.isOut:
animation = .init(scale: .init(from: 1, to: 0, duration: 0.3))
case 1:
animation = .init(scale: .init(from: 0, to: 1, duration: 0.3))
case 2 where action.isOut:
animation = .init(fade: .init(from: 1, to: 0, duration: 0.3))
case 2:
animation = .init(fade: .init(from: 0, to: 1, duration: 0.3))
default:
break
}
}
}
| 32.054348 | 129 | 0.584944 |
69c71caafe2a26ea6f44db42a77fc9fbd75cf03e
| 1,139 |
//
// BadgeLevelViewModel.swift
// DriveKitDriverAchievementUI
//
// Created by Fanny Tavart Pro on 5/15/20.
// Copyright © 2020 DriveQuant. All rights reserved.
//
import Foundation
import DriveKitDBAchievementAccessModule
class BadgeLevelViewModel {
let level: DKBadgeCharacteristics
init(level: DKBadgeCharacteristics) {
self.level = level
}
var tripsLeft: Int {
return Int(round(Double(level.threshold) - level.progressValue))
}
var title: String {
return level.name.dkAchievementLocalized()
}
var iconKey: String {
return tripsLeft > 0 ? level.defaultIcon : level.icon
}
var description: String {
return level.descriptionValue.dkAchievementLocalized()
}
var progress: String {
return level.progress.dkAchievementLocalized()
}
var congrats: String {
return level.congrats.dkAchievementLocalized()
}
var levelValue: DKLevel {
return level.level
}
var threshold: Int {
return level.threshold
}
var progressValue: Double {
return level.progressValue
}
}
| 20.709091 | 72 | 0.660228 |
dd9f6d2630784d4d3c6fa309a425c1e479af458f
| 1,646 |
//
// InstructionCell.swift
// virtual-machine-v2
//
// Created by Roger Oba on 22/08/18.
// Copyright © 2018 Roger Oba. All rights reserved.
//
import UIKit
final class InstructionCell : UITableViewCell {
@IBOutlet private var breakpointButton: UIButton!
@IBOutlet private var label: UILabel!
@IBOutlet private var indexLabel: UILabel!
static let reuseIdentifier = "InstructionCell"
var item: Instruction! = nil { didSet { handleItemChanged() } }
var line: Int = 0
// MARK: Initialization
override func awakeFromNib() {
super.awakeFromNib()
breakpointButton.setImage(#imageLiteral(resourceName: "checkbox-unchecked"), for: .normal)
breakpointButton.setImage(#imageLiteral(resourceName: "checkbox-checked"), for: .selected)
breakpointButton.adjustsImageWhenHighlighted = false
}
// MARK: Update
private func handleItemChanged() {
label.text = {
switch item {
case .null(let label)?: return "\(label)\t\(item.opcode)"
default: return "\t\(item.opcode) \(item.argument1 ?? "") \(item.argument2 ?? "")"
}
}()
breakpointButton.isSelected = Engine.shared.hasBreakpoint(at: line)
indexLabel.text = "\(line)"
}
override func prepareForReuse() {
super.prepareForReuse()
label.text = nil
breakpointButton.isSelected = false
}
// MARK: Interaction
@IBAction private func handleBreakpointSelected(sender: UIButton) {
sender.isSelected = !sender.isSelected
Engine.shared.setBreakpoint(active: sender.isSelected, at: line)
}
}
| 31.056604 | 98 | 0.651883 |
03e183d31f664ca95bc6768c2d66f133c79c154c
| 14,930 |
//
// RelativeFormatter.swift
// SwiftDate
//
// Created by Daniele Margutti on 08/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
public class RelativeFormatter: DateToStringTrasformable {
/// Private singleton for relative formatter
private static let shared = RelativeFormatter()
/// A cache with all loaded languagues
private var languagesCache: [String: RelativeFormatterLang] = [:]
/// Mapping for languages file to be loaded. Languages table are
/// loaded only upon request.
private var languagesMap: [String: RelativeFormatterLang.Type] = [
lang_af.identifier: lang_af.self,
lang_en.identifier: lang_en.self,
lang_am.identifier: lang_am.self,
lang_ar.identifier: lang_ar.self,
lang_arAE.identifier: lang_arAE.self,
lang_as.identifier: lang_as.self,
lang_be.identifier: lang_be.self,
lang_bg.identifier: lang_bg.self,
lang_bn.identifier: lang_bn.self,
lang_br.identifier: lang_br.self,
lang_bs.identifier: lang_bs.self,
lang_bsCyrl.identifier: lang_bsCyrl.self,
lang_ca.identifier: lang_ca.self,
lang_cs.identifier: lang_cs.self,
lang_cy.identifier: lang_cy.self,
lang_da.identifier: lang_da.self,
lang_de.identifier: lang_de.self,
lang_dsb.identifier: lang_dsb.self,
lang_dz.identifier: lang_dz.self,
lang_ee.identifier: lang_ee.self,
lang_el.identifier: lang_el.self,
lang_es.identifier: lang_es.self,
lang_esAR.identifier: lang_esAR.self,
lang_esMX.identifier: lang_esMX.self,
lang_esPY.identifier: lang_esPY.self,
lang_esUS.identifier: lang_esUS.self,
lang_et.identifier: lang_et.self,
lang_eu.identifier: lang_eu.self,
lang_fa.identifier: lang_fa.self,
lang_fi.identifier: lang_fi.self,
lang_fil.identifier: lang_fil.self,
lang_fo.identifier: lang_fo.self,
lang_fr.identifier: lang_fr.self,
lang_frCA.identifier: lang_frCA.self,
lang_fur.identifier: lang_fur.self,
lang_fy.identifier: lang_fy.self,
lang_ga.identifier: lang_ga.self,
lang_gd.identifier: lang_gd.self,
lang_gl.identifier: lang_gl.self,
lang_gu.identifier: lang_gu.self,
lang_he.identifier: lang_he.self,
lang_hi.identifier: lang_hi.self,
lang_hr.identifier: lang_hr.self,
lang_hsb.identifier: lang_hsb.self,
lang_hu.identifier: lang_hu.self,
lang_hy.identifier: lang_hy.self,
lang_id.identifier: lang_id.self,
lang_is.identifier: lang_is.self,
lang_it.identifier: lang_it.self,
lang_ja.identifier: lang_ja.self,
lang_jgo.identifier: lang_jgo.self,
lang_ka.identifier: lang_ka.self,
lang_kea.identifier: lang_kea.self,
lang_kk.identifier: lang_kk.self,
lang_kl.identifier: lang_kl.self,
lang_km.identifier: lang_km.self,
lang_kn.identifier: lang_kn.self,
lang_ko.identifier: lang_ko.self,
lang_kok.identifier: lang_kok.self,
lang_ksh.identifier: lang_ksh.self,
lang_ky.identifier: lang_ky.self,
lang_lb.identifier: lang_lb.self,
lang_lkt.identifier: lang_lkt.self,
lang_lo.identifier: lang_lo.self,
lang_lt.identifier: lang_lt.self,
lang_lv.identifier: lang_lv.self,
lang_mk.identifier: lang_mk.self,
lang_ml.identifier: lang_ml.self,
lang_mn.identifier: lang_mn.self,
lang_mr.identifier: lang_mr.self,
lang_ms.identifier: lang_ms.self,
lang_mt.identifier: lang_mt.self,
lang_my.identifier: lang_my.self,
lang_mzn.identifier: lang_mzn.self,
lang_nb.identifier: lang_nb.self,
lang_ne.identifier: lang_ne.self,
lang_nl.identifier: lang_nl.self,
lang_nn.identifier: lang_nn.self,
lang_or.identifier: lang_or.self,
lang_pa.identifier: lang_pa.self,
lang_pl.identifier: lang_pl.self,
lang_ps.identifier: lang_ps.self,
lang_pt.identifier: lang_pt.self,
lang_ro.identifier: lang_ro.self,
lang_ru.identifier: lang_ru.self,
lang_sah.identifier: lang_sah.self,
lang_sd.identifier: lang_sd.self,
lang_seFI.identifier: lang_seFI.self,
lang_se.identifier: lang_se.self,
lang_si.identifier: lang_si.self,
lang_sk.identifier: lang_sk.self,
lang_sl.identifier: lang_sl.self,
lang_sq.identifier: lang_sq.self,
lang_srLatn.identifier: lang_srLatn.self,
lang_sv.identifier: lang_sv.self,
lang_sw.identifier: lang_sw.self,
lang_ta.identifier: lang_ta.self,
lang_te.identifier: lang_te.self,
lang_th.identifier: lang_th.self,
lang_ti.identifier: lang_ti.self,
lang_tk.identifier: lang_tk.self,
lang_to.identifier: lang_to.self,
lang_tr.identifier: lang_tr.self,
lang_ug.identifier: lang_ug.self,
lang_uk.identifier: lang_uk.self,
lang_urIN.identifier: lang_urIN.self,
lang_ur.identifier: lang_ur.self,
lang_uz.identifier: lang_uz.self,
lang_uzCyrl.identifier: lang_uzCyrl.self,
lang_vi.identifier: lang_vi.self,
lang_wae.identifier: lang_wae.self,
lang_yi.identifier: lang_yi.self,
lang_zh.identifier: lang_zh.self,
lang_zhHansHK.identifier: lang_zhHansHK.self,
lang_yueHans.identifier: lang_yueHans.self,
lang_yueHant.identifier: lang_yueHant.self,
lang_zhHansMO.identifier: lang_zhHansMO.self,
lang_zhHansSG.identifier: lang_zhHansSG.self,
lang_zhHantHK.identifier: lang_zhHantHK.self,
lang_zhHant.identifier: lang_zhHant.self,
lang_zu.identifier: lang_zu.self
]
/// Return all languages supported by the library for relative date formatting
public static var allLanguages: [RelativeFormatterLang.Type] {
return Array(RelativeFormatter.shared.languagesMap.values)
}
private init() {}
/// Add/replace a new language table.
///
/// - Parameter lang: language file type
public static func addLanguage(_ lang: RelativeFormatterLang.Type) {
self.shared.languagesMap[lang.identifier] = lang // replace or add
self.shared.languagesCache.removeValue(forKey: lang.identifier) // cleanup cache
}
/// Return the language table for a specified locale.
/// If not loaded yet a new instance of the table is loaded and cached.
///
/// - Parameter locale: locale to load
/// - Returns: language table
private func language(forLocale locale: Locale) -> RelativeFormatterLang {
let localeId = (locale.collatorIdentifier ?? Locales.english.toLocale().collatorIdentifier!)
guard let table = self.languagesCache[localeId] else {
guard let tableType = self.languagesMap[localeId] else {
return language(forLocale: Locales.english.toLocale())
}
let instanceOfTable = tableType.init()
self.languagesCache[localeId] = instanceOfTable
return instanceOfTable
}
return table
}
/// Implementation of the protocol for DateToStringTransformable.
public static func format(_ date: DateRepresentable, options: Any?) -> String {
let dateToFormat = (date as? DateInRegion ?? DateInRegion(date.date, region: SwiftDate.defaultRegion))
return RelativeFormatter.format(date: dateToFormat, style: (options as? Style), locale: date.region.locale)
}
/// Return relative formatted string result of comparison of two passed dates.
///
/// - Parameters:
/// - date: date to compare
/// - toDate: date to compare against for (if `nil` current date in the same region of `date` is used)
/// - style: style of the relative formatter.
/// - locale: locale to use; if not passed the `date`'s region locale is used.
/// - Returns: formatted string, empty string if formatting fails
public static func format(date: DateRepresentable, to toDate: DateRepresentable? = nil,
style: Style?, locale fixedLocale: Locale? = nil) -> String {
let refDate = (toDate ?? date.region.nowInThisRegion()) // a now() date is created if no reference is passed
let options = (style ?? RelativeFormatter.defaultStyle()) // default style if not used
let locale = (fixedLocale ?? date.region.locale) // date's locale is used if no value is forced
// how much time elapsed (in seconds)
let elapsed = (refDate.date.timeIntervalSince1970 - date.date.timeIntervalSince1970)
// get first suitable flavour for a given locale
let (flavour, localeData) = suitableFlavour(inList: options.flavours, forLocale: locale)
// get all units which can be represented by the locale data for required style
let allUnits = suitableUnits(inLocaleData: localeData, requiredUnits: options.allowedUnits)
guard allUnits.count > 0 else {
debugPrint("Required units in style were not found in locale spec. Returning empty string")
return ""
}
guard let suitableRule = ruleToRepresent(timeInterval: abs(elapsed),
referenceInterval: refDate.date.timeIntervalSince1970,
units: allUnits,
gradation: options.gradation) else {
// If no time unit is suitable, just output an empty string.
// E.g. when "now" unit is not available
// and "second" has a threshold of `0.5`
// (e.g. the "canonical" grading scale).
return ""
}
if let customFormat = suitableRule.customFormatter {
return customFormat(date)
}
var amount = (abs(elapsed) / suitableRule.unit.factor)
// Apply granularity to the time amount
// (and fallback to the previous step
// if the first level of granularity
// isn't met by this amount)
if let granularity = suitableRule.granularity {
// Recalculate the elapsed time amount based on granularity
amount = round(amount / granularity) * granularity
}
let value: Double = -1.0 * Double(elapsed.sign) * round(amount)
let formatString = relativeFormat(locale: locale, flavour: flavour, value: value, unit: suitableRule.unit)
return formatString.replacingOccurrences(of: "{0}", with: String(Int(abs(value))))
}
private static func relativeFormat(locale: Locale, flavour: Flavour, value: Double, unit: Unit) -> String {
let table = RelativeFormatter.shared.language(forLocale: locale)
guard let styleTable = table.flavours[flavour.rawValue] as? [String: Any] else {
return ""
}
if let fixedValue = styleTable[unit.rawValue] as? String {
return fixedValue
}
guard let unitRules = styleTable[unit.rawValue] as? [String: Any] else {
return ""
}
// Choose either "past" or "future" based on time `value` sign.
// If "past" is same as "future" then they're stored as "other".
// If there's only "other" then it's being collapsed.
let quantifierKey = (value <= 0 ? "past" : "future")
if let fixedValue = unitRules[quantifierKey] as? String {
return fixedValue
} else if let quantifierRules = unitRules[quantifierKey] as? [String: Any] {
// plurar/translations forms
// "other" rule is supposed to always be present.
// If only "other" rule is present then "rules" is not an object and is a string.
let quantifier = (table.quantifyKey(forValue: abs(value)) ?? .other).rawValue
return (quantifierRules[quantifier] as? String ?? "")
} else {
return ""
}
}
/// Return the first suitable flavour into the list which is available for a given locale.
///
/// - Parameters:
/// - flavours: ordered flavours.
/// - locale: locale to use.
/// - Returns: a pair of found flavor and locale table
private static func suitableFlavour(inList flavours: [Flavour], forLocale locale: Locale) -> (flavour: Flavour, locale: [String: Any]) {
let localeData = RelativeFormatter.shared.language(forLocale: locale) // get the locale table
for flavour in flavours {
if let flavourData = localeData.flavours[flavour.rawValue] as? [String: Any] {
return (flavour, flavourData) // found our required flavor in passed locale
}
}
// long must be always present
// swiftlint:disable force_cast
return (.long, localeData.flavours[Flavour.long.rawValue] as! [String: Any])
}
/// Return a list of available time units in locale filtered by required units of style.
/// If resulting array if empty there is not any time unit which can be rapresented with given locale
/// so formatting fails.
///
/// - Parameters:
/// - localeData: local table.
/// - styleUnits: required time units.
/// - Returns: available units.
private static func suitableUnits(inLocaleData localeData: [String: Any], requiredUnits styleUnits: [Unit]?) -> [Unit] {
let localeUnits: [Unit] = localeData.keys.compactMap { Unit(rawValue: $0) }
guard let restrictedStyleUnits = styleUnits else { return localeUnits } // no restrictions
return localeUnits.filter({ restrictedStyleUnits.contains($0) })
}
/// Return the best rule in gradation to represent given time interval.
///
/// - Parameters:
/// - elapsed: elapsed interval to represent
/// - referenceInterval: reference interval
/// - units: units
/// - gradation: gradation
/// - Returns: best rule to represent
private static func ruleToRepresent(timeInterval elapsed: TimeInterval, referenceInterval: TimeInterval, units: [Unit], gradation: Gradation) -> Gradation.Rule? {
// Leave only allowed time measurement units.
// E.g. omit "quarter" unit.
let filteredGradation = gradation.filtered(byUnits: units)
// If no steps of gradation fit the conditions
// then return nothing.
guard gradation.count > 0 else {
return nil
}
// Find the most appropriate gradation step
let i = findGradationStep(elapsed: elapsed, now: referenceInterval, gradation: filteredGradation)
let step = filteredGradation[i]!
// Apply granularity to the time amount
// (and fall back to the previous step
// if the first level of granularity
// isn't met by this amount)
if let granurality = step.granularity {
// Recalculate the elapsed time amount based on granularity
let amount = round( (elapsed / step.unit.factor) / granurality) * granurality
// If the granularity for this step
// is too high, then fallback
// to the previous step of gradation.
// (if there is any previous step of gradation)
if amount == 0 && i > 0 {
return filteredGradation[i - 1]
}
}
return step
}
private static func findGradationStep(elapsed: TimeInterval, now: TimeInterval, gradation: Gradation, step: Int = 0) -> Int {
// If the threshold for moving from previous step
// to this step is too high then return the previous step.
let fromGradation = gradation[step - 1]
let currentGradation = gradation[step]!
let thresholdValue = threshold(from: fromGradation, to: currentGradation, now: now)
if let t = thresholdValue, elapsed < t {
return step - 1
}
// If it's the last step of gradation then return it.
if step == (gradation.count - 1) {
return step
}
// Move to the next step.
return findGradationStep(elapsed: elapsed, now: now, gradation: gradation, step: step + 1)
}
/// Evaluate threshold.
private static func threshold(from fromRule: Gradation.Rule?, to toRule: Gradation.Rule, now: TimeInterval) -> Double? {
var threshold: Double? = nil
// Allows custom thresholds when moving
// from a specific step to a specific step.
if let fromStepUnit = fromRule?.unit {
threshold = toRule.thresholdPrevious?[fromStepUnit]
}
// If no custom threshold is set for this transition
// then use the usual threshold for the next step.
if threshold == nil {
threshold = toRule.threshold?.evaluateForTimeInterval(now)
}
return threshold
}
}
| 38.779221 | 163 | 0.736169 |
6a7b36825c2c0534966006b011ed863145f85d21
| 558 |
//
// Event.swift
// TravelPlanner
//
// Created by Junwei Liang on 5/14/19.
// Copyright © 2019 Junwei Liang. All rights reserved.
//
import UIKit
//event class
class Event: Codable {
let description: String
let location: String
let time: String
let cost: Double
var check: Bool
init(description: String, location: String, time: String, cost: Double, check: Bool) {
self.description = description
self.location = location
self.time = time
self.cost = cost
self.check = check
}
}
| 21.461538 | 90 | 0.630824 |
871fdff9f2181f02296663bb986a60de609e765c
| 706 |
//
// Copyright © 2020 Essential Developer. All rights reserved.
//
import UIKit
extension UIView {
public func makeContainer() -> UIView {
let container = UIView()
container.backgroundColor = .clear
container.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: container.leadingAnchor),
container.trailingAnchor.constraint(equalTo: trailingAnchor),
topAnchor.constraint(equalTo: container.topAnchor),
container.bottomAnchor.constraint(equalTo: bottomAnchor),
])
return container
}
}
| 27.153846 | 73 | 0.651558 |
3af73916e9890cd5bd408e9d6b79a61502cdee5f
| 2,197 |
//
// MatchMatchAppDelegate.swift
// MatchMatch
//
// Created by Park, Chanick on 5/23/17.
// Copyright © 2017 Chanick Park. All rights reserved.
//
import UIKit
@UIApplicationMain
class MatchMatchAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.744681 | 285 | 0.756941 |
8a19b60866d01debbc0e5c3e0d38ab811560652e
| 826 |
# https://www.hackerrank.com/challenges/30-generics/problem
#
# Written in Swift because Python wasn't supported.
import Foundation
struct Printer<T> {
/**
* Name: printArray
* Print each element of the generic array on a new line. Do not return anything.
* @param A generic array
**/
// Write your code here
func printArray(array: [Any]) {
for a in array {
print(a)
}
}
}
var n = Int(readLine()!)!
var intArray = Array(repeating: 0, count: n);
for i in 0...n - 1 {
intArray[i] = Int(readLine()!)!;
}
n = Int(readLine()!)!
var stringArray = Array(repeating: "", count: n);
for i in 0...n - 1 {
stringArray[i] = readLine()!;
}
Printer<Int>().printArray(array: intArray)
Printer<String>().printArray(array: stringArray)
| 22.944444 | 90 | 0.595642 |
cc8c6b1d01a1bcb882a4582d73a274dc756ccf05
| 832 |
//
// FetchUser.swift
// NetworkRequestExample
//
// Created by David on 2017/7/4.
//
//
import Foundation
import NetworkRequestKit
import SwiftyJSON
import Alamofire
import PromiseKit
final public class FetchUser : NetworkRequest {
public typealias ResponseType = User
// I use httpbin here, check httpbin for futher information
// For normal usage, this is the endpoint that your request is going.
public var endpoint: String { return "/post" }
public var method: HTTPMethod { return .post }
// parameter here is passed to httpbin, then will be return by httpbin.
public var parameters: [String : Any]? {
return ["username": "1", "age": "100", "height": "100.1"]
}
public func perform() -> Promise<ResponseType> {
return networkClient.performRequest(self).then(responseHandler)
}
}
| 24.470588 | 73 | 0.705529 |
dde82d317f27bd54d466cc2a0babe34d07cf9b4f
| 25,178 |
//
// CodeLine.swift
// Cubeling
//
// Created by Heiko Etzold on 21.07.20.
// MIT License
//
import UIKit
class CodeLine: UIView, UIGestureRecognizerDelegate, UIPointerInteractionDelegate {
var lineNumber = Int(0)
var loopDepth = Int(0)
var setOfFixedCodeLines : Set<CodeLine> = []
var numberOfFixedLinesBelow = Int(0)
var contentView = UIView()
var label = UILabel()
let handleView = UIView(frame: CGRect(x: 300, y: 0, width: 40, height: codeLineHeight))
let deleteView = UIView(frame: CGRect(x: 300, y: 0, width: 40, height: codeLineHeight))
var numberOfValues = Int(0)
var listOfStrings : [NSMutableAttributedString] = []
var listOfValues : [NumberValueBox] = []
var emptyLineNumber = Int(0)
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if(gestureRecognizer is UISwipeGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer){
return true
}
return false
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@available(iOS 13.4, *)
func pointerInteraction(_ interaction: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? {
var pointerStyle: UIPointerStyle? = nil
if let interactionView = interaction.view {
let targetedPreview = UITargetedPreview(view: interactionView)
pointerStyle = UIPointerStyle(effect: UIPointerEffect.automatic(targetedPreview))
}
return pointerStyle
}
init(lineNumber: Int) {
super.init(frame: .zero)
self.frame.origin = displayPositionByLineNumber(codeView.insertLineNumber, depth: loopDepth)
self.lineNumber = lineNumber
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panCodeLine))
panRecognizer.delegate = self
if #available(iOS 13.4, *) {
panRecognizer.allowedScrollTypesMask = .continuous
}
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressCodeLine))
longPressRecognizer.delegate = self
longPressRecognizer.minimumPressDuration = 0.25
let leftSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(leftSwipeCodeLine))
leftSwipeRecognizer.direction = .left
leftSwipeRecognizer.delegate = self
let rightSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(rightSwipeCodeLine))
rightSwipeRecognizer.direction = .right
rightSwipeRecognizer.delegate = self
self.addSubview(contentView)
handleView.addGestureRecognizer(panRecognizer)
handleView.addGestureRecognizer(longPressRecognizer)
if #available(iOS 13.4, *) {
let pointerInteraction = UIPointerInteraction(delegate: self)
handleView.addInteraction(pointerInteraction)
}
self.addGestureRecognizer(leftSwipeRecognizer)
self.addGestureRecognizer(rightSwipeRecognizer)
setOfFixedCodeLines.insert(self)
self.frame.size.height = codeLineHeight+5
self.frame.size.width = codeLineWidth
self.backgroundColor = systemBackgroundColor.withAlphaComponent(0.8)
contentView.backgroundColor = .clear
contentView.isUserInteractionEnabled = false
setSpecialContent()
//Codezeilen-Texlabel
label.frame = CGRect(x: codeView.widthOfLineNumbers+CGFloat(loopDepth)*20+leftLabelOffset, y: 0, width: codeLineWidth-leftLabelOffset, height: codeLineHeight)
label.font = UIFont(name: "Menlo", size: characterSize)
contentView.addSubview(label)
//Erzeuge Text- und Variablenliste
setNumberOfValues()
let string = NSMutableAttributedString(string: "")
for _ in 0 ..< numberOfValues{
listOfStrings += [string]
let value = NumberValueBox(codeLine: self, initValue: Int(0))
listOfValues += [value]
self.addSubview(value)
}
listOfStrings += [string]
//Passe entsprechend des Codezeilentyps an
setCodeLineContent()
renewCodeLine()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setNumberOfValues(){
}
func setCodeLineContent(){
}
func setSpecialValue(){
}
func changeColorOfLineLabel(){
}
func setSpecialContent(){
self.addSubview(handleView)
handleView.translatesAutoresizingMaskIntoConstraints = false
handleView.widthAnchor.constraint(equalToConstant: 40).isActive = true
handleView.heightAnchor.constraint(equalToConstant: codeLineHeight).isActive = true
handleView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
handleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
for i in -1...1{
let lineView = UIView(frame: CGRect(x: 10, y: handleView.frame.height/2+CGFloat(i)*5-1, width: 20, height: 2))
lineView.backgroundColor = opaqueSeparatorColor
lineView.layer.cornerRadius = 1
handleView.addSubview(lineView)
}
self.addSubview(deleteView)
deleteView.translatesAutoresizingMaskIntoConstraints = false
deleteView.widthAnchor.constraint(equalTo: handleView.widthAnchor).isActive = true
deleteView.heightAnchor.constraint(equalTo: handleView.heightAnchor).isActive = true
deleteView.leftAnchor.constraint(equalTo: handleView.rightAnchor).isActive = true
deleteView.topAnchor.constraint(equalTo: handleView.topAnchor).isActive = true
deleteView.backgroundColor = .systemRed
deleteView.frame.origin.x = codeView.codeLinesView.frame.width//-deleteView.frame.width
let deleteButton = UIButton(type: .system)
if #available(iOS 13.0, *) {
deleteButton.setImage(UIImage(systemName: "trash"), for: .normal)
} else {
}
deleteButton.addTarget(self, action: #selector(removeCodeLine), for: .touchUpInside)
deleteButton.tintColor = secondaryBackgroundColor
deleteButton.sizeToFit()
deleteButton.center = CGPoint(x: deleteView.frame.width/2, y: deleteView.frame.height/2)
deleteView.addSubview(deleteButton)
}
override func layoutSubviews() {
renewShape()
}
func renewShape(){
codeView.codeLinesView.layoutIfNeeded()
contentView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: CGFloat(setOfFixedCodeLines.count)*codeLineHeight+5)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path().cgPath
let maskLayer = CAShapeLayer()
maskLayer.frame = contentView.bounds
maskLayer.path = path().cgPath
contentView.layer.mask = maskLayer
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
line.superview?.bringSubviewToFront(line)
}
}
func renewCodeLine(){
//Text
let text = NSMutableAttributedString()
for i in 0 ..< listOfStrings.count-1{
//Text bis zur i-ten Valuebox
text.append(listOfStrings[i])
//passe Valuebox an
listOfValues[i].renewPosition(textBeforeBox: text)
//Inhalt der i-ten Valuebox
if(listOfValues[i].value == 0){
if(listOfValues[i].isActive){
switch (listOfValues[i].signumIsMinus,listOfValues[i].valueIsSet){
case (false,false):
text.append(NSMutableAttributedString(string: " "))
case (true,false):
text.append(NSMutableAttributedString(string: "-"))
default:
text.append(NSMutableAttributedString(string: "0"))
}
}
else{
if(listOfValues[i].valueIsSet){
text.append(NSMutableAttributedString(string: "0"))
}
else{
text.append(NSMutableAttributedString(string: "?"))
}
}
}
else{
if(listOfValues[i] is StringValueBox){
text.append(NSMutableAttributedString(string: "\(NSLocalizedString("CodePositionText",comment:"position"))\(alphabet[listOfValues[i].value])"))
}
else{
text.append(NSMutableAttributedString(string: "\(listOfValues[i].value)"))
}
}
}
//restlicher Text
text.append(listOfStrings.last!)
label.attributedText = text
changeColorOfLineLabel()
renewShape()
label.frame.origin.x = codeView.widthOfLineNumbers+CGFloat(loopDepth)*20+leftLabelOffset
}
var topConstraint = NSLayoutConstraint()
func path() -> UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: CGFloat(setOfFixedCodeLines.count)*codeLineHeight))
path.addLine(to: CGPoint(x: 0, y: CGFloat(setOfFixedCodeLines.count)*codeLineHeight))
path.close()
return path
}
func insertShadow(){
UIView.animate(withDuration: 0.2, animations: {
for line in setOfCodeLines{
line.hideDeleteButton()
}
})
removeShadow()
codeView.insertCodeLineNumberIndicator.alpha = 0
let shadowLayer = CAShapeLayer()
shadowLayer.path = path().cgPath
shadowLayer.frame = contentView.bounds
shadowLayer.shadowOpacity = 0.8
shadowLayer.shadowRadius = 8
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0, height: 0)
let maskLayer = CAShapeLayer()
let bigPath = UIBezierPath(rect: CGRect(x: -20, y: -20, width: contentView.frame.width+40, height: contentView.frame.height+40))
bigPath.append(path())
maskLayer.path = bigPath.cgPath
maskLayer.fillRule = .evenOdd
shadowLayer.mask = maskLayer
self.layer.insertSublayer(shadowLayer, at: 0)
}
func removeShadow(){
if let subLayers = self.layer.sublayers?.filter({$0 is CAShapeLayer}){
for subLayer in subLayers{
subLayer.removeFromSuperlayer()
}
}
codeView.insertCodeLineNumberIndicator.alpha = 1
}
@objc func longPressCodeLine(sender: UILongPressGestureRecognizer){
if(sender.state == .began){
var exeptLineNumbers : [Int] = []
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
line.superview?.bringSubviewToFront(line)
exeptLineNumbers.append(line.lineNumber)
}
exeptLineNumbers.removeLast()
insertShadow()
}
if(sender.state == .ended){
removeShadow()
codeView.strokesBetweenCodeLinesView.clearLines()
}
}
@objc func panCodeLine(sender: UIPanGestureRecognizer){
//save lines that must not be moved
if(sender.state == .began){
var exceptLineNumbers : [Int] = []
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
line.superview?.bringSubviewToFront(line)
exceptLineNumbers.append(line.lineNumber)
}
exceptLineNumbers.removeLast()
insertShadow()
emptyLineNumber = lineNumber
}
//move current line and connected fixed lines
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
if(sender.state == .began){
line.superview?.bringSubviewToFront(line)
}
line.frame.origin.y += sender.translation(in: self).y
if(codeView.scrollView.contentSize.height > codeView.scrollView.frame.height){
codeView.scrollView.contentOffset.y += sender.translation(in: self).y
}
}
//rearrange line when it is upper than first line
if(self.frame.origin.y < -codeLineHeight/2){
var i = 0
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
line.frame.origin.y = -codeLineHeight/2+CGFloat(i)*codeLineHeight
i+=1
}
}
//rearrange line when it is downer than last line
if(setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}).last!.frame.origin.y > CGFloat(setOfCodeLines.count-1)*codeLineHeight+codeLineHeight/2){
var i = -1
for line in setOfFixedCodeLines.sorted(by: {$0.lineNumber > $1.lineNumber}){
line.frame.origin.y = codeLineHeight/2+CGFloat(setOfCodeLines.count+i)*codeLineHeight
i-=1
}
}
//when line is moving up
if(sender.translation(in: self).y < 0){
//reduce line number of up moved lines, when half of upper line is reached (with condition not to be smaller than line 1)
if(lineNumberByDisplayPosition(self.frame.origin.y-codeLineHeight/2) <= lineNumber && lineNumberByDisplayPosition(self.frame.origin.y-codeLineHeight/2)>=1){
if(!(self is CodeLineLoopStart && self.lineNumber == 1)){
for line in setOfFixedCodeLines{
line.lineNumber = lineNumberByDisplayPosition(line.frame.origin.y+codeLineHeight/2)
line.topConstraint.constant = line.frame.origin.y
}
}
}
}
//when line is moving down
if(sender.translation(in: self).y > 0){
//when line is moves down more than a half line height (with condition not to be downer then last line)
if(lineNumberByDisplayPosition(self.frame.origin.y+codeLineHeight/2) >= lineNumber && lineNumberByDisplayPosition(self.frame.origin.y+codeLineHeight/2)+numberOfFixedLinesBelow <= setOfCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}).last!.lineNumber){
//enlarge line number for current line and connected fixed lines
for line in setOfFixedCodeLines{
line.lineNumber = lineNumberByDisplayPosition(line.frame.origin.y+codeLineHeight/2)
}
//recalc loop depths
for line in setOfFixedCodeLines{
line.loopDepth = setOfCodeLines.filter({$0.lineNumber < line.lineNumber && $0 is CodeLineLoopStart}).count-setOfCodeLines.filter({$0.lineNumber <= line.lineNumber && $0 is CodeLineLoopEnd}).count
line.topConstraint.constant = line.frame.origin.y
}
}
}
//when line was moved up, change other lines
if(emptyLineNumber > lineNumber){
for line in setOfCodeLines.filter({!setOfFixedCodeLines.contains($0) && lineNumber <= $0.lineNumber && $0.lineNumber < emptyLineNumber}).sorted(by: {$0.lineNumber > $1.lineNumber}){
line.lineNumber += 1+numberOfFixedLinesBelow
// line.label.text = "\(line.lineNumber)"
emptyLineNumber -= 1
var exeptLineNumbers : [Int] = []
for fixedLine in self.setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
exeptLineNumbers.append(fixedLine.lineNumber)
}
line.topConstraint.constant = displayPositionByLineNumber(line.lineNumber, depth: line.loopDepth).y
UIView.animate(withDuration: 0.2, animations: {
codeView.codeLinesView.layoutIfNeeded()
//das lässt die aktuelle Zeile irgendwie zuckeln
}, completion: {(_: Bool) in
var exeptLineNumbers : [Int] = []
for fixedLine in self.setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
exeptLineNumbers.append(fixedLine.lineNumber)
}
exeptLineNumbers.removeLast()
})
for anyLine in setOfCodeLines{
anyLine.loopDepth = setOfCodeLines.filter({$0.lineNumber < anyLine.lineNumber && $0 is CodeLineLoopStart}).count-setOfCodeLines.filter({$0.lineNumber <= anyLine.lineNumber && $0 is CodeLineLoopEnd}).count
}
for fixedLine in setOfFixedCodeLines{
fixedLine.renewCodeLine()
}
self.insertShadow()
}
}
//when line finally was moved down, change other lines
if(emptyLineNumber < lineNumber){
//look for lines previously lying directly under current line (or connected fixed lines)
for line in setOfCodeLines.filter({!setOfFixedCodeLines.contains($0)}).sorted(by: {$0.lineNumber < $1.lineNumber}).filter({lineNumber+numberOfFixedLinesBelow >= $0.lineNumber && $0.lineNumber > emptyLineNumber+numberOfFixedLinesBelow }){
//move other line up
line.lineNumber -= 1+numberOfFixedLinesBelow
emptyLineNumber += 1
var exceptLineNumbers : [Int] = []
for fixedLine in self.setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
exceptLineNumbers.append(fixedLine.lineNumber)
}
exceptLineNumbers.removeLast()
exceptLineNumbers.append(lineNumber-1)
line.topConstraint.constant = displayPositionByLineNumber(line.lineNumber, depth: line.loopDepth).y
UIView.animate(withDuration: 0.2, animations: {
codeView.codeLinesView.layoutIfNeeded()
}, completion: {(_: Bool) in
var exceptLineNumbers : [Int] = []
for fixedLine in self.setOfFixedCodeLines.sorted(by: {$0.lineNumber < $1.lineNumber}){
exceptLineNumbers.append(fixedLine.lineNumber)
}
exceptLineNumbers.removeLast()
})
for anyLine in setOfCodeLines{
anyLine.loopDepth = setOfCodeLines.filter({$0.lineNumber < anyLine.lineNumber && $0 is CodeLineLoopStart}).count-setOfCodeLines.filter({$0.lineNumber <= anyLine.lineNumber && $0 is CodeLineLoopEnd}).count
}
for fixedLine in self.setOfFixedCodeLines{
fixedLine.renewCodeLine()
}
self.insertShadow()
}
}
//set moved line to final position
if(sender.state == .ended){
for line in setOfCodeLines.filter({$0 is CodeLineLoopStart}).sorted(by: {$0.lineNumber < $1.lineNumber}){
line.numberOfFixedLinesBelow = (line as! CodeLineLoopStart).connectedEndLine.lineNumber-line.lineNumber
for otherLine in setOfCodeLines{
if(line.lineNumber <= otherLine.lineNumber && otherLine.lineNumber <= (line as! CodeLineLoopStart).connectedEndLine.lineNumber){
line.setOfFixedCodeLines.insert(otherLine)
}
else{
line.setOfFixedCodeLines.remove(otherLine)
}
}
line.topConstraint.constant = displayPositionByLineNumber(line.lineNumber, depth: line.loopDepth).y
codeView.codeLinesView.layoutIfNeeded()
line.renewCodeLine()
}
for line in setOfFixedCodeLines{
line.topConstraint.constant = displayPositionByLineNumber(line.lineNumber, depth: line.loopDepth).y
UIView.animate(withDuration: 0.1, animations: {
codeView.codeLinesView.layoutIfNeeded()
}, completion: {(_: Bool) in
self.removeShadow()
line.renewCodeLine()
})
}
codeView.showAllCubes()
}
//reset translation
sender.setTranslation(.zero, in: self)
}
@objc func leftSwipeCodeLine(sender: UISwipeGestureRecognizer){
for line in setOfCodeLines{
line.hideDeleteButton()
}
UIView.animate(withDuration: 0.2, animations: {
self.deleteView.frame.origin.x = codeView.codeLinesView.frame.width-self.deleteView.frame.width
self.backgroundColor = secondaryBackgroundColor
if(self is CodeLineLoopStart){
for line in self.setOfFixedCodeLines{
line.backgroundColor = secondaryBackgroundColor
}
}
})
}
@objc func rightSwipeCodeLine(sender: UISwipeGestureRecognizer){
hideDeleteButton()
}
func hideDeleteButton(){
UIView.animate(withDuration: 0.2, animations: {
self.deleteView.frame.origin.x = codeView.codeLinesView.frame.width
self.backgroundColor = systemBackgroundColor.withAlphaComponent(0.8)
if(self is CodeLineLoopStart){
for line in self.setOfFixedCodeLines{
if(line.deleteView.frame.origin.x == codeView.codeLinesView.frame.width){
line.backgroundColor = systemBackgroundColor.withAlphaComponent(0.8)
}
}
}
})
}
@objc func removeCodeLine(sender: UIButton){
for fixedLine in self.setOfFixedCodeLines{
setOfCodeLines.remove(fixedLine)
fixedLine.removeFromSuperview()
}
for line in setOfCodeLines{
for fixedLine in self.setOfFixedCodeLines{
line.setOfFixedCodeLines.remove(fixedLine)
}
}
codeView.updateLineNumbers()
for line in setOfCodeLines.filter({$0.lineNumber > self.lineNumber}){
line.lineNumber -= self.setOfFixedCodeLines.count
line.topConstraint.constant = displayPositionByLineNumber(line.lineNumber, depth: line.loopDepth).y
UIView.animate(withDuration: 0.2, animations: {
codeView.codeLinesView.layoutIfNeeded()
})
}
if(codeView.insertLineNumber > self.lineNumber+self.setOfFixedCodeLines.count){
codeView.insertLineNumber -= self.setOfFixedCodeLines.count
UIView.animate(withDuration: 0.2, animations: {
codeView.insertCodeLineNumberIndicator.center.y = displayPositionByLineNumber(codeView.insertLineNumber, depth: 0).y
if(codeView.insertLineNumber == 1){
codeView.insertCodeLineNumberIndicator.center.y = displayPositionByLineNumber(codeView.insertLineNumber, depth: 0).y+5
}
})
}
else if(codeView.insertLineNumber > self.lineNumber){
codeView.insertLineNumber = self.lineNumber
UIView.animate(withDuration: 0.2, animations: {
codeView.insertCodeLineNumberIndicator.center.y = displayPositionByLineNumber(codeView.insertLineNumber, depth: 0).y
if(codeView.insertLineNumber == 1){
codeView.insertCodeLineNumberIndicator.center.y = displayPositionByLineNumber(codeView.insertLineNumber, depth: 0).y+5
}
})
}
codeView.renewTextViewContentHeight()
codeView.showAllCubes()
}
}
| 39.46395 | 268 | 0.588609 |
e53e9793a76a6b2af8d0e8916a1e505d162fec02
| 3,338 |
//
// LandmarkList.swift
// LandmarksSwiftUI
//
// Created by Adem Deliaslan on 28.03.2022.
//
import SwiftUI
struct LandmarkList: View {
@EnvironmentObject var modelData: ModelData
@State private var showFavoritesOnly = false
@State private var filter = FilterCategory.all
@State private var selectedLandmark: LandMark?
enum FilterCategory: String, CaseIterable, Identifiable {
case all = "All"
case lakes = "Lakes"
case rivers = "Rivers"
case mountains = "Mountains"
var id: FilterCategory { self }
}
var filteredLandMarks: [LandMark] {
modelData.landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite)
&& (filter == .all || filter.rawValue == landmark.category.rawValue)
}
}
var title: String {
let title = filter == .all ? "Landmarks" : filter.rawValue
return showFavoritesOnly ? "Favorite \(title)" : title
}
var index: Int? {
modelData.landmarks.firstIndex(where: { $0.id == selectedLandmark?.id })
}
var body: some View {
NavigationView{
// List(landmarks, id: \.id) { landmark in
List(selection: $selectedLandmark) {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites Only")
.font(.headline)
}
ForEach(filteredLandMarks) { landmark in
NavigationLink{
LandmarkDetail(landmark: landmark)
} label: {
LandmarkRow(landmark: landmark)
// LandmarkRow(landmark: landmarks[0])
// LandmarkRow(landmark: landmarks[1])
}
.tag(landmark)
}
}
.navigationTitle(title)
.frame(minWidth: 300)
#if !os(watchOS)
.toolbar {
ToolbarItem {
Menu {
Picker("Category", selection: $filter) {
ForEach(FilterCategory.allCases) { category in
Text(category.rawValue).tag(category)
}
}
.pickerStyle(.inline)
Toggle(isOn: $showFavoritesOnly) {
Label("Favorites only", systemImage: "star.fill")
}
} label: {
Label("Filter", systemImage: "slider.horizontal.3")
}
}
}
#endif
Text("Select a Landmark")
}
.focusedValue(\.selectedLandmark, $modelData.landmarks[index ?? 0])
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
// ForEach(["iPhone 12 Pro", "iPhone SE (3rd generation)"], id: \.self) { deviceName in
LandmarkList()
.environmentObject(ModelData())
// .previewDevice(PreviewDevice(rawValue: deviceName))
// .previewDisplayName(deviceName)
// }
}
}
| 32.72549 | 94 | 0.482924 |
bbc42e0dfa5ea21b8a6eff6234ffac308fa29673
| 308 |
//
// EmailRes.swift
// Pandora
//
// Created by 申铭 on 2021/3/25.
//
import HandyJSON
class EmailRes: HandyJSON {
var status: String?
var data: Array<Email>?
required init() {}
}
class Email: HandyJSON {
var id: String?
var emailAddress: String?
required init() {}
}
| 12.833333 | 31 | 0.597403 |
e66bfc60861158ac434d51e414b967df980cf8a8
| 2,798 |
// 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 SPSafeSymbol {
public static var chart: Chart { .init(name: "chart") }
open class Chart: SPSafeSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var bar: SPSafeSymbol { ext(.start + ".bar") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var barDocHorizontal: SPSafeSymbol { ext(.start + ".bar.doc.horizontal") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var barDocHorizontalFill: SPSafeSymbol { ext(.start + ".bar.doc.horizontal".fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var barFill: SPSafeSymbol { ext(.start + ".bar".fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var barXaxis: SPSafeSymbol { ext(.start + ".bar.xaxis") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var lineUptrendXyaxis: SPSafeSymbol { ext(.start + ".line.uptrend.xyaxis") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var lineUptrendXyaxisCircle: SPSafeSymbol { ext(.start + ".line.uptrend.xyaxis".circle) }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var lineUptrendXyaxisCircleFill: SPSafeSymbol { ext(.start + ".line.uptrend.xyaxis".circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var pie: SPSafeSymbol { ext(.start + ".pie") }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var pieFill: SPSafeSymbol { ext(.start + ".pie".fill) }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var xyaxisLine: SPSafeSymbol { ext(.start + ".xyaxis.line") }
}
}
| 50.872727 | 105 | 0.708006 |
dd22ee1a42d9fe8c29359d9d3dfe93c272240797
| 5,118 |
//
// coherent-swift
//
// Created by Arthur Alves on 26/05/2020.
//
import Foundation
import SwiftSyntax
typealias FactoryDefinitionResponse = ((_ name: String, _ definition: inout CSDefinition) -> Void)
typealias FactoryMethodResponse = ((inout CSMethod) -> Void)
public class CSFactory {
public init() {}
func process(definition: CSDefinition,
withMembers members: MemberDeclListSyntax,
completion: @escaping FactoryDefinitionResponse) {
var localDefinition = definition
var reportProperties: [CSProperty] = []
let properties = members.filter { $0.decl.is(VariableDeclSyntax.self) }
properties.forEach { (property) in
let props = processProperties(property.tokens)
reportProperties.append(contentsOf: props)
}
localDefinition.properties = reportProperties
completion(localDefinition.name, &localDefinition)
}
func process(node: FunctionDeclSyntax, completion: @escaping FactoryMethodResponse) {
var name = node.identifier.description+node.signature.description
name = Cleaner.shared.methodName(name)
var method = CSMethod(name: name)
node.modifiers?.tokens.forEach { (item) in
switch item.tokenKind {
case .privateKeyword, .fileprivateKeyword:
method.methodType = .Private
case .internalKeyword:
method.methodType = .Internal
case .staticKeyword:
method.methodType = .Static
default:
break
}
}
guard let body = node.body else {
method.cohesion = "0.00"
return completion(&method)
}
let properties = body.statements.filter { $0.item.is(VariableDeclSyntax.self) }
properties.forEach { (property) in
let props = processProperties(property.tokens)
method.properties.append(contentsOf: props)
}
method.contentString = body.description
completion(&method)
}
func mapExtensions(_ extensions: ParsingDefition, to highLevelDefinitions: ParsingDefition) -> ParsingDefition {
var finalDefinitions: ParsingDefition = highLevelDefinitions
extensions.forEach { (key, value) in
var definition = value
if var existingDefinition = highLevelDefinitions[key] {
definition.methods.mutateEach { (method) in
let cohesion = Measurer.shared.generateCohesion(for: method, withinDefinition: existingDefinition)
method.cohesion = cohesion.formattedCohesion()
existingDefinition.methods.append(method)
}
definition = existingDefinition
}
finalDefinitions[definition.name] = definition
}
finalDefinitions.forEach { (key, value) in
finalDefinitions[key] = processCohesion(for: value)
}
return finalDefinitions
}
// MARK: - Private
private func processProperties(_ tokens: TokenSequence, defaultType: CSPropertyType = .Instance) -> [CSProperty] {
var properties: [CSProperty] = []
if tokens.contains(where: { (syntax) -> Bool in
syntax.tokenKind == .letKeyword
|| syntax.tokenKind == .varKeyword
}) {
var keyword = ""
var propertyName = ""
var type = defaultType
tokens.forEach { (item) in
switch item.tokenKind {
case .identifier(let name) where !["IBOutlet", "weak"].contains(where: { $0.contains(name) }):
propertyName = propertyName.isEmpty ? name : propertyName
case .letKeyword:
keyword = "let"
case .varKeyword:
keyword = "var"
case .staticKeyword:
type = .Static
case .privateKeyword:
type = .Private
default:
break
}
}
if !keyword.isEmpty, !propertyName.isEmpty {
properties.append(CSProperty(keyword: keyword,
name: propertyName,
propertyType: type))
}
}
return properties
}
private func processCohesion(for definition: CSDefinition) -> CSDefinition {
var cohesion: Double = 0
var definition = definition
if !definition.methods.isEmpty {
cohesion = Measurer.shared.generateCohesion(for: definition)
} else {
/*
* if a definition doesn't contain properties nor methods, its
* still considered as highly cohesive
*/
cohesion = 100
}
definition.cohesion = cohesion.formattedCohesion()
return definition
}
}
| 36.297872 | 118 | 0.563501 |
e018a8c3143dc375931683674a72a34ca8dfc03f
| 27,984 |
// Copyright (c) 2020, OpenEmu Team
//
// 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 the OpenEmu Team 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 OpenEmu Team ''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 OpenEmu Team 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 OpenEmuSystem
final class GameScannerViewController: NSViewController {
@objc public static let OEGameScannerToggleNotification = Notification.Name("OEGameScannerToggleNotification")
private static let importGuideURL = URL(string: "https://github.com/OpenEmu/OpenEmu/wiki/User-guide:-Importing")!
@IBOutlet weak var scannerView: NSView!
@IBOutlet var headlineLabel: NSTextField!
@IBOutlet var togglePauseButton: GameScannerButton!
@IBOutlet var progressIndicator: NSProgressIndicator!
@IBOutlet var statusLabel: NSTextField!
@IBOutlet var fixButton: TextButton!
@IBOutlet var issuesView: NSTableView!
@IBOutlet var actionPopUpButton: NSPopUpButton!
@IBOutlet var applyButton: NSButton!
@IBOutlet private weak var sourceListScrollView: NSScrollView!
private var itemsRequiringAttention = [OEImportOperation]()
private var itemsFailedImport = [OEImportOperation]()
private var isScanningDirectory = false
private var isGameScannerVisible = true // The game scanner view is already visible in SidebarController.xib.
private var importer: ROMImporter { return OELibraryDatabase.default!.importer }
required init?(coder: NSCoder) {
super.init(coder: coder)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(gameInfoHelperWillUpdate(_:)), name: .GameInfoHelperWillUpdate, object: nil)
notificationCenter.addObserver(self, selector: #selector(gameInfoHelperDidChangeUpdateProgress(_:)), name: .GameInfoHelperDidChangeUpdateProgress, object: nil)
notificationCenter.addObserver(self, selector: #selector(gameInfoHelperDidUpdate(_:)), name: .GameInfoHelperDidUpdate, object: nil)
notificationCenter.addObserver(self, selector: #selector(toggleGameScannerView), name: GameScannerViewController.OEGameScannerToggleNotification, object: nil)
}
override var nibName: NSNib.Name? { "GameScanner" }
override func awakeFromNib() {
super.awakeFromNib()
_ = view // load other xib as well
guard let issuesView = issuesView else { return }
setUpActionsMenu()
var item: NSMenuItem!
let menu = NSMenu()
item = NSMenuItem(title: NSLocalizedString("Select All", comment: ""), action: #selector(selectAll(_:)), keyEquivalent: "")
item.target = self
menu.addItem(item)
item = NSMenuItem(title: NSLocalizedString("Deselect All", comment: ""), action: #selector(deselectAll(_:)), keyEquivalent: "")
item.target = self
menu.addItem(item)
issuesView.menu = menu
statusLabel.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
fixButton.font = .monospacedDigitSystemFont(ofSize: 11, weight: .bold)
layOutSidebarViews(withVisibleGameScanner: false, animated: false)
itemsRequiringAttention = []
importer.delegate = self
// Show game scanner if importer is running already or game info is downloading.
if importer.status == .running || OpenVGDB.shared.isUpdating {
updateProgress()
showGameScannerView(animated: true)
}
}
override func viewWillAppear() {
super.viewWillAppear()
var styleMask = self.view.window!.styleMask
styleMask.remove(.resizable)
self.view.window!.styleMask = styleMask
issuesView.reloadData()
enableOrDisableApplyButton()
}
private func setUpActionsMenu() {
let systemIDs = Set(itemsRequiringAttention.flatMap { $0.systemIdentifiers })
let menu = NSMenu()
let context = OELibraryDatabase.default!.mainThreadContext
let menuItems: [NSMenuItem] = systemIDs.map { systemID in
let system = OEDBSystem(forPluginIdentifier: systemID, in: context)
let menuItem = NSMenuItem(title: system.name, action: nil, keyEquivalent: "")
menuItem.image = system.icon
menuItem.representedObject = systemID
return menuItem
}.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
menu.addItem(withTitle: NSLocalizedString("Don't Import Selected", comment: ""), action: nil, keyEquivalent: "")
menu.addItem(.separator())
for item in menuItems {
menu.addItem(item)
}
actionPopUpButton.menu = menu
}
private func layOutSidebarViews(withVisibleGameScanner visibleGameScanner: Bool, animated: Bool) {
var gameScannerFrame = scannerView.frame
gameScannerFrame.origin.y = visibleGameScanner ? 0 : -gameScannerFrame.height
var sourceListFrame = sourceListScrollView.frame
sourceListFrame.origin.y = gameScannerFrame.maxY
sourceListFrame.size.height = sourceListScrollView.superview!.frame.height - sourceListFrame.minY
if animated {
NSAnimationContext.beginGrouping()
// Set frames through animator proxies to implicitly animate changes.
scannerView.animator().frame = gameScannerFrame
sourceListScrollView.animator().frame = sourceListFrame
NSAnimationContext.endGrouping()
} else {
// Set frames directly without implicit animations.
scannerView.frame = gameScannerFrame
sourceListScrollView.frame = sourceListFrame
}
isGameScannerVisible = visibleGameScanner
}
@objc private func updateProgress() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateProgress), object: nil)
CATransaction.begin()
defer { CATransaction.commit() }
headlineLabel.stringValue = NSLocalizedString("Game Scanner", comment: "")
let helper = OpenVGDB.shared
if helper.isUpdating {
progressIndicator.minValue = 0
progressIndicator.doubleValue = helper.downloadProgress
progressIndicator.maxValue = 1
progressIndicator.isIndeterminate = false
progressIndicator.startAnimation(self)
fixButton.isHidden = true
togglePauseButton.isHidden = true
statusLabel.stringValue = NSLocalizedString("Downloading Game DB", comment: "")
} else {
let maxItems = importer.totalNumberOfItems
progressIndicator.minValue = 0
progressIndicator.doubleValue = Double(importer.numberOfProcessedItems)
progressIndicator.maxValue = Double(maxItems)
togglePauseButton.isHidden = false
var status: String
switch importer.status {
case .running:
progressIndicator.isIndeterminate = false
progressIndicator.startAnimation(self)
let count = min(importer.numberOfProcessedItems + 1, maxItems)
if isScanningDirectory {
status = NSLocalizedString("Scanning Directory", comment: "")
} else {
status = String(format: NSLocalizedString("Game %ld of %ld", comment: ""), count, maxItems)
}
togglePauseButton.isEnabled = true
togglePauseButton.icon = "game_scanner_pause"
case .stopped:
progressIndicator.stopAnimation(self)
progressIndicator.isIndeterminate = true
status = NSLocalizedString("Done", comment: "")
togglePauseButton.isEnabled = !itemsRequiringAttention.isEmpty
togglePauseButton.icon = itemsRequiringAttention.isEmpty ? "game_scanner_pause" : "game_scanner_cancel"
default:
progressIndicator.stopAnimation(self)
progressIndicator.isIndeterminate = true
status = NSLocalizedString("Scanner Paused", comment: "")
togglePauseButton.isEnabled = true
togglePauseButton.icon = "game_scanner_continue"
}
let shouldHideFixButton: Bool
if !itemsRequiringAttention.isEmpty {
fixButton.title = itemsRequiringAttention.count > 1 ?
String(format: NSLocalizedString("Resolve %ld Issues", comment: ""), itemsRequiringAttention.count) :
String(format: NSLocalizedString("Resolve %ld Issue", comment: ""), itemsRequiringAttention.count)
shouldHideFixButton = false
status = ""
} else {
shouldHideFixButton = true
}
fixButton.isHidden = shouldHideFixButton
statusLabel.stringValue = status
}
}
private func enableOrDisableApplyButton() {
applyButton.isEnabled = itemsRequiringAttention.contains { $0.isChecked }
}
func showGameScannerView(animated: Bool = true) {
layOutSidebarViews(withVisibleGameScanner: true, animated: animated)
}
func hideGameScannerView(animated: Bool = true) {
guard itemsRequiringAttention.isEmpty else { return }
layOutSidebarViews(withVisibleGameScanner: false, animated: animated)
}
@objc func toggleGameScannerView() {
if isGameScannerVisible {
hideGameScannerView()
} else {
showGameScannerView()
}
}
@objc override func selectAll(_ sender: Any?) {
for item in itemsRequiringAttention {
item.isChecked = true
}
issuesView.reloadData()
enableOrDisableApplyButton()
}
@objc func deselectAll(_ sender: Any?) {
for item in itemsRequiringAttention {
item.isChecked = false
}
issuesView.reloadData()
enableOrDisableApplyButton()
}
@IBAction func resolveIssues(_ sender: Any?) {
let selectedItemIndexes = itemsRequiringAttention.indices.filter { itemsRequiringAttention[$0].isChecked }
issuesView.beginUpdates()
issuesView.removeRows(at: IndexSet(selectedItemIndexes), withAnimation: .effectGap)
issuesView.endUpdates()
if let selectedSystemID = actionPopUpButton.selectedItem?.representedObject as? String {
for item in selectedItemIndexes.map({ itemsRequiringAttention[$0] }) {
item.systemIdentifiers = [selectedSystemID]
item.importer.rescheduleOperation(item)
item.completionBlock = nil
item.completionHandler = nil
}
} else {
for item in selectedItemIndexes.map({ itemsRequiringAttention[$0] }) {
if let extractedFileURL = item.extractedFileURL {
try? FileManager.default.removeItem(at: extractedFileURL)
}
}
}
for i in selectedItemIndexes.reversed() {
itemsRequiringAttention.remove(at: i)
}
setUpActionsMenu()
updateProgress()
issuesView.reloadData()
importer.start()
NotificationCenter.default.post(name: .OESidebarSelectionDidChange, object: self)
if importer.numberOfProcessedItems == importer.totalNumberOfItems {
hideGameScannerView(animated: true)
}
dismiss(self)
}
@IBAction func buttonAction(_ sender: Any?) {
if !itemsRequiringAttention.isEmpty {
importer.pause()
let cancelAlert = OEAlert()
cancelAlert.messageText = NSLocalizedString("Do you really want to cancel importation?", comment: "")
cancelAlert.informativeText = NSLocalizedString("This will remove all items from the queue. Items that finished importing will be preserved in your library.", comment: "")
cancelAlert.defaultButtonTitle = NSLocalizedString("Stop", comment: "")
cancelAlert.alternateButtonTitle = NSLocalizedString("Resume", comment: "")
let button = sender as! NSButton
button.state = button.state == .on ? .off : .on
if cancelAlert.runModal() == .alertFirstButtonReturn {
importer.cancel()
itemsRequiringAttention.removeAll()
updateProgress()
hideGameScannerView(animated: true)
button.state = .off
dismiss(self)
} else {
importer.start()
}
} else {
importer.togglePause()
}
updateProgress()
}
}
// MARK: - Notifications
extension GameScannerViewController {
@objc func gameInfoHelperWillUpdate(_ notification: Notification) {
DispatchQueue.main.async {
self.updateProgress()
self.showGameScannerView(animated: true)
}
}
@objc func gameInfoHelperDidChangeUpdateProgress(_ notification: Notification) {
updateProgress()
}
@objc func gameInfoHelperDidUpdate(_ notification: Notification) {
updateProgress()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
if self.importer.totalNumberOfItems == self.importer.numberOfProcessedItems {
self.hideGameScannerView(animated: true)
}
}
}
}
// MARK: - NSTableViewDataSource
extension GameScannerViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return itemsRequiringAttention.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
let item = itemsRequiringAttention[row]
switch tableColumn!.identifier.rawValue {
case "path":
return item.url.lastPathComponent
case "checked":
return item.isChecked
default:
return nil
}
}
func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) {
if tableColumn!.identifier.rawValue == "checked" {
let item = itemsRequiringAttention[row]
item.isChecked = (object as? Bool) ?? false
}
enableOrDisableApplyButton()
}
}
// MARK: - NSTableViewDelegate
extension GameScannerViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return false
}
func tableView(_ tableView: NSTableView, shouldTrackCell cell: NSCell, for tableColumn: NSTableColumn?, row: Int) -> Bool {
return true
}
func tableView(_ tableView: NSTableView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, row: Int, mouseLocation: NSPoint) -> String {
guard row < itemsRequiringAttention.count else { return "" }
if tableColumn!.identifier.rawValue == "path" {
let item = itemsRequiringAttention[row]
return item.sourceURL.path
} else {
return ""
}
}
}
// MARK: - OEROMImporterDelegate
extension GameScannerViewController: ROMImporterDelegate {
func romImporterDidStart(_ importer: ROMImporter) {
DLog("")
isScanningDirectory = false
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
if self.importer.totalNumberOfItems != self.importer.numberOfProcessedItems {
self.updateProgress()
self.showGameScannerView(animated: true)
}
}
}
func romImporterDidCancel(_ importer: ROMImporter) {
DLog("")
updateProgress()
}
func romImporterDidPause(_ importer: ROMImporter) {
DLog("")
updateProgress()
}
func romImporterDidFinish(_ importer: ROMImporter) {
DLog("")
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
if self.importer.totalNumberOfItems == self.importer.numberOfProcessedItems && !OpenVGDB.shared.isUpdating {
self.hideGameScannerView(animated: true)
}
}
// Show items that failed during import operation
if !itemsFailedImport.isEmpty {
showFailedImportItems()
itemsFailedImport.removeAll()
}
}
func romImporterChangedItemCount(_ importer: ROMImporter) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) {
self.updateProgress()
}
}
func romImporter(_ importer: ROMImporter, stoppedProcessingItem item: OEImportOperation) {
if let error = item.error {
if (error as NSError).domain == OEImportErrorDomainResolvable && (error as NSError).code == OEImportErrorCode.multipleSystems.rawValue {
itemsRequiringAttention.append(item)
issuesView.reloadData()
setUpActionsMenu()
showGameScannerView(animated: true)
} else {
os_log(.debug, log: OE_LOG_IMPORT, "Import error: %{public}@", error.localizedDescription)
// Track item that failed import
//if item.exitStatus == OEImportExitStatus.errorFatal {
if (error as NSError).domain == OEImportErrorDomainFatal || error is OEDiscDescriptorErrors || error is OECUESheetErrors || error is OEDreamcastGDIErrors {
itemsFailedImport.append(item)
}
}
}
updateProgress()
}
private func showFailedImportItems() {
var itemsAlreadyInDatabase: String?
var itemsAlreadyInDatabaseFileUnreachable: String?
var itemsNoSystem: String?
var itemsDisallowArchivedFile: String?
var itemsEmptyFile: String?
var itemsDiscDescriptorUnreadableFile: String?
var itemsDiscDescriptorMissingFiles: String?
var itemsDiscDescriptorNotPlainTextFile: String?
var itemsDiscDescriptorNoPermissionReadFile: String?
var itemsCueSheetInvalidFileFormat: String?
var itemsDreamcastGDIInvalidFileFormat: String?
// Build messages for failed items
for failedItem in itemsFailedImport {
let error = failedItem.error! as NSError
let failedFilename = failedItem.url.lastPathComponent
if error.domain == OEImportErrorDomainFatal && error.code == OEImportErrorCode.alreadyInDatabase.rawValue {
if itemsAlreadyInDatabase == nil {
itemsAlreadyInDatabase = NSLocalizedString("Already in library:", comment:"")
}
itemsAlreadyInDatabase! += "\n• " + String(format: NSLocalizedString("\"%@\" in %@", comment:"Import error description: file already imported (first item: filename, second item: system library name)"), failedFilename, failedItem.romLocation!)
} else if error.domain == OEImportErrorDomainFatal && error.code == OEImportErrorCode.alreadyInDatabaseFileUnreachable.rawValue {
if itemsAlreadyInDatabaseFileUnreachable == nil {
itemsAlreadyInDatabaseFileUnreachable = NSLocalizedString("Already in library, but manually deleted or unreachable:", comment:"")
}
itemsAlreadyInDatabaseFileUnreachable! += "\n• " + String(format: NSLocalizedString("\"%@\" in %@", comment:"Import error description: file already imported (first item: filename, second item: system library name)"), failedFilename, failedItem.romLocation!)
} else if error.domain == OEImportErrorDomainFatal && error.code == OEImportErrorCode.noSystem.rawValue {
if itemsNoSystem == nil {
itemsNoSystem = NSLocalizedString("No valid system detected:", comment:"")
}
itemsNoSystem! += "\n• \"\(failedFilename)\""
} else if error.domain == OEImportErrorDomainFatal && error.code == OEImportErrorCode.disallowArchivedFile.rawValue {
if itemsDisallowArchivedFile == nil {
itemsDisallowArchivedFile = NSLocalizedString("Must not be compressed:", comment:"")
}
itemsDisallowArchivedFile! += "\n• \"\(failedFilename)\""
} else if error.domain == OEImportErrorDomainFatal && error.code == OEImportErrorCode.emptyFile.rawValue {
if itemsEmptyFile == nil {
itemsEmptyFile = NSLocalizedString("Contains no data:", comment:"")
}
itemsEmptyFile! += "\n• \"\(failedFilename)\""
} else if let error2 = error as? OEDiscDescriptorErrors {
switch error2.code {
case .unreadableFileError:
if itemsDiscDescriptorUnreadableFile == nil {
itemsDiscDescriptorUnreadableFile = NSLocalizedString("Unexpected error:", comment:"")
}
let underlyingError = error2.userInfo[NSUnderlyingErrorKey] as! NSError
itemsDiscDescriptorUnreadableFile! += "\n• \"\(failedFilename)\""
itemsDiscDescriptorUnreadableFile! += "\n\n\(underlyingError)"
case .missingFilesError:
if let underlyingError = error2.userInfo[NSUnderlyingErrorKey] as? CocoaError, underlyingError.code == .fileReadNoSuchFile {
if itemsDiscDescriptorMissingFiles == nil {
itemsDiscDescriptorMissingFiles = NSLocalizedString("Missing referenced file:", comment:"")
}
let missingFilename = (underlyingError.userInfo[NSFilePathErrorKey] as! NSString).lastPathComponent
let notFoundMsg = String(format: NSLocalizedString("NOT FOUND: \"%@\"", comment:"Import error description: referenced file not found"), missingFilename)
itemsDiscDescriptorMissingFiles! += "\n• \"\(failedFilename)\"\n - \(notFoundMsg)"
}
case .notPlainTextFileError:
if itemsDiscDescriptorNotPlainTextFile == nil {
itemsDiscDescriptorNotPlainTextFile = NSLocalizedString("Not plain text:", comment:"")
}
itemsDiscDescriptorNotPlainTextFile! += "\n• \"\(failedFilename)\""
case .noPermissionReadFileError:
if itemsDiscDescriptorNoPermissionReadFile == nil {
itemsDiscDescriptorNoPermissionReadFile = NSLocalizedString("No permission to open:", comment:"")
}
itemsDiscDescriptorNoPermissionReadFile! += "\n• \"\(failedFilename)\""
@unknown default:
continue
}
} else if error is OECUESheetErrors {
if itemsCueSheetInvalidFileFormat == nil {
itemsCueSheetInvalidFileFormat = NSLocalizedString("Invalid cue sheet format:", comment:"")
}
itemsCueSheetInvalidFileFormat! += "\n• \"\(failedFilename)\""
} else if error is OEDreamcastGDIErrors {
if itemsDreamcastGDIInvalidFileFormat == nil {
itemsDreamcastGDIInvalidFileFormat = NSLocalizedString("Invalid gdi format:", comment:"")
}
itemsDreamcastGDIInvalidFileFormat! += "\n• \"\(failedFilename)\""
}
}
// Add instructions to fix permission errors
if itemsDiscDescriptorNoPermissionReadFile != nil {
itemsDiscDescriptorNoPermissionReadFile! += "\n\n"+NSLocalizedString("Choose Apple menu > System Preferences, click Security & Privacy then select the Privacy tab. Remove the existing Files and Folders permission for OpenEmu, if exists, and instead grant Full Disk Access.", comment: "")
}
// Concatenate messages
let failedMessage = [itemsAlreadyInDatabase, itemsAlreadyInDatabaseFileUnreachable, itemsNoSystem, itemsDisallowArchivedFile, itemsEmptyFile, itemsDiscDescriptorUnreadableFile, itemsDiscDescriptorMissingFiles, itemsDiscDescriptorNotPlainTextFile, itemsDiscDescriptorNoPermissionReadFile, itemsCueSheetInvalidFileFormat, itemsDreamcastGDIInvalidFileFormat].compactMap{$0}.joined(separator:"\n\n")
let alert = OEAlert()
alert.messageText = NSLocalizedString("Files failed to import.", comment: "")
alert.informativeText = failedMessage
alert.defaultButtonTitle = NSLocalizedString("View Guide in Browser", comment:"")
alert.alternateButtonTitle = NSLocalizedString("Dismiss", comment:"")
for window in NSApp.windows {
if window.windowController is MainWindowController {
alert.beginSheetModal(for: window) { result in
if result == .alertFirstButtonReturn {
NSWorkspace.shared.open(GameScannerViewController.importGuideURL)
}
}
break
}
}
}
}
| 40.972182 | 403 | 0.6131 |
20775fabf08abbb7d69a7135f7491a7b8c6c416f
| 7,740 |
//
// SPAlertControllerActionView.swift
// Swift_SPAlertController
//
// Created by lidongxi on 2019/12/6.
// Copyright © 2019 lidongxi. All rights reserved.
//
import UIKit
class SPAlertControllerActionView: UIView {
public var afterSpacing: CGFloat = SP_LINE_WIDTH
private var actionButtonConstraints = [NSLayoutConstraint]()
private var methodAction: Selector!
private var target: AnyObject!
func addTarget(target: AnyObject, action: Selector) {
self.target = target
self.methodAction = action
}
//手指按下然后在按钮有效事件范围内抬起
@objc func touchUpInside() {
_ = target.perform(self.methodAction, with: self)
}
//手指按下或者手指按下后往外拽再往内拽
@objc func touchDown(button: UIButton) {
guard let alert = self.findAlertController() else{ return }
if alert.needDialogBlur {
// 需要毛玻璃时,只有白色带透明,毛玻璃效果才更加清澈
button.backgroundColor = SP_SELECTED_COLOR
} else {
// 该颜色比'取消action'上的分割线的颜色浅一些
button.backgroundColor = UIColor.gray.withAlphaComponent(0.1)
}
}
// 手指被迫停止、手指按下后往外拽或者取消,取消的可能性:比如点击的那一刻突然来电话
@objc func touchDragExit(button: UIButton) {
button.backgroundColor = SP_NORMAL_COLOR
}
func findAlertController() -> SPAlertController? {
var next = self.next
while next != nil {
if next is SPAlertController {
return next as? SPAlertController
} else {
next = next?.next
}
}
return nil
}
// 安全区域发生了改变,在这个方法里自动适配iPhoneX
override func safeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.safeAreaInsetsDidChange()
self.actionButton.contentEdgeInsets = self.edgeInsetsAddEdgeInsets(i1: self.safeAreaInsets, i2: action.titleEdgeInsets)
} else {
// Fallback on earlier versions
}
self.setNeedsUpdateConstraints()
}
override func updateConstraints() {
super.updateConstraints()
if self.actionButtonConstraints.count > 0 {
NSLayoutConstraint.deactivate(self.actionButtonConstraints)
self.actionButtonConstraints.removeAll()
}
actionButtonConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[actionButton]-0-|", options: [], metrics: nil, views: ["actionButton": actionButton]))
actionButtonConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[actionButton]-0-|", options: [], metrics: nil, views: ["actionButton": actionButton]))
// 按钮必须确认高度,因为其父视图及父视图的父视图乃至根视图都没有设置高度,而且必须用NSLayoutRelationEqual,如果用NSLayoutRelationGreaterThanOrEqual,虽然也能撑起父视图,但是当某个按钮的高度有所变化以后,stackView会将其余按钮按的高度同比增减
// titleLabel的内容自适应的高度 55
let labelH: CGFloat = actionButton.titleLabel?.intrinsicContentSize.height ?? 0.0
// 按钮的上下内边距之和 0
let topBottom_insetsSum: CGFloat = actionButton.contentEdgeInsets.top+actionButton.contentEdgeInsets.bottom
// 文字的上下间距之和,等于SP_ACTION_HEIGHT-默认字体大小,这是为了保证文字上下有一个固定间距值,不至于使文字靠按钮太紧,,由于按钮内容默认垂直居中,所以最终的顶部或底部间距为topBottom_marginSum/2.0,这个间距,几乎等于18号字体时,最小高度为49时的上下间距 33.5
let topBottom_marginSum: CGFloat = SP_ACTION_HEIGHT-UIFont.systemFont(ofSize: SP_ACTION_TITLE_FONTSIZE).lineHeight
// 按钮高度
let buttonH = labelH+topBottom_insetsSum+topBottom_marginSum
var relation = NSLayoutConstraint.Relation.equal
if let stackView = self.superview as? UIStackView, stackView.axis == .horizontal {
relation = .greaterThanOrEqual
}
// 如果字体保持默认18号,只有一行文字时最终结果约等于SP_ACTION_HEIGHT
let buttonHonstraint = NSLayoutConstraint.init(item: actionButton, attribute: .height, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: buttonH)
buttonHonstraint.priority = UILayoutPriority(rawValue: 999)
actionButtonConstraints.append(buttonHonstraint)
// 给一个最小高度,当按钮字体很小时,如果还按照上面的高度计算,高度会比较小
let minHConstraint = NSLayoutConstraint.init(item: actionButton, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: SP_ACTION_HEIGHT+topBottom_insetsSum)
minHConstraint.priority = UILayoutPriority.required
self.addConstraints(actionButtonConstraints)
}
private func edgeInsetsAddEdgeInsets(i1: UIEdgeInsets, i2: UIEdgeInsets) -> UIEdgeInsets {
var bottom: CGFloat = i1.bottom
if bottom > 21 {// 34的高度太大,这里转为21
bottom = 21
}
return .init(top: i1.top+i2.top, left: i1.left+i2.left, bottom: bottom+i2.bottom, right: i1.right+i2.right)
}
lazy var actionButton: UIButton = {
let btn = UIButton.init(type: .custom)
btn.backgroundColor = SP_NORMAL_COLOR
btn.translatesAutoresizingMaskIntoConstraints = false
btn.titleLabel?.textAlignment = .center
btn.titleLabel?.adjustsFontSizeToFitWidth = true
btn.titleLabel?.baselineAdjustment = .alignCenters
btn.titleLabel?.minimumScaleFactor = 0.5
btn.addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
btn.addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragInside])
btn.addTarget(self, action: #selector(touchDragExit), for: [.touchDragExit, .touchUpOutside, .touchCancel])
self.addSubview(btn)
return btn
}()
public var action: SPAlertAction! {
didSet {
self.actionButton.titleLabel?.font = action.titleFont
if action.isEnabled == true {
self.actionButton.setTitleColor(action.titleColor, for: .normal)
} else {
self.actionButton.setTitleColor(.lightGray, for: .normal)
}
// 注意不能赋值给按钮的titleEdgeInsets,当只有文字时,按钮的titleEdgeInsets设置top和bottom值无效
self.actionButton.contentEdgeInsets = action.titleEdgeInsets
self.actionButton.isEnabled = action.isEnabled
if action.attributedTitle != nil {
// 这里之所以要设置按钮颜色为黑色,是因为如果外界在addAction:之后设置按钮的富文本,那么富文本的颜色在没有采用NSForegroundColorAttributeName的情况下会自动读取按钮上普通文本的颜色,在addAction:之前设置会保持默认色(黑色),为了在addAction:前后设置富文本保持统一,这里先将按钮置为黑色,富文本就会是黑色
self.actionButton.setTitleColor(.black, for: .normal)
if action.attributedTitle!.string.contains("\n") || action.attributedTitle!.string.contains("\r") {
self.actionButton.titleLabel?.lineBreakMode = .byWordWrapping
}
self.actionButton.setAttributedTitle(action.attributedTitle!, for: .normal)
// 设置完富文本之后,还原按钮普通文本的颜色,其实这行代码加不加都不影响,只是为了让按钮普通文本的颜色保持跟action.titleColor一致
self.actionButton.setTitleColor(action.titleColor, for: .normal)
} else {
if let title = action.title {
if title.contains("\n") || title.contains("\r") {
self.actionButton.titleLabel?.lineBreakMode = .byWordWrapping
}
self.actionButton.setTitle(title, for: .normal)
}
}
self.actionButton.setImage(action.image, for: .normal)
self.actionButton.titleEdgeInsets = .init(top: 0, left: action.imageTitleSpacing, bottom: 0, right: -action.imageTitleSpacing)
self.actionButton.imageEdgeInsets = .init(top: 0, left: -action.imageTitleSpacing, bottom: 0, right: action.imageTitleSpacing)
}
}
}
| 46.347305 | 230 | 0.659432 |
675e0145c36fab71aaf8632f2defb84904e96b43
| 16,034 |
//
// TweetDetailTableViewCell.swift
// Twitter
//
// Created by Shayin Feng on 2/25/17.
// Copyright © 2017 Shayin Feng. All rights reserved.
//
import UIKit
import ActiveLabel
import AVKit
import AVFoundation
class TweetDetailTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenLabel: UILabel!
@IBOutlet weak var contentLabel: ActiveLabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var contentMediaView: UIView!
@IBOutlet weak var contentMediaHeight: NSLayoutConstraint!
@IBOutlet weak var timeLabelToImage: NSLayoutConstraint!
@IBOutlet weak var retweetStack: UIStackView!
@IBOutlet weak var retweetStackHeight: NSLayoutConstraint!
@IBOutlet weak var retweetStackLabel: UILabel!
@IBOutlet weak var avatarToRetweetStack: NSLayoutConstraint!
@IBOutlet weak var contentToAvatar: NSLayoutConstraint!
var tapGesture = UITapGestureRecognizer()
var delegate: TweetDetailTableViewCellDelegate?
var popDelegate: TweetTableViewDelegate?
let client = TwitterClient.sharedInstance!
var videoUrl: String?
var player = AVPlayer()
var playButton = UIButton()
var tweet: TweetModel! {
didSet {
updateUIWithTweetDetails()
}
}
var retweet: TweetModel? {
didSet {
if let username = retweet?.user?.name {
if username == (UserModel.currentUser!.name) {
retweetStackLabel.text = " You Retweeted"
} else {
retweetStackLabel.text = " \(username) Retweeted"
}
avatarToRetweetStack.constant = 10
retweetStackHeight.constant = 20
retweetStack.isHidden = false
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
avatarImage.layer.masksToBounds = true
avatarImage.layer.cornerRadius = 5
avatarImage.image = #imageLiteral(resourceName: "noImage")
timeLabelToImage.constant = 3
contentMediaView.layer.masksToBounds = true
contentMediaView.layer.cornerRadius = 5
self.layoutIfNeeded()
contentLabel.customize { contentLabel in
contentLabel.handleHashtagTap { hashtag in
print("Success. You just tapped the \(hashtag) hashtag")
}
contentLabel.handleURLTap { (mention) in
print("Success. You just tapped the \(mention) mention")
}
contentLabel.removeHandle(for: ActiveType.url)
}
}
override func prepareForReuse() {
contentMediaHeight.constant = 0
timeLabelToImage.constant = 3
contentMediaView.translatesAutoresizingMaskIntoConstraints = false
retweetStackHeight.constant = 0
avatarToRetweetStack.constant = 5
retweetStack.isHidden = true
playButton.removeFromSuperview()
}
private func updateUIWithTweetDetails () {
if let avatarURL = tweet?.user?.profile_image_url {
avatarImage.setImageWith(avatarURL)
}
if let nameString = tweet?.user?.name {
if let verified = tweet.user?.verified {
if verified == true {
let attachment = NSTextAttachment()
attachment.image = #imageLiteral(resourceName: "verified-account")
// attachment.image = UIImage(cgImage: (attachment.image?.cgImage)!, scale: 6, orientation: .up)
attachment.bounds = CGRect(x: 0, y: -4, width: 18, height: 18)
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "\(nameString) ")
myString.append(attachmentString)
nameLabel.attributedText = myString
} else {
nameLabel.text = nameString
}
}
} else {
nameLabel.text = ""
}
if let screenNameString = tweet?.user!.screen_name {
screenLabel.text = screenNameString
} else {
screenLabel.text = ""
}
if let timeCreated = tweet?.createdAt {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, HH:mm"
timeLabel.text = dateFormatter.string(from: timeCreated)
}
if var contentString = tweet?.text {
var tmpContentString = contentString
// should show medias
if let media = tweet.media {
// should show media view, height should be set based on situation
contentMediaView.isHidden = false
timeLabelToImage.constant = 15
// width of contentMediaView
let frameWidth = contentMediaView.frame.width
// count of images or video in data model
let mediaCount = media.count
var photoCount = 0
// image collection frames
let imageCollectionHeight = frameWidth * 0.56
let frame1 = CGRect(x: 0, y: 0, width: frameWidth, height: imageCollectionHeight)
let stack0 = UIStackView(frame: frame1)
let stack1 = UIStackView()
let stack2 = UIStackView()
stack0.axis = .horizontal
stack0.distribution = .fillEqually
stack0.alignment = .fill
stack0.spacing = 4
stack1.axis = .vertical
stack1.distribution = .fillEqually
stack1.alignment = .fill
stack1.spacing = 4
stack2.axis = .vertical
stack2.distribution = .fillEqually
stack2.alignment = .fill
stack2.spacing = 4
if mediaCount > 2 {
stack0.addArrangedSubview(stack1)
stack0.addArrangedSubview(stack2)
}
// madia is NSArray which stores NSDictionaries
for mediaDictionary in media as? [NSDictionary] ?? []{
let media_url = mediaDictionary["media_url"] as! String
let url_should_be_replaced = mediaDictionary["url"] as! String
// photo, animated_gif
let type = mediaDictionary["type"] as! String
// range of url which should be replaced by images or video
if let range = tmpContentString.range(of: url_should_be_replaced) {
tmpContentString = contentString.replacingCharacters(in: range, with: "")
contentString = tmpContentString
}
// ratio for original
let size = mediaDictionary["sizes"] as! NSDictionary
let large = size["large"] as! NSDictionary
let h = large["h"] as! CGFloat
let w = large["w"] as! CGFloat
let ratio = h / w
let frameHeight = frameWidth * ratio
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "loadingImage")
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
if type == "animated_gif" {
// content media view height
contentMediaHeight.constant = frameHeight
imageView.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
// cache image
let imageRequest = URLRequest(url: URL(string: media_url)!)
imageView.setImageWith(imageRequest, placeholderImage: #imageLiteral(resourceName: "loadingImage"), success: { (request, response, image) in
imageView.image = image
})
// tap to view image in fullscreen
imageView.isUserInteractionEnabled = true
tapGesture = UITapGestureRecognizer(target: self, action: #selector(openVideo(sender:)))
imageView.addGestureRecognizer(tapGesture)
// play Button for video
playButton = UIButton(frame: CGRect(x: (frameWidth / 2 - 25), y: (frameHeight / 2 - 25), width: 50, height: 50))
playButton.setImage(#imageLiteral(resourceName: "play-icon"), for: .normal)
playButton.addTarget(self, action: #selector(playTapped(sender:)), for: .touchUpInside)
// video infromation in dictionary
let video_info = mediaDictionary["video_info"] as! NSDictionary
let variants = video_info["variants"] as! [NSDictionary]
let variant = variants[0]
let urlString = variant["url"] as! String
videoUrl = urlString
contentMediaView.addSubview(imageView)
contentMediaView.addSubview(playButton)
}
else if type == "photo" {
contentMediaHeight.constant = imageCollectionHeight
let imageRequest = URLRequest(url: URL(string: media_url)!)
imageView.setImageWith(imageRequest, placeholderImage: #imageLiteral(resourceName: "loadingImage"), success: { (request, response, image) in
UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
imageView.image = image
})
})
imageView.isUserInteractionEnabled = true
tapGesture = UITapGestureRecognizer(target: self, action: #selector(popOverImage(sender:)))
imageView.addGestureRecognizer(tapGesture)
if mediaCount == 1 {
contentMediaHeight.constant = frameHeight
imageView.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
contentMediaView.addSubview(imageView)
}
else if mediaCount == 2 {
stack0.addArrangedSubview(imageView)
}
else if mediaCount == 3 {
if photoCount == 0 {
stack1.addArrangedSubview(imageView)
} else {
stack2.addArrangedSubview(imageView)
}
}
else if mediaCount == 4 {
if photoCount == 0 || photoCount == 2 {
stack1.addArrangedSubview(imageView)
} else {
stack2.addArrangedSubview(imageView)
}
}
else {
print("Photo Collection: Media count invalid")
}
photoCount += 1
}
}
if mediaCount >= 2 {
contentMediaView.addSubview(stack0)
}
}
if let urls = tweet.urls {
for item in urls {
if let urlDictionary = item as? NSDictionary {
let display_url = urlDictionary["display_url"] as! String
let url = urlDictionary["url"] as! String
let urlPattern = display_url
let urlType = ActiveType.custom(pattern: urlPattern)
contentLabel.enabledTypes.append(urlType)
contentLabel.customColor[urlType] = UIhelper.UIColorOption.twitterBlue
contentLabel.customSelectedColor[urlType] = UIhelper.UIColorOption.twitterGray
contentLabel.handleCustomTap(for: urlType, handler: { (urlString) in
print(url)
UIApplication.shared.open(URL(string: url)!)
})
print("\(tmpContentString) \(url)")
// find the range in contentString where contains url
if let range = tmpContentString.range(of: url) {
// replace url to displayed url
tmpContentString = contentString.replacingCharacters(in: range, with: display_url)
// reset attributedString with displayed url
contentString = tmpContentString
}
}
}
}
contentLabel.text = contentString
} else {
contentLabel.text = ""
}
if contentLabel.text == "" {
contentToAvatar.constant = -25
}
}
func popOverImage (sender: UITapGestureRecognizer) {
print("Tapped")
self.popDelegate?.getPopoverImage(imageView: sender.view as! UIImageView)
}
func openVideo (sender: UITapGestureRecognizer) {
UIApplication.shared.open(URL(string: videoUrl!)!)
}
func playTapped (sender: UIButton!) {
playButton.removeFromSuperview()
let playerView = contentMediaView.subviews[0]
self.layoutIfNeeded()
playerView.frame = contentMediaView.bounds
player = AVPlayer(url: URL(string: videoUrl!)!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = contentMediaView.bounds
playerView.layer.addSublayer(playerLayer)
player.play()
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
func playerDidFinishPlaying(note: NSNotification) {
print("Play end")
contentMediaView.addSubview(playButton)
}
@IBAction func menuButtonTapped(_ sender: UIButton) {
self.delegate?.tweetCellMenuTapped!(cell: self, withId: tweet.id!)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 39.885572 | 164 | 0.505114 |
03bb4e02f774d5de10a4c208b889b254e1ca15df
| 12,283 |
//
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
#if !swift(>=4.1)
import XCTest
import CloudKit
import ProcedureKit
import TestingProcedureKit
@testable import ProcedureKitCloud
class TestCKModifyRecordsOperation: TestCKDatabaseOperation, CKModifyRecordsOperationProtocol, AssociatedErrorProtocol {
typealias AssociatedError = ModifyRecordsError<Record, RecordID>
var saved: [Record]?
var deleted: [RecordID]?
var error: Error?
var recordsToSave: [Record]? = nil
var recordIDsToDelete: [RecordID]? = nil
var savePolicy: RecordSavePolicy = 0
var clientChangeTokenData: Data? = nil
var isAtomic: Bool = true
var perRecordProgressBlock: ((Record, Double) -> Void)? = nil
var perRecordCompletionBlock: ((Record?, Error?) -> Void)? = nil
var modifyRecordsCompletionBlock: (([Record]?, [RecordID]?, Error?) -> Void)? = nil
init(saved: [Record]? = nil, deleted: [RecordID]? = nil, error: Error? = nil) {
self.saved = saved
self.deleted = deleted
self.error = error
super.init()
}
override func main() {
modifyRecordsCompletionBlock?(saved, deleted, error)
}
}
class CKModifyRecordsOperationTests: CKProcedureTestCase {
var target: TestCKModifyRecordsOperation!
var operation: CKProcedure<TestCKModifyRecordsOperation>!
override func setUp() {
super.setUp()
target = TestCKModifyRecordsOperation()
operation = CKProcedure(operation: target)
}
override func tearDown() {
target = nil
operation = nil
super.tearDown()
}
func test__set_get__recordsToSave() {
let recordsToSave = [ "a-record", "another-record" ]
operation.recordsToSave = recordsToSave
XCTAssertNotNil(operation.recordsToSave)
XCTAssertEqual(operation.recordsToSave ?? [], recordsToSave)
XCTAssertNotNil(target.recordsToSave)
XCTAssertEqual(target.recordsToSave ?? [], recordsToSave)
}
func test__set_get__recordIDsToDelete() {
let recordIDsToDelete = [ "a-record-id", "another-record-id" ]
operation.recordIDsToDelete = recordIDsToDelete
XCTAssertNotNil(operation.recordIDsToDelete)
XCTAssertEqual(operation.recordIDsToDelete ?? [], recordIDsToDelete)
XCTAssertNotNil(target.recordIDsToDelete)
XCTAssertEqual(target.recordIDsToDelete ?? [], recordIDsToDelete)
}
func test__set_get__savePolicy() {
let savePolicy = 100
operation.savePolicy = savePolicy
XCTAssertEqual(operation.savePolicy, savePolicy)
XCTAssertEqual(target.savePolicy, savePolicy)
}
func test__set_get__clientChangeTokenData() {
let clientChangeTokenData = "this-is-some-data".data(using: .utf8)
operation.clientChangeTokenData = clientChangeTokenData
XCTAssertEqual(operation.clientChangeTokenData, clientChangeTokenData)
XCTAssertEqual(target.clientChangeTokenData, clientChangeTokenData)
}
func test__set_get__isAtomic() {
var isAtomic = true
operation.isAtomic = isAtomic
XCTAssertEqual(operation.isAtomic, isAtomic)
XCTAssertEqual(target.isAtomic, isAtomic)
isAtomic = false
operation.isAtomic = isAtomic
XCTAssertEqual(operation.isAtomic, isAtomic)
XCTAssertEqual(target.isAtomic, isAtomic)
}
func test__set_get__perRecordProgressBlock() {
var setByCompletionBlock = false
let block: (String, Double) -> Void = { record, progress in
setByCompletionBlock = true
}
operation.perRecordProgressBlock = block
XCTAssertNotNil(operation.perRecordProgressBlock)
target.perRecordProgressBlock?("a-record", 50.0)
XCTAssertTrue(setByCompletionBlock)
}
func test__set_get__perRecordCompletionBlock() {
var setByCompletionBlock = false
let block: (String?, Error?) -> Void = { record, error in
setByCompletionBlock = true
}
operation.perRecordCompletionBlock = block
XCTAssertNotNil(operation.perRecordCompletionBlock)
target.perRecordCompletionBlock?("a-record", nil)
XCTAssertTrue(setByCompletionBlock)
}
func test__success_without_completion_block() {
wait(for: operation)
PKAssertProcedureFinished(operation)
}
func test__success_with_completion_block() {
var didExecuteBlock = false
operation.setModifyRecordsCompletionBlock { savedRecords, deletedRecordIDs in
didExecuteBlock = true
}
wait(for: operation)
PKAssertProcedureFinished(operation)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block() {
target.error = TestError()
wait(for: operation)
PKAssertProcedureFinished(operation)
}
func test__error_with_completion_block() {
var didExecuteBlock = false
operation.setModifyRecordsCompletionBlock { savedRecords, deletedRecordIDs in
didExecuteBlock = true
}
target.error = TestError()
wait(for: operation)
XCTAssertProcedureFinishedWithErrors(operation, count: 1)
XCTAssertFalse(didExecuteBlock)
}
}
class CloudKitProcedureModifyRecordsOperationTests: CKProcedureTestCase {
typealias T = TestCKModifyRecordsOperation
var cloudkit: CloudKitProcedure<T>!
var setByPerRecordProgressBlock: CloudKitProcedure<T>.ModifyRecordsPerRecordProgress!
var setByPerRecordCompletionBlock: CloudKitProcedure<T>.ModifyRecordsPerRecordCompletion!
override func setUp() {
super.setUp()
cloudkit = CloudKitProcedure(strategy: .immediate) { TestCKModifyRecordsOperation() }
cloudkit.container = container
cloudkit.recordsToSave = [ "record 1" ]
cloudkit.recordIDsToDelete = [ "record 2 ID" ]
cloudkit.savePolicy = 1
cloudkit.clientChangeTokenData = "hello-world".data(using: .utf8)
cloudkit.isAtomic = true
cloudkit.perRecordProgressBlock = { self.setByPerRecordProgressBlock = ($0, $1) }
cloudkit.perRecordCompletionBlock = { self.setByPerRecordCompletionBlock = ($0, $1) }
}
override func tearDown() {
cloudkit = nil
setByPerRecordProgressBlock = nil
setByPerRecordCompletionBlock = nil
super.tearDown()
}
func test__set_get__errorHandlers() {
cloudkit.set(errorHandlers: [.internalError: cloudkit.passthroughSuggestedErrorHandler])
XCTAssertEqual(cloudkit.errorHandlers.count, 1)
XCTAssertNotNil(cloudkit.errorHandlers[.internalError])
}
func test__set_get_container() {
cloudkit.container = "I'm a different container!"
XCTAssertEqual(cloudkit.container, "I'm a different container!")
}
func test__set_get_database() {
cloudkit.database = "I'm a different database!"
XCTAssertEqual(cloudkit.database, "I'm a different database!")
}
func test__set_get_previousServerChangeToken() {
cloudkit.previousServerChangeToken = "I'm a different token!"
XCTAssertEqual(cloudkit.previousServerChangeToken, "I'm a different token!")
}
func test__set_get_resultsLimit() {
cloudkit.resultsLimit = 20
XCTAssertEqual(cloudkit.resultsLimit, 20)
}
func test__set_get_recordsToSave() {
cloudkit.recordsToSave = [ "record 3" ]
XCTAssertEqual(cloudkit.recordsToSave ?? [], [ "record 3" ])
}
func test__set_get_recordIDsToDelete() {
cloudkit.recordIDsToDelete = [ "record 4 ID" ]
XCTAssertEqual(cloudkit.recordIDsToDelete ?? [], [ "record 4 ID" ])
}
func test__set_get_savePolicy() {
cloudkit.savePolicy = 2
XCTAssertEqual(cloudkit.savePolicy, 2)
}
func test__set_get__clientChangeTokenData() {
let clientChangeTokenData = "this-is-some-data".data(using: .utf8)
cloudkit.clientChangeTokenData = clientChangeTokenData
XCTAssertEqual(cloudkit.clientChangeTokenData, clientChangeTokenData)
}
func test__set_get_isAtomic() {
cloudkit.isAtomic = false
XCTAssertEqual(cloudkit.isAtomic, false)
}
func test__set_get_perRecordProgressBlock() {
XCTAssertNotNil(cloudkit.perRecordProgressBlock)
cloudkit.perRecordProgressBlock?("record 1", 0.5)
XCTAssertEqual(setByPerRecordProgressBlock?.0 ?? "not record 1", "record 1")
XCTAssertEqual(setByPerRecordProgressBlock?.1 ?? 0.1, 0.5)
}
func test__set_get_perRecordCompletionBlock() {
XCTAssertNotNil(cloudkit.perRecordCompletionBlock)
let anError = TestError()
cloudkit.perRecordCompletionBlock?("record 2", anError)
XCTAssertEqual(setByPerRecordCompletionBlock?.0 ?? "not record 2", "record 2")
XCTAssertEqual(setByPerRecordCompletionBlock?.1 as? TestError ?? TestError(), anError)
}
func test__cancellation() {
cloudkit.cancel()
wait(for: cloudkit)
XCTAssertProcedureCancelledWithoutErrors(cloudkit)
}
func test__success_without_completion_block_set() {
wait(for: cloudkit)
PKAssertProcedureFinished(cloudkit)
}
func test__success_with_completion_block_set() {
var didExecuteBlock = false
cloudkit.setModifyRecordsCompletionBlock { _, _ in
didExecuteBlock = true
}
wait(for: cloudkit)
PKAssertProcedureFinished(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKModifyRecordsOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
wait(for: cloudkit)
PKAssertProcedureFinished(cloudkit)
}
func test__error_with_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKModifyRecordsOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
var didExecuteBlock = false
cloudkit.setModifyRecordsCompletionBlock { _, _ in
didExecuteBlock = true
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithErrors(cloudkit, count: 1)
XCTAssertFalse(didExecuteBlock)
}
func test__error_which_retries_using_retry_after_key() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKModifyRecordsOperation()
if shouldError {
let userInfo = [CKErrorRetryAfterKey: NSNumber(value: 0.001)]
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.serviceUnavailable.rawValue, userInfo: userInfo)
shouldError = false
}
return op
}
var didExecuteBlock = false
cloudkit.setModifyRecordsCompletionBlock { _, _ in didExecuteBlock = true }
wait(for: cloudkit)
PKAssertProcedureFinished(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_which_retries_using_custom_handler() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKModifyRecordsOperation()
if shouldError {
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.limitExceeded.rawValue, userInfo: nil)
shouldError = false
}
return op
}
var didRunCustomHandler = false
cloudkit.set(errorHandlerForCode: .limitExceeded) { _, _, _, suggestion in
didRunCustomHandler = true
return suggestion
}
var didExecuteBlock = false
cloudkit.setModifyRecordsCompletionBlock { _, _ in didExecuteBlock = true }
wait(for: cloudkit)
PKAssertProcedureFinished(cloudkit)
XCTAssertTrue(didExecuteBlock)
XCTAssertTrue(didRunCustomHandler)
}
}
#endif
| 35.602899 | 125 | 0.68086 |
09196034614b8c1162029e34d09b9cf9bba9122d
| 714 |
//
// Cw20TransferReq.swift
// Cosmostation
//
// Created by yongjoo jung on 2022/02/03.
// Copyright © 2022 wannabit. All rights reserved.
//
import Foundation
public struct Cw20TransferReq : Codable {
var transfer: TransferReq?
init(_ recipient: String, _ amount: String) {
self.transfer = TransferReq.init(recipient, amount)
}
func getEncode() -> Data {
let jsonEncoder = JSONEncoder()
return try! jsonEncoder.encode(self)
}
}
public struct TransferReq : Codable {
var recipient: String?
var amount: String?
init(_ recipient: String, _ amount: String) {
self.recipient = recipient
self.amount = amount
}
}
| 19.833333 | 59 | 0.634454 |
edccb4b25e1379855717f65acd6819146804c448
| 2,757 |
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Redwerk [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.
//
import Foundation
public struct Conditions<Model> where Model: Validatable {
private var rules: [ValidationRule<Model>] = []
public init(_ model: Model.Type) {}
public func check(_ model: Model) throws {
for rule in rules {
try rule.validate(model)
}
}
public mutating func add<ValueType>(_ keyPath: KeyPath<Model, ValueType>,
_ name: String,
_ rule: ValidationRule<ValueType>) {
add(keyPath, name, rule.info) { (value) in
try rule.validate(value)
}
}
private mutating func add<ValueType>(_ keyPath: KeyPath<Model, ValueType>,
_ name: String,
_ info: String,
_ closure: @escaping (ValueType) throws -> Void) {
add(info) { (model) in
try closure(model[keyPath: keyPath])
}
}
public mutating func add<ValueType>(value: ValueType,
_ name: String,
_ rule: ValidationRule<ValueType>) {
add(rule.info) { (_) in
try rule.validate(value)
}
}
public mutating func add(_ info: String,
_ closure: @escaping (Model) throws -> Void) {
let rule: ValidationRule<Model> = .init(info) { (model) in
try closure(model)
}
rules.append(rule)
}
}
| 37.256757 | 91 | 0.589046 |
d5e47f2b7f13bf2043e0fe52b487b98619140101
| 2,901 |
//
// ClassificationComparisonModel.swift
// MessageFilteringApp
//
// Created by Viacheslav Volodko on 3/1/19.
// Copyright © 2019 killobatt. All rights reserved.
//
import TextClassification
import CoreML
struct ClassificationResult {
var classifierName: String
var resultLabel: String
}
class ClassificationComparisonModel {
private(set) var classifiers: [NamedTextClassifier]
init() {
// let languageRecognizerClassifier = LanguageRecognizerClassifier()
// let coreMLClassifier = CoreMLLanguageClassifier()
// let naiveBayesClassifier = NaiveBayesClassifier.loadClassifier()
let memoryMappedNaiveBayes = MemoryMappedNaiveBayesClassifier.loadClassifier()
self.classifiers = [
// languageRecognizerClassifier,
// coreMLClassifier,
// naiveBayesClassifier,
memoryMappedNaiveBayes,
]
}
func comparePrediction(for text: String) -> [ClassificationResult] {
return classifiers.map { ClassificationResult(classifierName: $0.name,
resultLabel: $0.predictedLabel(for: text) ?? "unknown") }
}
}
protocol NamedTextClassifier: TextClassifier {
var name: String { get }
}
extension LanguageRecognizerClassifier: NamedTextClassifier {
var name: String {
return "NLLanguageRecognizer"
}
}
extension CoreMLLanguageClassifier: NamedTextClassifier {
var name: String {
return "Core ML"
}
func predictedLabel(for text: String) -> String? {
let prediction = try? self.prediction(text: text)
return prediction?.label
}
}
extension NaiveBayesClassifier: NamedTextClassifier {
var name: String {
return "Naive Bayes"
}
static func loadClassifier() -> NaiveBayesClassifier {
guard let url = Bundle.main.url(forResource: "NaiveBayes", withExtension: "model") else {
fatalError("Missing resource file: NaiveBayes.model")
}
do {
return try NaiveBayesClassifier(fileURL: url, preprocessor: TrivialPreprocessor())
} catch let error {
fatalError("Error loading NaiveBayesClassifier from \(url):\n \(error)")
}
}
}
extension MemoryMappedNaiveBayesClassifier: NamedTextClassifier {
var name: String {
return "Naive Bayes + Memory mapping"
}
static func loadClassifier() -> MemoryMappedNaiveBayesClassifier {
guard let url = Bundle.main.url(forResource: "MemoryMappedBayes", withExtension: "model") else {
fatalError("Missing resource file: NaiveBayes.model")
}
do {
return try MemoryMappedNaiveBayesClassifier(fileURL: url, preprocessor: TrivialPreprocessor())
} catch let error {
fatalError("Error loading MemoryMappedNaiveBayesClassifier from \(url):\n \(error)")
}
}
}
| 30.861702 | 111 | 0.665633 |
1ebe7a1d6a40e79aa6ce599902a661b714ece7ad
| 859 |
import XCTest
@testable import SwiftLockbookCore
class DeleteFileTests: SLCTest {
var account: Account?
var root: ClientFileMetadata?
override func setUpWithError() throws {
try super.setUpWithError()
let _ = try core.api.createAccount(username: randomUsername(), apiLocation: systemApiLocation()).get()
account = try core.api.getAccount().get()
root = try core.api.getRoot().get()
}
func testSimple() throws {
let newFile = try core.api.createFile(name: randomFilename(), dirId: root!.id, isFolder: false).get()
let resultDelete = core.api.deleteFile(id: newFile.id)
assertSuccess(resultDelete)
}
func testMissingFile() throws {
let resultDelete = core.api.deleteFile(id: UUID())
assertFailure(resultDelete) { $0 == .init(.FileDoesNotExist) }
}
}
| 29.62069 | 110 | 0.665891 |
f885c8cf0d0db285e3bb1afed0db80a4d5af0da2
| 804 |
//
// Created by apploft on 18.12.18.
// Copyright © 2019 apploft GmbH.
// MIT License · http://choosealicense.com/licenses/mit/
import UIKit
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
return machineMirror.children.reduce("") { (identifier: String, element: (label: String?, value: Any)) -> String in
guard let version = valueToVersion(element.value) else { return identifier }
return identifier + version
}
}
private func valueToVersion(_ value: Any) -> String? {
guard let value = value as? Int8, value != 0 else { return nil }
return String(UnicodeScalar(UInt8(value)))
}
}
| 30.923077 | 123 | 0.635572 |
1ccae6a2ea2ddc1976a1397701d50b25569aa166
| 646 |
//
// ContentView.swift
// UITransition
//
// Created by Cristian Amoddio on 23/03/22.
//
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack{
Color(UIColor.red)
VStack{
Text("Hello, world!")
.font(.largeTitle)
.padding()
UIKitButtonRepresentable()
.frame(width: 100, height: 100)
}
}
.ignoresSafeArea()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 19 | 51 | 0.478328 |
d7c766412fd93008231e9f44313fcba83011eabe
| 5,884 |
import UIKit
import CocoaAsyncSocket
public protocol SocketManagerDelegate {
func reconnectionSuccess()
func didReadData(data: Data, tag: Int)
}
typealias reconnetCompletionHandle = (Bool) ->()
class SESocketManager: NSObject, GCDAsyncSocketDelegate {
open var delegate: SocketManagerDelegate?
var reconncetStatusHandle : reconnetCompletionHandle? // 为了后续业务上用户主动连接处理
static let instance = SESocketManager()
var connectStatus = 0 //connect status:1 connect,-1 disconnect,0 connecting
var reconnectionCount = 0
var beatTimer:Timer!
var reconnectTimer:Timer!
var clientSocket:GCDAsyncSocket!
override init() {
super.init()
clientSocket = GCDAsyncSocket()
clientSocket.delegate = self
clientSocket.delegateQueue = DispatchQueue.main
creatSocketToConnectServer()
}
/**
用户主动重新连接(一般业务都有这个需求:断网后用户下拉)
*/
public func getReconncetHandle(handle: @escaping reconnetCompletionHandle) {
self.reconncetStatusHandle = handle
reconnection()
}
}
extension SESocketManager {
/**
创建长连接
*/
func creatSocketToConnectServer() -> Void {
do {
connectStatus = 0
try clientSocket.connect(toHost: kConnectorHost, onPort: UInt16(kConnectorPort), withTimeout: TimeInterval(timeOut))
} catch {
print("conncet error")
}
}
/**
长连接建立后 开始与服务器校验登录
*/
func socketDidConnectCreatLogin() -> Void {
let login = ["c":"1","p":"ca5542d60da951afeb3a8bc5152211a7","d":"dev_"]
socketWriteDataToServer(body: login)
reconnectionCount = 0
connectStatus = 1
reconncetStatusHandle?(true)
delegate?.reconnectionSuccess()
guard let timer = self.reconnectTimer else {
return
}
timer.invalidate()
}
/**
长连接建立后 开始发送心跳包
*/
func socketDidConnectBeginSendBeat() -> Void {
beatTimer = Timer.scheduledTimer(timeInterval: TimeInterval(heartBeatTimeinterval),
target: self,
selector: #selector(sendBeat),
userInfo: nil,
repeats: true)
RunLoop.current.add(beatTimer, forMode: RunLoopMode.commonModes)
}
/**
向服务器发送心跳包
*/
@objc func sendBeat() {
let beat = ["c":"3"]
socketWriteDataToServer(body:beat)
}
/**
向服务器发送数据
*/
func socketWriteDataToServer(body: Dictionary<String, Any>) {
// 1: do 2: try? 3: try!
guard let data:Data = try? Data(JSONSerialization.data(withJSONObject: body,
options: JSONSerialization.WritingOptions(rawValue: 1))) else {
return
}
print(body)
clientSocket.write(data, withTimeout: -1, tag: 0)
clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
}
/**
接收到服务器的数据
*/
func socketDidReadData(data:Data, tag:Int) -> Void {
delegate?.didReadData(data: data, tag: tag)
}
/**
重新连接操作
*/
func socketDidDisconectBeginSendReconnect() -> Void {
connectStatus = -1
if reconnectionCount >= 0 && reconnectionCount < beatLimit {
reconnectionCount = reconnectionCount + 1
timerInvalidate(timer: reconnectTimer)
let time:TimeInterval = pow(2, Double(reconnectionCount))
reconnectTimer = Timer.scheduledTimer(timeInterval: time,
target: self,
selector: #selector(reconnection),
userInfo: nil,
repeats: true)
RunLoop.current.add(reconnectTimer, forMode: RunLoopMode.commonModes)
} else {
reconnectionCount = -1
reconncetStatusHandle?(false)
timerInvalidate(timer: reconnectTimer)
}
}
/**
重新连接 在网络状态不佳或者断网情况下把具体情况抛出去处理
*/
@objc func reconnection() -> Void {
/**
在瞬间切换到后台再切回程序时状态某些时候不改变
但是未连接,所以添加一个重新连接时先断开连接
*/
if connectStatus != -1 {
clientSocket.disconnect()
}
// 重新初始化连接
creatSocketToConnectServer()
}
func timerInvalidate(timer: Timer!) -> Void {
guard let inTimer = timer else {
return
}
inTimer.invalidate()
}
}
/**
socket delegate
*/
extension SESocketManager {
/**
与服务器建立连接后根据业务需求发送登录请求、心跳包
*/
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
print("Successful")
socketDidConnectCreatLogin()
socketDidConnectBeginSendBeat()
}
/**
服务器接收到数据 -->> 接收到数据后抛出去
*/
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) -> Void {
clientSocket.write(data, withTimeout: -1, tag: 0)
clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
socketDidReadData(data: data, tag: tag)
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) -> Void {
clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
}
/**
断开连接
*/
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) -> Void {
socketDidDisconectBeginSendReconnect()
}
}
| 26.86758 | 129 | 0.553025 |
26f69d94c7b62a4e1b3db2f77059986131abf11a
| 2,471 |
//
// CarouselAnimatedFlowLayout.swift
// CarouselExample
//
// Created by Kumar, Sumit on 25/03/20.
// Copyright © 2020 sk. All rights reserved.
//
import Foundation
import UIKit
class CarouselAnimatedFlowLayout: CarouselFlowLayout {
// MARK: - Functions
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let rectAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
for attribute in rectAttributes where attribute.representedElementCategory == .cell {
configureAttributes(for: attribute)
}
return rectAttributes
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return .zero }
// Adding some snapping behaviour so that the zoomed cell is always centered
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.frame.width, height: collectionView.frame.height)
guard let rectAttributes = super.layoutAttributesForElements(in: targetRect) else { return .zero }
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalCenter = proposedContentOffset.x + collectionView.frame.width / 2
for layoutAttributes in rectAttributes {
let itemHorizontalCenter = layoutAttributes.center.x
if (itemHorizontalCenter - horizontalCenter).magnitude < offsetAdjustment.magnitude {
offsetAdjustment = itemHorizontalCenter - horizontalCenter
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
// Invalidate layout so that every cell get a chance to be zoomed when it reaches the center of the screen
return true
}
// swiftlint:disable force_cast
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
| 44.125 | 148 | 0.719142 |
4ade0a98677035dcd4dbe0e24a9fc11da558858e
| 666 |
//
// MockSynchronizer.swift
// HealthDataSync_Tests
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import Foundation
import HealthKit
public class MockSynchronizer : HDSObjectSynchronizer {
public var synchronizeCompletions = [Error?]()
public var synchronizeParams = [(objects: [HKObject]?, deletedObjects: [HKDeletedObject]?)]()
open override func synchronize(objects: [HKObject]?, deletedObjects: [HKDeletedObject]?, completion: @escaping (Error?) -> Void) {
synchronizeParams.append((objects, deletedObjects))
let comp = synchronizeCompletions.removeFirst()
completion(comp)
}
}
| 31.714286 | 134 | 0.717718 |
0e240890ce2f01816695adf6304e3a515298e107
| 72,917 |
//
// CarbStoreTests.swift
// LoopKitTests
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import XCTest
import HealthKit
import CoreData
@testable import LoopKit
class CarbStorePersistenceTests: PersistenceControllerTestCase, CarbStoreDelegate {
var healthStore: HKHealthStoreMock!
var carbStore: CarbStore!
override func setUp() {
super.setUp()
healthStore = HKHealthStoreMock()
carbStore = CarbStore(
healthStore: healthStore,
cacheStore: cacheStore,
cacheLength: .hours(24),
defaultAbsorptionTimes: (fast: .minutes(30), medium: .hours(3), slow: .hours(5)),
observationInterval: 0,
provenanceIdentifier: Bundle.main.bundleIdentifier!)
carbStore.testQueryStore = healthStore
carbStore.delegate = self
}
override func tearDown() {
carbStore.delegate = nil
carbStore = nil
healthStore = nil
carbStoreHasUpdatedCarbDataHandler = nil
super.tearDown()
}
// MARK: - CarbStoreDelegate
var carbStoreHasUpdatedCarbDataHandler: ((_ : CarbStore) -> Void)?
func carbStoreHasUpdatedCarbData(_ carbStore: CarbStore) {
carbStoreHasUpdatedCarbDataHandler?(carbStore)
}
func carbStore(_ carbStore: CarbStore, didError error: CarbStore.CarbStoreError) {}
// MARK: -
func testGetCarbEntriesAfterAdd() {
let firstCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(timeIntervalSinceNow: -1), foodType: "First", absorptionTime: .hours(5))
let secondCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 20), startDate: Date(), foodType: "Second", absorptionTime: .hours(3))
let thirdCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 30), startDate: Date(timeIntervalSinceNow: 1), foodType: "Third", absorptionTime: .minutes(30))
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
carbStore.addCarbEntry(firstCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.addCarbEntry(secondCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.addCarbEntry(thirdCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 3)
// First
XCTAssertNotNil(entries[0].uuid)
XCTAssertEqual(entries[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(entries[0].syncIdentifier)
XCTAssertEqual(entries[0].syncVersion, 1)
XCTAssertEqual(entries[0].startDate, firstCarbEntry.startDate)
XCTAssertEqual(entries[0].quantity, firstCarbEntry.quantity)
XCTAssertEqual(entries[0].foodType, firstCarbEntry.foodType)
XCTAssertEqual(entries[0].absorptionTime, firstCarbEntry.absorptionTime)
XCTAssertEqual(entries[0].createdByCurrentApp, true)
XCTAssertEqual(entries[0].userCreatedDate, firstCarbEntry.date)
XCTAssertNil(entries[0].userUpdatedDate)
// Second
XCTAssertNotNil(entries[1].uuid)
XCTAssertEqual(entries[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(entries[1].syncIdentifier)
XCTAssertEqual(entries[1].syncVersion, 1)
XCTAssertEqual(entries[1].startDate, secondCarbEntry.startDate)
XCTAssertEqual(entries[1].quantity, secondCarbEntry.quantity)
XCTAssertEqual(entries[1].foodType, secondCarbEntry.foodType)
XCTAssertEqual(entries[1].absorptionTime, secondCarbEntry.absorptionTime)
XCTAssertEqual(entries[1].createdByCurrentApp, true)
XCTAssertEqual(entries[1].userCreatedDate, secondCarbEntry.date)
XCTAssertNil(entries[1].userUpdatedDate)
// Third
XCTAssertNotNil(entries[2].uuid)
XCTAssertEqual(entries[2].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(entries[2].syncIdentifier)
XCTAssertEqual(entries[2].syncVersion, 1)
XCTAssertEqual(entries[2].startDate, thirdCarbEntry.startDate)
XCTAssertEqual(entries[2].quantity, thirdCarbEntry.quantity)
XCTAssertEqual(entries[2].foodType, thirdCarbEntry.foodType)
XCTAssertEqual(entries[2].absorptionTime, thirdCarbEntry.absorptionTime)
XCTAssertEqual(entries[2].createdByCurrentApp, true)
XCTAssertEqual(entries[2].userCreatedDate, thirdCarbEntry.date)
XCTAssertNil(entries[2].userUpdatedDate)
}
}
}
}
}
}
}
}
wait(for: [getCarbEntriesCompletion], timeout: 2, enforceOrder: true)
}
// MARK: -
func testAddCarbEntry() {
let addCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: "Add", absorptionTime: .hours(3))
let addHealthStoreHandler = expectation(description: "Add health store handler")
let addCarbEntryCompletion = expectation(description: "Add carb entry completion")
let addCarbEntryHandler = expectation(description: "Add carb entry handler")
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
var handlerInvocation = 0
var addUUID: UUID?
var addSyncIdentifier: String?
healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertEqual(sample.absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, addCarbEntry.foodType)
XCTAssertEqual(sample.quantity, addCarbEntry.quantity)
XCTAssertEqual(sample.startDate, addCarbEntry.startDate)
XCTAssertNotNil(sample.syncIdentifier)
XCTAssertEqual(sample.syncVersion, 1)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertNil(sample.userUpdatedDate)
addUUID = sample.uuid
addSyncIdentifier = sample.syncIdentifier
addHealthStoreHandler.fulfill()
})
carbStoreHasUpdatedCarbDataHandler = { (carbStore) in
handlerInvocation += 1
self.cacheStore.managedObjectContext.performAndWait {
switch handlerInvocation {
case 1:
addCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(objects.count, 1)
// Added object
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNil(objects[0].supercededDate)
XCTAssertGreaterThan(objects[0].anchorKey, 0)
DispatchQueue.main.async {
carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 1)
// Added sample
XCTAssertEqual(entries[0].uuid, addUUID)
XCTAssertEqual(entries[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(entries[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(entries[0].syncVersion, 1)
XCTAssertEqual(entries[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(entries[0].quantity, addCarbEntry.quantity)
XCTAssertEqual(entries[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(entries[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(entries[0].createdByCurrentApp, true)
XCTAssertEqual(entries[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(entries[0].userUpdatedDate)
}
}
}
default:
XCTFail("Unexpected handler invocation")
}
}
}
carbStore.addCarbEntry(addCarbEntry) { (result) in
addCarbEntryCompletion.fulfill()
}
wait(for: [addHealthStoreHandler, addCarbEntryCompletion, addCarbEntryHandler, getCarbEntriesCompletion], timeout: 10, enforceOrder: true)
}
func testAddAndReplaceCarbEntry() {
let addCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: "Add", absorptionTime: .hours(3))
let replaceCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: "Replace", absorptionTime: .hours(4))
let addHealthStoreHandler = expectation(description: "Add health store handler")
let addCarbEntryCompletion = expectation(description: "Add carb entry completion")
let addCarbEntryHandler = expectation(description: "Add carb entry handler")
let updateHealthStoreHandler = expectation(description: "Update health store handler")
let updateCarbEntryCompletion = expectation(description: "Update carb entry completion")
let updateCarbEntryHandler = expectation(description: "Update carb entry handler")
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
var handlerInvocation = 0
var addUUID: UUID?
var addSyncIdentifier: String?
var addAnchorKey: Int64?
var updateUUID: UUID?
healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertEqual(sample.absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, addCarbEntry.foodType)
XCTAssertEqual(sample.quantity, addCarbEntry.quantity)
XCTAssertEqual(sample.startDate, addCarbEntry.startDate)
XCTAssertNotNil(sample.syncIdentifier)
XCTAssertEqual(sample.syncVersion, 1)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertNil(sample.userUpdatedDate)
addUUID = sample.uuid
addSyncIdentifier = sample.syncIdentifier
addHealthStoreHandler.fulfill()
})
carbStoreHasUpdatedCarbDataHandler = { (carbStore) in
handlerInvocation += 1
self.cacheStore.managedObjectContext.performAndWait {
switch handlerInvocation {
case 1:
addCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(objects.count, 1)
// Added object
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNil(objects[0].supercededDate)
XCTAssertGreaterThan(objects[0].anchorKey, 0)
addAnchorKey = objects[0].anchorKey
self.healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertNotEqual(sample.uuid, addUUID)
XCTAssertEqual(sample.absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, replaceCarbEntry.foodType)
XCTAssertEqual(sample.quantity, replaceCarbEntry.quantity)
XCTAssertEqual(sample.startDate, replaceCarbEntry.startDate)
XCTAssertEqual(sample.syncIdentifier, addSyncIdentifier)
XCTAssertEqual(sample.syncVersion, 2)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertEqual(sample.userUpdatedDate, replaceCarbEntry.date)
updateUUID = sample.uuid
updateHealthStoreHandler.fulfill()
})
self.carbStore.replaceCarbEntry(StoredCarbEntry(managedObject: objects[0]), withEntry: replaceCarbEntry) { (result) in
updateCarbEntryCompletion.fulfill()
}
case 2:
updateCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all().sorted { $0.syncVersion! < $1.syncVersion! }
XCTAssertEqual(objects.count, 2)
// Added object, superceded
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNotNil(objects[0].supercededDate)
XCTAssertEqual(objects[0].anchorKey, addAnchorKey)
// Updated object
XCTAssertEqual(objects[1].absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(objects[1].createdByCurrentApp, true)
XCTAssertEqual(objects[1].foodType, replaceCarbEntry.foodType)
XCTAssertEqual(objects[1].grams, replaceCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[1].startDate, replaceCarbEntry.startDate)
XCTAssertEqual(objects[1].uuid, updateUUID)
XCTAssertEqual(objects[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[1].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[1].syncVersion, 2)
XCTAssertEqual(objects[1].userCreatedDate, addCarbEntry.date)
XCTAssertEqual(objects[1].userUpdatedDate, replaceCarbEntry.date)
XCTAssertNil(objects[1].userDeletedDate)
XCTAssertEqual(objects[1].operation, .update)
XCTAssertNotNil(objects[1].addedDate)
XCTAssertNil(objects[1].supercededDate)
XCTAssertGreaterThan(objects[1].anchorKey, addAnchorKey!)
DispatchQueue.main.async {
carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 1)
// Updated sample
XCTAssertEqual(entries[0].uuid, updateUUID)
XCTAssertEqual(entries[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(entries[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(entries[0].syncVersion, 2)
XCTAssertEqual(entries[0].startDate, replaceCarbEntry.startDate)
XCTAssertEqual(entries[0].quantity, replaceCarbEntry.quantity)
XCTAssertEqual(entries[0].foodType, replaceCarbEntry.foodType)
XCTAssertEqual(entries[0].absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(entries[0].createdByCurrentApp, true)
XCTAssertEqual(entries[0].userCreatedDate, addCarbEntry.date)
XCTAssertEqual(entries[0].userUpdatedDate, replaceCarbEntry.date)
}
}
}
default:
XCTFail("Unexpected handler invocation")
}
}
}
carbStore.addCarbEntry(addCarbEntry) { (result) in
addCarbEntryCompletion.fulfill()
}
wait(for: [addHealthStoreHandler, addCarbEntryCompletion, addCarbEntryHandler, updateHealthStoreHandler, updateCarbEntryCompletion, updateCarbEntryHandler, getCarbEntriesCompletion], timeout: 10, enforceOrder: true)
}
func testAddAndDeleteCarbEntry() {
let addCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: "Add", absorptionTime: .hours(3))
let addHealthStoreHandler = expectation(description: "Add health store handler")
let addCarbEntryCompletion = expectation(description: "Add carb entry completion")
let addCarbEntryHandler = expectation(description: "Add carb entry handler")
let deleteHealthStoreHandler = expectation(description: "Delete health store handler")
let deleteCarbEntryCompletion = expectation(description: "Delete carb entry completion")
let deleteCarbEntryHandler = expectation(description: "Delete carb entry handler")
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
var handlerInvocation = 0
var addUUID: UUID?
var addSyncIdentifier: String?
var addAnchorKey: Int64?
healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertEqual(sample.absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, addCarbEntry.foodType)
XCTAssertEqual(sample.quantity, addCarbEntry.quantity)
XCTAssertEqual(sample.startDate, addCarbEntry.startDate)
XCTAssertNotNil(sample.syncIdentifier)
XCTAssertEqual(sample.syncVersion, 1)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertNil(sample.userUpdatedDate)
addUUID = sample.uuid
addSyncIdentifier = sample.syncIdentifier
addHealthStoreHandler.fulfill()
})
carbStoreHasUpdatedCarbDataHandler = { (carbStore) in
handlerInvocation += 1
self.cacheStore.managedObjectContext.performAndWait {
switch handlerInvocation {
case 1:
addCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(objects.count, 1)
// Added object
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNil(objects[0].supercededDate)
XCTAssertGreaterThan(objects[0].anchorKey, 0)
addUUID = objects[0].uuid
addSyncIdentifier = objects[0].syncIdentifier
addAnchorKey = objects[0].anchorKey
self.healthStore.setDeletedObjectsHandler({ (objectType, predicate, success, count, error) in
XCTAssertEqual(objectType, HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates))
XCTAssertEqual(predicate.predicateFormat, "UUID == \(addUUID!)")
deleteHealthStoreHandler.fulfill()
})
self.carbStore.deleteCarbEntry(StoredCarbEntry(managedObject: objects[0])) { (result) in
deleteCarbEntryCompletion.fulfill()
}
case 2:
deleteCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(objects.count, 2)
// Added object, superceded
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNotNil(objects[0].supercededDate)
XCTAssertEqual(objects[0].anchorKey, addAnchorKey)
// Deleted object
XCTAssertEqual(objects[1].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[1].createdByCurrentApp, true)
XCTAssertEqual(objects[1].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[1].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[1].startDate, addCarbEntry.startDate)
XCTAssertNil(objects[1].uuid)
XCTAssertEqual(objects[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[1].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[1].syncVersion, 1)
XCTAssertEqual(objects[1].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[1].userUpdatedDate)
XCTAssertNotNil(objects[1].userDeletedDate)
XCTAssertEqual(objects[1].operation, .delete)
XCTAssertNotNil(objects[1].addedDate)
XCTAssertNil(objects[1].supercededDate)
XCTAssertGreaterThan(objects[1].anchorKey, addAnchorKey!)
DispatchQueue.main.async {
carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 0)
}
}
}
default:
XCTFail("Unexpected handler invocation")
}
}
}
carbStore.addCarbEntry(addCarbEntry) { (result) in
addCarbEntryCompletion.fulfill()
}
wait(for: [addHealthStoreHandler, addCarbEntryCompletion, addCarbEntryHandler, deleteHealthStoreHandler, deleteCarbEntryCompletion, deleteCarbEntryHandler, getCarbEntriesCompletion], timeout: 10, enforceOrder: true)
}
func testAddAndReplaceAndDeleteCarbEntry() {
let addCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: "Add", absorptionTime: .hours(3))
let replaceCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: "Replace", absorptionTime: .hours(4))
let addHealthStoreHandler = expectation(description: "Add health store handler")
let addCarbEntryCompletion = expectation(description: "Add carb entry completion")
let addCarbEntryHandler = expectation(description: "Add carb entry handler")
let updateHealthStoreHandler = expectation(description: "Update health store handler")
let updateCarbEntryCompletion = expectation(description: "Update carb entry completion")
let updateCarbEntryHandler = expectation(description: "Update carb entry handler")
let deleteHealthStoreHandler = expectation(description: "Delete health store handler")
let deleteCarbEntryCompletion = expectation(description: "Delete carb entry completion")
let deleteCarbEntryHandler = expectation(description: "Delete carb entry handler")
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
var handlerInvocation = 0
var addUUID: UUID?
var addSyncIdentifier: String?
var addAnchorKey: Int64?
var updateUUID: UUID?
var updateAnchorKey: Int64?
healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertEqual(sample.absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, addCarbEntry.foodType)
XCTAssertEqual(sample.quantity, addCarbEntry.quantity)
XCTAssertEqual(sample.startDate, addCarbEntry.startDate)
XCTAssertNotNil(sample.syncIdentifier)
XCTAssertEqual(sample.syncVersion, 1)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertNil(sample.userUpdatedDate)
addUUID = sample.uuid
addSyncIdentifier = sample.syncIdentifier
addHealthStoreHandler.fulfill()
})
carbStoreHasUpdatedCarbDataHandler = { (carbStore) in
handlerInvocation += 1
self.cacheStore.managedObjectContext.performAndWait {
switch handlerInvocation {
case 1:
addCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(objects.count, 1)
// Added object
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNil(objects[0].supercededDate)
XCTAssertGreaterThan(objects[0].anchorKey, 0)
addAnchorKey = objects[0].anchorKey
self.healthStore.setSaveHandler({ (objects, success, error) in
XCTAssertEqual(1, objects.count)
let sample = objects.first as! HKQuantitySample
XCTAssertNotEqual(sample.uuid, addUUID)
XCTAssertEqual(sample.absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(sample.foodType, replaceCarbEntry.foodType)
XCTAssertEqual(sample.quantity, replaceCarbEntry.quantity)
XCTAssertEqual(sample.startDate, replaceCarbEntry.startDate)
XCTAssertEqual(sample.syncIdentifier, addSyncIdentifier)
XCTAssertEqual(sample.syncVersion, 2)
XCTAssertEqual(sample.userCreatedDate, addCarbEntry.date)
XCTAssertEqual(sample.userUpdatedDate, replaceCarbEntry.date)
updateUUID = sample.uuid
updateHealthStoreHandler.fulfill()
})
self.carbStore.replaceCarbEntry(StoredCarbEntry(managedObject: objects[0]), withEntry: replaceCarbEntry) { (result) in
updateCarbEntryCompletion.fulfill()
}
case 2:
updateCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all().sorted { $0.syncVersion! < $1.syncVersion! }
XCTAssertEqual(objects.count, 2)
// Added object, superceded
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNotNil(objects[0].supercededDate)
XCTAssertEqual(objects[0].anchorKey, addAnchorKey)
// Updated object
XCTAssertEqual(objects[1].absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(objects[1].createdByCurrentApp, true)
XCTAssertEqual(objects[1].foodType, replaceCarbEntry.foodType)
XCTAssertEqual(objects[1].grams, replaceCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[1].startDate, replaceCarbEntry.startDate)
XCTAssertEqual(objects[1].uuid, updateUUID)
XCTAssertEqual(objects[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[1].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[1].syncVersion, 2)
XCTAssertEqual(objects[1].userCreatedDate, addCarbEntry.date)
XCTAssertEqual(objects[1].userUpdatedDate, replaceCarbEntry.date)
XCTAssertNil(objects[1].userDeletedDate)
XCTAssertEqual(objects[1].operation, .update)
XCTAssertNotNil(objects[1].addedDate)
XCTAssertNil(objects[1].supercededDate)
XCTAssertGreaterThan(objects[1].anchorKey, addAnchorKey!)
updateAnchorKey = objects[1].anchorKey
self.healthStore.setDeletedObjectsHandler({ (objectType, predicate, success, count, error) in
XCTAssertEqual(objectType, HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates))
XCTAssertEqual(predicate.predicateFormat, "UUID == \(updateUUID!)")
deleteHealthStoreHandler.fulfill()
})
self.carbStore.deleteCarbEntry(StoredCarbEntry(managedObject: objects[1])) { (result) in
deleteCarbEntryCompletion.fulfill()
}
case 3:
deleteCarbEntryHandler.fulfill()
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all().sorted { $0.syncVersion! < $1.syncVersion! }
XCTAssertEqual(objects.count, 3)
// Added object, superceded
XCTAssertEqual(objects[0].absorptionTime, addCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, addCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, addCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, addCarbEntry.startDate)
XCTAssertEqual(objects[0].uuid, addUUID)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[0].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, addCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNotNil(objects[0].supercededDate)
XCTAssertEqual(objects[0].anchorKey, addAnchorKey)
// Updated object, superceded
XCTAssertEqual(objects[1].absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(objects[1].createdByCurrentApp, true)
XCTAssertEqual(objects[1].foodType, replaceCarbEntry.foodType)
XCTAssertEqual(objects[1].grams, replaceCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[1].startDate, replaceCarbEntry.startDate)
XCTAssertEqual(objects[1].uuid, updateUUID)
XCTAssertEqual(objects[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[1].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[1].syncVersion, 2)
XCTAssertEqual(objects[1].userCreatedDate, addCarbEntry.date)
XCTAssertEqual(objects[1].userUpdatedDate, replaceCarbEntry.date)
XCTAssertNil(objects[1].userDeletedDate)
XCTAssertEqual(objects[1].operation, .update)
XCTAssertNotNil(objects[1].addedDate)
XCTAssertNotNil(objects[1].supercededDate)
XCTAssertEqual(objects[1].anchorKey, updateAnchorKey)
// Deleted object
XCTAssertEqual(objects[2].absorptionTime, replaceCarbEntry.absorptionTime)
XCTAssertEqual(objects[2].createdByCurrentApp, true)
XCTAssertEqual(objects[2].foodType, replaceCarbEntry.foodType)
XCTAssertEqual(objects[2].grams, replaceCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[2].startDate, replaceCarbEntry.startDate)
XCTAssertNil(objects[2].uuid)
XCTAssertEqual(objects[2].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertEqual(objects[2].syncIdentifier, addSyncIdentifier)
XCTAssertEqual(objects[2].syncVersion, 2)
XCTAssertEqual(objects[2].userCreatedDate, addCarbEntry.date)
XCTAssertEqual(objects[2].userUpdatedDate, replaceCarbEntry.date)
XCTAssertNotNil(objects[2].userDeletedDate)
XCTAssertEqual(objects[2].operation, .delete)
XCTAssertNotNil(objects[2].addedDate)
XCTAssertNil(objects[2].supercededDate)
XCTAssertGreaterThan(objects[2].anchorKey, updateAnchorKey!)
DispatchQueue.main.async {
carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 0)
}
}
}
default:
XCTFail("Unexpected handler invocation")
}
}
}
carbStore.addCarbEntry(addCarbEntry) { (result) in
addCarbEntryCompletion.fulfill()
}
wait(for: [addHealthStoreHandler, addCarbEntryCompletion, addCarbEntryHandler, updateHealthStoreHandler, updateCarbEntryCompletion, updateCarbEntryHandler, deleteHealthStoreHandler, deleteCarbEntryCompletion, deleteCarbEntryHandler, getCarbEntriesCompletion], timeout: 10, enforceOrder: true)
}
// MARK: -
func testGetSyncCarbObjects() {
let firstCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(timeIntervalSinceNow: -1), foodType: "First", absorptionTime: .hours(5))
let secondCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 20), startDate: Date(), foodType: "Second", absorptionTime: .hours(3))
let thirdCarbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 30), startDate: Date(timeIntervalSinceNow: 1), foodType: "Third", absorptionTime: .minutes(30))
let getSyncCarbObjectsCompletion = expectation(description: "Get sync carb objects completion")
carbStore.addCarbEntry(firstCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.addCarbEntry(secondCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.addCarbEntry(thirdCarbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.getSyncCarbObjects(start: Date().addingTimeInterval(-.minutes(1))) { result in
getSyncCarbObjectsCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 3)
// First
XCTAssertEqual(objects[0].absorptionTime, firstCarbEntry.absorptionTime)
XCTAssertEqual(objects[0].createdByCurrentApp, true)
XCTAssertEqual(objects[0].foodType, firstCarbEntry.foodType)
XCTAssertEqual(objects[0].grams, firstCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[0].startDate, firstCarbEntry.startDate)
XCTAssertNotNil(objects[0].uuid)
XCTAssertEqual(objects[0].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(objects[0].syncIdentifier)
XCTAssertEqual(objects[0].syncVersion, 1)
XCTAssertEqual(objects[0].userCreatedDate, firstCarbEntry.date)
XCTAssertNil(objects[0].userUpdatedDate)
XCTAssertNil(objects[0].userDeletedDate)
XCTAssertEqual(objects[0].operation, .create)
XCTAssertNotNil(objects[0].addedDate)
XCTAssertNil(objects[0].supercededDate)
// Second
XCTAssertEqual(objects[1].absorptionTime, secondCarbEntry.absorptionTime)
XCTAssertEqual(objects[1].createdByCurrentApp, true)
XCTAssertEqual(objects[1].foodType, secondCarbEntry.foodType)
XCTAssertEqual(objects[1].grams, secondCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[1].startDate, secondCarbEntry.startDate)
XCTAssertNotNil(objects[1].uuid)
XCTAssertEqual(objects[1].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(objects[1].syncIdentifier)
XCTAssertEqual(objects[1].syncVersion, 1)
XCTAssertEqual(objects[1].userCreatedDate, secondCarbEntry.date)
XCTAssertNil(objects[1].userUpdatedDate)
XCTAssertNil(objects[1].userDeletedDate)
XCTAssertEqual(objects[1].operation, .create)
XCTAssertNotNil(objects[1].addedDate)
XCTAssertNil(objects[1].supercededDate)
// Third
XCTAssertEqual(objects[2].absorptionTime, thirdCarbEntry.absorptionTime)
XCTAssertEqual(objects[2].createdByCurrentApp, true)
XCTAssertEqual(objects[2].foodType, thirdCarbEntry.foodType)
XCTAssertEqual(objects[2].grams, thirdCarbEntry.quantity.doubleValue(for: .gram()))
XCTAssertEqual(objects[2].startDate, thirdCarbEntry.startDate)
XCTAssertNotNil(objects[2].uuid)
XCTAssertEqual(objects[2].provenanceIdentifier, Bundle.main.bundleIdentifier!)
XCTAssertNotNil(objects[2].syncIdentifier)
XCTAssertEqual(objects[2].syncVersion, 1)
XCTAssertEqual(objects[2].userCreatedDate, thirdCarbEntry.date)
XCTAssertNil(objects[2].userUpdatedDate)
XCTAssertNil(objects[2].userDeletedDate)
XCTAssertEqual(objects[2].operation, .create)
XCTAssertNotNil(objects[2].addedDate)
XCTAssertNil(objects[2].supercededDate)
}
}
}
}
}
}
}
}
wait(for: [getSyncCarbObjectsCompletion], timeout: 2, enforceOrder: true)
}
func testSetSyncCarbObjects() {
let carbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(timeIntervalSinceNow: -1), foodType: "First", absorptionTime: .hours(5))
let syncCarbObjects = [SyncCarbObject(absorptionTime: .hours(5),
createdByCurrentApp: true,
foodType: "Pizza",
grams: 45,
startDate: Date(timeIntervalSinceNow: -30),
uuid: UUID(),
provenanceIdentifier: "com.loopkit.Loop",
syncIdentifier: UUID().uuidString,
syncVersion: 4,
userCreatedDate: Date(timeIntervalSinceNow: -35),
userUpdatedDate: Date(timeIntervalSinceNow: -34),
userDeletedDate: nil,
operation: .update,
addedDate: Date(timeIntervalSinceNow: -34),
supercededDate: nil),
SyncCarbObject(absorptionTime: .hours(3),
createdByCurrentApp: false,
foodType: "Pasta",
grams: 25,
startDate: Date(timeIntervalSinceNow: -15),
uuid: UUID(),
provenanceIdentifier: "com.abc.Example",
syncIdentifier: UUID().uuidString,
syncVersion: 1,
userCreatedDate: Date(timeIntervalSinceNow: -16),
userUpdatedDate: nil,
userDeletedDate: nil,
operation: .create,
addedDate: Date(timeIntervalSinceNow: -16),
supercededDate: nil),
SyncCarbObject(absorptionTime: .minutes(30),
createdByCurrentApp: true,
foodType: "Sugar",
grams: 15,
startDate: Date(timeIntervalSinceNow: 0),
uuid: UUID(),
provenanceIdentifier: "com.loopkit.Loop",
syncIdentifier: UUID().uuidString,
syncVersion: 1,
userCreatedDate: Date(timeIntervalSinceNow: -1),
userUpdatedDate: nil,
userDeletedDate: nil,
operation: .create,
addedDate: Date(timeIntervalSinceNow: -1),
supercededDate: nil)
]
let getCarbEntriesCompletion = expectation(description: "Get carb entries completion")
// Add a carb entry first, that will be purged when setSyncCarbObjects is invoked
carbStore.addCarbEntry(carbEntry) { (_) in
DispatchQueue.main.async {
self.carbStore.setSyncCarbObjects(syncCarbObjects) { (error) in
XCTAssertNil(error)
DispatchQueue.main.async {
self.carbStore.getCarbEntries(start: Date().addingTimeInterval(-.minutes(1))) { result in
getCarbEntriesCompletion.fulfill()
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let entries):
XCTAssertEqual(entries.count, 3)
for index in 0..<3 {
XCTAssertEqual(entries[index].uuid, syncCarbObjects[index].uuid)
XCTAssertEqual(entries[index].provenanceIdentifier, syncCarbObjects[index].provenanceIdentifier)
XCTAssertEqual(entries[index].syncIdentifier, syncCarbObjects[index].syncIdentifier)
XCTAssertEqual(entries[index].syncVersion, syncCarbObjects[index].syncVersion)
XCTAssertEqual(entries[index].startDate, syncCarbObjects[index].startDate)
XCTAssertEqual(entries[index].quantity, syncCarbObjects[index].quantity)
XCTAssertEqual(entries[index].foodType, syncCarbObjects[index].foodType)
XCTAssertEqual(entries[index].absorptionTime, syncCarbObjects[index].absorptionTime)
XCTAssertEqual(entries[index].createdByCurrentApp, syncCarbObjects[index].createdByCurrentApp)
XCTAssertEqual(entries[index].userCreatedDate, syncCarbObjects[index].userCreatedDate)
XCTAssertEqual(entries[index].userCreatedDate, syncCarbObjects[index].userCreatedDate)
}
}
}
}
}
}
}
wait(for: [getCarbEntriesCompletion], timeout: 2, enforceOrder: true)
}
// MARK: -
private func generateSyncIdentifier() -> String {
return UUID().uuidString
}
}
class CarbStoreQueryAnchorTests: XCTestCase {
var rawValue: CarbStore.QueryAnchor.RawValue = [
"anchorKey": Int64(123)
]
func testInitializerDefault() {
let queryAnchor = CarbStore.QueryAnchor()
XCTAssertEqual(queryAnchor.anchorKey, 0)
}
func testInitializerRawValue() {
let queryAnchor = CarbStore.QueryAnchor(rawValue: rawValue)
XCTAssertNotNil(queryAnchor)
XCTAssertEqual(queryAnchor?.anchorKey, 123)
}
func testInitializerRawValueMissingAnchorKey() {
rawValue["anchorKey"] = nil
XCTAssertNil(CarbStore.QueryAnchor(rawValue: rawValue))
}
func testInitializerRawValueInvalidAnchorKey() {
rawValue["anchorKey"] = "123"
XCTAssertNil(CarbStore.QueryAnchor(rawValue: rawValue))
}
func testInitializerRawValueIgnoresDeprecatedStoredModificationCounter() {
rawValue["storedModificationCounter"] = Int64(456)
let queryAnchor = CarbStore.QueryAnchor(rawValue: rawValue)
XCTAssertNotNil(queryAnchor)
XCTAssertEqual(queryAnchor?.anchorKey, 123)
}
func testInitializerRawValueUsesDeprecatedStoredModificationCounter() {
rawValue["anchorKey"] = nil
rawValue["storedModificationCounter"] = Int64(456)
let queryAnchor = CarbStore.QueryAnchor(rawValue: rawValue)
XCTAssertNotNil(queryAnchor)
XCTAssertEqual(queryAnchor?.anchorKey, 456)
}
func testRawValueWithDefault() {
let rawValue = CarbStore.QueryAnchor().rawValue
XCTAssertEqual(rawValue.count, 1)
XCTAssertEqual(rawValue["anchorKey"] as? Int64, Int64(0))
}
func testRawValueWithNonDefault() {
var queryAnchor = CarbStore.QueryAnchor()
queryAnchor.anchorKey = 123
let rawValue = queryAnchor.rawValue
XCTAssertEqual(rawValue.count, 1)
XCTAssertEqual(rawValue["anchorKey"] as? Int64, Int64(123))
}
}
class CarbStoreQueryTests: PersistenceControllerTestCase {
var carbStore: CarbStore!
var completion: XCTestExpectation!
var queryAnchor: CarbStore.QueryAnchor!
var limit: Int!
override func setUp() {
super.setUp()
carbStore = CarbStore(
healthStore: HKHealthStoreMock(),
cacheStore: cacheStore,
cacheLength: .hours(24),
defaultAbsorptionTimes: (fast: .minutes(30), medium: .hours(3), slow: .hours(5)),
observationInterval: 0,
provenanceIdentifier: Bundle.main.bundleIdentifier!)
completion = expectation(description: "Completion")
queryAnchor = CarbStore.QueryAnchor()
limit = Int.max
}
override func tearDown() {
limit = nil
queryAnchor = nil
completion = nil
carbStore = nil
super.tearDown()
}
func testEmptyWithDefaultQueryAnchor() {
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 0)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testEmptyWithMissingQueryAnchor() {
queryAnchor = nil
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 0)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testEmptyWithNonDefaultQueryAnchor() {
queryAnchor.anchorKey = 1
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 1)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testDataWithUnusedQueryAnchor() {
let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()]
addData(withSyncIdentifiers: syncIdentifiers)
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 3)
XCTAssertEqual(created.count, 1)
XCTAssertEqual(created[0].syncIdentifier, syncIdentifiers[0])
XCTAssertEqual(created[0].syncVersion, 0)
XCTAssertEqual(updated.count, 1)
XCTAssertEqual(updated[0].syncIdentifier, syncIdentifiers[1])
XCTAssertEqual(updated[0].syncVersion, 1)
XCTAssertEqual(deleted.count, 1)
XCTAssertEqual(deleted[0].syncIdentifier, syncIdentifiers[2])
XCTAssertEqual(deleted[0].syncVersion, 2)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testDataWithStaleQueryAnchor() {
let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()]
addData(withSyncIdentifiers: syncIdentifiers)
queryAnchor.anchorKey = 2
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 3)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 1)
XCTAssertEqual(deleted[0].syncIdentifier, syncIdentifiers[2])
XCTAssertEqual(deleted[0].syncVersion, 2)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testDataWithCurrentQueryAnchor() {
let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()]
addData(withSyncIdentifiers: syncIdentifiers)
queryAnchor.anchorKey = 3
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 3)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testDataWithLimitZero() {
let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()]
addData(withSyncIdentifiers: syncIdentifiers)
limit = 0
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 0)
XCTAssertEqual(created.count, 0)
XCTAssertEqual(updated.count, 0)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
func testDataWithLimitCoveredByData() {
let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()]
addData(withSyncIdentifiers: syncIdentifiers)
limit = 2
carbStore.executeCarbQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let anchor, let created, let updated, let deleted):
XCTAssertEqual(anchor.anchorKey, 2)
XCTAssertEqual(created.count, 1)
XCTAssertEqual(created[0].syncIdentifier, syncIdentifiers[0])
XCTAssertEqual(created[0].syncVersion, 0)
XCTAssertEqual(updated.count, 1)
XCTAssertEqual(updated[0].syncIdentifier, syncIdentifiers[1])
XCTAssertEqual(updated[0].syncVersion, 1)
XCTAssertEqual(deleted.count, 0)
}
self.completion.fulfill()
}
wait(for: [completion], timeout: 2, enforceOrder: true)
}
private func addData(withSyncIdentifiers syncIdentifiers: [String]) {
cacheStore.managedObjectContext.performAndWait {
for (index, syncIdentifier) in syncIdentifiers.enumerated() {
let cachedCarbObject = CachedCarbObject(context: self.cacheStore.managedObjectContext)
cachedCarbObject.createdByCurrentApp = true
cachedCarbObject.startDate = Date()
cachedCarbObject.uuid = UUID()
cachedCarbObject.syncIdentifier = syncIdentifier
cachedCarbObject.syncVersion = index
cachedCarbObject.operation = Operation(rawValue: index % Operation.allCases.count)!
cachedCarbObject.addedDate = Date()
self.cacheStore.save()
}
}
}
private func generateSyncIdentifier() -> String {
return UUID().uuidString
}
}
class CarbStoreCriticalEventLogTests: PersistenceControllerTestCase {
var carbStore: CarbStore!
var outputStream: MockOutputStream!
var progress: Progress!
override func setUp() {
super.setUp()
let objects = [SyncCarbObject(absorptionTime: nil, createdByCurrentApp: true, foodType: nil, grams: 11, startDate: dateFormatter.date(from: "2100-01-02T03:08:00Z")!, uuid: nil, provenanceIdentifier: nil, syncIdentifier: nil, syncVersion: nil, userCreatedDate: nil, userUpdatedDate: nil, userDeletedDate: nil, operation: .create, addedDate: dateFormatter.date(from: "2100-01-02T03:08:00Z")!, supercededDate: nil),
SyncCarbObject(absorptionTime: nil, createdByCurrentApp: true, foodType: nil, grams: 12, startDate: dateFormatter.date(from: "2100-01-02T03:10:00Z")!, uuid: nil, provenanceIdentifier: nil, syncIdentifier: nil, syncVersion: nil, userCreatedDate: nil, userUpdatedDate: nil, userDeletedDate: nil, operation: .create, addedDate: dateFormatter.date(from: "2100-01-02T03:10:00Z")!, supercededDate: nil),
SyncCarbObject(absorptionTime: nil, createdByCurrentApp: true, foodType: nil, grams: 13, startDate: dateFormatter.date(from: "2100-01-02T03:04:00Z")!, uuid: nil, provenanceIdentifier: nil, syncIdentifier: nil, syncVersion: nil, userCreatedDate: nil, userUpdatedDate: nil, userDeletedDate: nil, operation: .create, addedDate: dateFormatter.date(from: "2100-01-02T02:04:00Z")!, supercededDate: dateFormatter.date(from: "2100-01-02T03:04:00Z")!),
SyncCarbObject(absorptionTime: nil, createdByCurrentApp: true, foodType: nil, grams: 14, startDate: dateFormatter.date(from: "2100-01-02T03:06:00Z")!, uuid: nil, provenanceIdentifier: nil, syncIdentifier: nil, syncVersion: nil, userCreatedDate: nil, userUpdatedDate: nil, userDeletedDate: nil, operation: .create, addedDate: dateFormatter.date(from: "2100-01-02T03:06:00Z")!, supercededDate: nil),
SyncCarbObject(absorptionTime: nil, createdByCurrentApp: true, foodType: nil, grams: 15, startDate: dateFormatter.date(from: "2100-01-02T03:02:00Z")!, uuid: nil, provenanceIdentifier: nil, syncIdentifier: nil, syncVersion: nil, userCreatedDate: nil, userUpdatedDate: nil, userDeletedDate: nil, operation: .create, addedDate: dateFormatter.date(from: "2100-01-02T03:02:00Z")!, supercededDate: nil)]
carbStore = CarbStore(
healthStore: HKHealthStoreMock(),
cacheStore: cacheStore,
cacheLength: .hours(24),
defaultAbsorptionTimes: (fast: .minutes(30), medium: .hours(3), slow: .hours(5)),
observationInterval: 0,
provenanceIdentifier: Bundle.main.bundleIdentifier!)
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
carbStore.setSyncCarbObjects(objects) { error in
XCTAssertNil(error)
dispatchGroup.leave()
}
dispatchGroup.wait()
outputStream = MockOutputStream()
progress = Progress()
}
override func tearDown() {
carbStore = nil
super.tearDown()
}
func testExportProgressTotalUnitCount() {
switch carbStore.exportProgressTotalUnitCount(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!,
endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!) {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let progressTotalUnitCount):
XCTAssertEqual(progressTotalUnitCount, 3 * 1)
}
}
func testExportProgressTotalUnitCountEmpty() {
switch carbStore.exportProgressTotalUnitCount(startDate: dateFormatter.date(from: "2100-01-02T03:00:00Z")!,
endDate: dateFormatter.date(from: "2100-01-02T03:01:00Z")!) {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let progressTotalUnitCount):
XCTAssertEqual(progressTotalUnitCount, 0)
}
}
func testExport() {
XCTAssertNil(carbStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!,
endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!,
to: outputStream,
progress: progress))
XCTAssertEqual(outputStream.string, """
[
{"addedDate":"2100-01-02T03:08:00.000Z","anchorKey":1,"createdByCurrentApp":true,"grams":11,"operation":0,"startDate":"2100-01-02T03:08:00.000Z"},
{"addedDate":"2100-01-02T02:04:00.000Z","anchorKey":3,"createdByCurrentApp":true,"grams":13,"operation":0,"startDate":"2100-01-02T03:04:00.000Z","supercededDate":"2100-01-02T03:04:00.000Z"},
{"addedDate":"2100-01-02T03:06:00.000Z","anchorKey":4,"createdByCurrentApp":true,"grams":14,"operation":0,"startDate":"2100-01-02T03:06:00.000Z"}
]
"""
)
XCTAssertEqual(progress.completedUnitCount, 3 * 1)
}
func testExportEmpty() {
XCTAssertNil(carbStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:00:00Z")!,
endDate: dateFormatter.date(from: "2100-01-02T03:01:00Z")!,
to: outputStream,
progress: progress))
XCTAssertEqual(outputStream.string, "[]")
XCTAssertEqual(progress.completedUnitCount, 0)
}
func testExportCancelled() {
progress.cancel()
XCTAssertEqual(carbStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!,
endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!,
to: outputStream,
progress: progress) as? CriticalEventLogError, CriticalEventLogError.cancelled)
}
private let dateFormatter = ISO8601DateFormatter()
}
| 54.701425 | 466 | 0.578096 |
3a60e35503dc1acc07e9bb73c37e2aff8157221c
| 501 |
//
// ViewController.swift
// macOSAppWithSPM
//
// Created by Andrey Kornich on 2020-02-06.
// Copyright © 2020 Andrey Kornich (Wide Spectrum Computing LLC). All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 17.892857 | 87 | 0.642715 |
1aa7d176edcbd1965d0809ae7200cc467fe7e3d1
| 445 |
import UIKit
import Anchors
import Hue
class CollectionViewCell: UICollectionViewCell {
let label = UILabel()
override func didMoveToSuperview() {
super.didMoveToSuperview()
addSubview(label)
activate(
label.anchor.center
)
backgroundColor = UIColor(hex: "#e67e22")
layer.cornerRadius = 5
layer.masksToBounds = true
label.font = UIFont.boldSystemFont(ofSize: 20)
label.textColor = .white
}
}
| 18.541667 | 50 | 0.698876 |
9be2c5030d6fa98f09dab030a648c56051701b96
| 2,170 |
//
// AppDelegate.swift
// KDSafetyTimer
//
// Created by Kingiol on 2018/7/21.
// Copyright © 2018 Kingiol. 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.170213 | 285 | 0.75576 |
1130cea6573644e31eef9e8cb3bad9dd393207bd
| 1,038 |
import Foundation
extension MercadoPagoCheckout {
func showPaymentMethodPluginConfigScreen() {
guard let paymentMethodPlugin = self.viewModel.paymentOptionSelected as? PXPaymentMethodPlugin else {
return
}
guard let paymentMethodConfigPluginComponent = paymentMethodPlugin.paymentMethodConfigPlugin else {
return
}
viewModel.populateCheckoutStore()
paymentMethodConfigPluginComponent.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance, theme: ThemeManager.shared.getCurrentTheme())
// Create navigation handler.
paymentMethodConfigPluginComponent.navigationHandler?(navigationHandler: PXPluginNavigationHandler(withCheckout: self))
if let configPluginVC = paymentMethodConfigPluginComponent.configViewController() {
viewModel.pxNavigationHandler.addDynamicView(viewController: configPluginVC)
viewModel.pxNavigationHandler.pushViewController(targetVC: configPluginVC, animated: true)
}
}
}
| 41.52 | 147 | 0.753372 |
ab0db22de2e1b382d1aaba2399c41ca07bc7cbc9
| 416 |
//
// Walk+CoreDataProperties.swift
// CoreData_Swift
//
// Created by 韩承海 on 2017/11/22.
// Copyright © 2017年 韩承海. All rights reserved.
//
//
import Foundation
import CoreData
extension Walk {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Walk> {
return NSFetchRequest<Walk>(entityName: "Walk")
}
@NSManaged public var date: NSDate?
@NSManaged public var dog: Dog?
}
| 17.333333 | 71 | 0.677885 |
11ab5cfe150ac3e972584d8fed6fc0a57f6ef562
| 1,369 |
//
// CCHDarwinNotificationCenter_ExampleTests.swift
// CCHDarwinNotificationCenter ExampleTests
//
// Created by Hoefele, Claus on 30.03.15.
// Copyright (c) 2015 Claus Höfele. All rights reserved.
//
import UIKit
import XCTest
let NOTIFICATION = "CCHDarwinNotificationCenterTests"
class CCHDarwinNotificationCenterTests: XCTestCase {
func testDarwinNotifications() {
let expectation = expectationForNotification(NOTIFICATION, object: nil, handler: nil)
CCHDarwinNotificationCenter.startForwardingDarwinNotificationsWithIdentifier(NOTIFICATION)
CCHDarwinNotificationCenter.postDarwinNotificationWithIdentifier(NOTIFICATION)
waitForExpectationsWithTimeout(1, handler: nil);
CCHDarwinNotificationCenter.stopForwardingDarwinNotificationsWithIdentifier(NOTIFICATION)
}
func testMangledNotifications() {
let expectation = expectationForNotification(NOTIFICATION, object: nil, handler: nil)
CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION, fromEndpoints: .All)
CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION)
waitForExpectationsWithTimeout(1, handler: nil);
CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION, fromEndpoints: .All)
}
}
| 37 | 113 | 0.775018 |
61b93339f0735a05c38ce2b4fd3c76acfe0a5235
| 3,684 |
//
// ArgumentsManager.swift
// urlcodec
//
// Created by larryhou on 1/8/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import Foundation
class ArgumentsManager
{
class ArgumentOption
{
let name:String, abbr:String, help:String, hasValue:Bool, trigger:()->Void
var value:String?
init(name:String, abbr:String, help:String, hasValue:Bool, trigger:()->Void)
{
self.name = name
self.abbr = abbr
self.help = help
self.hasValue = hasValue
self.trigger = trigger
}
}
private var map:[String:ArgumentOption]
private var options:[ArgumentOption]
private var pattern:NSRegularExpression!
private var name:String
private var usageAppending:String
init(name:String, usageAppending:String = "")
{
self.name = name
self.usageAppending = usageAppending
self.options = []
self.map = [:]
do
{
pattern = try NSRegularExpression(pattern: "^-[a-z]+|--[a-z_-]{2,}$", options: NSRegularExpressionOptions.CaseInsensitive)
}
catch {}
}
func insertOption(name:String, abbr:String, help:String, hasValue:Bool, trigger:()->Void)
{
if name == "" && abbr == ""
{
return
}
let argOption = ArgumentOption(name: name, abbr: abbr, help: help, hasValue: hasValue, trigger: trigger)
options.append(argOption)
map[name] = argOption
map[abbr] = argOption
}
func getOption(name:String) -> ArgumentOption?
{
return map[name]
}
func recognizeOption(value:String, triggerWhenMatch:Bool = false) -> Bool
{
let matches = pattern.matchesInString(value,
options: NSMatchingOptions.ReportProgress,
range: NSRange(location: 0, length: NSString(string: value).length))
if matches.count > 0
{
if triggerWhenMatch
{
trigger(value)
}
return true
}
return false
}
func trigger(name:String)
{
map[name]?.trigger()
}
func padding(var value:String, length:Int, var filling:String = " ") -> String
{
if NSString(string: filling).length == 0
{
filling = " "
}
else
{
filling = filling.substringToIndex(filling.startIndex.successor())
}
while NSString(string: value).length < length
{
value += filling
}
return value
}
func showHelpMessage(stream:UnsafeMutablePointer<FILE> = stdout)
{
var maxNameLength = 0
var maxAbbrLength = 0
var abbrs:[String] = []
for var i = 0; i < options.count; i++
{
maxNameLength = max(maxNameLength, NSString(string: options[i].name).length)
maxAbbrLength = max(maxAbbrLength, NSString(string: options[i].abbr).length)
abbrs.append(options[i].abbr + (options[i].hasValue ? " OPTION_VALUE" : ""))
}
fputs("Usage: \(self.name) " + " ".join(abbrs) + " \(usageAppending)\n", stream)
for i in 0 ..< options.count
{
let item = options[i]
var help = padding(item.abbr, length: maxAbbrLength)
help += item.name == "" || item.abbr == "" ? " " : ","
help += " " + padding(item.name, length: maxNameLength) + "\t" + item.help
fputs(help + "\n", stream)
}
}
}
| 27.288889 | 134 | 0.533116 |
e29598e3b0e9699ca773cf2d7acdc3b541b49839
| 6,068 |
//
// Tracked.swift
// DagoTracked
//
// Created by Douwe Bos on 21/10/20.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
public protocol TrackedEvent {
associatedtype TrackedEventProperties
var eventTitle: String { get }
var eventProperties: TrackedEventProperties { get }
func post()
}
public struct Tracked<Base> {
/// Base object to extend.
public let base: Base
/// Creates extensions with base object.
///
/// - parameter base: Base object.
public init(_ base: Base) {
self.base = base
}
}
/// A type that has constrained extensions.
public protocol TrackedCompatible {
/// Extended type
associatedtype TrackedBase
/// Tracked extensions.
static var tracked: Tracked<TrackedBase>.Type { get set }
/// Tracked extensions.
var tracked: Tracked<TrackedBase> { get set }
}
extension TrackedCompatible {
/// Tracked extensions.
public static var tracked: Tracked<Self>.Type {
get {
return Tracked<Self>.self
}
// swiftlint:disable:next unused_setter_value
set {
// this enables using Tracked to "mutate" base type
}
}
/// Tracked extensions.
public var tracked: Tracked<Self> {
get {
return Tracked(self)
}
// swiftlint:disable:next unused_setter_value
set {
// this enables using Tracked to "mutate" base object
}
}
}
import class Foundation.NSObject
extension NSObject: TrackedCompatible { }
#if os(iOS)
extension Tracked where Base: UIButton {
public func tap<Event: TrackedEvent>(_ event: Event, block: @escaping (() -> Swift.Void)) -> Disposable {
return self.base.rx.tap
.subscribe(
onNext: {
event.post()
block()
}
)
}
public func tap<Event: TrackedEvent>(block: @escaping (() -> Swift.Void), event: @escaping (() -> Event)) -> Disposable {
return self.base.rx.tap
.subscribe(
onNext: {
event().post()
block()
}
)
}
}
#endif
#if os(tvOS)
extension Tracked where Base: UIButton {
public func tap<Event: TrackedEvent>(_ event: Event, block: @escaping (() -> Swift.Void)) -> Disposable {
return self.base.rx.primaryAction
.subscribe(
onNext: {
event.post()
block()
}
)
}
public func tap<Event: TrackedEvent>(block: @escaping (() -> Swift.Void), event: @escaping (() -> Event)) -> Disposable {
return self.base.rx.primaryAction
.subscribe(
onNext: {
event().post()
block()
}
)
}
}
#endif
#if os(iOS)
extension Tracked where Base: UISwitch {
public func value<Event: TrackedEvent>(skip: Int = 0, _ event: Event, block: @escaping ((Bool) -> Swift.Void)) -> Disposable {
return self.base.rx.value
.skip(skip)
.subscribe(
onNext: { value in
event.post()
block(value)
}
)
}
public func value<Event: TrackedEvent>(skip: Int = 0, block: @escaping ((Bool) -> Swift.Void), event: @escaping ((Bool) -> Event)) -> Disposable {
return self.base.rx.value
.skip(skip)
.subscribe(
onNext: { value in
event(value).post()
block(value)
}
)
}
}
#endif
extension Tracked where Base: UIBarButtonItem {
public func tap<Event: TrackedEvent>(_ event: Event, block: @escaping (() -> Swift.Void)) -> Disposable {
return self.base.rx.tap
.subscribe(
onNext: {
event.post()
block()
}
)
}
public func tap<Event: TrackedEvent>(block: @escaping (() -> Swift.Void), event: @escaping (() -> Event)) -> Disposable {
return self.base.rx.tap
.subscribe(
onNext: {
event().post()
block()
}
)
}
}
extension Tracked where Base: UITextField {
public func text<Event: TrackedEvent>(_ event: Event, block: @escaping ((String?) -> Swift.Void)) -> Disposable {
return self.base.rx.text
.subscribe(
onNext: { newText in
event.post()
block(newText)
}
)
}
public func text<Event: TrackedEvent>(block: @escaping ((String?) -> Swift.Void), event: @escaping ((String?) -> Event)) -> Disposable {
return self.base.rx.text
.subscribe(
onNext: { newText in
event(newText).post()
block(newText)
}
)
}
}
extension Tracked where Base: UISegmentedControl {
public func value<Event: TrackedEvent>(_ event: Event, block: @escaping ((Int) -> Swift.Void)) -> Disposable {
return self.base.rx.value
.subscribe(
onNext: { newText in
event.post()
block(newText)
}
)
}
public func value<Event: TrackedEvent>(block: @escaping ((Int) -> Swift.Void), event: @escaping ((Int) -> Event)) -> Disposable {
return self.base.rx.value
.subscribe(
onNext: { newText in
event(newText).post()
block(newText)
}
)
}
}
| 26.968889 | 150 | 0.486816 |
20610bd210c070a5c0b1034a74c102ce30f295aa
| 2,253 |
// --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
/// User-configurable options for the `ResponseDouble` operation.
public struct ResponseDoubleOptions: RequestOptions {
/// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// Highly recommended for correlating client-side activites with requests received by the server.
public let clientRequestId: String?
/// A token used to make a best-effort attempt at canceling a request.
public let cancellationToken: CancellationToken?
/// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
public var dispatchQueue: DispatchQueue?
/// A `PipelineContext` object to associate with the request.
public var context: PipelineContext?
/// Initialize a `ResponseDoubleOptions` structure.
/// - Parameters:
/// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// - cancellationToken: A token used to make a best-effort attempt at canceling a request.
/// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
/// - context: A `PipelineContext` object to associate with the request.
public init(
clientRequestId: String? = nil,
cancellationToken: CancellationToken? = nil,
dispatchQueue: DispatchQueue? = nil,
context: PipelineContext? = nil
) {
self.clientRequestId = clientRequestId
self.cancellationToken = cancellationToken
self.dispatchQueue = dispatchQueue
self.context = context
}
}
| 44.176471 | 122 | 0.682202 |
141c72788135f0adc4fb35d1d4f6f4027c3c0f0b
| 165 |
// @copyright Trollwerks Inc.
import Foundation
enum Document {
case html
case wordpress
}
enum Visited: String {
case yes = "✅"
case no = "◻️"
}
| 11.785714 | 29 | 0.612121 |
76bb8d761d2d2b11ab86112dee1cb8118c8618b5
| 5,219 |
// Copyright (c) 2020, Martin Allusse and Alexandre Baret and Jessy Barritault and Florian
// Bertonnier and Lisa Fougeron and François Gréau and Thibaud Lambert and Antoine
// Orgerit and Laurent Rayez
// All rights reserved.
// 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 UIKit
class FormSecondPageViewController: ParentModalViewController, ButtonsPrevNextDelegate {
var onNextButton: (() -> Void)?
var onPreviousButton: (() -> Void)?
fileprivate var formulaire: FormDateView!
fileprivate var formData = [[String:String]]()
override func viewDidLoad() {
super.viewDidLoad()
var boutonsNav: ButtonsPrevNext
let titre: FormTitlePage!
if UserPrefs.getInstance().bool(forKey: UserPrefs.KEY_FORMULAIRE_CONSENT) {
titre = FormTitlePage(title: Tools.getTranslate(key: "form_title"), pageIndex: "2/4")
boutonsNav = FabricCustomButton.createButton(type: .nextPrev)
} else {
titre = FormTitlePage(title: Tools.getTranslate(key: "form_title_anonym"), pageIndex: "1/3")
boutonsNav = FabricCustomButton.createButton(type: .next)
}
titre.translatesAutoresizingMaskIntoConstraints = false
self.rootView.addSubview(titre)
boutonsNav.delegate = self
boutonsNav.translatesAutoresizingMaskIntoConstraints = false
self.rootView.addSubview(boutonsNav)
self.formulaire = FormDateView()
self.formulaire.translatesAutoresizingMaskIntoConstraints = false
self.rootView.addSubview(self.formulaire)
NSLayoutConstraint.activate([
//position du titre 2 dans la rootview
titre.topAnchor.constraint(equalTo: self.titleBar.bottomAnchor, constant: Constantes.FIELD_SPACING_VERTICAL),
titre.leftAnchor.constraint(equalTo: self.rootView.leftAnchor, constant: Constantes.PAGE_PADDING),
titre.rightAnchor.constraint(equalTo: self.rootView.rightAnchor, constant: -Constantes.PAGE_PADDING),
//position du formulaire
self.formulaire.topAnchor.constraint(equalTo: titre.bottomAnchor, constant: Constantes.FIELD_SPACING_VERTICAL),
self.formulaire.rightAnchor.constraint(equalTo: self.rootView.rightAnchor, constant: -Constantes.PAGE_PADDING),
self.formulaire.leftAnchor.constraint(equalTo: self.rootView.leftAnchor, constant: Constantes.PAGE_PADDING),
//position des boutons dans la rootView
boutonsNav.bottomAnchor.constraint(equalTo: self.rootView.bottomAnchor, constant: -Constantes.FIELD_SPACING_VERTICAL),
boutonsNav.leftAnchor.constraint(equalTo: self.rootView.leftAnchor, constant: Constantes.FIELD_SPACING_HORIZONTAL),
boutonsNav.rightAnchor.constraint(equalTo: self.rootView.rightAnchor, constant: -Constantes.FIELD_SPACING_HORIZONTAL),
])
}
func getFormDat() -> [[String: Any]] {
self.formData.append(["1": self.formulaire.zoneDateArrivee.dateTxtFld.textfield.text!])
self.formData.append(["2": self.formulaire.zoneDateDepart.dateTxtFld.textfield.text!])
return formData
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func boutonsPrevNext(boutonsPrevNext: ButtonsPrevNext, onNext: Bool) {
self.onNextButton?()
}
func boutonsPrevNext(boutonsPrevNext: ButtonsPrevNext, onPrevious: Bool) {
self.onPreviousButton?()
}
func validationPage() -> Bool {
return self.formulaire.isValid
}
}
| 48.775701 | 130 | 0.71757 |
50d07b844a58322d74209a1ed41e902e3638d8e2
| 1,523 |
//
// SettingViewController.swift
// iDragProject
//
// Created by runforever on 2017/2/3.
// Copyright © 2017年 defcoding. All rights reserved.
//
import Cocoa
class SettingViewController: NSViewController {
@IBOutlet var accessKeyInput: NSTextField!
@IBOutlet var secretKeyInput: NSTextField!
@IBOutlet var bucketInput: NSTextField!
@IBOutlet var domainInput: NSTextField!
var userDefaults: UserDefaults!
var settingMeta: [String: NSTextField]!
override func viewDidLoad() {
super.viewDidLoad()
// 设置项与UI的对应配置,方便存取设置数据
settingMeta = [
"accessKey": accessKeyInput,
"secretKey": secretKeyInput,
"bucket": bucketInput,
"domain": domainInput,
]
userDefaults = NSUserDefaultsController.shared().defaults
// 展示已经保存的设置项
displaySettings()
}
func displaySettings() {
// 根据设置项与UI的对应配置,展示相应的设置到UI中
for (key, input) in settingMeta {
if let value = userDefaults.string(forKey: key) {
input.stringValue = value
}
}
}
@IBAction func confirmAction(_ sender: NSButton) {
// 保存UI中的值到配置中
for (key, input) in settingMeta {
let setting = input.stringValue
userDefaults.set(setting, forKey: key)
}
userDefaults.synchronize()
self.view.window?.close()
}
@IBAction func cancelAction(_ sender: NSButton) {
self.view.window?.close()
}
}
| 24.967213 | 65 | 0.61392 |
e45d5a3183b5098493a733bc72d55a78ce13e247
| 643 |
//
// WeatherUndergroundService.swift
// RainyShine
//
// Created by Chris Brown on 4/20/17.
// Copyright © 2017 Chris Brown. All rights reserved.
//
import Foundation
class WeatherUndergroundService: WeatherService {
private let apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
private func createCurrentWeatherURL(location: Location) -> String {
return ""
}
private func createForecastURL(location: Location, count: Int) -> String {
return ""
}
func getWeather(location: Location, callback: @escaping WeatherCallback) {
}
}
| 20.09375 | 78 | 0.63297 |
d7a70386702c360fdfd4d268ee9f37e2fe394f8f
| 505 |
//
// Client.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Client: JSONEncodable {
public var client: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["client"] = self.client
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| 18.703704 | 85 | 0.647525 |
9c1451c6e99c45e05c65c86675f9407aeb5864b3
| 400 |
//
// AnimateTransition.swift
// Pods
//
// Created by Eric Vennaro on 10/5/16.
//
//
import Foundation
///Animation protocol
protocol AnimateTransition {
///tracks the currently highlighted button
var currentState: Int { get set }
/**
Controls button animation
- Parameter newState: Int, corresponding to the buttons tag
*/
func animate(to newState: Int)
}
| 18.181818 | 64 | 0.6625 |
f5c3bd06ae4725275d824d5b39124962c7fbcc1e
| 4,476 |
import Foundation
extension String {
public subscript(range: Range<Int>) -> String {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(startIndex, offsetBy: range.upperBound)
let indexRange = lowerBound..<upperBound
return String(self[indexRange])
}
// Make this compile with both Xcode 9 and Xcode 10's slightly different versions of
// Swift 4.1. This can be removed once Xcode 9 is no longer supported.
#if !swift(>=4.1.50)
public subscript(range: CountableRange<Int>) -> String {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(startIndex, offsetBy: range.upperBound)
let indexRange = lowerBound..<upperBound
return String(self[indexRange])
}
#endif
public subscript(range: CountableClosedRange<Int>) -> String {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(startIndex, offsetBy: range.upperBound)
let indexRange = lowerBound...upperBound
return String(self[indexRange])
}
/// Returns a substring in the given range.
/// If the range is beyond the string's length, returns the substring up to its bounds.
public subscript(ip_safely range: Range<Int>) -> String {
if range.lowerBound < 0 {
return self[ip_safely: 0..<range.upperBound]
} else if range.upperBound > count {
let newRange = range.lowerBound..<count
return String(self[newRange])
} else {
return String(self[range])
}
}
/// Returns a substring in the given range.
/// If the range is beyond the string's length, returns the substring up to its bounds.
public subscript(ip_safely range: CountableClosedRange<Int>) -> String {
if range.lowerBound < 0 {
return self[ip_safely: 0...range.upperBound]
} else if range.upperBound >= count {
let newRange = range.lowerBound...(count - 1)
return String(self[newRange])
} else {
return String(self[range])
}
}
@available (*, unavailable, message: "use ip_safelyRemoveFirst() instead.")
public mutating func ip_dropFirst() {
guard !isEmpty else { return }
self = self[1..<count]
}
/// Removes and returns the first character of the string.
///
/// - returns: The removed character, or `nil` if string is empty.
@discardableResult
public mutating func ip_safelyRemoveFirst() -> Character? {
guard !isEmpty else { return nil }
return removeFirst()
}
/// From http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index/32379600#32379600
/// Returns a String range based on an NSRange
///
/// - parameter range: The input NSRange
///
/// - returns: The string range
public func ip_range(from range: NSRange) -> Range<String.Index>? {
guard range.location >= 0 else { return nil }
return Range(range, in: self)
}
/// Returns a String range based on an Int range. It is up to the caller to ensure that the
/// int range is not out of bounds.
///
/// - parameter uncheckedRange: An unchecked range, meaning the range could be out of bounds.
///
/// - returns: The string range
public func ip_range(from uncheckedRange: ClosedRange<Int>) -> Range<String.Index> {
let from = index(startIndex, offsetBy: uncheckedRange.lowerBound)
let to = index(from, offsetBy: uncheckedRange.count)
return from..<to
}
public var ip_fullrange: NSRange {
return NSRange(location: 0, length: count)
}
/// Returns a new string containing the characters of the String up to, but not including, the first occurrence of the given string.
/// If the string is not found, nil is returned.
public func ip_prefix(upTo string: String) -> String? {
guard let range = self.range(of: string) else { return nil }
return String(self[..<range.lowerBound])
}
/// Returns a new string containing the characters of the String from the end of the first occurrence of the given String.
/// If the string is not found, nil is returned.
public func ip_suffix(from string: String) -> String? {
guard let range = self.range(of: string) else { return nil }
return String(self[range.upperBound...])
}
}
| 39.610619 | 136 | 0.6479 |
9b9ab5ce2d731af7043097d80e75eab37313947f
| 68,837 |
//
// Copyright © 2020 Curato Research BV. All rights reserved.
//
import Quick
import Nimble
import InjectableLoggers
class LoggerSpec: QuickSpec {
override func spec() {
describe("Logger") {
var sut: Logger!
var settings: Logger.Settings!
var mockDestination: MockLogger!
beforeEach {
mockDestination = MockLogger()
settings = Logger.Settings()
settings.destination = mockDestination
}
context("default lineNumber", closure: {
beforeEach {
settings.activeLogLevel = .verbose
settings.defaultLogLevel = .verbose
settings.loglevelStrings = [.verbose: "🎉"]
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true)]
sut = Logger(settings: settings)
}
it("logs to destination", closure: {
sut.log()
sut.log("message")
sut.log("message", atLevel: Loglevel.verbose)
expect(mockDestination.loggedMessages.count).to(equal(3))
expect(mockDestination.loggedMessages[0].message as? String).to(equal("🎉 LoggerSpec.spec() 30"))
expect(mockDestination.loggedMessages[1].message as? String).to(equal("🎉 LoggerSpec.spec() 31 message"))
expect(mockDestination.loggedMessages[2].message as? String).to(equal("🎉 LoggerSpec.spec() 32 message"))
})
})
context("empty loglevelStrings", closure: {
beforeEach {
settings.activeLogLevel = .verbose
settings.defaultLogLevel = .verbose
settings.loglevelStrings = [.verbose: "🎉"]
settings.formatSettings = [Loglevel: Logger.FormatSettings]()
sut = Logger(settings: settings)
}
it("logs to destination", closure: {
sut.log(atLine: 42)
sut.log("message", atLine: 42)
sut.log("message", atLevel: Loglevel.verbose, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(3))
expect(mockDestination.loggedMessages[0].message as? String).to(equal(""))
expect(mockDestination.loggedMessages[1].message as? String).to(equal("message"))
expect(mockDestination.loggedMessages[2].message as? String).to(equal("message"))
})
})
context("empty formatterSettings", closure: {
beforeEach {
settings.activeLogLevel = .verbose
settings.defaultLogLevel = .verbose
settings.loglevelStrings = [Loglevel: String]()
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true)]
sut = Logger(settings: settings)
}
it("logs to destination", closure: {
sut.log(atLine: 42)
sut.log("message", atLine: 42)
sut.log("message", atLevel: Loglevel.verbose, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(3))
expect(mockDestination.loggedMessages[0].message as? String).to(equal("LoggerSpec.spec() 42"))
expect(mockDestination.loggedMessages[1].message as? String).to(equal("LoggerSpec.spec() 42 message"))
expect(mockDestination.loggedMessages[2].message as? String).to(equal("LoggerSpec.spec() 42 message"))
})
})
context("relay", closure: {
let mockRelay = MockLogger()
beforeEach {
settings.activeLogLevel = .inactive
settings.defaultLogLevel = .inactive
sut = Logger(settings: settings)
sut.relay = mockRelay
}
it("logs everyting to relay", closure: {
sut.log("aaa", atLevel: .verbose, inFile: "bbb", inFunction: "ccc", atLine: 42)
sut.log("ddd", atLevel: .inactive, inFile: "eee", inFunction: "fff", atLine: 22)
expect(mockRelay.loggedMessages.count).to(equal(2))
let loggedMessage0 = mockRelay.loggedMessages[0]
expect(loggedMessage0.message as? String).to(equal("aaa"))
expect(loggedMessage0.level).to(equal(.verbose))
expect(loggedMessage0.file).to(equal("bbb"))
expect(loggedMessage0.function).to(equal("ccc"))
expect(loggedMessage0.line).to(equal(42))
let loggedMessage1 = mockRelay.loggedMessages[1]
expect(loggedMessage1.message as? String).to(equal("ddd"))
expect(loggedMessage1.level).to(equal(.inactive))
expect(loggedMessage1.file).to(equal("eee"))
expect(loggedMessage1.function).to(equal("fff"))
expect(loggedMessage1.line).to(equal(22))
})
})
context("When initializing with settings that contains a relay", {
beforeEach {
settings.relay = Logger()
sut = Logger(settings: settings)
}
it("Then it's relay is the relay from settings", closure: {
expect(sut.relay).to(beIdenticalTo(settings.relay))
})
})
context("verbose active loglevel", {
beforeEach {
settings.activeLogLevel = .verbose
}
//MARK: non empty loglevelStrings
context("non empty loglevelStrings", closure: {
beforeEach {
settings.loglevelStrings = [.verbose: "🔍", .info: "ℹ️", .warning: "⚠️", .error:"⛔️"]
}
//MARK: formatter settings A
context("formatter settings A", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log(atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec.spec() 42"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message", atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec.spec() 42 message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log(atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec.spec() 42"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message", atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec.spec() 42 message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose, atLine: 42)
sut.log(atLevel: Loglevel.warning, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec.spec() 42"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec.spec() 42"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose, atLine: 42)
sut.log("message", atLevel: Loglevel.warning, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec.spec() 42 message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec.spec() 42 message"))
})
})
})
})
//MARK: formatter settings B
context("formatter settings B", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec.spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec.spec() message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec.spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec.spec() message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec.spec()"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec.spec()"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec.spec() message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec.spec() message"))
})
})
})
})
//MARK: formatter settings C
context("formatter settings C", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 LoggerSpec message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ LoggerSpec message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 LoggerSpec message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ LoggerSpec message"))
})
})
})
})
//MARK: formatter settings D
context("formatter settings D", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("🔍 message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️ message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("🔍 message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️ message"))
})
})
})
})
//MARK: formatter settings E
context("formatter settings E", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal(""))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
})
//MARK: formatter settings F
context("formatter settings F", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: true, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: true, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: true, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: false, shouldShowFile: false, shouldShowFunction: true, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec() message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec() message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("spec()"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec()"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("spec() message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("spec() message"))
})
})
})
})
})
//MARK: empty loglevelStrings
context("empty loglevelStrings", closure: {
beforeEach {
settings.loglevelStrings = [.verbose: "", .info: "", .warning: "", .error:""]
}
//MARK: formatter settings A
context("formatter settings A", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: true)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log(atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message", atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42 message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log(atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message", atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42 message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose, atLine: 42)
sut.log(atLevel: Loglevel.warning, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec.spec() 42"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose, atLine: 42)
sut.log("message", atLevel: Loglevel.warning, atLine: 42)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec.spec() 42 message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() 42 message"))
})
})
})
})
//MARK: formatter settings B
context("formatter settings B", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: true, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec()"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec.spec()"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec()"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec.spec() message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec.spec() message"))
})
})
})
})
//MARK: formatter settings C
context("formatter settings C", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: true, shouldShowFunction: false, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec"))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec"))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("LoggerSpec message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("LoggerSpec message"))
})
})
})
})
//MARK: formatter settings D
context("formatter settings D", {
beforeEach {
settings.formatSettings = [.verbose : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.info : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.warning : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
.error : Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false)]
}
context("verbose default loglevel", {
beforeEach {
settings.defaultLogLevel = .verbose
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
context("info default loglevel", {
beforeEach {
settings.defaultLogLevel = .info
sut = Logger(settings: settings)
}
context("log", {
it("logs to destination", closure: {
sut.log()
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message", {
it("logs to destination", closure: {
sut.log("message")
expect(mockDestination.loggedMessages.count).to(equal(1))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
context("independent of default loglevel", closure: {
beforeEach {
sut = Logger(settings: settings)
}
context("log at level", closure: {
it("logs to destination", closure: {
sut.log(atLevel: Loglevel.verbose)
sut.log(atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal(""))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal(""))
})
})
context("log message at level", closure: {
it("logs to destination", closure: {
sut.log("message", atLevel: Loglevel.verbose)
sut.log("message", atLevel: Loglevel.warning)
expect(mockDestination.loggedMessages.count).to(equal(2))
expect(mockDestination.loggedMessages.first?.message as? String).to(equal("message"))
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("message"))
})
})
})
})
})
})
context("other active loglevels", closure: {
beforeEach {
settings.loglevelStrings = [.verbose: "🔍", .info: "ℹ️", .warning: "⚠️", .error:"⛔️", .inactive: "🔥"]
settings.formatSettings = [ Loglevel.verbose: Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
Loglevel.info: Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
Loglevel.warning: Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
Loglevel.error: Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false),
Loglevel.inactive: Logger.FormatSettings(shouldShowLevel: true, shouldShowFile: false, shouldShowFunction: false, shouldShowLine: false)]
settings.activeLogLevel = .info
}
context("info level", closure: {
beforeEach {
settings.activeLogLevel = .info
settings.destination = mockDestination
sut = Logger(settings: settings)
}
it("logs to destination when needed", closure: {
sut.log(atLevel: .verbose)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .info)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("ℹ️"))
sut.log(atLevel: .warning)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️"))
sut.log(atLevel: .error)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
sut.log(atLevel: .inactive)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
expect(mockDestination.loggedMessages.count).to(equal(3))
})
})
context("warning level", closure: {
beforeEach {
settings.activeLogLevel = .warning
settings.destination = mockDestination
sut = Logger(settings: settings)
}
it("logs to destination when needed", closure: {
sut.log(atLevel: .verbose)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .info)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .warning)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⚠️"))
sut.log(atLevel: .error)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
sut.log(atLevel: .inactive)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
expect(mockDestination.loggedMessages.count).to(equal(2))
})
})
context("error level", closure: {
beforeEach {
settings.activeLogLevel = .error
settings.destination = mockDestination
sut = Logger(settings: settings)
}
it("logs to destination when needed", closure: {
sut.log(atLevel: .verbose)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .info)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .warning)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .error)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
sut.log(atLevel: .inactive)
expect(mockDestination.loggedMessages.last?.message as? String).to(equal("⛔️"))
expect(mockDestination.loggedMessages.count).to(equal(1))
})
})
context("inactive level", closure: {
beforeEach {
settings.activeLogLevel = .inactive
settings.destination = mockDestination
sut = Logger(settings: settings)
}
it("logs to destination when needed", closure: {
sut.log(atLevel: .verbose)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .info)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .warning)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .error)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
sut.log(atLevel: .inactive)
expect(mockDestination.loggedMessages.last?.message as? String).to(beNil())
expect(mockDestination.loggedMessages.count).to(equal(0))
})
})
})
}
}
}
| 59.599134 | 185 | 0.397083 |
187fa371c2faff48c43814aaaac9cf506e18df5c
| 1,006 |
//
// NavigationController.swift
// Rise
//
// Created by Vladimir Korolev on 07.12.2021.
// Copyright © 2021 VladimirBrejcha. All rights reserved.
//
import UIKit
final class NavigationController: UINavigationController, UINavigationControllerDelegate {
// MARK: - LifeCycle
init(items: [UIViewController]) {
super.init(nibName: nil, bundle: nil)
self.viewControllers = items
self.isNavigationBarHidden = true
self.delegate = self
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UINavigationControllerDelegate
func navigationController(
_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
CrossDissolveTransition()
}
}
| 26.473684 | 90 | 0.694831 |
1d5f0b53d4a201575cce33690ec8ef3350cb92d2
| 4,202 |
import UIKit
enum Section: Hashable {
case main
}
struct Item: Hashable {
let videos: VideoInfo
init(videos: VideoInfo) {
self.videos = videos
}
private let identifier = UUID()
static let all = [
Item(videos: VideoInfo(thumbnail: R.image.thumbnail1()!, icon: R.image.thumbnail1()!, videoTitle: "Let me show you my speciality", createrName: "HikakinTV", viewsCount: "13M", uploadedTime: "2020/2/21")),
Item(videos: VideoInfo(thumbnail: R.image.thumbnail2()!, icon: R.image.thumbnail1()!, videoTitle: "How to deal with cold", createrName: "HikakinTV", viewsCount: "14M", uploadedTime: "2020/2/23")),
Item(videos: VideoInfo(thumbnail: R.image.thumbnail3()!, icon: R.image.thumbnail1()!, videoTitle: "Quitting broadcasts", createrName: "HikakinTV", viewsCount: "130K", uploadedTime: "2020/3/20")),
Item(videos: VideoInfo(thumbnail: R.image.thumbnail4()!, icon: R.image.thumbnail1()!, videoTitle: "Marriage prank!", createrName: "Raphael", viewsCount: "4M", uploadedTime: "2020/3/20"))
]
}
final class ListViewController: UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
self.view.backgroundColor = .white
}
required init?(coder: NSCoder) { fatalError() }
private lazy var collectionView: UICollectionView = .init(frame: self.view.bounds, collectionViewLayout: createLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! = nil
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(SuggestCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: SuggestCollectionViewCell.self))
configureHierachy()
configureDataSource()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
// MARK: Layout
extension ListViewController {
// Use UICollectionViewList
private func createLayout() -> UICollectionViewLayout {
let config = UICollectionLayoutListConfiguration(appearance: .plain)
return UICollectionViewCompositionalLayout.list(using: config)
}
}
// MARK: DataSource
// Not Inheriting UICollectionViewDataSource, but works like it is
extension ListViewController {
private func configureHierachy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
view.addSubview(collectionView)
collectionView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
collectionView.delegate = self
}
private func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<SuggestCollectionViewCell, Item> { cell, indexPath, item in
cell.updateWithItem(item)
cell.accessories = [.disclosureIndicator()]
}
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) {
collectionView, indexPath, item -> UICollectionViewCell? in
let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
cell.setup(info: Item.all[indexPath.row].videos)
return cell
}
// initial data
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.main])
snapshot.appendItems(Item.all)
dataSource.apply(snapshot, animatingDifferences: false)
}
}
// MARK: Delegate
extension ListViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let watchViewController = WatchViewController(video: Item.all[indexPath.row].videos)
watchViewController.modalPresentationStyle = .overFullScreen
self.present(watchViewController, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = .clear
}
}
| 38.907407 | 212 | 0.704426 |
0a29a65e652f66599be17220c087dc0b3b0b47fb
| 1,658 |
//
// Reference.swift
// goSellSDK
//
// Copyright © 2019 Tap Payments. All rights reserved.
//
/// Reference object.
@objcMembers public final class Reference: NSObject, Codable {
// MARK: - Public -
// MARK: Properties
/// Acquirer reference.
public private(set) var acquirer: String?
/// Gateway reference.
public private(set) var gatewayReference: String?
/// Payment reference.
public private(set) var paymentReference: String?
/// Tracking number.
public private(set) var trackingNumber: String?
/// Merchant transaction reference number.
public var transactionNumber: String?
/// Merchant order number.
public var orderNumber: String?
public var gosellID: String?
// MARK: Methods
/// Initializes reference object with transaction number and order number.
///
/// - Parameters:
/// - transactionNumber: Merchant transaction reference number.
/// - orderNumber: Merchant order number.
public init(transactionNumber: String? = nil, orderNumber: String? = nil) {
self.transactionNumber = transactionNumber
self.orderNumber = orderNumber
super.init()
}
// MARK: - Private
private enum CodingKeys: String, CodingKey {
case acquirer = "acquirer"
case gatewayReference = "gateway"
case paymentReference = "payment"
case trackingNumber = "track"
case transactionNumber = "transaction"
case orderNumber = "order"
case gosellID = "gosell_id"
}
}
| 26.741935 | 79 | 0.61158 |
e4315854ffaa36382bec1684179ca14aa1ef303d
| 283 |
//
// ToDoModel.swift
// testtestSPM
//
// Created by Дмитрий Торопкин on 22.06.2020.
// Copyright © 2020 Dmitriy Toropkin. All rights reserved.
//
import Foundation
class ToDoModel: Codable {
var id: Int
var title: String
var completed: Bool
var userId: Int
}
| 16.647059 | 59 | 0.674912 |
bbd3d395465d36d338c11e81e7bde5493b9fbcc2
| 3,952 |
import UIKit
public final class TutorialContentPagerViewController: UIPageViewController {
public var changes: [String]?
private let pages: [TutorialPageViewController] = [
loadPage("Intro"),
loadPage("SoundFontList"),
loadPage("TagsList"),
loadPage("Presets"),
loadPage("InfoBar1"),
loadPage("InfoBar2"),
loadPage("Favorites"),
loadPage("Reverb"),
loadPage("Delay"),
loadPage("Settings"),
loadPage("Done")
]
override public func viewDidLoad() {
super.viewDidLoad()
dataSource = self
if let changes = changes {
setViewControllers([loadChanges(changes)], direction: .forward, animated: true)
} else {
setViewControllers([pages[0]], direction: .forward, animated: true)
}
let appearance = UIPageControl.appearance(whenContainedInInstancesOf: [
UIPageViewController.self
])
appearance.pageIndicatorTintColor = .systemTeal
appearance.currentPageIndicatorTintColor = .systemOrange
}
@IBAction func donePressed(_ sender: Any) {
dismiss(animated: true)
}
public func nextPage() {
guard changes == nil, let next = page(after: self.viewControllers?.first) else { return }
setViewControllers([next], direction: .forward, animated: true, completion: nil)
}
public func previousPage() {
guard changes == nil, let prev = page(before: self.viewControllers?.first) else { return }
setViewControllers([prev], direction: .reverse, animated: true, completion: nil)
}
private static func loadPage(_ name: String) -> TutorialPageViewController {
let storyboard = UIStoryboard(name: name, bundle: Bundle(for: TutorialViewController.self))
guard
let viewController = storyboard.instantiateInitialViewController()
as? TutorialPageViewController
else {
fatalError("failed to load tutorial page \(name)")
}
return viewController
}
private func loadChanges(_ changes: [String]) -> ChangesPageViewController {
let storyboard = UIStoryboard(name: "Changes", bundle: Bundle(for: TutorialViewController.self))
guard
let viewController = storyboard.instantiateInitialViewController()
as? ChangesPageViewController
else {
fatalError("failed to load Changes page")
}
viewController.changes = changes
return viewController
}
}
extension TutorialContentPagerViewController: UIPageViewControllerDataSource {
public func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
changes != nil ? nil : page(before: viewController)
}
public func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController
) -> UIViewController? {
changes != nil ? nil : page(after: viewController)
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
changes != nil ? 1 : pages.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let viewController = viewControllers?.first as? TutorialPageViewController else {
return 0
}
return changes != nil ? 0 : pages.firstIndex(of: viewController)!
}
}
extension TutorialContentPagerViewController {
private func page(before viewController: UIViewController?) -> UIViewController? {
guard let pageViewController = viewController as? TutorialPageViewController,
let index = pages.firstIndex(of: pageViewController)
else { return nil }
return index == 0 ? nil : pages[index - 1]
}
private func page(after viewController: UIViewController?) -> UIViewController? {
guard let pageViewController = viewController as? TutorialPageViewController,
let index = pages.firstIndex(of: pageViewController)
else { return nil }
return index == pages.count - 1 ? nil : pages[index + 1]
}
}
| 32.661157 | 100 | 0.716599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.