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
|
---|---|---|---|---|---|
5dfa094ce5a05330db2e18d28bd9ca93ca6783ee | 6,541 | //
// ViewController.swift
// RxGesture
//
// Created by Marin Todorov on 03/22/2016.
// Copyright (c) 2016 Marin Todorov. All rights reserved.
//
import UIKit
import RxSwift
import RxGesture
let infoList = [
"Tap the red square",
"Double tap the green square",
"Swipe the square down",
"Swipe horizontally (e.g. left or right)",
"Do a long press",
"Drag the square to a different location",
"Rotate the square",
"Do either a tap, long press, or swipe in any direction"
]
let codeList = [
"myView.rx.gesture(.tap).subscribeNext {...}",
"myView.rx.gesture(.tapNumberOfTimes(2)).subscribeNext {...}",
"myView.rx.gesture(.swipeDown).subscribeNext {...}",
"myView.rx.gesture(.swipeLeft, .swipeRight).subscribeNext {",
"myView.rx.gesture(.longPress).subscribeNext {...}",
"myView.rx.gesture(.pan(.changed), .pan(.ended)]).subscribeNext {...}",
"myView.rx.gesture(.rotate(.changed), .rotate(.ended)]).subscribeNext {...}",
"myView.rx.gesture().subscribeNext {...}"
]
class ViewController: UIViewController {
@IBOutlet var myView: UIView!
@IBOutlet var myViewText: UILabel!
@IBOutlet var info: UILabel!
@IBOutlet var code: UITextView!
private let nextStep😁 = PublishSubject<Void>()
private let bag = DisposeBag()
private var stepBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
nextStep😁.scan(0, accumulator: {acc, _ in
return acc < 6 ? acc + 1 : 0
})
.startWith(0)
.subscribe(onNext: step)
.addDisposableTo(bag)
}
func step(step: Int) {
//release previous recognizers
stepBag = DisposeBag()
info.text = "\(step+1). \(infoList[step])"
code.text = codeList[step]
//add current step recognizer
switch step {
case 0: //tap recognizer
myView.rx.gesture(.tap).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.backgroundColor = UIColor.green
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 1: //tap number of times recognizer
myView.rx.gesture(.tapNumberOfTimes(2)).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.backgroundColor = UIColor.blue
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 2: //swipe down
myView.rx.gesture(.swipeDown).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform(scaleX: 1.0, y: 2.0)
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 3: //swipe horizontally
myView.rx.gesture(.swipeLeft, .swipeRight).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 4: //long press
myView.rx.gesture(.longPress).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 5: //panning
myView.rx.gesture(.pan(.changed)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .pan(let data):
this.myViewText.text = "(\(data.translation.x), \(data.translation.y))"
this.myView.transform = CGAffineTransform(translationX: data.translation.x, y: data.translation.y)
default: break
}
}).addDisposableTo(stepBag)
myView.rx.gesture(.pan(.ended)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .pan(_):
UIView.animate(withDuration: 0.5, animations: {
this.myViewText.text = nil
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
default: break
}
}).addDisposableTo(stepBag)
case 6: //rotating
myView.rx.gesture(.rotate(.changed)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .rotate(let data):
this.myViewText.text = String(format: "angle: %.2f", data.rotation)
this.myView.transform = CGAffineTransform(rotationAngle: data.rotation)
default: break
}
}).addDisposableTo(stepBag)
myView.rx.gesture(.rotate(.ended)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .rotate(_):
UIView.animate(withDuration: 0.5, animations: {
this.myViewText.text = nil
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
default: break
}
}).addDisposableTo(stepBag)
case 7: //any gesture
myView.rx.gesture().subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.backgroundColor = UIColor.red
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
default: break
}
print("active gestures: \(myView.gestureRecognizers!.count)")
}
}
| 37.377143 | 118 | 0.547317 |
38cc214610c6179abb9a557e0fc232eabdfac5c1 | 1,081 | //
// MovieDetailConfigurator.swift
// TraktTV
//
// Created by dede.exe on 20/08/17.
// Copyright © 2017 dede.exe. All rights reserved.
//
import UIKit
public class MovieDetailConfigurator {
public init() {}
func create(using movie:Movie) throws -> MovieDetailViewController {
guard let viewController = StoryboardIdentifier.movies.storyboard?.instantiateViewController(withIdentifier: "MovieDetailViewController") as? MovieDetailViewController else {
throw ConfiguratorError.viewControllerNotFound
}
let presenter = MovieDetailPresenter(movie: movie)
let router = MovieDetailRouter()
let interactor = MovieDetailInputInteractor()
presenter.inject(view: viewController, interactor: interactor, router: router)
interactor.inject(output: presenter)
viewController.inject(presenter: presenter)
viewController.inject(tableHandler: presenter)
router.inject(viewController: viewController)
return viewController
}
}
| 30.027778 | 182 | 0.690102 |
33e692e45ef61635ac174a1bfb63fd42840b4f9f | 915 | //
// HairProductModel.swift
// PerfectlyCrafted
//
// Created by Ashli Rankin on 2/18/19.
// Copyright © 2019 Ashli Rankin. All rights reserved.
//
import Foundation
struct AllHairProducts: Codable, Hashable {
let id: String
let results: HairProductDetails
}
struct HairProductDetails: Codable, Hashable {
let gtins: [String]
let upc: String
let created_at: Int
let name: String
let images: [URL]
let sitedetails: [SiteDetails]
let description: String
let features: Features?
let category: String
}
struct SiteDetails: Codable, Hashable {
let url: URL
let latestoffers: [LatestOffers]
}
struct Features: Codable, Hashable {
let blob: String?
}
struct LatestOffers: Codable, Hashable {
let price: String
let lastrecorded_at: Int
let isActive: Int?
let currency: String
let firstrecorded_at: Int
let id: String
let avalibility: String?
let seller: String
}
| 19.0625 | 55 | 0.721311 |
750758788b09f2facb50df1ac0aa39a777f03a47 | 4,907 | //
// FinalScreenViewController.swift
// TheInterviewer
//
// Created by Athos Lagemann on 11/09/19.
// Copyright © 2019 Athos Lagemann. All rights reserved.
//
import UIKit
protocol FinalScreenDelegate: class {
func didTapShare(_ viewController: FinalScreenViewController)
func didTapSave(_ viewController: FinalScreenViewController)
func didTapDiscard(_ viewController: FinalScreenViewController)
}
final class FinalScreenViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var shareButton: UIButton!
@IBOutlet private weak var saveButton: UIButton!
@IBOutlet private weak var discardButton: UIButton!
private let displayMode: Mode
private let viewModel: InterviewViewModel
weak var delegate: FinalScreenDelegate?
init(viewModel: InterviewViewModel, displayMode: Mode) {
self.viewModel = viewModel
self.displayMode = displayMode
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
setupUI()
}
private func setupUI() {
// Navigation
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.hidesBackButton = true
navigationItem.title = viewModel.title
// TableView
tableView.allowsSelection = false
tableView.tableFooterView = UIView()
// Share
shareButton.setTitleColor(.white, for: .normal)
shareButton.backgroundColor = AppConfiguration.mainColor
shareButton.layer.cornerRadius = shareButton.layer.bounds.height / 2
shareButton.titleLabel?.font = UIFont(SFPro: .text, variant: .semibold, size: 18)
// Save
saveButton.setTitleColor(.navyBlue, for: .normal)
saveButton.backgroundColor = .white
saveButton.layer.borderColor = UIColor.navyBlue.cgColor
saveButton.layer.borderWidth = 0.5
saveButton.layer.cornerRadius = saveButton.layer.bounds.height / 2
saveButton.titleLabel?.font = UIFont(SFPro: .text, variant: .semibold, size: 18)
// Discard
discardButton.setTitleColor(.fireRed, for: .normal)
discardButton.backgroundColor = .white
discardButton.layer.borderColor = UIColor.fireRed.cgColor
discardButton.layer.borderWidth = 0.5
discardButton.layer.cornerRadius = discardButton.layer.bounds.height / 2
discardButton.titleLabel?.font = UIFont(SFPro: .text, variant: .semibold, size: 18)
// Exit
if displayMode == .review {
discardButton.setTitle("Sair", for: .normal)
discardButton.setTitleColor(AppConfiguration.mainColor, for: .normal)
discardButton.layer.borderColor = AppConfiguration.mainColor.cgColor
saveButton.isHidden = true
}
}
}
// MARK - Actions
extension FinalScreenViewController {
@IBAction private func didTapShare(_ sender: UIButton) {
delegate?.didTapShare(self)
}
@IBAction private func didTapSave(_ sender: UIButton) {
delegate?.didTapSave(self)
}
@IBAction private func didTapDiscard(_ sender: UIButton) {
delegate?.didTapDiscard(self)
}
}
// MARK - TableView
extension FinalScreenViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfParts
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfSections(part: section)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.partTitle(part: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sectionTitle = viewModel.sectionTitle(part: indexPath.section, section: indexPath.row)
let total = Double(viewModel.sections[indexPath.row].questionPairs.count)
let answered = Double(viewModel.sections[indexPath.row].questionPairs.filter{ !($0.answer?.isEmpty ?? true) }.count)
let percentage = Double((answered / total) * 100).format(f: ".0")
let sectionDetail = "\(percentage)% respondida"
let cell: UITableViewCell
if let dequeued = tableView.dequeueReusableCell(withIdentifier: "FinalScreen") {
cell = dequeued
} else {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "FinalScreen")
}
cell.textLabel?.text = sectionTitle
cell.detailTextLabel?.text = sectionDetail
return cell
}
}
| 36.348148 | 124 | 0.674954 |
164eb7721f4cbab5e14af523976a4d1b15a4546a | 1,300 | //
// LoginViewController.swift
// Tweeter
//
// Created by Kyle Sit on 2/23/17.
// Copyright © 2017 Kyle Sit. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class LoginViewController: UIViewController {
//viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//memory warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//login onClick handle
@IBAction func onLoginButton(_ sender: Any) {
let client = TwitterClient.sharedInstance
client?.login(success: {
self.performSegue(withIdentifier: "loginSegue", sender: nil)
}, failure: { (error: NSError) in
print("Error: \(error.localizedDescription)")
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 25 | 106 | 0.639231 |
767e699311f779d27fef8796ed8d5e646ed262b6 | 1,069 | //
// PulleyPassthroughScrollViewDelegate.swift
// Visual Recognition
//
// Created by Nicholas Bourdakos on 3/17/17.
// Copyright © 2017 Nicholas Bourdakos. All rights reserved.
//
import UIKit
protocol PulleyPassthroughScrollViewDelegate: class {
func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool
func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView
}
class PulleyPassthroughScrollView: UIScrollView {
weak var touchDelegate: PulleyPassthroughScrollViewDelegate?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let touchDel = touchDelegate
{
if touchDel.shouldTouchPassthroughScrollView(scrollView: self, point: point)
{
return touchDel.viewToReceiveTouch(scrollView: self).hitTest(touchDel.viewToReceiveTouch(scrollView: self).convert(point, from: self), with: event)
}
}
return super.hitTest(point, with: event)
}
}
| 31.441176 | 163 | 0.700655 |
086594221552753512f8adb0ae61880e7fd6d341 | 746 | import XCTest
import ODRSample
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.724138 | 111 | 0.600536 |
e526c4fdd5e7765a34385ed687b74f8622e04bfb | 5,664 | //
// TalkDetailView.swift
// TEDxConnect
//
// Created by Tadeh Alexani on 9/10/20.
// Copyright © 2020 Alexani. All rights reserved.
//
import SwiftUI
import struct Kingfisher.KFImage
struct TalkDetailView: View {
let id: String
@ObservedObject var viewModel = TalkDetailViewModel()
@State private var titleLocalizedKey = ""
var body: some View {
ScrollView(.vertical) {
ZStack {
if self.viewModel.statusView == .complete {
self.content
}
if self.viewModel.statusView == .error {
ErrorView(errorText: self.viewModel.errorMessage)
.onTapGesture {
self.viewModel.setup(withId: Int(self.id) ?? 0)
}
}
if self.viewModel.statusView == .loading {
Indicator()
}
} // ZStack
.frame(maxWidth: .infinity)
} // ScrollView
.navigationBarTitle(Text(self.viewModel.repository.talk.speakers.map { $0.title }.joined(separator: ", ")))
.onAppear {
self.viewModel.setup(withId: Int(self.id) ?? 0)
}
}
private var content : some View {
VStack(alignment: .trailing) {
Button(action: {
if let url = URL(string: viewModel.repository.talk.videoLink ?? Configuration.placeholderUrl){
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}) {
ZStack {
KFImage(URL(string: Images.urlExtension + (self.viewModel.repository.talk.section.image)))
.placeholder {
ImagePlaceholder()
}
.resizable()
.scaledToFill()
.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity)
.frame(height: 200)
.clipped()
Rectangle()
.fill(Color.gray.opacity(0.35))
.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity)
.frame(height: 200)
.overlay(
Image(systemName: "play")
.resizable()
.scaledToFit()
.foregroundColor(.white)
.frame(width: 50, height: 50)
)
}
}
.buttonStyle(PlainButtonStyle())
VStack(alignment: TalkDetailView.alignment,spacing: 10) {
LocalizedNumberText(self.viewModel.repository.talk.title)
.customFont(name: Configuration.shabnam, style: .title3, weight: .bold)
.foregroundColor(Colors.primaryDarkGray)
.multilineTextAlignment(TalkDetailView.textAlignment)
LocalizedNumberText(self.viewModel.repository.talk.speakers.map { $0.title }.joined(separator: ", "))
.customFont(name: Configuration.shabnamBold, style: .subheadline)
.foregroundColor(.secondary)
}
.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity)
.padding(.horizontal)
VStack(alignment: TalkDetailView.alignment,spacing: 10) {
HStack {
LocalizedNumberText("Description".localized())
.foregroundColor(.secondary)
.overlay(Rectangle().frame(width: nil, height: 1, alignment: .bottom)
.foregroundColor(Colors.primaryRed), alignment: .bottom)
.customFont(name: Configuration.shabnam, style: .body)
Spacer()
}
LocalizedNumberText(self.viewModel.repository.talk.description ?? "")
.foregroundColor(.secondary)
.customFont(name: Configuration.shabnamBold, style: .body)
}
.environment(\.layoutDirection, Configuration.direction)
.padding(.horizontal)
.padding(.vertical, 10)
VStack(spacing: 10) {
HStack {
LocalizedNumberText("Related Talks".localized())
.foregroundColor(.secondary)
.overlay(Rectangle().frame(width: nil, height: 1, alignment: .bottom)
.foregroundColor(Colors.primaryRed), alignment: .bottom)
.padding(.horizontal)
.customFont(name: Configuration.shabnam, style: .body)
Spacer()
}
TalksRow(talks: self.viewModel.repository.suggestedTalks)
.padding(.top)
}
.buttonStyle(PlainButtonStyle())
.layoutPriority(1)
.environment(\.layoutDirection, Configuration.direction)
} // VStack
}
}
struct TalkDetailView_Previews: PreviewProvider {
static var previews: some View {
TalkDetailView(id: "0")
}
}
| 38.27027 | 117 | 0.466808 |
8fb97ee500ab6d3a737758ef5a8001031336552d | 1,889 | // _____ ____ __.
// / _ \ _____ _______ | |/ _|____ ___.__.
// / /_\ \\__ \\_ __ \ | < \__ \< | |
// / | \/ __ \| | \/ | | \ / __ \\___ |
// \____|__ (____ /__| |____|__ (____ / ____|
// \/ \/ \/ \/\/
//
// Copyright (c) 2016 RahulKatariya. All rights reserved.
//
import Quick
import Nimble
import Alamofire
class PersonArrayGETServiceSpec: ServiceSpec {
override func spec() {
describe("PersonArrayGETService") {
it("executeTask") {
let actual: [NSDictionary] = [
["id": 12345, "name": "Rahul Katariya"],
["id": 12346, "name": "Aar Kay"]
]
var expected: [NSDictionary]!
PersonArrayGETService().executeTask() {
if let value = $0.result.value {
expected = value
}
}
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
it("executeRequestOperation") {
let actual: [NSDictionary] = [
["id": 12345, "name": "Rahul Katariya"],
["id": 12346, "name": "Aar Kay"]
]
var expected: [NSDictionary]!
let requestOperation = PersonArrayGETService().requestOperation() {
if let value = $0.result.value {
expected = value
}
}
requestOperation.start()
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
}
}
}
| 30.967213 | 116 | 0.421387 |
ff5996671d968801c4166ecef6d4144ec9658357 | 1,006 | //
// This file is part of PHANTOM Swift Crypto.
//
// (c) PhantomChain <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
import Foundation
public enum TransactionType: Int {
case transfer = 0
case secondSignatureRegistration = 1
case delegateRegistration = 2
case vote = 3
case multiSignatureRegistration = 4
case ipfs = 5
case timelockTransfer = 6
case multiPayment = 7
case delegateResignation = 8
}
public struct TransactionFee {
static let transfer: UInt64 = 10000000
static let secondSignatureRegistration: UInt64 = 500000000
static let delegateRegistration: UInt64 = 2500000000
static let vote: UInt64 = 100000000
static let multiSignatureRegistration: UInt64 = 500000000
static let ipfs: UInt64 = 0
static let timelockTransfer: UInt64 = 0
static let multiPayment: UInt64 = 0
static let delegateResignation: UInt64 = 0
}
| 28.742857 | 74 | 0.727634 |
dee5c6a9ae54b592328199f2073acda81999d085 | 2,553 | //
// AppDelegate.swift
// MVVM Demo
//
// Created by Malav Soni on 10/11/19.
// Copyright © 2019 Malav Soni. All rights reserved.
//
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
}
// MARK: UISceneSession Lifecycle
@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
@available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if MSGoogleHelper.application(app, open: url, options: options) == true {
return true
}else if MSFacebookHelper.application(app, open: url, options: options){
return true
}else{
return false
}
}
}
extension AppDelegate{
class func change(rootController rootViewController:UIViewController) -> Void{
if #available(iOS 13.0, *) {
if let window = UIApplication.shared.keyWindowRef{
window.rootViewController = rootViewController
window.makeKeyAndVisible()
}
} else {
// Fallback on earlier versions
if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
appDelegate.window?.rootViewController = rootViewController
appDelegate.window?.makeKeyAndVisible()
}
}
}
}
| 38.104478 | 179 | 0.672934 |
dd1527d08baee7d17c184f0b6d005384ebb47637 | 189 | //
// Extension.swift
// QuickSimulator
//
// Created by zkhCreator on 2020/7/19.
// Copyright © 2020 zkhCreator. All rights reserved.
//
import Foundation
extension Process {
}
| 13.5 | 53 | 0.677249 |
dde5baea10d1252b472b0d13a88460d40bc1c86e | 2,468 | //
// LineClick.swift
// ZJWidPackExtension
//
// Created by wangshuailong on 2020/10/20.
//
import WidgetKit
import SwiftUI
import Intents
struct LineClickProvider: IntentTimelineProvider {
//默认视图
func placeholder(in context: Context) -> LineSimpleEntry {
LineSimpleEntry(date: Date(), configuration: ConfigurationIntent())
}
//预览快照,一个大致情况
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (LineSimpleEntry) -> ()) {
let entry = LineSimpleEntry(date: Date(), configuration: configuration)
completion(entry)
}
//刷新事件
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<LineSimpleEntry>) -> ()) {
var entries: [LineSimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = LineSimpleEntry(date: entryDate, configuration: configuration)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
//用来保存所需要的数据
struct LineSimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
}
//用来展示的视图View
struct LineEntryView : View {
//三种样式
//@Environment(\.widgetFamily) var family: WidgetFamily
var entry: LineClickProvider.Entry
var body: some View {
LineContentView()
}
}
struct LineClick: Widget {
let kind: String = "LineClick" // 标识符,不能和其他Widget重复,最好就是使用当前Widgets的名字。
public var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: LineClickProvider()) { entry in
LineEntryView(entry: entry)
}
.configurationDisplayName("快速启动") //Widget显示的名字
.description("快速到达想要的页面") //Widget的描述
.supportedFamilies([.systemMedium]) //组建显示的类型
}
}
struct LineClick_Previews: PreviewProvider {
static var previews: some View {
LineEntryView(entry: LineSimpleEntry(date: Date(), configuration: ConfigurationIntent()))
.previewContext(WidgetPreviewContext(family: .systemMedium))
}
}
| 29.73494 | 140 | 0.666937 |
0175694c24cddf90780e385961daf24e10a6fa60 | 3,525 | //
// ResolverTests.swift
// ResolverTests
//
// Created by Michael Long on 11/14/17.
// Copyright © 2017 com.hmlong. All rights reserved.
//
import XCTest
@testable import Resolver
class ResolverBasicTests: XCTestCase {
var resolver: Resolver!
override func setUp() {
super.setUp()
resolver = Resolver()
}
override func tearDown() {
super.tearDown()
}
func testRegistrationAndExplicitResolution() {
resolver.register { XYZSessionService() }
let session: XYZSessionService? = resolver.resolve(XYZSessionService.self)
XCTAssertNotNil(session)
}
func testRegistrationAndInferedResolution() {
resolver.register { XYZSessionService() }
let session: XYZSessionService? = resolver.resolve() as XYZSessionService
XCTAssertNotNil(session)
}
func testRegistrationAndOptionalResolution() {
resolver.register { XYZSessionService() }
let session: XYZSessionService? = resolver.optional()
XCTAssertNotNil(session)
}
func testRegistrationAndOptionalResolutionFailure() {
let session: XYZSessionService? = resolver.optional()
XCTAssertNil(session)
}
func testRegistrationAndResolutionChain() {
resolver.register { XYZSessionService() }
resolver.register { XYZService( self.resolver.optional() ) }
let service: XYZService? = resolver.optional()
XCTAssertNotNil(service)
XCTAssertNotNil(service?.session)
}
func testRegistrationOverwritting() {
resolver.register() { XYZNameService("Fred") }
resolver.register() { XYZNameService("Barney") }
let service: XYZNameService? = resolver.optional()
XCTAssertNotNil(service)
XCTAssert(service?.name == "Barney")
}
func testRegistrationAndPassedResolver() {
resolver.register { XYZSessionService() }
resolver.register { (r) -> XYZService in
return XYZService( r.optional() )
}
let service: XYZService? = resolver.optional()
XCTAssertNotNil(service)
XCTAssertNotNil(service?.session)
}
func testRegistrationAndResolutionProperties() {
resolver.register { XYZSessionService() }
.resolveProperties { (r, s) in
s.name = "updated"
}
let session: XYZSessionService? = resolver.optional()
XCTAssertNotNil(session)
XCTAssert(session?.name == "updated")
}
func testRegistrationAndResolutionResolve() {
resolver.register { XYZSessionService() }
let session: XYZSessionService = resolver.resolve()
XCTAssertNotNil(session)
}
func testRegistrationAndResolutionResolveArgs() {
let service: XYZService = Resolver.resolve(args: true)
XCTAssertNotNil(service.session)
}
func testStaticRegistrationAndResolution() {
Resolver.register { XYZSessionService() }
let service: XYZService = Resolver.resolve()
XCTAssertNotNil(service.session)
}
func testStaticRegistrationWithArgsAndResolution() {
Resolver.register { _, _ in XYZSessionService() }
let service: XYZService = Resolver.resolve()
XCTAssertNotNil(service.session)
}
func testRegistrationWithArgsCodeCoverage() {
resolver.register(XYZSessionProtocol.self) { return nil } // induce internal error
let session: XYZSessionProtocol? = resolver.optional()
XCTAssertNil(session)
}
}
| 30.921053 | 90 | 0.662695 |
75cb31c16feeccf367b4a1bea9d229cde337ff01 | 10,421 | import UIKit
extension UIImageView {
/// Sets the image property of the view based on initial text, a specified background color, custom text attributes, and a circular clipping
///
/// - Parameters:
/// - string: The string used to generate the initials. This should be a user's full name if available.
/// - color: This optional paramter sets the background of the image. By default, a random color will be generated.
/// - circular: This boolean will determine if the image view will be clipped to a circular shape.
/// - textAttributes: This dictionary allows you to specify font, text color, shadow properties, etc.
open func setImage(string: String?, color: UIColor? = nil, circular: Bool = false, textAttributes: [NSAttributedString.Key: Any]? = nil) {
let image = imageSnap(text: string != nil ? string?.initials : "", color: color ?? UIColor.random, circular: circular, textAttributes: textAttributes)
if let newImage = image {
self.image = newImage
}
}
private func imageSnap(text: String?, color: UIColor, circular: Bool, textAttributes: [NSAttributedString.Key: Any]?) -> UIImage? {
let scale = Float(UIScreen.main.scale)
var size = bounds.size
if contentMode == .scaleToFill || contentMode == .scaleAspectFill || contentMode == .scaleAspectFit || contentMode == .redraw {
size.width = CGFloat(floorf((Float(size.width) * scale) / scale))
size.height = CGFloat(floorf((Float(size.height) * scale) / scale))
}
UIGraphicsBeginImageContextWithOptions(size, false, CGFloat(scale))
let context = UIGraphicsGetCurrentContext()
if circular {
let path = CGPath(ellipseIn: bounds, transform: nil)
context?.addPath(path)
context?.clip()
}
// Fill
context?.setFillColor(color.cgColor)
context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
// Text
if let text = text {
let attributes: [NSAttributedString.Key: Any] = textAttributes ?? [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15.0)]
let textSize = text.size(withAttributes: attributes)
let bounds = self.bounds
let rect = CGRect(x: bounds.size.width/2 - textSize.width/2, y: bounds.size.height/2 - textSize.height/2, width: textSize.width, height: textSize.height)
text.draw(in: rect, withAttributes: attributes)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
// MARK: String Helper
extension String {
public var initials: String {
var finalString = String()
var words = components(separatedBy: .whitespacesAndNewlines)
if let firstCharacter = words.first?.first {
finalString.append(String(firstCharacter))
words.removeFirst()
}
if let lastCharacter = words.last?.first {
finalString.append(String(lastCharacter))
}
return finalString.uppercased()
//return self.components(separatedBy: .whitespacesAndNewlines).reduce("") { ($0.isEmpty ? "" : "\($0.uppercased().first!)") + ($1.isEmpty ? "" : "\($1.uppercased().first!)") }
}
}
let kFontResizingProportion: CGFloat = 0.4
let kColorMinComponent: Int = 30
let kColorMaxComponent: Int = 214
public typealias GradientColors = (top: UIColor, bottom: UIColor)
typealias HSVOffset = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat)
let kGradientTopOffset: HSVOffset = (hue: -0.025, saturation: 0.05, brightness: 0, alpha: 0)
let kGradientBotomOffset: HSVOffset = (hue: 0.025, saturation: -0.05, brightness: 0, alpha: 0)
extension UIImageView {
public func setImageForName(string: String, backgroundColor: UIColor? = nil, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false) {
setImageForName(string: string, backgroundColor: backgroundColor, circular: circular, textAttributes: textAttributes, gradient: gradient, gradientColors: nil)
}
public func setImageForName(string: String, gradientColors: GradientColors? = nil, circular: Bool = true, textAttributes: [NSAttributedString.Key: AnyObject]? = nil) {
setImageForName(string: string, backgroundColor: nil, circular: circular, textAttributes: textAttributes, gradient: true, gradientColors: gradientColors)
}
public func setImageForName(string: String, backgroundColor: UIColor? = nil, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]? = nil, gradient: Bool = false, gradientColors: GradientColors? = nil) {
let initials: String = initialsFromString(string: string)
let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor(for: string)
let gradientColors = gradientColors ?? topAndBottomColors(for: color)
let attributes: [NSAttributedString.Key: AnyObject] = (textAttributes != nil) ? textAttributes! : [
.font: self.fontForFontName(name: nil),
.foregroundColor: UIColor.white
]
self.image = imageSnapshot(text: initials, backgroundColor: color, circular: circular, textAttributes: attributes, gradient: gradient, gradientColors: gradientColors)
}
private func fontForFontName(name: String?) -> UIFont {
let fontSize = self.bounds.width * kFontResizingProportion;
if name != nil {
return UIFont(name: name!, size: fontSize)!
}
else {
return UIFont.systemFont(ofSize: fontSize)
}
}
private func imageSnapshot(text imageText: String, backgroundColor: UIColor, circular: Bool, textAttributes: [NSAttributedString.Key : AnyObject], gradient: Bool, gradientColors: GradientColors) -> UIImage {
let scale: CGFloat = UIScreen.main.scale
var size: CGSize = self.bounds.size
if (self.contentMode == .scaleToFill ||
self.contentMode == .scaleAspectFill ||
self.contentMode == .scaleAspectFit ||
self.contentMode == .redraw) {
size.width = (size.width * scale) / scale
size.height = (size.height * scale) / scale
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext = UIGraphicsGetCurrentContext()!
if circular {
// Clip context to a circle
let path: CGPath = CGPath(ellipseIn: self.bounds, transform: nil)
context.addPath(path)
context.clip()
}
if gradient {
// Draw a gradient from the top to the bottom
let baseSpace = CGColorSpaceCreateDeviceRGB()
let colors = [gradientColors.top.cgColor, gradientColors.bottom.cgColor]
let gradient = CGGradient(colorsSpace: baseSpace, colors: colors as CFArray, locations: nil)!
let startPoint = CGPoint(x: self.bounds.midX, y: self.bounds.minY)
let endPoint = CGPoint(x: self.bounds.midX, y: self.bounds.maxY)
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
} else {
// Fill background of context
context.setFillColor(backgroundColor.cgColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
// Draw text in the context
let textSize: CGSize = imageText.size(withAttributes: textAttributes)
let bounds: CGRect = self.bounds
imageText.draw(in: CGRect(x: bounds.midX - textSize.width / 2,
y: bounds.midY - textSize.height / 2,
width: textSize.width,
height: textSize.height),
withAttributes: textAttributes)
let snapshot: UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();
return snapshot;
}
}
private func randomColorComponent() -> Int {
let limit = kColorMaxComponent - kColorMinComponent
return kColorMinComponent + Int(drand48() * Double(limit))
}
private func randomColor(for string: String) -> UIColor {
srand48(string.hashValue)
let red = CGFloat(randomColorComponent()) / 255.0
let green = CGFloat(randomColorComponent()) / 255.0
let blue = CGFloat(randomColorComponent()) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
private func initialsFromString(string: String) -> String {
return string.components(separatedBy: .whitespacesAndNewlines).reduce("") {
($0.isEmpty ? "" : "\($0.uppercased().first!)") + ($1.isEmpty ? "" : "\($1.uppercased().first!)")
}
}
private func clampColorComponent(_ value: CGFloat) -> CGFloat {
return min(max(value, 0), 1)
}
private func correctColorComponents(of color: UIColor, withHSVOffset offset: HSVOffset) -> UIColor {
var hue = CGFloat(0)
var saturation = CGFloat(0)
var brightness = CGFloat(0)
var alpha = CGFloat(0)
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
hue = clampColorComponent(hue + offset.hue)
saturation = clampColorComponent(saturation + offset.saturation)
brightness = clampColorComponent(brightness + offset.brightness)
alpha = clampColorComponent(alpha + offset.alpha)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
return color
}
private func topAndBottomColors(for color: UIColor, withTopHSVOffset topHSVOffset: HSVOffset = kGradientTopOffset, withBottomHSVOffset bottomHSVOffset: HSVOffset = kGradientBotomOffset) -> GradientColors {
let topColor = correctColorComponents(of: color, withHSVOffset: topHSVOffset)
let bottomColor = correctColorComponents(of: color, withHSVOffset: bottomHSVOffset)
return (top: topColor, bottom: bottomColor)
}
| 44.534188 | 221 | 0.643316 |
1f0181985737b0a893a29b4d25641a1376ed8151 | 1,910 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Implementation details of a structure used to describe a joint.
*/
import CoreGraphics
class Joint {
enum Name: Int, CaseIterable {
case nose
case leftEye
case rightEye
case leftEar
case rightEar
case leftShoulder
case rightShoulder
case leftElbow
case rightElbow
case leftWrist
case rightWrist
case leftHip
case rightHip
case leftKnee
case rightKnee
case leftAnkle
case rightAnkle
var name: String {
get { return String(describing: self) }
}
}
/// The total number of joints available.
static var numberOfJoints: Int {
return Name.allCases.count
}
/// The name used to identify the joint.
let name: Name
/// The position of the joint relative to the image.
///
/// The position is initially relative to the model's input image size and then mapped to the original image
/// size after constructing the associated pose.
var position: CGPoint
/// The joint's respective cell index into model's output grid.
var cell: PoseNetOutput.Cell
/// The confidence score associated with this joint.
///
/// The joint confidence is obtained from the `heatmap` array output by the PoseNet model.
var confidence: Double
/// A boolean value that indicates if the joint satisfies the joint threshold defined in the configuration.
var isValid: Bool
init(name: Name,
cell: PoseNetOutput.Cell = .zero,
position: CGPoint = .zero,
confidence: Double = 0,
isValid: Bool = false) {
self.name = name
self.cell = cell
self.position = position
self.confidence = confidence
self.isValid = isValid
}
}
| 26.527778 | 112 | 0.627749 |
3ae9aa2400fdfb3a0ba848833b1c5cca7d21db69 | 158 | import XCTest
import GoogleAnalyticsPublishPluginTests
var tests = [XCTestCaseEntry]()
tests += GoogleAnalyticsPublishPluginTests.allTests()
XCTMain(tests)
| 19.75 | 53 | 0.835443 |
f930921fcd4dc6098237986fe1a2ab0b43c846b7 | 4,198 | //
// ScheduleCoreTests.swift
// ScheduleCoreTests
//
// Created by Eric Liang on 6/30/19.
// Copyright © 2019 Eric Liang. All rights reserved.
//
import XCTest
@testable import ScheduleCore
class ScheduleCoreTests: XCTestCase {
func testEmptySchedule() {
let sc = SCSchedule()
for dp in SCDayPeriod.allCases {
XCTAssertEqual(sc[dp], nil)
}
}
func testPutSingleDays() {
var schedule = SCSchedule()
schedule.put(class: SCClass(name: "English"), dayPeriod: .A1)
var history = SCClass(name: "History")
history.location = "loc"
history.teacher = "teacher"
schedule.put(class: SCClass(name: "History"), dayPeriod: .A2)
XCTAssertEqual(schedule[.A1]?.name, "English")
XCTAssertEqual(schedule[.A1]?.teacher, "teacher")
XCTAssertEqual(schedule[.A1]?.location, "loc")
XCTAssertEqual(schedule[.A2]?.name, "History")
XCTAssertEqual(schedule[.A2]?.teacher, nil)
XCTAssertEqual(schedule[.A2]?.location, nil)
XCTAssertEqual(schedule[.A3], nil)
XCTAssertEqual(schedule[.B1], nil)
XCTAssertEqual(schedule[.B2], nil)
XCTAssertEqual(schedule[.B3], nil)
XCTAssertEqual(schedule[.B4], nil)
XCTAssertEqual(schedule[.B5], nil)
XCTAssertEqual(schedule[.B6], nil)
XCTAssertEqual(schedule[.B7], nil)
XCTAssertEqual(schedule[.B8], nil)
}
func testGetClassesForDay() {
var schedule = SCSchedule()
schedule.put(class: SCClass(name: "English"), dayPeriod: .G1)
schedule.put(class: SCClass(name: "History"), dayPeriod: .G2)
schedule.put(class: SCClass(name: "Math"), dayPeriod: .G3)
schedule.put(class: SCClass(name: "Music"), dayPeriod: .G4)
XCTAssertEqual(schedule[.G].map( { $0?.name } ), ["English", "History", "Math", "Music", nil, nil, nil, nil])
}
func testPutReplaces() {
var schedule = SCSchedule()
schedule.put(class: SCClass(name: "English"), dayPeriod: .A1)
schedule.put(class: SCClass(name: "History"), dayPeriod: .A1)
XCTAssertEqual(schedule[.A1]?.name, "History")
XCTAssertEqual(schedule[.A1]?.teacher, nil)
XCTAssertEqual(schedule[.A1]?.location, nil)
}
func testPutMultiple() {
var scheduleHigh = SCSchedule()
let c = SCClass(name: "English")
scheduleHigh.put(class: c, dayPeriod: .A1, all: true)
XCTAssertEqual(scheduleHigh[.A1], c)
XCTAssertEqual(scheduleHigh[.B2], c)
XCTAssertEqual(scheduleHigh[.C3], c)
XCTAssertEqual(scheduleHigh[.D4], c)
XCTAssertEqual(scheduleHigh[.E7], c)
XCTAssertEqual(scheduleHigh[.F8], c)
}
func testPutMultipleMiddleSchool() {
let c1 = SCClass(name: "English")
let c2 = SCClass(name: "History")
var scheduleMiddle = SCSchedule()
scheduleMiddle.degree = .middle
scheduleMiddle.put(class: c1, dayPeriod: .A1, all: true)
XCTAssertEqual(scheduleMiddle[.A1], c1)
XCTAssertEqual(scheduleMiddle[.B2], c1)
XCTAssertEqual(scheduleMiddle[.C3], c1)
XCTAssertEqual(scheduleMiddle[.D5], c1)
XCTAssertEqual(scheduleMiddle[.E7], c1)
XCTAssertEqual(scheduleMiddle[.F6], c1)
scheduleMiddle.put(class: c2, dayPeriod: .F4, all: true)
XCTAssertEqual(scheduleMiddle[.A4], c2)
XCTAssertEqual(scheduleMiddle[.B4], c2)
XCTAssertEqual(scheduleMiddle[.C4], c2)
XCTAssertEqual(scheduleMiddle[.D4], c2)
XCTAssertEqual(scheduleMiddle[.E4], c2)
XCTAssertEqual(scheduleMiddle[.F4], c2)
XCTAssertEqual(scheduleMiddle[.G4], c2)
}
func testDecode() {
var data = SCUserData()
var s1 = SCSchedule()
s1.put(class: SCClass(name: "English"), dayPeriod: .G1)
s1.put(class: SCClass(name: "History"), dayPeriod: .G2)
s1.put(class: SCClass(name: "Math"), dayPeriod: .G3)
s1.put(class: SCClass(name: "Music"), dayPeriod: .G4)
data.add(user: "erix", schedule: s1)
XCTAssertEqual(try? JSONDecoder().decode(SCUserData.self, from: JSONEncoder().encode(data)), data)
}
}
| 38.163636 | 117 | 0.628394 |
ab1d3ce09ff8dd52b027a0b4f41101c7f7f0ca45 | 2,277 | //
// HardwareFormatterTests.swift
// Tests
//
// Created by Shams Ahmed on 04/09/2019.
// Copyright © 2020 Bitrise. All rights reserved.
//
import Foundation
import SnapshotTesting
import XCTest
@testable import Trace
final class HardwareFormatterTests: XCTestCase {
// MARK: - Property
let hardware: HardwareFormatter = {
let cpu = CPU()
let memory = Memory()
let connectivity = Connectivity()
let formatter = HardwareFormatter(cpu: cpu, memory: memory, connectivity: connectivity)
return formatter
}()
// MARK: - Setup
override func setUp() {
}
override func tearDown() {
}
// MARK: - Tests
func testErrorNil() {
XCTAssertNotNil(hardware)
XCTAssertNotNil(hardware.data)
XCTAssertNotNil(hardware.jsonString)
}
func testReadMetrics() {
let metrics = hardware.metrics
XCTAssertNotNil(metrics)
XCTAssertNil(metrics.resource)
XCTAssertNotNil(hardware.details)
XCTAssertEqual(metrics.metrics.count, 3)
}
func testReadMetrics_readOne() {
let metric = hardware.metrics.metrics.first!
XCTAssertNotNil(metric)
XCTAssertNotNil(metric.descriptor)
XCTAssertNotNil(metric.timeseries)
XCTAssertEqual(metric.descriptor.name, Metric.Descriptor.Name.systemCpuPct)
XCTAssertEqual(metric.timeseries.count, 4)
XCTAssertNotNil(hardware.details)
}
func testReadMetrics_readPoints() {
let points = hardware.metrics.metrics.first!.timeseries[0].points
let point = hardware.metrics.metrics.first!.timeseries[0].points[0]
XCTAssertEqual(points.count, 1)
XCTAssertNotNil(point)
}
func testReadMetrics_readValues() {
let values = hardware.metrics.metrics.first!.timeseries[0].values
let value = hardware.metrics.metrics.first!.timeseries[0].values[0]
XCTAssertEqual(values.count, 1)
XCTAssertTrue(value.hasValue)
}
func testFormatterMatchesJSON_descriptor() {
assertSnapshot(matching: hardware.metrics.metrics[0].descriptor, as: .json)
}
}
| 26.172414 | 95 | 0.634168 |
219784730f1b7bacc08d9b3bb02edb14810601b3 | 2,182 | //
// AppDelegate.swift
// MagicalGrid
//
// Created by Per Kristensen on 03/06/2017.
// Copyright © 2017 Per Dalsgaard. 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.425532 | 285 | 0.756187 |
726ab7f45a3b999b0a8e7374eabb755d4a0d3abd | 7,042 | // https://github.com/tryWabbit/Layout-Helper
import UIKit
enum UIDeviceSize {
case i3_5Inch
case i4Inch
case i4_7Inch
case i5_5Inch
case i5_8Inch
case i6_1Inch
case i6_5Inch
case i7_9Inch
case i9_7Inch
case i10_5Inch
case i12_9Inch
case unknown
}
let deviceSize : UIDeviceSize = {
let w: Double = Double(UIScreen.main.bounds.width)
let h: Double = Double(UIScreen.main.bounds.height)
let screenHeight: Double = max(w, h)
switch screenHeight {
case 480:
return .i3_5Inch
case 568:
return .i4Inch
case 667:
return UIScreen.main.scale == 3.0 ? .i5_5Inch : .i4_7Inch
case 736:
return .i5_5Inch
case 812:
return .i5_8Inch
case 896:
switch UIDevice().type {
case .iPhoneXSMax:
return .i6_5Inch
default:
return .i6_1Inch
}
case 1024:
switch UIDevice().type {
case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4:
return .i7_9Inch
case .iPadPro10_5:
return .i10_5Inch
default:
return .i9_7Inch
}
case 1112:
return .i10_5Inch
case 1366:
return .i12_9Inch
default:
return .unknown
}
}()
// This Model and Extention has been taken from the Answer by
// Alessandro Ornano : https://stackoverflow.com/a/46234519/6330448
// Feel free to update it
public enum Model : String {
case simulator = "simulator/sandbox",
//iPod
iPod1 = "iPod 1",
iPod2 = "iPod 2",
iPod3 = "iPod 3",
iPod4 = "iPod 4",
iPod5 = "iPod 5",
//iPad
iPad2 = "iPad 2",
iPad3 = "iPad 3",
iPad4 = "iPad 4",
iPadAir = "iPad Air ",
iPadAir2 = "iPad Air 2",
iPad5 = "iPad 5", //aka iPad 2017
iPad6 = "iPad 6", //aka iPad 2018
//iPad mini
iPadMini = "iPad Mini",
iPadMini2 = "iPad Mini 2",
iPadMini3 = "iPad Mini 3",
iPadMini4 = "iPad Mini 4",
//iPad pro
iPadPro9_7 = "iPad Pro 9.7\"",
iPadPro10_5 = "iPad Pro 10.5\"",
iPadPro12_9 = "iPad Pro 12.9\"",
iPadPro2_12_9 = "iPad Pro 2 12.9\"",
//iPhone
iPhone4 = "iPhone 4",
iPhone4S = "iPhone 4S",
iPhone5 = "iPhone 5",
iPhone5S = "iPhone 5S",
iPhone5C = "iPhone 5C",
iPhone6 = "iPhone 6",
iPhone6plus = "iPhone 6 Plus",
iPhone6S = "iPhone 6S",
iPhone6Splus = "iPhone 6S Plus",
iPhoneSE = "iPhone SE",
iPhone7 = "iPhone 7",
iPhone7plus = "iPhone 7 Plus",
iPhone8 = "iPhone 8",
iPhone8plus = "iPhone 8 Plus",
iPhoneX = "iPhone X",
iPhoneXS = "iPhone XS",
iPhoneXSMax = "iPhone XS Max",
iPhoneXR = "iPhone XR",
//Apple TV
AppleTV = "Apple TV",
AppleTV_4K = "Apple TV 4K",
unrecognized = "?unrecognized?"
}
public extension UIDevice {
var type: Model {
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: 1) {
ptr in String.init(validatingUTF8: ptr)
}
}
let modelMap : [ String : Model ] = [
"i386" : .simulator,
"x86_64" : .simulator,
//iPod
"iPod1,1" : .iPod1,
"iPod2,1" : .iPod2,
"iPod3,1" : .iPod3,
"iPod4,1" : .iPod4,
"iPod5,1" : .iPod5,
//iPad
"iPad2,1" : .iPad2,
"iPad2,2" : .iPad2,
"iPad2,3" : .iPad2,
"iPad2,4" : .iPad2,
"iPad3,1" : .iPad3,
"iPad3,2" : .iPad3,
"iPad3,3" : .iPad3,
"iPad3,4" : .iPad4,
"iPad3,5" : .iPad4,
"iPad3,6" : .iPad4,
"iPad4,1" : .iPadAir,
"iPad4,2" : .iPadAir,
"iPad4,3" : .iPadAir,
"iPad5,3" : .iPadAir2,
"iPad5,4" : .iPadAir2,
"iPad6,11" : .iPad5, //aka iPad 2017
"iPad6,12" : .iPad5,
"iPad7,5" : .iPad6, //aka iPad 2018
"iPad7,6" : .iPad6,
//iPad mini
"iPad2,5" : .iPadMini,
"iPad2,6" : .iPadMini,
"iPad2,7" : .iPadMini,
"iPad4,4" : .iPadMini2,
"iPad4,5" : .iPadMini2,
"iPad4,6" : .iPadMini2,
"iPad4,7" : .iPadMini3,
"iPad4,8" : .iPadMini3,
"iPad4,9" : .iPadMini3,
"iPad5,1" : .iPadMini4,
"iPad5,2" : .iPadMini4,
//iPad pro
"iPad6,3" : .iPadPro9_7,
"iPad6,4" : .iPadPro9_7,
"iPad7,3" : .iPadPro10_5,
"iPad7,4" : .iPadPro10_5,
"iPad6,7" : .iPadPro12_9,
"iPad6,8" : .iPadPro12_9,
"iPad7,1" : .iPadPro2_12_9,
"iPad7,2" : .iPadPro2_12_9,
//iPhone
"iPhone3,1" : .iPhone4,
"iPhone3,2" : .iPhone4,
"iPhone3,3" : .iPhone4,
"iPhone4,1" : .iPhone4S,
"iPhone5,1" : .iPhone5,
"iPhone5,2" : .iPhone5,
"iPhone5,3" : .iPhone5C,
"iPhone5,4" : .iPhone5C,
"iPhone6,1" : .iPhone5S,
"iPhone6,2" : .iPhone5S,
"iPhone7,1" : .iPhone6plus,
"iPhone7,2" : .iPhone6,
"iPhone8,1" : .iPhone6S,
"iPhone8,2" : .iPhone6Splus,
"iPhone8,4" : .iPhoneSE,
"iPhone9,1" : .iPhone7,
"iPhone9,3" : .iPhone7,
"iPhone9,2" : .iPhone7plus,
"iPhone9,4" : .iPhone7plus,
"iPhone10,1" : .iPhone8,
"iPhone10,4" : .iPhone8,
"iPhone10,2" : .iPhone8plus,
"iPhone10,5" : .iPhone8plus,
"iPhone10,3" : .iPhoneX,
"iPhone10,6" : .iPhoneX,
"iPhone11,2" : .iPhoneXS,
"iPhone11,4" : .iPhoneXSMax,
"iPhone11,6" : .iPhoneXSMax,
"iPhone11,8" : .iPhoneXR,
//AppleTV
"AppleTV5,3" : .AppleTV,
"AppleTV6,2" : .AppleTV_4K
]
if let model = modelMap[String.init(validatingUTF8: modelCode!)!] {
if model == .simulator {
if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
if let simModel = modelMap[String.init(validatingUTF8: simModelCode)!] {
return simModel
}
}
}
return model
}
return Model.unrecognized
}
}
| 31.159292 | 95 | 0.463505 |
f912664901da9e7d4312688470b48602a3e04ec0 | 1,413 | //
// AppDelegate.swift
// LYCoreText
//
// Created by 李玉臣 on 2020/1/14.
// Copyright © 2020 LYfinacial.com. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.184211 | 179 | 0.747346 |
1d55c14a15ffb68b8479ee75425894e9c3700e77 | 261 | //
// ImageName.swift
// dota-helper
//
// Created by Canna Wen on 2016-11-26.
// Copyright © 2016 Canna Wen. All rights reserved.
//
import Foundation
enum ImageName: String {
case observerWard = "observer_ward"
case sentryWard = "sentry_ward"
}
| 17.4 | 52 | 0.681992 |
bb3b4785a0ce5a45ad585db14c7b69b8ec65a06e | 18,271 | // BaseButtonBarPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.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.
import Foundation
open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
public var settings = ButtonBarPagerTabStripSettings()
public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarCellType>!
public var changeCurrentIndex: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ animated: Bool) -> Void)?
public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
@IBOutlet public weak var buttonBarView: ButtonBarView!
lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
return self.calculateWidths()
}()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
let buttonBarViewAux = buttonBarView ?? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: settings.style.buttonBarLeftContentInset ?? 35, bottom: 0, right: settings.style.buttonBarRightContentInset ?? 35)
let buttonBarHeight = settings.style.buttonBarHeight ?? 44
let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
buttonBar.backgroundColor = .orange
buttonBar.selectedBar.backgroundColor = .black
buttonBar.autoresizingMask = .flexibleWidth
var newContainerViewFrame = containerView.frame
newContainerViewFrame.origin.y = buttonBarHeight
newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y)
containerView.frame = newContainerViewFrame
return buttonBar
}()
buttonBarView = buttonBarViewAux
if buttonBarView.superview == nil {
view.addSubview(buttonBarView)
}
if buttonBarView.delegate == nil {
buttonBarView.delegate = self
}
if buttonBarView.dataSource == nil {
buttonBarView.dataSource = self
}
buttonBarView.scrollsToTop = false
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = settings.style.buttonBarMinimumInteritemSpacing ?? flowLayout.minimumInteritemSpacing
flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing
let sectionInset = flowLayout.sectionInset
flowLayout.sectionInset = UIEdgeInsets(top: sectionInset.top, left: settings.style.buttonBarLeftContentInset ?? sectionInset.left, bottom: sectionInset.bottom, right: settings.style.buttonBarRightContentInset ?? sectionInset.right)
buttonBarView.showsHorizontalScrollIndicator = false
buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor
buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor
buttonBarView.selectedBarVerticalAlignment = settings.style.selectedBarVerticalAlignment
buttonBarView.selectedBarHeight = settings.style.selectedBarHeight
// register button bar item cell
switch buttonBarItemSpec! {
case .nibFile(let nibName, let bundle, _):
buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell")
case .cellClass:
buttonBarView.register(ButtonBarCellType.self, forCellWithReuseIdentifier:"Cell")
}
//-
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonBarView.layoutIfNeeded()
isViewAppearing = true
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewAppearing = false
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isViewAppearing || isViewRotating else { return }
// Force the UICollectionViewFlowLayout to get laid out again with the new size if
// a) The view is appearing. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called for a second time
// when the view is shown and when the view *frame(s)* are actually set
// (we need the view frame's to have been set to work out the size's and on the
// first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
// aren't set correctly)
// b) The view is rotating. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
// *new* frame so that the buttonBarView cell's actually get resized correctly
cachedCellWidths = calculateWidths()
buttonBarView.collectionViewLayout.invalidateLayout()
// When the view first appears or is rotated we also need to ensure that the barButtonView's
// selectedBar is resized and its contentOffset/scroll is set correctly (the selected
// tab/cell may end up either skewed or off screen after a rotation otherwise)
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
}
// MARK: - View Rotation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: - Public Methods
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
buttonBarView.reloadData()
cachedCellWidths = calculateWidths()
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
}
open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
var numberOfLargeCells = 0
var totalWidthOfLargeCells: CGFloat = 0
for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
totalWidthOfLargeCells += minimumCellWidthValue
numberOfLargeCells += 1
}
guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
let numberOfCells = minimumCellWidths.count
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
let numberOfSmallCells = numberOfCells - numberOfLargeCells
let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
if let changeCurrentIndex = changeCurrentIndex {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndex(oldCell, newCell, true)
}
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
}
}
// MARK: - UICollectionViewDelegateFlowLayut
@objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.height)
}
return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.item != currentIndex else { return }
buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
shouldUpdateButtonBarView = false
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(oldCell, newCell, true)
}
}
moveToViewController(at: indexPath.item)
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
return UICollectionViewCell()
}
let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
configure(cell: cell, for: indicatorInfo)
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false)
}
}
return cell
}
// MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
super.scrollViewDidEndScrollingAnimation(scrollView)
guard scrollView == containerView else { return }
shouldUpdateButtonBarView = true
}
open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
fatalError("You must override this method to set up ButtonBarView cell accordingly")
}
private func calculateWidths() -> [CGFloat] {
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let numberOfCells = viewControllers.count
var minimumCellWidths = [CGFloat]()
var collectionViewContentWidth: CGFloat = 0
for viewController in viewControllers {
let childController = viewController as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
switch buttonBarItemSpec! {
case .cellClass(let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
case .nibFile(_, _, let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
}
}
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
collectionViewContentWidth += cellSpacingTotal
let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth {
return minimumCellWidths
} else {
let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
var stretchedCellWidths = [CGFloat]()
for minimumCellWidthValue in minimumCellWidths {
let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
stretchedCellWidths.append(cellWidth)
}
return stretchedCellWidths
}
}
private var shouldUpdateButtonBarView = true
}
open class ExampleBaseButtonBarPagerTabStripViewController: BaseButtonBarPagerTabStripViewController<ButtonBarViewCell> {
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open func initialize() {
var bundle = Bundle(for: ButtonBarViewCell.self)
if let resourcePath = bundle.path(forResource: "XLPagerTabStrip", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: bundle, width: { [weak self] (childItemInfo) -> CGFloat in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = self?.settings.style.buttonBarItemFont ?? label.font
label.text = childItemInfo.title
let labelSize = label.intrinsicContentSize
return labelSize.width + CGFloat(self?.settings.style.buttonBarItemLeftRightMargin ?? 8 * 2)
})
}
open override func configure(cell: ButtonBarViewCell, for indicatorInfo: IndicatorInfo) {
cell.label.text = indicatorInfo.title
cell.accessibilityLabel = indicatorInfo.accessibilityLabel
if let image = indicatorInfo.image {
cell.imageView.image = image
}
if let highlightedImage = indicatorInfo.highlightedImage {
cell.imageView.highlightedImage = highlightedImage
}
}
}
| 51.759207 | 239 | 0.715396 |
8a38ae08e280d7e789098cdda613c4322c89ab3a | 376 | //
// NSDate-Extension.swift
// DouYuZB
//
// Created by belief on 2018/4/23.
// Copyright © 2018年 PRG. All rights reserved.
//
import Foundation
extension Date {
//MARK: 获取当前时间
static func getCurrentTime() -> String {
let nowDate = Date()
let interval = Int(nowDate.timeIntervalSince1970)
return "\(interval)"
}
}
| 17.090909 | 57 | 0.595745 |
72c941f7b904657b55f08cd68b436c7d8f3836d0 | 1,036 | //
// ViewController.swift
// 09-Unwrapping Optionals
//
// Created by michael on 2017/6/8.
// Copyright © 2017年 MYNavigationController. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let stockCode: String? = findStockCode(company: "Facebook")
let text = "Stock Code - "
/// compile-time error,Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
let message = text + stockCode! /// runtime error,unexpectedly found nil while unwrapping an Optional value
print(message)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func findStockCode(company: String) -> String? {
if (company == "Apple") {
return "AAPL"
} else if (company == "Google") {
return "GOOG"
}
return nil
}
}
| 27.263158 | 115 | 0.609073 |
5d9bc4cb649d6a2fd042468d9b76ef9753c798e2 | 16,734 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore>
public struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
public init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
public init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@warn_unused_result
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
var deferredTypeCheckMask : Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
@warn_unused_result
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/19915280> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
public init(_ source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
var arrayPropertyIsNativeTypeChecked : Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@warn_unused_result
mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
@warn_unused_result
mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// - Precondition: `_isBridgedToObjectiveC(Element.self)`.
/// O(1) if the element type is bridged verbatim, O(N) otherwise.
@warn_unused_result
public func _asCocoaArray() -> _NSArrayCore {
_sanityCheck(
_isBridgedToObjectiveC(Element.self),
"Array element type is not bridged to Objective-C")
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@warn_unused_result
public mutating func requestUniqueMutableBackingBuffer(
minimumCapacity minimumCapacity: Int
) -> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@warn_unused_result
public func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
internal func _typeCheckSlowPath(index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAt(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
func _typeCheck(subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in subRange {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer past-the-end of the
/// just-initialized memory.
public func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location: bounds.startIndex,
length: bounds.endIndex - bounds.startIndex)
let buffer = UnsafeMutablePointer<AnyObject>(target)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in bounds {
result.initialize(with: result.pointee)
result += 1
}
return result
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
public subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices)
if cocoaStorageBaseAddress != nil {
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress),
indices: bounds,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let boundsCount = bounds.count
let result = _ContiguousArrayBuffer<Element>(
uninitializedCount: boundsCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutablePointer(result.firstElementAddress),
range: _SwiftNSRange(
location: bounds.startIndex,
length: boundsCount))
return _SliceBuffer(result, shiftedToStartIndex: bounds.startIndex)
}
set {
fatalError("not implemented")
}
}
public var _unconditionalMutableSubscriptBaseAddress:
UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
public var firstElementAddress: UnsafeMutablePointer<Element> {
if (_fastPath(_isNative)) {
return _native.firstElementAddress
}
return nil
}
/// The number of elements the buffer stores.
public var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
internal func _checkInoutAndNativeTypeCheckedBounds(
index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
public var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@inline(__always)
@warn_unused_result
func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@inline(never)
@warn_unused_result
func _getElementSlowPath(i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAt(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
public subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
public func withUnsafeBufferPointer<R>(
@noescape body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
public mutating func withUnsafeMutableBufferPointer<R>(
@noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
firstElementAddress != nil || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
public var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
public var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
public var identity: UnsafePointer<Void> {
if _isNative {
return _native.identity
}
else {
return unsafeAddress(of: _nonNative)
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Int {
return count
}
//===--- private --------------------------------------------------------===//
typealias Storage = _ContiguousArrayStorage<Element>
public typealias NativeBuffer = _ContiguousArrayBuffer<Element>
var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
var _nonNative: _NSArrayCore {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| 32.305019 | 80 | 0.681188 |
ede98947dd68f1bf424cc69c4c51c282d62a1107 | 593 | // swift-tools-version:4.1
import PackageDescription
/**
# TODO - integrate the following tools into the build process:
# jazzy (a documentation generator)
# Sourcery (a code generator, e.g. lomok for swift)
#
**/
let package = Package(
name: "SwiftScientificLibrary" ,
products: [
.library(name: "SwiftScientificLibrary", targets: ["SwiftScientificLibrary"]),
],
targets: [
.target(name: "SwiftScientificLibrary"),
.testTarget(
name: "SwiftScientificLibraryTests",
dependencies: ["SwiftScientificLibrary"])
]
)
| 26.954545 | 86 | 0.647555 |
fefec73e6d49d2cff28c2a2784382d9af8d02514 | 2,634 | //
// HomeViewController.swift
// Viper-v2-Demo
//
// Created by Donik Vrsnak on 4/11/18.
// Copyright (c) 2018 Infinum. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
final class HomeViewController: UIViewController {
// MARK: - Public properties -
var presenter: HomePresenterInterface!
@IBOutlet private weak var emptyPlaceholderLabel: UILabel!
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
_setupView()
presenter.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
private func _setupView() {
emptyPlaceholderLabel.isHidden = true
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
@IBAction private func logoutButtonActionHandler() {
presenter.didSelectLogoutAction()
}
@IBAction private func addButtonActionHandler() {
presenter.didSelectAddAction()
}
}
// MARK: - Extensions -
extension HomeViewController: HomeViewInterface {
func reloadData() {
tableView.reloadData()
}
func setLoadingVisible(_ visible: Bool) {
if visible {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func setEmptyPlaceholderHidden(_ hidden: Bool) {
emptyPlaceholderLabel.isHidden = hidden
}
}
extension HomeViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return presenter.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.numberOrItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell
let item = presenter.item(at: indexPath)
cell.configure(with: item)
return cell
}
}
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
presenter.didSelectItem(at: indexPath)
}
}
| 26.877551 | 110 | 0.671222 |
eb41d7614e5a97d3c9d6e3c31eae55f0173c836b | 448 | //
// Birds.swift
// feAviumSonusBeta
//
// Created by Ari on 8/5/21.
/// Birds Model
import Foundation
struct Bird: Codable, Identifiable {
let id = UUID()
var view: String
var channel: String
var beginFile: String
var beginTimeSec: Int
var endTimeSec: Int
var lowFreqHz: String
var highFreqHz: String
var speciesCode: String
var commonName: String
var confidence: Double
var rank: String
}
| 16.592593 | 36 | 0.662946 |
90aa19e2f42d2a5213665993339c71fead5aaca7 | 1,401 | //
// CharacterRepository.swift
// DataProviders
//
// Created by Rafael Bartolome on 21/03/2020.
// Copyright © 2020 Rafael Bartolome. All rights reserved.
//
import Foundation
import Support
import Storage
import Promises
public protocol CharacterRepository: AnyObject {
func characters(offset: Int?) -> Promise<[Character], CharacterRepositoryError>
func character(with id: Int) -> Promise<Character, CharacterRepositoryError>
}
public final class InternalCharacterRepository {
let provider: CharacterProviding
let cache: Caching
public init(provider: CharacterProviding, cache: Caching) {
self.provider = provider
self.cache = cache
}
}
extension InternalCharacterRepository: CharacterRepository {
public func characters(offset: Int?) -> Promise<[Character], CharacterRepositoryError> {
provider.characters(offset: offset).then {
$0.forEach { self.cache.set(value: $0) }
}
}
public func character(with id: Int) -> Promise<Character, CharacterRepositoryError> {
if let character = cache.get(id: id as Character.ID) as Character? {
return Promise(value: character)
} else {
return provider.character(by: id).then { self.cache.set(value: $0) }
}
}
}
extension Character: Identifiable {}
extension Array: Runnable {}
extension Character: Runnable {}
| 29.1875 | 92 | 0.690935 |
1ca6554bd74b419db2ba6be21b7f38d3f7d8ca92 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{{}if true{struct B<g{func b:AnyObject{struct d<d where B:a{let:a | 47.8 | 87 | 0.761506 |
565dc532d1c9eefb043effaab116932881f50965 | 6,947 | //
// LSGesture.swift
// Littlstar
//
// Created by Huy Dao on 10/10/17.
// Copyright © 2017 Huy Dao. All rights reserved.
//
protocol LSGestureDelegate {
func lsGestureGetDeviceVector() -> (Float, Float, Float)
func lgGestureDidTap()
}
class LSGesture: NSObject, UIGestureRecognizerDelegate {
var panGesture: UIPanGestureRecognizer!
var zoomGesture: UIPinchGestureRecognizer!
var rotationGesture: UIRotationGestureRecognizer!
var tapGesture: UITapGestureRecognizer!
var delegate: LSGestureDelegate?
// Pan
var previousX: Float = 0
var previousY: Float = 0
var translationX: Float = 0
var translationY: Float = 0
var translationXBuffer = RingBuffer<Float>(count: 8)
var translationYBuffer = RingBuffer<Float>(count: 8)
// Both RingBuffers must read/write after each other immediately, otherwise write is not recorded properly
var dampen: Float = 500
var isPanning: Bool = false
let pitchRotationMaxValue: Float = 1300
// Zoom
var scaleBuffer = RingBuffer<Float>(count: 8)
var previousScale: Float = 0
var scaleValue: Float = 0
let maxZoomValue: Float = 24.0
let minZoomValue: Float = 19.5
// Slerp Value
let minSlerp: Float!
init(minSlerp: Float) {
self.minSlerp = minSlerp
super.init()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(pan))
zoomGesture = UIPinchGestureRecognizer.init(target: self, action: #selector(zoom))
rotationGesture = UIRotationGestureRecognizer.init(target: self, action: #selector(rotate))
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tap))
if !translationXBuffer.write(0.0) { print("error writing to X ring buffer") }
if !translationYBuffer.write(0.0) { print("error writing to Y ring buffer") }
if !scaleBuffer.write(0.0) { print("error writing to scaleDelta ring buffer") }
panGesture.delegate = self
zoomGesture.delegate = self
rotationGesture.delegate = self
tapGesture.delegate = self
// Init values
scaleValue = minZoomValue
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func normalize(x: Float, y: Float) -> ((Float, Float)) {
let deviceVector = delegate!.lsGestureGetDeviceVector()
let thetaXY = atan2(deviceVector.0, deviceVector.1)
var normalizedX: Float = 0 // horizontal
var normalizedY: Float = 0 // vertical
if thetaXY < .pi && thetaXY > .pi/2 { // Quadrant 1
let normalizedTheta = Float((thetaXY - .pi/2) / (.pi/2))
normalizedX = x * normalizedTheta + y * (1 - normalizedTheta)
normalizedY = x * -(1 - normalizedTheta) + y * normalizedTheta
} else if thetaXY > 0 && thetaXY < .pi/2{ // Quadrant 4
let normalizedTheta = Float((thetaXY / (.pi/2)))
normalizedX = x * -(1 - normalizedTheta) + y * normalizedTheta
normalizedY = x * -normalizedTheta + y * -(1 - normalizedTheta)
} else if thetaXY < 0 && thetaXY > (-.pi/2) { // Quadrant 3
let normalizedTheta = Float((thetaXY - (-.pi/2)) / (.pi/2))
normalizedX = x * -normalizedTheta + y * -(1 - normalizedTheta)
normalizedY = x * (1 - normalizedTheta) + y * -normalizedTheta
} else if thetaXY > -.pi && thetaXY < -.pi/2 { // Quadrant 2
let normalizedTheta = Float((thetaXY - (-.pi)) / (.pi/2))
normalizedX = x * (1 - normalizedTheta) + y * -normalizedTheta
normalizedY = x * normalizedTheta + y * (1 - normalizedTheta)
}
return (normalizedX, normalizedY)
}
func pan(_ gestureRecognizer: UIPanGestureRecognizer) {
let view = gestureRecognizer.view
if gestureRecognizer.state == .changed {
isPanning = true
let normalizedTranslation: (Float, Float) = normalize(x: Float(gestureRecognizer.translation(in: view).x),
y: -Float(gestureRecognizer.translation(in: view).y))
// Translation in X
let deltaX = normalizedTranslation.0 - previousX
translationX = translationXBuffer.read()!
if !( translationXBuffer.write( translationX + deltaX)) { print("error in writing gesture point value") }
previousX = normalizedTranslation.0
// Translation in Y
let deltaY = normalizedTranslation.1 - previousY
translationY = translationYBuffer.read()!
if !( translationYBuffer.write( translationY + deltaY)) { print("error in writing gesture point value") }
previousY = normalizedTranslation.1
} else if gestureRecognizer.state == .ended {
isPanning = false
previousX = 0.0
previousY = 0.0
LSConstants.currentSlerp = minSlerp
let normalizedVelocity: (Float, Float) = normalize(x: Float(gestureRecognizer.velocity(in: view).x),
y: -Float(gestureRecognizer.velocity(in: view).y))
// Velocity in X
var dampenedXVelocity: Float = normalizedVelocity.0/2
if dampenedXVelocity >= 1000 || dampenedXVelocity <= -1000 {
dampenedXVelocity = dampenedXVelocity > 0 ? 1000 : -1000
}
translationX = translationXBuffer.read()! + dampenedXVelocity
if !( translationXBuffer.write( translationX)) { print("error in writing gesture pointX value") }
previousX = 0.0
// Velocity in Y
translationY = translationYBuffer.read()! + normalizedVelocity.1/4
if !( translationYBuffer.write( translationY)) { print("error in writing gesture pointY value") }
previousY = 0.0
}
}
func clampPitchRotation() {
if translationY < -pitchRotationMaxValue || translationY > pitchRotationMaxValue {
if !(translationYBuffer.write(0)) { print("error in writing gesture pointY value") } else {
translationY = translationYBuffer.read()!
}
previousY = 0.0
}
}
func zoom(_ gestureRecognizer: UIPinchGestureRecognizer) {
if gestureRecognizer.state == .began {
previousScale = Float(gestureRecognizer.scale)
} else if gestureRecognizer.state == .changed {
let delta = Float(gestureRecognizer.scale) - previousScale
scaleValue = scaleBuffer.read()!
let gesturePoint = scaleValue - delta
if gesturePoint >= maxZoomValue {
if false == scaleBuffer.write(maxZoomValue) { print("error in writing max gesture point scale/zoom value") }
} else if gesturePoint <= minZoomValue {
if false == scaleBuffer.write(minZoomValue) { print("error in writing min gesture point scale/zoom value") }
} else {
if false == scaleBuffer.write(gesturePoint) { print("error in writing gesture point scale/zoom value") }
}
previousScale = Float(gestureRecognizer.scale)
}
}
func rotate(_ gestureRecognizer: UIRotationGestureRecognizer) {
}
func tap(_ gestureRecognizer: UITapGestureRecognizer) {
delegate?.lgGestureDidTap()
}
}
| 39.697143 | 116 | 0.67324 |
f7fe734904da144193a3925156db23f1a6916445 | 2,343 | //
// SceneDelegate.swift
// tips calculator
//
// Created by Dai Le on 12/22/19.
// Copyright © 2019 Dai Le. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.388889 | 147 | 0.712335 |
72e970205f51270653c7d0a414dca6d7b23c2a86 | 2,296 | //
// UICollectionView.swift
// DequeueKit
//
// Created by Tai Le on 11/17/19.
// Copyright © 2019 Tai Le. All rights reserved.
//
import UIKit
public extension UICollectionView {
func register<CellType: UICollectionViewCell>(class type: CellType.Type) {
let identifier = String(describing: type)
register(type, forCellWithReuseIdentifier: identifier)
}
func register<CellType: UICollectionViewCell>(nib type: CellType.Type) {
let identifier = String(describing: type)
let nib = UINib(nibName: identifier, bundle: nil)
register(nib, forCellWithReuseIdentifier: identifier)
}
func dequeueReusableCell<CellType: UICollectionViewCell>(type: CellType.Type, for indexPath: IndexPath) -> CellType {
let identifier = String(describing: type)
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CellType
}
func register<ViewType: UICollectionReusableView>(class type: ViewType.Type, of kind: UICollectionView.SupplementaryView) {
let identifier = String(describing: type)
register(type, forSupplementaryViewOfKind: kind.element, withReuseIdentifier: identifier)
}
func register<ViewType: UICollectionReusableView>(nib type: ViewType.Type, of kind: UICollectionView.SupplementaryView) {
let identifier = String(describing: type)
let nib = UINib(nibName: identifier, bundle: nil)
register(nib, forSupplementaryViewOfKind: kind.element, withReuseIdentifier: identifier)
}
func dequeueReusableSupplementaryView<ViewType: UICollectionReusableView>(type: ViewType.Type, of kind: UICollectionView.SupplementaryView, for indexPath: IndexPath) -> ViewType {
let identifier = String(describing: type)
return dequeueReusableSupplementaryView(ofKind: kind.element, withReuseIdentifier: identifier, for: indexPath) as! ViewType
}
}
public extension UICollectionView {
enum SupplementaryView {
case header
case footer
var element: String {
switch self {
case .header:
return UICollectionView.elementKindSectionHeader
case .footer:
return UICollectionView.elementKindSectionFooter
}
}
}
}
| 38.266667 | 183 | 0.704704 |
46666ef82da4ae70071dc54fccbff9d9e62aacdd | 1,585 | //
// AboutView.swift
// ToneBoard
//
// Created by Kevin Bell on 12/18/21.
//
import SwiftUI
struct AboutView: View {
var body: some View {
StaticContent("About") {
Header("Motivation")
Text("It can be very difficult for language learners to remember Mandarin Chinese tones, especially when using language learning apps and typing with standard Pinyin keyboards. These keyboards don't require you to input tones, making it very easy to type the correct characters without knowing the correct tones. These keyboards also tend to remember your frequently used words or suggest complete phrases, which is not helpful for language learners.")
Text("By requiring you to enter tones along with Pinyin spellings before displaying characters, ToneBoard lets you practice recalling the correct tone for each syllable whenever you type.")
Header("Data Sources")
Text("ToneBoard gets Pinyin spellings and tones for words and characters from [CC-CEDICT](https://cc-cedict.org/). The word frequency data used to show the most common words first comes from the [Google Ngram data](https://books.google.com/ngrams/datasets) and the [Unihan database](https://www.unicode.org/charts/unihan.html).")
Header("Source Code")
Text("The ToneBoard keyboard is free and open-source software. You can find the source code on GitHub [here](https://github.com/bellkev/ToneBoard).")
}
}
}
struct AboutView_Previews: PreviewProvider {
static var previews: some View {
AboutView()
}
}
| 54.655172 | 464 | 0.718612 |
8736d9313407cbd43913af17d6c425c120f455c4 | 2,304 | //
// Thumbnail.swift
// YoutubeKit
//
// Created by Ryo Ishikawa on 12/30/2017
//
import Foundation
// MARK: - Namespace
public enum Thumbnails {}
extension Thumbnails {
public struct Default: Codable {
public let url: String?
public let height: Int?
public let width: Int?
}
}
extension Thumbnails {
public struct SearchList: Codable {
public let high: Default
public let `default`: Default
public let medium: Default
public enum CodingKeys: String, CodingKey {
case high
case `default` = "default"
case medium
}
}
}
extension Thumbnails {
public struct VideoList: Codable {
public let high: Default
public let `default`: Default
public let medium: Default
public enum CodingKeys: String, CodingKey {
case high
case `default` = "default"
case medium
}
}
}
extension Thumbnails {
public struct ActivityList: Codable {
public let high: Default
public let medium: Default
public let `default`: Default
public let standard: Default?
public let maxres: Default?
public enum CodingKeys: String, CodingKey {
case high
case medium
case `default` = "default"
case maxres
case standard
}
}
}
extension Thumbnails {
public struct PlaylistsList: Codable {
public let high: Default
public let medium: Default
public let `default`: Default
public let standard: Default?
public let maxres: Default?
public enum CodingKeys: String, CodingKey {
case high = "high"
case medium = "medium"
case `default` = "default"
case standard = "standard"
case maxres = "maxres"
}
}
}
extension Thumbnails {
public struct PlaylistItemsList: Codable {
public let high: Default
public let medium: Default
public let `default`: Default
public enum CodingKeys: String, CodingKey {
case high = "high"
case medium = "medium"
case `default` = "default"
}
}
}
| 23.510204 | 51 | 0.565104 |
e92d2e4a7b40c8881bbb3bb897148bc8912763ba | 4,690 | //
// GCFError.swift
// GenericConnectionFramework
//
// Created by Alan Downs on 3/13/18.
// Copyright © 2018 mobileforming LLC. All rights reserved.
//
import Foundation
public enum GCFError: Error {
case parsingError(DecodingError?)
case requestError(NSError?)
case pluginError(NSError?)
case authError(error: Error)
public static var parsingError: GCFError {
return .parsingError(nil)
}
public enum PluginError: Error {
case failureAbortRequest // don't process remaining plugins, fail entire request
case failureCompleteRequest // don't process remaining plugins, finish the request
case failureContinue // continue with remaining plugins
case failureRetryRequest // don't process remaining plugins, retry the request
}
public enum ParsingError: Error {
case codable(DecodingError?)
case jsonSerialization(Error?)
case noData
}
public enum RoutableError: Error {
case invalidURL(message: String)
}
}
extension GCFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .parsingError(decodingError: let decodeError):
guard
let desc = decodeError?.errorDescription
else {
return NSLocalizedString("Unknown reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .requestError(nserror: let nserror):
guard
let desc = (nserror as? LocalizedError)?.errorDescription
else {
return NSLocalizedString("Unknown reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .pluginError(nserror: let nserror):
guard
let desc = (nserror as? LocalizedError)?.errorDescription
else {
return NSLocalizedString("Unknown reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .authError(let error):
let desc = error.localizedDescription
return NSLocalizedString(desc, comment: "")
}
}
public var failureReason: String? {
switch self {
case .parsingError(decodingError: let decodeError):
guard
let desc = decodeError?.failureReason
else {
return NSLocalizedString("Unknown failure reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .requestError(nserror: let nserror):
guard
let desc = (nserror as? LocalizedError)?.failureReason
else {
return NSLocalizedString("Unknown failure reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .pluginError(nserror: let nserror):
guard
let desc = (nserror as? LocalizedError)?.failureReason
else {
return NSLocalizedString("Unknown failure reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .authError(let error):
guard
let desc = (error as? LocalizedError)?.failureReason
else {
return NSLocalizedString("Unknown failure reason", comment: "")
}
return NSLocalizedString(desc, comment: "")
}
}
public var recoverySuggestion: String? {
switch self {
case .parsingError(decodingError: let decodeError):
guard
let desc = decodeError?.recoverySuggestion
else {
return NSLocalizedString("Unknown recovery suggestion", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .requestError(nserror: let nserror):
guard
let desc = nserror?.localizedDescription
else {
return NSLocalizedString("Unknown recovery suggestion", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .pluginError(nserror: let nserror):
guard
let desc = nserror?.localizedDescription
else {
return NSLocalizedString("Unknown recovery suggestion", comment: "")
}
return NSLocalizedString(desc, comment: "")
case .authError(let error):
let desc = (error as NSError).localizedDescription
return NSLocalizedString(desc, comment: "")
}
}
}
extension GCFError: CustomNSError {
}
| 34.485294 | 93 | 0.584435 |
1dda34dc2ff6acc849faf27532fa4203f6c1b7d7 | 7,994 | //
// BLEViewController.swift
// Robo-AR
//
// Created by Anmol Parande on 11/15/20.
// Copyright © 2020 Anmol Parande. All rights reserved.
//
import UIKit
import CoreBluetooth
/**
An abstract view controller which implements BLE logic (so theoretically we could have different UI's which share the same BLE logic.
Loosely based on https://www.raywenderlich.com/231-core-bluetooth-tutorial-for-ios-heart-rate-monitor
*/
class BLEViewController: UIViewController {
// Reference to BLE manager
var centralManager: CBCentralManager!
// Reference to Romi Peripheral
var romiPeripheral: CBPeripheral?
// References to characteristics
var instructionCharacteristic: CBCharacteristic?
var acknowledgeCharacteristic: CBCharacteristic?
// Reference to the status view
@IBOutlet weak var bleStatusView: BLEStatusView?
// Constants
static let ROMI_NAME = "Robo-AR"
static let ROMI_SERVICE_UUID = CBUUID(string: "4607EDA0-F65E-4D59-A9FF-84420D87A4CA")
static let ROMI_INSTRUCTION_CHARACTERISTIC_UUID = CBUUID(string: "4607EDA1-F65E-4D59-A9FF-84420D87A4CA")
static let ROMI_ACKNOWLEDGE_CHARACTERISTIC_UUID = CBUUID(string: "4607EDA2-F65E-4D59-A9FF-84420D87A4CA")
static let ROMI_CHARACTERISTIC_UUIDS = [ROMI_INSTRUCTION_CHARACTERISTIC_UUID, ROMI_ACKNOWLEDGE_CHARACTERISTIC_UUID]
override func viewDidLoad() {
// Setup the BLE manager to start bluetooth
centralManager = CBCentralManager(delegate: self, queue: nil)
}
/**
Send an instruction via bluetooth
*/
func sendInstruction(instruction: Instruction) {
// Hide the instruction variable because parameters are immutable and we need a mutable paramter for UnsafeBufferPointers
var instruction = instruction
guard let romi = romiPeripheral, let characteristic = instructionCharacteristic else {
print("Wasn't connected to Romi")
return
}
var payload = Data(buffer: UnsafeBufferPointer(start: &instruction.distance, count: 1))
payload.append(Data(buffer: UnsafeBufferPointer(start: &instruction.angle, count: 1)))
romi.writeValue(payload, for: characteristic, type: CBCharacteristicWriteType.withResponse)
print("Transmitted instruction: (\(instruction)")
bleStatusView?.instruction = instruction
bleStatusView?.status = .transmitting
}
/**
Template for compiling an instruction that subclasses must override
*/
func compileNextInstruction(fromAck: Bool) -> Instruction? {
preconditionFailure("Compile Next Instruction Not Implemented")
}
/**
Reconnection logic
*/
func onDisconnect() {
// Try to reconnect if disconnected
bleStatusView?.status = .connecting
centralManager.scanForPeripherals(withServices: nil)
}
}
/**
Allow BLE View Controller to implement receive messags as the BLE Central
*/
extension BLEViewController: CBCentralManagerDelegate {
/**
System function called when BLE status changes
*/
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("central.state is .unknown")
case .resetting:
print("central.state is .resetting")
case .unsupported:
print("central.state is .unsupported")
case .unauthorized:
print("central.state is .unauthorized")
case .poweredOff:
print("central.state is .poweredOff")
case .poweredOn:
print("central.state is .poweredOn. Scanning for Romi")
bleStatusView?.status = .connecting
centralManager.scanForPeripherals(withServices: nil)
default:
print("Unrecognized state")
}
}
/**
System function for when a peripheral is discovered
*/
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if peripheral.name == BLEViewController.ROMI_NAME {
print(peripheral)
romiPeripheral = peripheral
romiPeripheral?.delegate = self
centralManager.stopScan()
centralManager.connect(peripheral, options: nil)
}
}
/**
System function for when the peripheral is connected to
*/
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected to Romi")
bleStatusView?.status = .connected
romiPeripheral?.discoverServices([BLEViewController.ROMI_SERVICE_UUID])
}
}
/**
Allow BLEViewController to receive messages from the peripheral
*/
extension BLEViewController: CBPeripheralDelegate {
/**
System function for when services are discovered on a connected peripheral
*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let services = peripheral.services else { return }
for service in services {
print(service)
peripheral.discoverCharacteristics(BLEViewController.ROMI_CHARACTERISTIC_UUIDS, for: service)
}
}
/**
System function for when characteristics are discovered on a connected peripheral
*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
if characteristic.uuid == BLEViewController.ROMI_INSTRUCTION_CHARACTERISTIC_UUID {
print("Found instruction characteristic")
instructionCharacteristic = characteristic
} else if characteristic.uuid == BLEViewController.ROMI_ACKNOWLEDGE_CHARACTERISTIC_UUID {
print("Found acknowledge characteristic")
acknowledgeCharacteristic = characteristic
// Enable notifications from the acknowledge characteristic
romiPeripheral?.setNotifyValue(true, for: characteristic)
}
}
}
/**
System function for reading values from characteristics on a connected peripheral
*/
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
switch characteristic.uuid {
case BLEViewController.ROMI_INSTRUCTION_CHARACTERISTIC_UUID:
print(characteristic.value ?? "No value for instruction")
case BLEViewController.ROMI_ACKNOWLEDGE_CHARACTERISTIC_UUID:
print(characteristic.value ?? "No value for acknowledge")
guard let acknowledge = characteristic.value?.withUnsafeBytes({
(pointer: UnsafePointer<Int>) -> Int in
return pointer.pointee
}) else { print("Couldn't get characteristic value"); return; }
// If the Romi acknowledges, then try to send the next waypoint
if acknowledge == 0 {
if let inst = compileNextInstruction(fromAck: true) {
sendInstruction(instruction: inst)
} else {
print("Finished executing instructions")
bleStatusView?.status = .done
}
} else {
print("Romi Received Instruction!")
}
default:
print("Unhandled characteristic UUID: \(characteristic.uuid)")
}
}
/**
System function for when a peripheral disconnects. Triggers reconnection logic
*/
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("Romi Disconnected")
onDisconnect()
}
}
| 38.995122 | 148 | 0.661996 |
089b41af0188f2a9dc6e4f89429b5240927e80f1 | 11,582 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018 Realm Inc.
//
// 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 XCTest
import RealmSwift
final class PermissionUser: Object {
// A class with a name that conflicts with an Object class from RealmSwift to verify
// that it doesn't break anything
}
class SwiftPermissionsAPITests: SwiftSyncTestCase {
var userA: SyncUser!
var userB: SyncUser!
var userC: SyncUser!
override func setUp() {
super.setUp()
let baseName = UUID().uuidString
userA = try! synchronouslyLogInUser(for: .usernamePassword(username: baseName + "-a", password: "a", register: true),
server: SwiftSyncTestCase.authServerURL())
userB = try! synchronouslyLogInUser(for: .usernamePassword(username: baseName + "-b", password: "a", register: true),
server: SwiftSyncTestCase.authServerURL())
userC = try! synchronouslyLogInUser(for: .usernamePassword(username: baseName + "-c", password: "a", register: true),
server: SwiftSyncTestCase.authServerURL())
}
override func tearDown() {
userA.logOut()
userB.logOut()
userC.logOut()
super.tearDown()
}
// MARK: Helper functions
func openRealm(_ url: URL, _ user: SyncUser) -> Realm {
let realm = try! Realm(configuration: user.configuration(realmURL: url))
waitForSync(realm)
return realm
}
func subscribe<T: Object>(realm: Realm, type: T.Type, _ filter: String = "TRUEPREDICATE") {
let ex = expectation(description: "Add partial sync query")
realm.subscribe(to: type, where: filter) { _, err in
if let err = err {
XCTFail("Partial sync subsription failed: \(err)")
} else {
ex.fulfill()
}
}
waitForExpectations(timeout: 2.0, handler: nil)
}
func waitForSync(_ realm: Realm) {
waitForUploads(for: realm)
waitForDownloads(for: realm)
realm.refresh()
}
func createRealm(name: String, permissions: (Realm) -> Void) -> URL {
// Create a new Realm with an admin user
let admin = createAdminUser(for: SwiftSyncTestCase.authServerURL(),
username: UUID().uuidString + "-admin")
let url = URL(string: "realm://127.0.0.1:9080/\(name.replacingOccurrences(of: "()", with: ""))")!
let adminRealm = openRealm(url, admin)
// FIXME: we currently need to add a subscription to get the permissions types sent to us
subscribe(realm: adminRealm, type: SwiftSyncObject.self)
// Set up permissions on the Realm
try! adminRealm.write {
adminRealm.create(SwiftSyncObject.self, value: ["obj 1"])
permissions(adminRealm)
}
// FIXME: we currently need to also add the old realm-level permissions
let ex1 = expectation(description: "Setting a permission should work.")
let ex2 = expectation(description: "Setting a permission should work.")
let ex3 = expectation(description: "Setting a permission should work.")
admin.apply(SyncPermission(realmPath: url.path, identity: userA.identity!, accessLevel: .read)) { error in
XCTAssertNil(error)
ex1.fulfill()
}
admin.apply(SyncPermission(realmPath: url.path, identity: userB.identity!, accessLevel: .read)) { error in
XCTAssertNil(error)
ex2.fulfill()
}
admin.apply(SyncPermission(realmPath: url.path, identity: userC.identity!, accessLevel: .read)) { error in
XCTAssertNil(error)
ex3.fulfill()
}
waitForExpectations(timeout: 2.0, handler: nil)
waitForSync(adminRealm)
return url
}
func createDefaultPermisisons(_ permissions: List<Permission>) {
var p = permissions.findOrCreate(forRoleNamed: "everyone")
p.canCreate = false
p.canRead = false
p.canQuery = false
p.canDelete = false
p.canUpdate = false
p.canModifySchema = false
p.canSetPermissions = false
p = permissions.findOrCreate(forRoleNamed: "reader")
p.canRead = true
p.canQuery = true
p = permissions.findOrCreate(forRoleNamed: "writer")
p.canUpdate = true
p.canCreate = true
p.canDelete = true
p = permissions.findOrCreate(forRoleNamed: "admin")
p.canSetPermissions = true
}
func add(user: SyncUser, toRole roleName: String, inRealm realm: Realm) {
let user = realm.create(RealmSwift.PermissionUser.self, value: [user.identity!], update: .modified)
realm.create(PermissionRole.self, value: [roleName], update: .modified).users.append(user)
}
// MARK: Tests
func testAsyncOpenWaitsForPermissions() {
let url = createRealm(name: #function) { realm in
createDefaultPermisisons(realm.permissions)
add(user: userA, toRole: "reader", inRealm: realm)
}
let ex = expectation(description: "asyncOpen")
var subscription: SyncSubscription<SwiftSyncObject>!
var token: NotificationToken!
Realm.asyncOpen(configuration: userA.configuration(realmURL: url)) { realm, error in
XCTAssertNil(error)
// Will crash if the __Class object for swiftSyncObject wasn't downloaded
_ = realm!.permissions(forType: SwiftSyncObject.self)
// Make sure that the dummy subscription we created hasn't interfered
// with adding new subscriptions.
subscription = realm!.objects(SwiftSyncObject.self).subscribe()
token = subscription.observe(\.state, options: .initial) { state in
if state == .complete {
ex.fulfill()
}
}
}
waitForExpectations(timeout: 10.0, handler: nil)
token.invalidate()
}
func testRealmRead() {
let url = createRealm(name: "testRealmRead") { realm in
createDefaultPermisisons(realm.permissions)
add(user: userA, toRole: "reader", inRealm: realm)
}
// userA should now be able to open the Realm and see objects
let realmA = openRealm(url, userA)
subscribe(realm: realmA, type: SwiftSyncObject.self)
XCTAssertEqual(realmA.getPrivileges(), [.read])
XCTAssertEqual(realmA.getPrivileges(SwiftSyncObject.self), [.read, .subscribe])
XCTAssertEqual(realmA.getPrivileges(realmA.objects(SwiftSyncObject.self).first!), [.read])
// userA should not be able to create new objects
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 1)
try! realmA.write {
realmA.create(SwiftSyncObject.self, value: ["obj 2"])
}
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 2)
waitForSync(realmA)
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 1)
// userB should not be able to read any objects
let realmB = openRealm(url, userB)
subscribe(realm: realmB, type: SwiftSyncObject.self)
XCTAssertEqual(realmB.getPrivileges(), [])
XCTAssertEqual(realmB.getPrivileges(SwiftSyncObject.self), [])
XCTAssertEqual(realmB.objects(SwiftSyncObject.self).count, 0)
}
func testRealmWrite() {
let url = createRealm(name: "testRealmWrite") { realm in
createDefaultPermisisons(realm.permissions)
add(user: userA, toRole: "reader", inRealm: realm)
add(user: userA, toRole: "writer", inRealm: realm)
add(user: userB, toRole: "reader", inRealm: realm)
}
// userA should now be able to open the Realm and see objects
let realmA = openRealm(url, userA)
subscribe(realm: realmA, type: SwiftSyncObject.self)
XCTAssertEqual(realmA.getPrivileges(), [.read, .update])
XCTAssertEqual(realmA.getPrivileges(SwiftSyncObject.self),
[.read, .subscribe, .update, .create, .setPermissions])
XCTAssertEqual(realmA.getPrivileges(realmA.objects(SwiftSyncObject.self).first!),
[.read, .update, .delete, .setPermissions])
// userA should be able to create new objects
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 1)
try! realmA.write {
realmA.create(SwiftSyncObject.self, value: ["obj 2"])
}
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 2)
waitForSync(realmA)
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 2)
// userB's insertions should be reverted
let realmB = openRealm(url, userB)
subscribe(realm: realmB, type: SwiftSyncObject.self)
XCTAssertEqual(realmB.objects(SwiftSyncObject.self).count, 2)
try! realmB.write {
realmB.create(SwiftSyncObject.self, value: ["obj 3"])
}
XCTAssertEqual(realmB.objects(SwiftSyncObject.self).count, 3)
waitForSync(realmB)
XCTAssertEqual(realmB.objects(SwiftSyncObject.self).count, 2)
}
func testRealmSetPermissions() {
}
func testRealmModifySchema() {
}
func testClassRead() {
let url = createRealm(name: "testClassRead") { realm in
createDefaultPermisisons(realm.permissions(forType: SwiftSyncObject.self))
add(user: userA, toRole: "reader", inRealm: realm)
}
// userA should now be able to open the Realm and see objects
let realmA = openRealm(url, userA)
subscribe(realm: realmA, type: SwiftSyncObject.self)
XCTAssertEqual(realmA.getPrivileges(), [.read, .update, .setPermissions, .modifySchema])
XCTAssertEqual(realmA.getPrivileges(SwiftSyncObject.self), [.read, .subscribe])
XCTAssertEqual(realmA.getPrivileges(realmA.objects(SwiftSyncObject.self).first!), [.read])
// userA should not be able to create new objects
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 1)
try! realmA.write {
realmA.create(SwiftSyncObject.self, value: ["obj 2"])
}
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 2)
waitForSync(realmA)
XCTAssertEqual(realmA.objects(SwiftSyncObject.self).count, 1)
// userB should not be able to read any objects
let realmB = openRealm(url, userB)
subscribe(realm: realmB, type: SwiftSyncObject.self)
XCTAssertEqual(realmB.getPrivileges(), [.read, .update, .setPermissions, .modifySchema])
XCTAssertEqual(realmB.getPrivileges(SwiftSyncObject.self), [])
XCTAssertEqual(realmB.objects(SwiftSyncObject.self).count, 0)
}
func testClassWrite() {
}
func testClassSetPermissions() {
}
}
| 41.217082 | 125 | 0.62977 |
d5e4b223f09e393b78421c1df1db3ab6563bc55e | 9,191 | //
// ParseBandMembersTests.swift
// Metal ArchivesTests
//
// Created by Thanh-Nhon Nguyen on 15/05/2019.
// Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved.
//
import XCTest
@testable import Metal_Archives
@testable import Kanna
class ParseBandMembersTests: XCTestCase {
func testParseArtistsWithCompleteInformation() {
// Given
// Load from mock file
// Original url: https://www.metal-archives.com/bands/Death/141
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "DeathLastKnownLineup", ofType: "txt")!
let inputString = try! String(contentsOfFile: path)
let doc = try! Kanna.HTML(html: inputString, encoding: String.Encoding.utf8)
// When
let artists = Band.parseBandArtists(inDiv: doc.at_css("table")!)
/*
Attention to " " space
copy this " "
*/
// Then
XCTAssertEqual(artists!.count, 4, "List of artists should be parsed successfully.")
// 1: Chuck Schuldiner
XCTAssertEqual(artists![0].name, "Chuck Schuldiner")
XCTAssertEqual(artists![0].instrumentsInBand, "Guitars, Vocals (1984-2001)")
XCTAssertEqual(artists![0].seeAlsoString, "(R.I.P. 2001) See also: ex-Control Denied, ex-Mantas, ex-Slaughter, ex-Voodoocult")
XCTAssertEqual(artists![0].bands?.count, 4)
XCTAssertEqual(artists![0].bands![0].name, "Control Denied")
XCTAssertEqual(artists![0].bands![0].urlString, "https://www.metal-archives.com/bands/Control_Denied/549")
XCTAssertEqual(artists![0].bands![1].name, "Mantas")
XCTAssertEqual(artists![0].bands![1].urlString, "https://www.metal-archives.com/bands/Mantas/35328")
XCTAssertEqual(artists![0].bands![2].name, "Slaughter")
XCTAssertEqual(artists![0].bands![2].urlString, "https://www.metal-archives.com/bands/Slaughter/376")
XCTAssertEqual(artists![0].bands![3].name, "Voodoocult")
XCTAssertEqual(artists![0].bands![3].urlString, "https://www.metal-archives.com/bands/Voodoocult/1599")
// 2: Scott Clendenin
XCTAssertEqual(artists![1].name, "Scott Clendenin")
XCTAssertEqual(artists![1].instrumentsInBand, "Bass (1996-2001)")
XCTAssertEqual(artists![1].seeAlsoString, "(R.I.P. 2015) See also: ex-Control Denied")
XCTAssertEqual(artists![1].bands?.count, 1)
XCTAssertEqual(artists![1].bands![0].name, "Control Denied")
XCTAssertEqual(artists![1].bands![0].urlString, "https://www.metal-archives.com/bands/Control_Denied/549")
// 3: Richard Christy
XCTAssertEqual(artists![2].name, "Richard Christy")
XCTAssertEqual(artists![2].instrumentsInBand, "Drums (1996-2001)")
XCTAssertEqual(artists![2].seeAlsoString, "See also: Charred Walls of the Damned, Monument of Bones, ex-Burning Inside, ex-Control Denied, Boar Glue, ex-Iced Earth, ex-Tiwanaku, ex-Demons and Wizards (live), ex-Incantation (live), ex-Wykked Wytch (live), ex-Acheron, ex-Leash Law, ex-Public Assassin, ex-Caninus, ex-Bung Dizeez (live), ex-Syzygy (live)")
XCTAssertEqual(artists![2].bands?.count, 12)
XCTAssertEqual(artists![2].bands![0].name, "Charred Walls of the Damned")
XCTAssertEqual(artists![2].bands![0].urlString, "https://www.metal-archives.com/bands/Charred_Walls_of_the_Damned/3540299757")
XCTAssertEqual(artists![2].bands![1].name, "Monument of Bones")
XCTAssertEqual(artists![2].bands![1].urlString, "https://www.metal-archives.com/bands/Monument_of_Bones/127290")
XCTAssertEqual(artists![2].bands![2].name, "Burning Inside")
XCTAssertEqual(artists![2].bands![2].urlString, "https://www.metal-archives.com/bands/Burning_Inside/1233")
XCTAssertEqual(artists![2].bands![3].name, "Control Denied")
XCTAssertEqual(artists![2].bands![3].urlString, "https://www.metal-archives.com/bands/Control_Denied/549")
XCTAssertEqual(artists![2].bands![4].name, "Iced Earth")
XCTAssertEqual(artists![2].bands![4].urlString, "https://www.metal-archives.com/bands/Iced_Earth/4")
XCTAssertEqual(artists![2].bands![5].name, "Tiwanaku")
XCTAssertEqual(artists![2].bands![5].urlString, "https://www.metal-archives.com/bands/Tiwanaku/17095")
XCTAssertEqual(artists![2].bands![6].name, "Demons and Wizards")
XCTAssertEqual(artists![2].bands![6].urlString, "https://www.metal-archives.com/bands/Demons_%26_Wizards/158")
XCTAssertEqual(artists![2].bands![7].name, "Incantation")
XCTAssertEqual(artists![2].bands![7].urlString, "https://www.metal-archives.com/bands/Incantation/885")
XCTAssertEqual(artists![2].bands![8].name, "Wykked Wytch")
XCTAssertEqual(artists![2].bands![8].urlString, "https://www.metal-archives.com/bands/Wykked_Wytch/3968")
XCTAssertEqual(artists![2].bands![9].name, "Acheron")
XCTAssertEqual(artists![2].bands![9].urlString, "https://www.metal-archives.com/bands/Acheron/123")
XCTAssertEqual(artists![2].bands![10].name, "Leash Law")
XCTAssertEqual(artists![2].bands![10].urlString, "https://www.metal-archives.com/bands/Leash_Law/8580")
XCTAssertEqual(artists![2].bands![11].name, "Public Assassin")
XCTAssertEqual(artists![2].bands![11].urlString, "https://www.metal-archives.com/bands/Public_Assassin/32920")
// 4: Shannon Hamm
XCTAssertEqual(artists![3].name, "Shannon Hamm")
XCTAssertEqual(artists![3].instrumentsInBand, "Guitars (1996-2001)")
XCTAssertEqual(artists![3].seeAlsoString, "See also: Beyond Unknown, ex-Control Denied, ex-Metalstorm, ex-Synesis Absorption, ex-Order of Ennead (live), ex-Talonzfury")
XCTAssertEqual(artists![3].bands?.count, 5)
XCTAssertEqual(artists![3].bands![0].name, "Beyond Unknown")
XCTAssertEqual(artists![3].bands![0].urlString, "https://www.metal-archives.com/bands/Beyond_Unknown/3540387976")
XCTAssertEqual(artists![3].bands![1].name, "Control Denied")
XCTAssertEqual(artists![3].bands![1].urlString, "https://www.metal-archives.com/bands/Control_Denied/549")
XCTAssertEqual(artists![3].bands![2].name, "Metalstorm")
XCTAssertEqual(artists![3].bands![2].urlString, "https://www.metal-archives.com/bands/Metalstorm/91344")
XCTAssertEqual(artists![3].bands![3].name, "Synesis Absorption")
XCTAssertEqual(artists![3].bands![3].urlString, "https://www.metal-archives.com/bands/Synesis_Absorption/3540320347")
XCTAssertEqual(artists![3].bands![4].name, "Order of Ennead")
XCTAssertEqual(artists![3].bands![4].urlString, "https://www.metal-archives.com/bands/Order_of_Ennead/3540265080")
}
func testParseArtistsWithIncompleteInformation() {
// Given
// Load from mock file
// Original url: https://www.metal-archives.com/bands/Graves/3540442067
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "GravesCurrentLineup", ofType: "txt")!
let inputString = try! String(contentsOfFile: path)
let doc = try! Kanna.HTML(html: inputString, encoding: String.Encoding.utf8)
// When
let artists = Band.parseBandArtists(inDiv: doc.at_css("table")!)
// Then
XCTAssertEqual(artists!.count, 3, "List of artists should be parsed successfully.")
// 1: Necro.
XCTAssertEqual(artists![0].name, "Necro.")
XCTAssertEqual(artists![0].instrumentsInBand, "Drums")
XCTAssertNil(artists![0].seeAlsoString)
XCTAssertNil(artists![0].bands)
// 2: M.v.K
XCTAssertEqual(artists![1].name, "M.v.K")
XCTAssertEqual(artists![1].instrumentsInBand, "Guitars")
XCTAssertEqual(artists![1].seeAlsoString, "See also: S.U.N.D.S., ex-Nihilum, ex-Vermen, Cold June, ex-Flagellum Dei, ex-Revage (live), ex-Cold Floor to Embrace, ex-W.O.U.N.D.")
XCTAssertEqual(artists![1].bands?.count, 5)
XCTAssertEqual(artists![1].bands![0].name, "S.U.N.D.S.")
XCTAssertEqual(artists![1].bands![0].urlString, "https://www.metal-archives.com/bands/S.U.N.D.S./60212")
XCTAssertEqual(artists![1].bands![1].name, "Nihilum")
XCTAssertEqual(artists![1].bands![1].urlString, "https://www.metal-archives.com/bands/Nihilum/39545")
XCTAssertEqual(artists![1].bands![2].name, "Vermen")
XCTAssertEqual(artists![1].bands![2].urlString, "https://www.metal-archives.com/bands/Vermen/59553")
XCTAssertEqual(artists![1].bands![3].name, "Flagellum Dei")
XCTAssertEqual(artists![1].bands![3].urlString, "https://www.metal-archives.com/bands/Flagellum_Dei/11146")
XCTAssertEqual(artists![1].bands![4].name, "Revage")
XCTAssertEqual(artists![1].bands![4].urlString, "https://www.metal-archives.com/bands/Revage/54995")
// 3: N.
XCTAssertEqual(artists![2].name, "N.")
XCTAssertEqual(artists![2].instrumentsInBand, "Vocals")
XCTAssertNil(artists![2].seeAlsoString)
XCTAssertNil(artists![2].bands)
}
}
| 62.101351 | 362 | 0.668915 |
f537e02b551696d8e85e3d5f8b1ad80c17c0b5c1 | 758 | //
// Button+RX.swift
// WLUserKitDemo
//
// Created by three stone 王 on 2019/4/15.
// Copyright © 2019 three stone 王. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
extension Reactive where Base: UIButton {
public var CATSkipTitle: Binder<String> {
return Binder(self.base) {
$0.setTitle($1, for: .normal)
$0.setTitle($1, for: .highlighted)
}
}
}
extension Reactive where Base: UIButton {
public var CATSms: Binder<(Bool ,String)> {
return Binder(self.base) { item, arg in
item.isEnabled = arg.0
item.setTitle(arg.1, for: arg.0 ? .normal : .disabled)
}
}
}
| 19.947368 | 66 | 0.548813 |
1a89c1a071e8e3da5891488f10b7826ababd7fad | 7,905 | //
// MealTableViewController.swift
// FoodTracker
//
// Created by Jane Appleseed on 11/15/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
import UIKit
import os.log
class MealTableViewController: UITableViewController {
//MARK: Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem
// Load any saved meals, otherwise load sample data
if let savedMeals = loadMeals() {
meals += savedMeals
} else {
// Load the sample data.
loadSampleMeals()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "MealTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
// Fetches the appropriate meal for the data source layout.
let meal = meals[indexPath.row]
cell.nameLabel.text = meal.name
cell.photoImageView.image = meal.photo
cell.ratingControl.rating = Int(meal.rating)
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
/* TODO: Delete a meal
1. remove the element from the array
2. save the changes in the txt file
3. use the method tableView.deleteRows with the correct indexPath and choose an animation style
*/
// step 1
meals.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
// Not used
}
saveMeals()
}
//MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch(segue.identifier ?? "") {
case "AddItem":
os_log("Adding a new meal.", log: OSLog.default, type: .debug)
case "ShowDetail":
guard let mealDetailViewController = segue.destination as? MealViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
guard let selectedMealCell = sender as? MealTableViewCell else {
fatalError("Unexpected sender: \(String(describing: sender))")
}
guard let indexPath = tableView.indexPath(for: selectedMealCell) else {
fatalError("The selected cell is not being displayed by the table")
}
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
default:
fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
}
}
//MARK: Actions
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
meals.remove(at: selectedIndexPath.row)
meals.insert(meal, at: selectedIndexPath.row)
tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
} else {
meals.insert(meal, at: 0)
let firstPath = IndexPath.init(row: 0, section: 0)
tableView.insertRows(at: [firstPath], with: .automatic)
}
//TODO: Make sure to save the meal list when going back to the table
saveMeals()
}
}
//MARK: Private Methods
private func loadSampleMeals() {
let photo1 = UIImage(named: "meal1")
let photo2 = UIImage(named: "meal2")
let photo3 = UIImage(named: "meal3")
guard let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else {
fatalError("Unable to instantiate meal1")
}
guard let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else {
fatalError("Unable to instantiate meal2")
}
guard let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else {
fatalError("Unable to instantiate meal2")
}
meals += [meal1, meal2, meal3]
}
private func saveMeals() {
let jsonEncoder = JSONEncoder()
guard let savedMeals = try? jsonEncoder.encode(meals) else { return
}
print(savedMeals)
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
if let documentDirectory: URL = urls.first {
// get the url
let documentURL = documentDirectory.appendingPathComponent("Meals.txt")
// data you want to write to file
let data: Data? = savedMeals
do {
try data!.write(to: documentURL, options: .atomic)
} catch {
print(error.localizedDescription)
}
}
//append a filename called meals.txt to the doc directory
}
private func loadMeals() -> [Meal]? {
//TODO: Use JSONDecoder to get data from a file called: Meals.txt located in Documents Directory
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
// get url
if let docDirect: URL = urls.first {
let docURL = docDirect.appendingPathComponent("Meals.txt")
do {
let data = try Data(contentsOf: docURL)
let jsonDecoder = JSONDecoder()
guard let daMeals = try? jsonDecoder.decode([Meal].self, from: data) else { return nil }
return daMeals
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
| 33.927039 | 137 | 0.573435 |
299824f0137bac511778c5eadc42c95deebe9398 | 1,847 | //
// Copyright © 2019 An Tran. All rights reserved.
//
import SuperArcCoreUI
import SuperArcFoundation
import UIKit
class ActivityView: View, ClassNameDerivable {
// MARK: Properties
// IBOutlet
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var backgroundView: UIView!
// MARK: Setup
override func setup() {
if let acitivityView = ActivityView.instantiateFromNib(owner: self) {
addAndStretchSubView(acitivityView)
backgroundView.cornerRadius = 7.0
activityIndicatorView.startAnimating()
}
}
// MARK: APIs
class func showInView(_ view: UIView, animated: Bool, style: ActivityViewStyle) -> ActivityView {
let activityView = ActivityView(frame: view.frame)
activityView.backgroundColor = style.backdropColor
activityView.backgroundView.backgroundColor = style.backgroundColor
activityView.activityIndicatorView.color = style.spinnerColor
view.addSubview(activityView)
activityView.alpha = 0.0
UIView.animate(withDuration: animated ? 0.5: 0) {
activityView.alpha = 1.0
}
return activityView
}
class func showInMainWindow(_ animated: Bool, style: ActivityViewStyle) -> ActivityView {
guard let mainWindow = UIApplication.shared.keyWindow else {
fatalError("no key windows found")
}
return showInView(mainWindow, animated: animated, style: style)
}
func hide(_ animated: Bool) {
activityIndicatorView.stopAnimating()
UIView.animate(
withDuration: animated ? 0.5 : 0,
animations: {
self.alpha = 0.0
},
completion: { _ in
self.removeFromSuperview()
}
)
}
}
| 27.161765 | 101 | 0.637791 |
fbb93b8ab1d2363bf2b01ceb2b022f703d29b060 | 485 | public enum SearchMode {
// Do not scroll
case useCurrentlyVisible
// Scroll
case scrollUntilFound
// Temporary (UPD: more than 1 year now) case to scroll "blindly" without knowledge where the element is.
// For example, might be useful when element doesn't appear until scroll view is scrolled to it and it can
// not be faked out (as in UICollectionView).
case scrollBlindly
public static let `default`: SearchMode = .scrollUntilFound
}
| 34.642857 | 110 | 0.703093 |
d64a3a0e65b8cb11e91de5017897f4348f6bb0fc | 1,244 | //
// LyMapProtocolUITests.swift
// LyMapProtocolUITests
//
// Created by 张杰 on 2017/6/19.
// Copyright © 2017年 张杰. All rights reserved.
//
import XCTest
class LyMapProtocolUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.621622 | 182 | 0.663987 |
71b39c30c9784ae70760ff1030febfad449a6962 | 6,335 | // MIT License
//
// Copyright (c) 2016 Hyun Min Choi
//
// 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
/// Swiftry is an abstraction over Swift's error handling.
public enum Swiftry<T> {
case success(T)
case failure(Error)
/// - Parameter closure: closure that generates a value of type T or throws an error
public init(_ closure: @escaping () throws -> T) {
do {
self = .success(try closure())
} catch let e {
self = .failure(e)
}
}
/// - Parameter closure: closure that generates a value of type T
public init(_ closure: @escaping () -> T) {
self = .success(closure())
}
/// - Parameter closure: closure that generates a value of type T or throws an error
public init(_ closure: @autoclosure () throws -> T) {
do {
self = .success(try closure())
} catch let e {
self = .failure(e)
}
}
/// - Parameter closure: closure that generates a value of type T
public init(_ closure: @autoclosure () -> T) {
self = .success(closure())
}
public init(value: T) {
self = .success(value)
}
public init(error: Error) {
self = .failure(error)
}
//: Given a function of type `(T) -> U`, maps a `Swiftry<T>` instance to a `Swiftry<U>` instance.
/// - Parameter f: the function to be applied to the instance's value, if self is of case .success
/// - Returns: Swiftry<U>
public func map<U>(_ f: @escaping (T) -> U) -> Swiftry<U> {
let sugar: (T) throws -> U = f
return self.map(sugar)
}
//: Given a function of type `(T) throws -> U`, maps a `Swiftry<T>` instance to a `Swiftry<U>` instance.
/// - Parameter f: the function to be applied to the instance's value, if self is of case .success
/// - Returns: Swiftry<U>
public func map<U>(_ f: @escaping (T) throws -> U) -> Swiftry<U> {
switch self {
case let .success(t):
do {
return .success(try f(t))
} catch let e {
return .failure(e)
}
case let .failure(e):
return .failure(e)
}
}
//: Given a function of type `(T) -> Swiftry<U>`, maps a `Swiftry<T>` instance to a `Swiftry<U>` instance.
/// - Parameter f: the function to be applied to the instance's value, if self is of case .success
/// - Returns: Swiftry<U>
public func flatMap<U>(_ f: @escaping (T) -> Swiftry<U>) -> Swiftry<U> {
let sugar: (T) throws -> Swiftry<U> = f
return self.flatMap(sugar)
}
//: Given a function of type `(T) throws -> Swiftry<U>`, maps a `Swiftry<T>` instance to a `Swiftry<U>` instance.
/// - Parameter f: the function to be applied to the instance's value, if self is of case .success
/// - Returns: Swiftry<U>
public func flatMap<U>(_ f: @escaping (T) throws -> Swiftry<U>) -> Swiftry<U> {
switch self {
case let .success(t):
do {
return try f(t)
} catch let e {
return .failure(e)
}
case let .failure(e):
return .failure(e)
}
}
/// Converts this instance of an equivalent optional type.
///
/// When `self.isErrored == true`, this conversion leads to the loss of error.
public var toOption: Optional<T> {
switch self {
case let .success(t):
return t
case .failure(_):
return nil
}
}
/// Chains another `Swiftry<T>` and returns a new `Swiftry<T>`
public func orElse(_ rightTry: @autoclosure () -> Swiftry<T>) -> Swiftry<T> {
switch self {
case .success(_):
return self
case .failure(_):
return rightTry()
}
}
/// Returns the wrapped value of this instance.
///
/// Use at caution, as this will crash when `self.isError == true`
public var get: T {
return try! _get()
}
/// Whether this instance contains a value
public var isSuccessful: Bool {
switch self {
case .success(_):
return true
case .failure(_):
return false
}
}
/// Whether this instance contains an error
public var isErrored: Bool {
return !self.isSuccessful
}
internal func _get() throws -> T {
switch self {
case let .success(t):
return t
case let .failure(e):
throw e
}
}
}
infix operator =>: AdditionPrecedence
public func =><T>(lhs: Swiftry<T>, rhs: @autoclosure () -> Swiftry<T>) -> Swiftry<T> {
return lhs.orElse(rhs)
}
infix operator <^>: AdditionPrecedence
public func <^><T, U>(lhs: Swiftry<T>, f: @escaping (T) -> U) -> Swiftry<U> {
return lhs.map(f)
}
public func <^><T, U>(lhs: Swiftry<T>, f: @escaping (T) throws -> U) -> Swiftry<U> {
return lhs.map(f)
}
infix operator >>-: AdditionPrecedence
public func >>-<T, U>(lhs: Swiftry<T>, f: @escaping (T) -> Swiftry<U>) -> Swiftry<U> {
return lhs.flatMap(f)
}
public func >>-<T, U>(lhs: Swiftry<T>, f: @escaping (T) throws -> Swiftry<U>) -> Swiftry<U> {
return lhs.flatMap(f)
}
| 32.823834 | 117 | 0.583741 |
ed1577252f17be28b0f9db04a084b3ff5e1b8dd1 | 268 | //
// Coordinator.swift
// thanos menu
//
// Created by Lucas Moreton on 19/07/20.
// Copyright © 2020 Lucas Moreton. All rights reserved.
//
import Foundation
protocol Coordinator: class {
var childCoordinators: [Coordinator] { get set }
func start()
}
| 17.866667 | 56 | 0.682836 |
505df9ead15b955dc704f5eee05eb1c23b17e939 | 1,667 | //
// ViewController.swift
// Mobile
//
// Created by Mathew Gacy on 6/11/18.
// Copyright © 2018 Mathew Gacy. All rights reserved.
//
import UIKit
import RxSwift
class MGViewController: UIViewController {
// MARK: - Properties
let wasPopped: Observable<Void>
private let disposeBag = DisposeBag()
internal let wasPoppedSubject = PublishSubject<Void>()
// MARK: - Lifecycle
init() {
wasPopped = wasPoppedSubject.asObservable()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
//self.wasPopped = wasPoppedSubject.asObservable()
//super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
//override func viewWillAppear(_ animated: Bool) {}
//override func didReceiveMemoryWarning() {}
// MARK: - View Methods
private func setupView() {
// ...
setupConstraints()
}
private func setupConstraints() {
//let guide: UILayoutGuide
//if #available(iOS 11, *) {
// guide = view.safeAreaLayoutGuide
//} else {
// guide = view.layoutMarginsGuide
//}
//let constraints = [
//]
//NSLayoutConstraint.activate(constraints)
}
private func setupBindings() {
// ...
}
}
// MARK: - ErrorAlertDisplayable
extension MGViewController: ErrorAlertDisplayable {}
// MARK: - PoppedObservable
extension MGViewController: PoppedObservable {
func viewWasPopped() {
wasPoppedSubject.onNext(())
}
}
| 21.101266 | 59 | 0.615477 |
56af871c6ed42b43602c9e07faaa58afe08106aa | 693 | //
// Orientation.swift
// DynamicAppResizer
//
// Created by Marcos Griselli on 08/09/2018.
//
import UIKit
/// Orientation of the device. We're not supporting all the orientations for now.
internal enum Orientation: Int, CaseIterable {
case portrait
case landscape
/// Init based on all the posible orientations into our supported ones
///
/// - Parameter current: current device orientation
init(current: UIInterfaceOrientation) {
switch current {
case .portrait, .portraitUpsideDown, .unknown:
self = Orientation.portrait
case .landscapeLeft, .landscapeRight:
self = Orientation.landscape
}
}
}
| 25.666667 | 81 | 0.663781 |
fb20bcd4061d29d0164f3ef3a7491a8e2ad98e8e | 4,239 | import FluentSQL
extension FluentBenchmarker {
public func testSchema(foreignKeys: Bool = true) throws {
try self.testSchema_addConstraint()
try self.testSchema_addNamedConstraint()
if foreignKeys {
try self.testSchema_fieldReference()
}
}
private func testSchema_addConstraint() throws {
try self.runTest(#function, [
CreateCategories()
]) {
guard let sql = self.database as? SQLDatabase, sql.dialect.alterTableSyntax.allowsBatch else {
self.database.logger.warning("Skipping \(#function)")
return
}
// Add unique constraint
try AddUniqueConstraintToCategories().prepare(on: self.database).wait()
try Category(name: "a").create(on: self.database).wait()
try Category(name: "b").create(on: self.database).wait()
do {
try Category(name: "a").create(on: self.database).wait()
XCTFail("Duplicate save should have errored")
} catch let error as DatabaseError where error.isConstraintFailure {
// pass
}
// Remove unique constraint
try AddUniqueConstraintToCategories().revert(on: self.database).wait()
try Category(name: "a").create(on: self.database).wait()
}
}
private func testSchema_addNamedConstraint() throws {
try self.runTest(#function, [
CreateCategories()
]) {
guard let sql = self.database as? SQLDatabase, sql.dialect.alterTableSyntax.allowsBatch else {
self.database.logger.warning("Skipping \(#function)")
return
}
// Add unique constraint
try AddNamedUniqueConstraintToCategories().prepare(on: self.database).wait()
try Category(name: "a").create(on: self.database).wait()
try Category(name: "b").create(on: self.database).wait()
do {
try Category(name: "a").create(on: self.database).wait()
XCTFail("Duplicate save should have errored")
} catch let error as DatabaseError where error.isConstraintFailure {
// pass
}
// Remove unique constraint
try AddNamedUniqueConstraintToCategories().revert(on: self.database).wait()
try Category(name: "a").create(on: self.database).wait()
}
}
private func testSchema_fieldReference() throws {
try self.runTest(#function, [
SolarSystem()
]) {
XCTAssertThrowsError(
try Star.query(on: self.database)
.filter(\.$name == "Sun")
.delete().wait()
)
}
}
}
final class Category: Model {
static let schema = "categories"
@ID var id: UUID?
@Field(key: "name") var name: String
init() { }
init(id: UUID? = nil, name: String) {
self.id = id
self.name = name
}
}
struct CreateCategories: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.id()
.field("name", .string, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.delete()
}
}
struct AddUniqueConstraintToCategories: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.unique(on: "name")
.update()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.deleteUnique(on: "name")
.update()
}
}
struct AddNamedUniqueConstraintToCategories: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.unique(on: "name", name: "foo")
.update()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("categories")
.deleteConstraint(name: "foo")
.update()
}
}
| 33.377953 | 106 | 0.570889 |
e5463a663fff3d605b38afe9abd1e4c75eaa1586 | 1,921 | //
// MatchScoreBreakdown2015.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** See the 2015 FMS API documentation for a description of each value */
open class MatchScoreBreakdown2015: Codable {
public enum Coopertition: String, Codable {
case _none = "None"
case unknown = "Unknown"
case stack = "Stack"
}
public var blue: MatchScoreBreakdown2015Alliance?
public var red: MatchScoreBreakdown2015Alliance?
public var coopertition: Coopertition?
public var coopertitionPoints: Int?
public init(blue: MatchScoreBreakdown2015Alliance?, red: MatchScoreBreakdown2015Alliance?, coopertition: Coopertition?, coopertitionPoints: Int?) {
self.blue = blue
self.red = red
self.coopertition = coopertition
self.coopertitionPoints = coopertitionPoints
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encodeIfPresent(blue, forKey: "blue")
try container.encodeIfPresent(red, forKey: "red")
try container.encodeIfPresent(coopertition, forKey: "coopertition")
try container.encodeIfPresent(coopertitionPoints, forKey: "coopertition_points")
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
blue = try container.decodeIfPresent(MatchScoreBreakdown2015Alliance.self, forKey: "blue")
red = try container.decodeIfPresent(MatchScoreBreakdown2015Alliance.self, forKey: "red")
coopertition = try container.decodeIfPresent(Coopertition.self, forKey: "coopertition")
coopertitionPoints = try container.decodeIfPresent(Int.self, forKey: "coopertition_points")
}
}
| 32.559322 | 151 | 0.714732 |
cccc238600d6a9f4e55ac54dab9237777b0ea08c | 2,755 | //
// AppDelegate.swift
// TextReader
//
// Created by Simon Ng on 12/12/2017.
// Copyright © 2017 AppCoda. 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:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let message = url.host?.removingPercentEncoding
let alertController = UIAlertController(title: "Incoming Message", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(okAction)
window?.rootViewController?.present(alertController, animated: true, completion: nil)
return true
}
}
| 47.5 | 285 | 0.73902 |
87cfa0065deb580754c45fb4e8d318d74d9673d3 | 181 | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
protocol A{typealias e}extension A{typealias e:e l#^A^# | 60.333333 | 104 | 0.745856 |
337ddd4c0238647efeff5541f8f39ac825f6a7ad | 12,242 | import Foundation
import WMF
extension NotificationsCenterCommonViewModel {
private func destinationText(for url: URL?) -> String? {
guard let url = url else {
return nil
}
return url.doesOpenInBrowser ? CommonStrings.notificationsCenterDestinationWeb : CommonStrings.notificationsCenterDestinationApp
}
// [Username]'s user page
var agentUserPageAction: NotificationsCenterAction? {
guard let agentName = notification.agentName,
let url = customPrefixAgentNameURL(pageNamespace: .user) else {
return nil
}
let format = WMFLocalizedString("notifications-center-go-to-user-page", value: "%1$@'s user page", comment: "Button text in Notifications Center that routes to a web view of the user page of the sender that triggered the notification. %1$@ is replaced with the sender's username.")
let text = String.localizedStringWithFormat(format, agentName)
let data = NotificationsCenterActionData(text: text, url: url, iconType: .person, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Diff
var diffAction: NotificationsCenterAction? {
guard let url = fullTitleDiffURL else {
return nil
}
let text = WMFLocalizedString("notifications-center-go-to-diff", value: "Diff", comment: "Button text in Notifications Center that routes to a diff screen of the revision that triggered the notification.")
let data = NotificationsCenterActionData(text: text, url: url, iconType: .diff, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
/// Outputs various actions based on the notification title payload.
/// - Parameters:
/// - needsConvertToOrFromTalk: Pass true if you want to construct an action based on the talk-equivalent or main-equivalent of the title payload. For example, if the title payload indicates the notification sourced from an article talk page, passing true here will construct the action based on the main namespace, i.e. "Cat" instead of "Talk:Cat".`
/// - simplified: Pass true if you want a generic phrasing of the action, i.e., "Article" or "Talk page" instead of "Cat" or "Talk:Cat" respectively.
/// - Returns: NotificationsCenterAction struct, for use in view models.
func titleAction(needsConvertToOrFromTalk: Bool, simplified: Bool) -> NotificationsCenterAction? {
guard let linkData = linkData,
let normalizedTitle = linkData.title?.normalizedPageTitle,
let sourceNamespace = linkData.titleNamespace else {
return nil
}
let namespace = needsConvertToOrFromTalk ? (sourceNamespace.convertedToOrFromTalk ?? sourceNamespace) : sourceNamespace
guard !simplified else {
// [your] talk page
// Talk page
// Collaboration page
// Discussion page
// Article
let simplifiedText = simplifiedTitleText(namespace: namespace, normalizedTitle: normalizedTitle) ?? titleText(namespace: namespace, normalizedTitle: normalizedTitle)
return titleAction(text: simplifiedText, namespace: namespace, normalizedTitle: normalizedTitle)
}
// [your] talk page
// [article] talk page
// [article] collaboration page
// [article] discussion page
// [article]
let text = titleText(namespace: namespace, normalizedTitle: normalizedTitle)
return titleAction(text: text, namespace: namespace, normalizedTitle: normalizedTitle)
}
private var goToTalkPageText: String {
WMFLocalizedString("notifications-center-go-to-talk-page", value: "Talk page", comment: "Button text in Notifications Center that routes to a talk page.")
}
private var goToDiscussionPageText: String {
WMFLocalizedString("notifications-center-go-to-discussion-page", value: "Discussion page", comment: "Button text in Notifications Center that routes to a discussion page.")
}
private var goToCollaborationPageText: String {
WMFLocalizedString("notifications-center-go-to-collaboration-page", value: "Collaboration page", comment: "Button text in Notifications Center that routes to a collaboration page.")
}
private var goToYourTalkPageText: String {
WMFLocalizedString("notifications-center-go-to-your-talk-page", value: "Your talk page", comment: "Button text in Notifications Center that routes to user's talk page.")
}
private var goToArticleText: String {
WMFLocalizedString("notifications-center-go-to-article", value: "Article", comment: "Button text in Notifications Center that routes to article.")
}
private var goToArticleTalkFormat: String {
WMFLocalizedString("notifications-center-go-to-article-talk-format", value: "%1$@ talk page", comment: "Button text in Notifications Center that routes to a particular article talk page. %1$@ is replaced with page title.")
}
private var goToArticleDiscussionFormat: String {
WMFLocalizedString("notifications-center-go-to-article-discussion-format", value: "%1$@ discussion page", comment: "Button text in Notifications Center that routes to a particular article discussion page. %1$@ is replaced with page title.")
}
private var goToArticleCollaborationFormat: String {
WMFLocalizedString("notifications-center-go-to-article-collaboration-format", value: "%1$@ collaboration page", comment: "Button text in Notifications Center that routes to a particular article collaboration page. %1$@ is replaced with page title.")
}
private func simplifiedTitleText(namespace: PageNamespace, normalizedTitle: String) -> String? {
if notification.type == .userTalkPageMessage {
return goToYourTalkPageText
} else if namespace == .userTalk {
return goToTalkPageText
} else if namespace == .talk {
switch project {
case .wikipedia:
return goToTalkPageText
case .wikinews:
return goToCollaborationPageText
default:
return goToDiscussionPageText
}
} else if namespace == .main {
switch project {
case .wikipedia:
return goToArticleText
default:
break
}
}
return nil
}
private func titleText(namespace: PageNamespace, normalizedTitle: String) -> String {
if notification.type == .userTalkPageMessage {
return goToYourTalkPageText
} else if namespace == .userTalk {
return goToTalkPageText
} else if namespace == .talk {
switch project {
case .wikipedia:
return String.localizedStringWithFormat(goToArticleTalkFormat, normalizedTitle)
case .wikinews:
return String.localizedStringWithFormat(goToArticleCollaborationFormat, normalizedTitle)
default:
return String.localizedStringWithFormat(goToArticleDiscussionFormat, normalizedTitle)
}
} else {
let prefix = namespace != .main ? "\(namespace.canonicalName):" : ""
return "\(prefix)\(normalizedTitle)"
}
}
private func titleAction(text: String, namespace: PageNamespace, normalizedTitle: String) -> NotificationsCenterAction {
let url = customPrefixTitleURL(pageNamespace: namespace)
let data = NotificationsCenterActionData(text: text, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// [Article where link was made]
var pageLinkToAction: NotificationsCenterAction? {
guard let url = pageLinkToURL,
let title = url.wmf_title else {
return nil
}
let data = NotificationsCenterActionData(text: title, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Wikidata item
var wikidataItemAction: NotificationsCenterAction? {
guard let url = connectionWithWikidataItemURL else {
return nil
}
let text = WMFLocalizedString("notifications-center-go-to-wikidata-item", value: "Wikidata item", comment: "Button text in Notifications Center that routes to a Wikidata item page.")
let data = NotificationsCenterActionData(text: text, url: url, iconType: .wikidata, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Specific Special:UserGroupRights#{Type} page
var specificUserGroupRightsAction: NotificationsCenterAction? {
guard let url = specificUserGroupRightsURL,
let type = url.fragment,
let title = url.wmf_title else {
return nil
}
let text = "\(title)#\(type)"
let data = NotificationsCenterActionData(text: text, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Special:UserGroupRights
var userGroupRightsAction: NotificationsCenterAction? {
guard let url = userGroupRightsURL,
let title = url.wmf_title else {
return nil
}
let data = NotificationsCenterActionData(text: title, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Help:GettingStarted
var gettingStartedAction: NotificationsCenterAction? {
guard let url = gettingStartedURL,
let title = url.wmf_title else {
return nil
}
let data = NotificationsCenterActionData(text: title, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Login Notifications
private var loginNotificationsText: String {
WMFLocalizedString("notifications-center-login-notifications", value: "Login notifications", comment: "Button text in Notifications Center that routes user to login notifications help page in web view.")
}
var loginNotificationsAction: NotificationsCenterAction? {
guard let url = loginNotificationsHelpURL else {
return nil
}
let data = NotificationsCenterActionData(text: loginNotificationsText, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Login Notifications
var loginNotificationsGoToAction: NotificationsCenterAction? {
guard let url = loginNotificationsHelpURL else {
return nil
}
let data = NotificationsCenterActionData(text: loginNotificationsText, url: url, iconType: .document, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
// Change password
var changePasswordAction: NotificationsCenterAction? {
guard let url = changePasswordURL else {
return nil
}
let text = CommonStrings.notificationsChangePassword
let data = NotificationsCenterActionData(text: text, url: url, iconType: .lock, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
func actionForGenericLink(link: RemoteNotificationLink) -> NotificationsCenterAction? {
guard let url = link.url,
let text = link.label else {
return nil
}
let data = NotificationsCenterActionData(text: text, url: url, iconType: .link, destinationText: destinationText(for: url))
return NotificationsCenterAction.custom(data)
}
}
| 43.411348 | 356 | 0.669825 |
0e957b2bad93fa9dfb191e6e3b94716434ef8e8e | 26,438 | import Foundation
//let input = """
//b inc 5 if a > 1
//a inc 1 if b < 5
//c dec -10 if a >= 1
//c inc -20 if c == 10
//"""
let input = """
uz inc 134 if hx > -10
qin dec -300 if h <= 1
ubi inc 720 if qin <= 306
si inc -108 if he <= 1
hx inc 278 if hx <= -10
nfi inc 955 if f <= 5
h dec 786 if a == 0
qin dec -965 if f >= -6
hx dec -463 if hx != -6
t dec -631 if ty <= 3
yf dec -365 if ke >= -1
z inc 270 if ke == 0
z inc -391 if nfi < 964
nfi inc -424 if sy >= 10
uz inc 152 if yu > -9
yu dec 137 if wg < 6
ke dec -562 if hx == 463
ke dec 944 if h != -794
ty dec -993 if qin < 1261
a inc 456 if wg <= 8
zwx inc 585 if ty != 2
z dec 744 if zwq <= 5
zwq inc -316 if he > -8
xf inc -614 if hx != 462
hx dec -589 if ke >= -391
xp inc 551 if f != 0
yu inc 640 if a < 464
uz inc -299 if t != 636
t dec -93 if a != 461
yu inc -202 if qin <= 1270
hx dec 552 if zwq < -312
ubi dec -562 if jke <= 4
nfi inc -531 if sy == 0
xf inc -620 if h < -791
ubi dec 164 if jke <= 2
xf inc 715 if xf == -614
si inc 832 if w < 4
xp inc 37 if t >= 721
yu inc -49 if u != 3
wg inc -500 if o > -3
he dec -740 if xp <= 46
ubi dec -946 if u != 0
fkh dec 973 if nfi < 434
zwx inc 796 if si >= 719
hx inc 443 if ty < -2
w inc -515 if wg != -490
xf inc -394 if xf != 109
u inc 176 if sy <= 7
sy inc 170 if w < -513
si dec -699 if fkh == -973
nfi dec 321 if w != -519
yu inc -846 if wg < -496
hx inc 953 if qin < 1270
w dec -394 if u < 183
xf dec -601 if he == 731
zwx inc 267 if h >= -777
zwq inc 781 if f > -3
jke inc 278 if jke >= -3
u inc -7 if u <= 184
zwq inc 449 if wg >= -503
si dec 368 if hx != 1446
h dec -24 if jke >= 282
ke dec -284 if yu < -587
si dec 17 if a > 458
o dec 177 if yu != -594
he inc -925 if ubi >= 1116
ubi inc 544 if zwq <= 915
hx dec -56 if yf < 373
wg dec -613 if z > -866
wg inc -580 if z >= -868
xp dec -445 if ty > 3
yu dec -419 if h < -776
ty dec -75 if xp <= 35
u dec 30 if xf < -283
o inc 69 if uz != -13
f dec 910 if t >= 716
he inc 100 if xf < -296
jke dec 125 if nfi >= 98
yu dec 526 if xp <= 45
fkh dec 708 if zwq >= 918
u dec -397 if w > -131
si dec 417 if u != 533
wg dec 247 if wg == -467
t inc 45 if yu < -700
ty dec 805 if o <= 8
he dec 734 if f < -909
z inc 812 if f > -907
w dec -508 if xf > -300
a inc -375 if uz == -13
zwx inc 160 if w >= 378
o inc -905 if qin < 1264
jke dec -594 if fkh != -971
fkh dec -392 if xp >= 32
t dec 512 if jke != 754
a dec -949 if ke == -98
f inc -70 if a > 1022
f dec -844 if qin > 1261
u dec 212 if sy <= 176
xf dec -779 if w == 396
uz inc -455 if zwx >= 1548
o dec 502 if wg > -723
sy inc 77 if u > 326
uz inc -996 if xp >= 32
nfi dec -355 if hx >= 1502
hx dec 855 if hx <= 1503
qin inc 376 if xf > -296
sy dec -519 if zwq != 916
a dec 459 if a > 1023
ty inc -289 if zwq > 905
he dec -722 if zwx >= 1532
jke inc 656 if sy < 691
u dec -989 if nfi < 466
a inc -377 if zwx >= 1545
sy dec -256 if yf == 365
ubi dec 597 if fkh > -591
xf inc 403 if ty == -1094
z dec 335 if o <= -498
yf dec -707 if zwq < 907
zwq inc 420 if h == -780
h dec -612 if uz >= -1010
hx dec 941 if w != 390
xp dec 345 if u != 1306
xp dec -409 if si <= 641
uz dec 877 if hx <= 574
t dec 615 if f > -142
wg dec 505 if hx >= 566
ubi inc 413 if o >= -506
uz dec -263 if h < -167
f dec 537 if xf != 110
wg dec -762 if sy > 935
o inc 458 if fkh == -591
ubi dec -914 if ubi != 1488
wg inc 203 if sy >= 952
zwq dec -879 if ty == -1094
h inc -676 if xp <= 103
he inc 544 if zwq <= 1795
jke inc 178 if si < 648
xf dec 262 if xp >= 96
sy dec -214 if w >= 383
u inc 88 if uz != -1633
yu dec 375 if t <= -358
wg dec 526 if hx == 568
yf dec 731 if si > 631
he inc -980 if zwq == 1793
ty dec 94 if t > -368
yf dec -849 if yu > -1077
ty dec 889 if f != -139
w dec 37 if f > -137
wg inc 552 if si > 631
he inc -989 if nfi > 457
f dec -500 if zwq > 1785
ubi inc -394 if jke >= 1578
yu dec -370 if o == -498
nfi dec 879 if hx >= 559
nfi inc -280 if h > -853
a inc -746 if wg != -431
h inc -362 if a >= 569
jke dec 740 if si > 631
zwx inc -152 if yf < 489
z inc -442 if wg == -431
t inc -404 if xp != 101
t inc 668 if ty != -2081
f dec 846 if yu >= -1084
xf inc -342 if z < -1638
xf inc 692 if ubi > 2003
qin inc 874 if sy == 1159
t inc -792 if jke < 850
jke dec 263 if ubi < 1997
xf dec -645 if w != 343
u inc -291 if yf < 485
wg inc 948 if fkh != -574
u inc 773 if zwx <= 1392
fkh dec -56 if jke != 836
w dec 436 if qin <= 2521
o inc 769 if ty >= -2079
o dec 457 if zwx < 1392
a dec -422 if fkh != -531
z dec -170 if qin <= 2518
qin inc -569 if ty >= -2077
uz inc -789 if zwq >= 1803
f dec 322 if xp < 103
xf inc -752 if xp <= 108
xp dec -46 if z == -1472
hx dec 378 if zwx <= 1390
ubi dec -746 if ubi < 2008
xf dec -22 if si > 635
h dec -274 if zwq <= 1794
u dec -980 if yf < 485
ty dec -41 if ty <= -2071
t dec -818 if ty != -2043
u dec -764 if nfi < -704
uz inc 233 if sy >= 1152
t dec 552 if xp > 145
h dec 689 if zwq >= 1789
h dec -219 if yf <= 485
uz inc 890 if uz == -1390
zwx dec -399 if z == -1472
jke inc 792 if w <= -85
si dec -991 if nfi == -701
f inc -355 if ke <= -91
ke dec -575 if wg > 516
hx dec -38 if ke <= 482
si inc 478 if he > -1623
ubi dec 18 if o < -185
fkh dec 394 if wg > 521
wg inc 988 if zwx != 1790
hx inc -777 if qin >= 1949
ubi inc 680 if he >= -1618
fkh inc -479 if qin > 1945
zwx dec 704 if jke != 1640
fkh dec -167 if t == -216
yu dec 881 if ubi >= 2724
wg dec -93 if qin >= 1940
nfi dec -763 if o <= -182
t dec -937 if t != -215
u inc 114 if t != 721
ubi dec 547 if uz < -507
qin dec 827 if sy == 1159
w inc -588 if t >= 721
zwx dec 548 if a > 997
a inc 929 if f < -1164
zwq inc -260 if zwx == 1084
ty dec -814 if si > 2100
yf dec 745 if w >= -665
t inc -257 if ke <= 486
u dec 522 if t < 471
hx inc 376 if z == -1472
t dec 996 if si != 2098
uz dec 375 if u >= 2337
fkh dec 823 if xp >= 149
z dec 497 if ty != -1212
t dec 0 if sy >= 1156
xp inc 742 if a != 993
xp dec -160 if f < -1149
zwx dec -988 if z < -1972
he dec -586 if w < -677
yu inc 646 if wg > 1594
jke dec -686 if he < -1616
a dec 375 if jke <= 2323
h dec -719 if ty < -1223
xp dec -169 if uz < -868
o inc 961 if f < -1155
si inc 462 if yu == -1321
hx inc 647 if ke != 487
jke inc 372 if xf == -579
xf inc 188 if f == -1159
a dec 78 if xp < 479
wg inc -818 if f >= -1166
yf inc 994 if h > -1418
fkh inc -812 if xf > -396
qin dec -321 if si == 2116
f inc 830 if nfi >= 58
u inc 24 if h >= -1399
uz inc 881 if jke != 2693
w dec 719 if ke != 479
jke inc 694 if nfi > 61
hx dec 84 if ty > -1224
ty dec -221 if zwq <= 1536
yu dec 236 if zwq == 1540
yu dec -763 if f != -339
a dec 892 if w <= -1391
jke dec -275 if ubi < 2733
nfi inc -121 if zwx < 1086
a inc 809 if t < -526
si inc -997 if jke != 3664
xf dec 787 if hx <= 1158
ty dec -599 if z > -1975
yu inc -534 if a <= 456
ty inc 573 if nfi < -49
sy dec -53 if sy < 1162
wg inc -751 if w == -1393
xf inc 704 if ubi > 2723
si inc 314 if wg != 27
wg inc 607 if h == -1408
zwx dec -263 if a >= 450
qin inc -390 if ke <= 482
ke inc 866 if f <= -330
f inc 79 if uz <= 9
hx dec 683 if z > -1975
si dec 678 if wg > 634
si inc -853 if zwx != 1338
z inc -586 if jke == 3665
he inc 810 if jke != 3656
uz inc -248 if o != 762
fkh dec 334 if xp != 474
w dec 368 if zwq == 1533
t dec -502 if f <= -259
yf inc -523 if u > 2344
yu inc -10 if ke != 477
u dec -918 if u < 2345
uz inc 580 if fkh <= -1979
t inc 144 if ke >= 485
xp dec -366 if zwx == 1338
ubi inc -26 if t < -524
xp inc -776 if he != -813
ubi inc 136 if a != 450
qin inc 13 if xf >= 306
yf dec 536 if uz != 333
hx dec -213 if z > -1978
f inc -224 if zwq >= 1542
wg dec -507 if f <= -246
yu inc -668 if w != -1761
ke inc -680 if t != -533
jke dec -283 if wg == 1143
f dec 870 if o >= 767
jke inc -124 if fkh <= -1976
u dec -567 if w < -1763
o dec 457 if xf <= 312
ty dec 576 if zwx > 1345
qin inc 142 if yu <= -555
ke dec 749 if hx != 702
wg dec 851 if w == -1763
a dec 686 if yf == 933
wg dec -701 if z > -1964
ty inc -877 if zwq < 1541
xf dec -990 if fkh == -1983
ubi inc 0 if ty == -1282
h inc -21 if h != -1400
sy dec -519 if xf != 1303
jke inc 603 if he > -818
ty dec -4 if hx > 699
xp inc 21 if wg > 1138
xp dec 745 if t <= -527
yu dec -614 if hx > 691
a inc -490 if xp != -1018
h dec -723 if jke != 4428
sy inc -594 if yf != 947
hx dec 851 if o <= 761
a dec -345 if t >= -532
ubi inc -359 if f < -1122
jke dec 738 if wg == 1143
ty dec 340 if xp != -1024
nfi inc -786 if w >= -1767
zwq dec 428 if qin == 740
zwq inc 503 if t < -527
zwq dec -98 if si != -113
sy dec 297 if he > -815
u inc -886 if xf < 1313
z dec 105 if h <= -704
yf dec -260 if f != -1127
w dec 920 if w != -1756
a inc 744 if hx == 697
sy inc 262 if t <= -528
si inc 347 if uz <= 347
si inc -188 if o <= 779
h dec 191 if he != -812
xp inc 1000 if sy >= 578
yf inc -563 if ke < -942
xf inc 547 if h > -710
f inc -783 if yu < 73
z dec 394 if h < -705
hx dec 765 if xf != 1856
t inc -817 if wg >= 1140
yu dec -8 if t != -1343
w dec 152 if zwx >= 1338
ubi dec -134 if fkh <= -1978
f dec 841 if jke >= 3679
uz dec -245 if t <= -1349
o dec 151 if a >= 1066
qin inc -219 if w <= -2840
yu inc -323 if yf != 637
sy dec -490 if xp == -24
xp dec -649 if qin != 735
xf inc 39 if nfi != -855
wg inc 581 if sy < 1074
f inc -42 if uz == 583
z inc 506 if he < -808
he dec 568 if he < -804
wg dec 60 if he >= -1381
hx dec -835 if qin < 748
ty inc -593 if qin > 739
wg dec 613 if wg == 1664
h dec 107 if h <= -706
yf dec -40 if a > 1058
fkh inc 511 if ke >= -949
wg dec -812 if yf == 638
xf dec -349 if zwx <= 1356
si dec -614 if ty <= -1868
z inc 28 if he <= -1376
he inc -666 if uz > 579
sy dec 584 if si == 666
sy inc 536 if o > 767
f dec 384 if t != -1342
jke dec 341 if xp != 625
w dec 894 if zwq <= 2139
si dec -871 if yu < -240
he inc 659 if nfi <= -838
qin inc 32 if xf == 2238
nfi dec -165 if z > -1938
h inc 473 if zwq == 2130
qin dec 666 if xf >= 2230
qin inc 469 if si > 1543
t dec 348 if h == -813
si inc 578 if jke != 3684
ke inc 186 if a == 1056
jke inc -61 if xp >= 616
u inc -347 if fkh > -1987
zwx dec -894 if ubi != 2968
h dec -204 if ke <= -768
yu dec -501 if sy != 1024
f dec 393 if wg > 1866
t inc 768 if hx != 766
he dec 459 if fkh == -1980
qin dec -650 if z >= -1933
sy inc 333 if yf <= 642
nfi inc 93 if xf >= 2247
z inc 829 if xp == 620
wg dec -396 if hx != 760
xp inc -71 if hx <= 765
w inc -837 if ty >= -1884
ty dec 380 if z < -1925
h inc -162 if yf <= 642
hx inc 324 if yu > 258
fkh dec -83 if ty > -2258
uz inc 716 if jke <= 3631
w inc -331 if nfi == -680
ubi dec 638 if wg >= 2252
wg inc 139 if ty < -2256
xp dec 21 if he >= -1387
fkh dec 723 if hx < 774
zwx dec -981 if f != -3170
f dec 650 if ty == -2263
f dec -247 if jke == 3623
hx inc -250 if z >= -1938
xp inc -236 if hx == 517
ke dec -408 if ubi == 2332
xp inc -266 if xp < 377
f inc -349 if hx > 509
u inc 945 if jke > 3621
si inc -843 if yu < 252
t dec 747 if ty == -2262
uz inc -684 if xf <= 2228
yu inc 73 if t <= -922
jke dec 435 if xf <= 2238
sy dec -495 if z < -1937
jke inc 293 if jke < 3198
fkh dec -220 if xf <= 2236
z dec -905 if wg >= 2252
wg dec 544 if nfi <= -679
ty inc 807 if a > 1050
qin dec 337 if ty < -1447
xf dec 178 if ty != -1455
nfi dec 119 if a >= 1055
he inc -956 if fkh < -2624
jke dec 224 if t == -923
fkh inc 135 if o != 765
si dec 428 if qin == -229
o inc -985 if si > 1114
he dec 100 if f != -3272
ty inc -707 if xp >= 94
jke dec 551 if w == -4895
yu dec -308 if h <= -968
h inc -429 if wg <= 1718
wg dec 278 if uz == 1299
uz inc -416 if fkh >= -2494
ty dec -876 if qin == -229
sy inc 213 if o >= 774
qin dec 664 if wg > 1434
h inc 273 if uz != 879
zwx inc -611 if ubi != 2334
hx dec 384 if wg >= 1429
he inc -84 if uz == 883
hx inc 23 if yu > 626
si dec 319 if wg == 1433
h dec 343 if ubi <= 2332
yf dec 941 if w == -4895
w inc -450 if u >= 2981
hx inc 435 if xf <= 2065
si dec -198 if xp <= 107
si inc -322 if he < -1467
o dec 21 if xf != 2055
zwx dec 251 if ty > -1284
ke dec 399 if yf > -309
f inc 965 if xf <= 2063
ke dec 488 if o != 749
a dec 163 if a != 1061
hx inc 2 if w != -4887
zwq inc -736 if uz < 888
qin inc 155 if a <= 884
zwx dec 798 if xf == 2060
o dec -566 if jke < 2933
yf inc 536 if u != 2965
f dec -782 if zwx != 575
nfi dec 603 if z <= -1024
f dec -409 if t == -929
zwx inc 140 if hx < 597
hx dec 778 if f > -1120
h dec -327 if wg > 1435
ke inc 146 if zwq <= 1406
sy dec -718 if xf != 2060
yf dec 125 if h < -1140
xf dec -154 if ubi == 2326
a dec 744 if xp > 93
yf inc 837 if si > 982
jke inc 526 if o < 1320
jke inc 919 if he <= -1470
xp dec -626 if xp != 102
h inc 18 if uz != 885
uz dec 39 if h >= -1133
o dec -642 if ubi > 2324
wg inc -500 if uz >= 842
zwx inc -530 if o <= 1956
u dec -334 if ke != -1100
yf dec -231 if o <= 1966
zwx dec 470 if fkh == -2488
zwq inc 345 if xp == 97
ubi dec -357 if fkh >= -2496
nfi dec 923 if ke >= -1100
ke inc 764 if si < 980
t inc 165 if fkh >= -2488
he inc -579 if yu > 626
xp dec 337 if w != -4897
o dec -573 if ubi < 2690
nfi inc -512 if jke != 4384
yf inc 85 if ubi != 2689
u dec 401 if zwq <= 1399
ty inc -528 if uz == 844
xf dec 254 if fkh == -2488
f dec 713 if z >= -1033
xf dec -632 if zwq > 1392
uz inc 166 if f >= -1823
zwq inc -492 if he >= -2051
hx inc 287 if uz != 851
ty inc -935 if wg != 929
h dec 74 if jke <= 4384
zwx inc 43 if hx == 102
jke inc 151 if z < -1025
w dec 839 if t == -764
wg dec -753 if fkh > -2492
o dec -751 if t != -764
ty inc -359 if yu > 635
yu inc -344 if z > -1024
uz dec -356 if xf >= 2440
u dec 797 if yu <= 634
zwq inc 141 if he != -2060
wg dec 365 if a < 156
t dec 382 if u < 2112
f inc 374 if wg == 1325
he dec -912 if qin >= -896
o dec 325 if o >= 2524
ty inc 276 if a > 143
ty inc 507 if zwx > 297
f dec -837 if yu > 627
wg inc 221 if ke != -1100
z dec 423 if si >= 977
o dec 551 if zwq < 1039
f inc 956 if si >= 978
fkh inc -236 if fkh >= -2496
he inc 206 if hx > 99
zwx dec -239 if he < -927
hx inc -246 if wg >= 1545
fkh inc 652 if he > -935
qin inc -429 if yf <= 1184
yu dec -3 if nfi == -2830
zwq dec -582 if sy <= 1359
ubi inc 728 if t >= -1138
fkh inc 327 if xp <= -231
w inc 85 if xp >= -227
t dec 983 if zwq < 1630
xf dec -568 if he >= -939
yu inc -193 if f >= 342
ty inc 210 if he < -925
f inc -345 if uz < 852
nfi dec -444 if h > -1206
xp inc -160 if nfi < -2389
f dec -919 if u > 2107
zwq inc 788 if ke > -1107
ty inc -628 if o != 2201
a inc 506 if jke > 4525
t inc 413 if t > -2130
nfi dec -131 if fkh == -1745
ke inc -475 if wg < 1553
wg dec 955 if jke > 4525
xf dec -41 if hx < -148
ubi dec 105 if uz < 846
h inc -312 if ke < -1568
ubi inc -552 if o != 2201
zwx dec -713 if w < -5732
zwq dec 437 if jke != 4520
a dec -164 if ke >= -1565
hx inc 189 if sy != 1356
o dec 856 if wg != 593
xf inc -563 if h > -1518
wg inc 313 if yf < 1186
he inc -628 if u >= 2102
he dec -537 if xf < 2447
zwq dec -64 if o >= 1345
t inc -465 if wg <= 905
jke inc -495 if u == 2107
qin dec -271 if zwq < 2046
zwx dec -18 if w == -5734
yu inc -376 if h == -1508
zwq dec 537 if zwq == 2044
nfi inc -751 if uz > 837
yf dec 135 if h < -1508
nfi inc 943 if u > 2106
si dec -835 if ty > -2889
zwq dec 334 if zwq > 1502
ubi inc 920 if jke != 4032
ke dec 939 if zwq > 1170
h dec -570 if jke != 4029
yf dec -80 if yf == 1047
h inc 104 if w >= -5731
a inc -173 if sy <= 1355
ke inc 689 if hx > 51
ubi dec -953 if si <= 1829
nfi inc -927 if qin <= -1060
qin inc 84 if qin < -1051
zwx dec -466 if u <= 2103
ubi dec -45 if xp <= -393
w dec 23 if fkh == -1745
u inc 658 if fkh >= -1738
wg dec -262 if uz == 844
f dec -46 if t <= -2176
si dec -622 if hx <= 46
qin dec -617 if uz > 837
uz dec 775 if sy <= 1361
ty inc 675 if t > -2191
xf inc -263 if nfi <= -2076
ke dec -502 if si <= 2436
z inc -704 if jke == 4031
nfi dec -154 if he > -1024
o inc 896 if he > -1027
hx dec 1 if qin != -440
sy inc -236 if h == -936
qin inc 38 if jke > 4021
wg inc 168 if ty == -2209
zwx inc 252 if ty > -2215
ty inc -296 if ty != -2215
a dec -346 if o > 2253
f inc 76 if u >= 2098
xp dec 22 if wg > 1330
xp dec 783 if w > -5754
sy dec -525 if yf >= 1037
xf inc -434 if yf >= 1046
u dec -160 if f < 117
nfi dec -498 if f > 124
fkh inc 654 if zwq >= 1164
yu dec 393 if sy != 1881
zwq dec 966 if qin > -404
zwx dec 146 if jke < 4032
nfi inc -531 if f > 108
si dec 607 if nfi < -2442
w inc -519 if u <= 2274
ke inc -299 if ty < -2502
zwx inc 1000 if nfi > -2456
o inc -746 if u >= 2269
ty inc -694 if ubi < 3941
z inc 37 if uz <= 75
fkh dec 785 if h < -938
sy dec -790 if yu <= 243
nfi dec -952 if u >= 2275
f inc -326 if ubi < 3957
u inc -716 if si >= 1826
xp inc -811 if z >= -2127
xf dec -825 if sy >= 2671
h dec -220 if jke >= 4023
t inc 405 if yf < 1038
qin inc 212 if t > -2188
h inc -738 if t < -2176
sy dec -659 if fkh > -1885
ke dec -94 if qin != -175
a inc 407 if a >= 653
qin inc 628 if h < -1456
a dec 363 if jke < 4033
ty dec 582 if zwx < 2376
zwx inc 93 if ubi < 3952
nfi dec -728 if xf >= 3265
fkh dec -652 if u != 1541
he dec -847 if fkh <= -1233
nfi inc 258 if t != -2185
a inc -703 if f >= -214
w dec 811 if nfi >= -1464
qin dec 41 if ty != -3082
xp inc 308 if uz != 71
zwx inc -688 if wg != 1328
zwq inc 319 if uz <= 61
he inc -906 if xf <= 3268
w inc -941 if ke >= -2722
h inc 74 if uz == 69
zwq inc 187 if uz <= 75
jke dec -909 if he <= -1921
z dec 820 if si < 1838
h inc -463 if uz > 68
ubi inc -3 if hx >= 44
w dec -250 if zwq == 394
t inc -910 if z > -2933
sy dec 917 if ty != -3087
yf inc -88 if nfi >= -1458
wg dec -945 if w < -7770
a inc 700 if zwx < 1778
jke inc 544 if h < -1848
o inc -646 if h <= -1857
h dec -640 if sy > 3324
zwq inc -743 if jke < 5478
w inc 13 if w <= -7770
u dec 806 if si < 1843
w dec 499 if si != 1826
wg inc -535 if uz >= 61
ubi inc -110 if si >= 1845
xf inc -114 if qin > 397
ke inc -509 if wg < 1747
xf dec -591 if t != -2181
ubi dec -5 if ubi < 3952
xf inc -123 if wg != 1744
u inc -84 if nfi < -1452
qin dec 489 if zwq != 387
z dec 399 if o == 2246
yu dec -468 if xf > 3145
zwq inc -882 if si == 1835
h dec 771 if he >= -1937
wg inc 11 if ubi < 3961
a inc -500 if ty < -3081
uz inc 809 if zwx < 1780
yf inc 364 if xf == 3148
o inc 324 if si == 1835
ke dec -113 if f < -215
xf inc 921 if uz > 872
zwx inc 143 if h <= -1974
t dec 163 if o > 2565
o dec -177 if si <= 1838
ubi dec -200 if fkh <= -1219
ke inc -62 if t <= -2340
f inc 546 if si >= 1830
t inc 467 if fkh >= -1226
z inc -229 if he < -1935
hx inc -486 if ubi < 4159
wg inc -290 if o < 2748
zwq dec 950 if ty < -3083
ubi inc 78 if uz != 886
h inc -842 if z <= -3331
ke inc 562 if fkh != -1233
u inc -464 if qin != -94
he inc 960 if wg == 1465
o dec -705 if a < 189
qin dec -769 if wg <= 1467
qin inc -43 if si < 1844
he inc -571 if yf == 1041
o inc 436 if t > -1883
zwq dec 839 if jke == 5484
z dec -233 if u <= 202
wg inc -313 if hx >= -451
ty inc 552 if zwx < 1913
ke inc 204 if si > 1826
yf inc -924 if si < 1840
u dec -30 if a < 197
z dec -753 if ke == -2523
qin dec -755 if uz <= 871
ke inc -787 if z > -2357
si inc -676 if qin <= 643
hx dec 301 if zwq != -2277
xp dec 617 if z <= -2346
ubi inc -445 if xp != -1529
h inc -784 if qin == 640
ty dec 524 if wg < 1143
t inc 313 if yu >= 701
zwq dec -716 if zwq < -2279
ke inc 258 if sy == 3332
wg dec -495 if w >= -8269
nfi inc -327 if uz >= 877
f inc -940 if zwx != 1923
jke inc -886 if uz <= 868
yu inc -619 if f >= -595
he inc -738 if h != -3613
fkh dec 354 if jke != 5486
h inc -6 if nfi != -1783
jke inc -691 if zwx < 1919
uz inc 142 if nfi == -1788
wg dec -303 if a > 186
jke dec -797 if yf >= 115
a dec -4 if xf <= 4075
xp dec -517 if zwx < 1919
xp inc -983 if ke >= -3050
f dec -83 if si != 1159
uz dec 110 if nfi >= -1793
si inc 219 if fkh != -1581
wg dec 946 if w < -8263
zwx dec -809 if nfi >= -1791
uz inc 664 if ty >= -3089
xp dec -210 if zwq != -2272
z inc -359 if ke > -3045
ke dec 863 if o == 3183
ty inc -748 if yu == 708
ty dec 539 if uz >= 1571
xp dec 666 if zwq < -2271
z dec 282 if h == -3615
u inc -702 if hx < -437
o dec -741 if yf > 114
h dec -238 if o > 3917
jke inc -344 if yf <= 118
qin dec -774 if qin < 648
xf dec -228 if uz < 1580
ubi inc 428 if f <= -602
yu inc -964 if xp < -1479
wg dec -725 if he <= -2273
sy inc 913 if ty <= -4378
xf inc 936 if nfi < -1796
yf inc 100 if xp > -1481
jke dec 876 if zwq == -2277
yu dec 373 if w > -8269
hx dec -542 if fkh >= -1572
xf inc 41 if yf >= 215
w inc -491 if qin < 1422
jke inc 643 if a == 200
si inc -74 if he == -2278
qin dec 842 if jke >= 5004
hx inc -797 if jke != 5009
sy dec 444 if uz != 1577
jke inc -606 if hx != -1244
qin inc -381 if sy > 2886
yf dec -922 if qin >= 184
ke inc 689 if ke > -3920
yf dec 850 if yf <= 1141
yu inc -120 if w >= -8750
ke inc 613 if uz != 1582
hx inc 620 if xf <= 4351
sy inc -631 if hx > -627
xp dec -781 if fkh <= -1569
nfi dec 196 if sy >= 2266
f dec -69 if yu >= 330
o inc 492 if ke > -2616
sy dec -837 if sy <= 2262
xf dec 862 if a != 203
yf inc -182 if zwq < -2272
wg inc -534 if o != 4406
si dec 788 if h > -3381
ty inc -85 if zwx == 2727
w inc 942 if hx == -619
o inc -880 if a >= 200
uz inc 654 if zwx <= 2732
u dec -710 if he != -2278
zwq dec -920 if f < -530
jke dec 21 if z > -2644
qin dec 529 if f != -537
jke inc -901 if u <= -470
w inc 900 if nfi <= -1783
ke inc 624 if o == 3536
wg dec 784 if qin == -338
yf dec 682 if w <= -6921
a dec 593 if sy <= 3097
xf dec 442 if hx != -616
nfi inc 852 if z == -2634
yf dec -338 if zwx < 2732
qin dec 511 if ty > -4451
xf dec -512 if si >= 508
u dec 172 if xf <= 3558
w dec -255 if jke >= 3476
zwq inc -879 if wg >= 408
zwx inc -498 if si < 518
xp dec -405 if f == -536
qin inc -76 if a != -391
nfi inc -734 if a >= -397
h dec -940 if o < 3541
o dec -41 if qin != -412
f dec -736 if h < -2436
fkh inc -180 if yu > 327
u inc 73 if ke < -1981
xf inc 932 if he > -2288
wg inc 103 if fkh < -1754
fkh inc 872 if fkh < -1757
xp dec 679 if si != 526
z inc 486 if w > -6661
jke inc -909 if f == 200
qin dec 443 if uz < 2223
f dec -653 if hx > -626
qin dec -106 if nfi >= -1675
uz inc 969 if uz == 2228
t inc -474 if w > -6660
xf inc -898 if f <= 854
zwq inc -246 if a <= -398
yf dec -931 if nfi <= -1665
h inc 770 if ty > -4461
u inc -20 if z == -2148
wg inc -317 if z == -2138
t inc -73 if a >= -384
xp dec -372 if fkh > -885
hx dec -592 if yu < 342
a inc 357 if uz == 3197
zwq dec 13 if si <= 520
h inc 97 if f <= 847
qin inc 133 if yu < 341
ty inc -437 if ke > -1988
ty dec -281 if yf <= 1374
uz inc 0 if xf < 3595
o inc -303 if fkh < -876
h inc -594 if yu == 335
zwq dec 422 if qin <= -173
xf dec 44 if u == -594
hx dec -264 if sy != 3087
si inc 539 if qin == -181
ke dec -667 if si < 523
uz dec 309 if he < -2269
yf inc -394 if zwx <= 2238
o inc -572 if w <= -6664
z inc 241 if t <= -2045
qin dec 285 if a < -27
xp dec 413 if zwq < -2667
ubi inc 317 if t >= -2033
yu inc -173 if sy <= 3094
nfi inc -262 if zwq <= -2669
a inc 98 if uz > 2878
sy inc 513 if wg == 514
yu inc -841 if ke != -1331
ke inc -426 if ubi != 4220
he dec 187 if he != -2277
fkh dec 717 if zwq >= -2661
f dec -191 if uz <= 2893
zwx dec -661 if yf != 972
fkh dec -112 if ubi <= 4220
ty dec 800 if fkh >= -775
sy inc 981 if xp > -1389
xp inc 893 if wg <= 510
nfi inc 944 if qin != -458
zwq inc -250 if qin != -454
uz inc -398 if jke != 2577
w dec -486 if hx >= 230
z dec -205 if xf < 3551
f dec 777 if xf == 3542
wg inc 667 if zwx != 2880
z dec -851 if ty != -5258
w dec 653 if t < -2036
he inc 459 if z > -1091
yf dec 331 if si != 516
zwx dec 327 if qin < -452
xf dec -293 if wg == 1181
fkh inc -469 if yu >= -679
a dec 440 if f >= 261
he dec -292 if xf >= 3833
xf inc 405 if uz == 2490
si inc 825 if sy <= 4588
ubi dec 306 if z != -1085
fkh dec -949 if jke < 2577
zwx dec 703 if o <= 3280
hx inc 951 if o >= 3268
ke inc 134 if z != -1088
w inc -621 if o <= 3274
sy inc 883 if he == -2177
w dec -900 if jke >= 2586
sy inc -56 if xf >= 4232
si dec -994 if zwx == 1860
u inc 726 if yu <= -675
si inc 989 if u <= 140
yf dec 609 if si > 3324
jke inc -872 if si < 3323
hx dec 873 if ubi < 3917
xp dec -284 if o <= 3280
zwq dec -69 if o <= 3280
yf inc 921 if he < -2169
wg dec -859 if h >= -2257
nfi inc -605 if u != 132
fkh inc -567 if yu > -682
w dec 260 if ty < -5262
si dec -809 if h != -2258
f dec 604 if qin > -460
nfi dec 603 if ke < -1609
jke inc -568 if nfi == -1583
ke dec 694 if a <= -378
t inc -188 if yu != -681
fkh dec 328 if w >= -7445
fkh inc 27 if si >= 4126
o dec -358 if f >= 267
xf inc -895 if ubi < 3913
fkh dec 829 if ke < -2315
qin dec 41 if uz == 2490
sy inc 649 if f != 259
wg inc 807 if t < -2224
ubi inc 580 if w == -7446
jke dec -195 if zwx == 1860
f inc -722 if si < 4131
xp inc -694 if xp > -1097
yu inc 810 if h == -2261
f inc -521 if uz == 2499
sy inc -534 if xp >= -1107
zwq dec 330 if nfi <= -1582
ke dec -846 if xp == -1098
h inc -585 if o != 3639
nfi inc 135 if yu <= 137
jke inc -779 if u != 138
a inc 509 if f > 265
uz inc -421 if h != -2848
he inc -36 if h != -2840
o inc 458 if wg == 1988
h dec -88 if wg > 1987
yf dec 98 if a == 131
h inc 729 if si != 4134
xp inc -973 if xf == 3345
zwx dec -483 if z < -1089
hx inc -171 if o > 4089
fkh dec -256 if nfi > -1462
xp inc 578 if h >= -2028
xp dec -194 if uz < 2062
ubi inc -933 if xf == 3347
h dec 944 if zwq == -3182
u dec -139 if ubi >= 4481
qin dec 581 if jke != 1998
ke dec 532 if yf >= 1805
sy inc -101 if fkh > -574
w dec -934 if ubi < 4491
t dec 799 if sy <= 4638
he inc -446 if xp > -2075
"""
var registers = [String: Int]()
var runningMax = 0
for line in input.split(separator: "\n") {
let parts = line.split(separator: " ")
let register = String(parts[0])
if registers[register] == nil {
registers[register] = 0
}
var val = Int(String(parts[2]))!
switch parts[1] {
case "inc":
// Nothing
break
case "dec":
val = -val
default:
break
}
let registerToCheck = String(parts[4])
if registers[registerToCheck] == nil {
registers[registerToCheck] = 0
}
let registerCheckValue = Int(String(parts[6]))!
let checked: Bool
switch parts[5] {
case ">":
checked = registers[registerToCheck]! > registerCheckValue
case "<":
checked = registers[registerToCheck]! < registerCheckValue
case "!=":
checked = registers[registerToCheck]! != registerCheckValue
case ">=":
checked = registers[registerToCheck]! >= registerCheckValue
case "<=":
checked = registers[registerToCheck]! <= registerCheckValue
case "==":
checked = registers[registerToCheck]! == registerCheckValue
default:
checked = false
assert(false)
}
if checked {
registers[register] = registers[register]! + val
}
runningMax = max(runningMax, registers[register]!)
}
print(registers.max(by: { return $0.1 < $1.1 }))
print(runningMax)
| 24.824413 | 67 | 0.612906 |
1af37b20268dd1b228cd81b5cc3721e8b2cdc77d | 1,324 | //
// BuildRelationship.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 17/11/2018.
//
import Foundation
public enum BuildRelationship: Codable {
case app(App)
case build(Build)
case betaTester(BetaTester)
enum CodingKeys: String, Decodable, CodingKey {
case type
case apps, builds, betaTesters
}
public init(from decoder: Decoder) throws {
switch try decoder.container(keyedBy: CodingKeys.self).decode(CodingKeys.self, forKey: .type) {
case .apps:
self = try .app(App(from: decoder))
case .builds:
self = try .build(Build(from: decoder))
case .betaTesters:
self = try .betaTester(BetaTester(from: decoder))
default:
throw DecodingError.typeMismatch(
BuildRelationship.self,
DecodingError.Context(codingPath: [], debugDescription: "Not convertable to \(BuildRelationship.self)")
)
}
}
public func encode(to encoder: Encoder) throws {
switch self {
case .app(let value):
try value.encode(to: encoder)
case .build(let value):
try value.encode(to: encoder)
case .betaTester(let value):
try value.encode(to: encoder)
}
}
}
| 28.170213 | 119 | 0.596677 |
5d0b4a4197d6cde21572731f3f5d30f8b8c5b83b | 3,878 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: akash/deployment/v1beta2/groupspec.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// GroupSpec stores group specifications
struct Akash_Deployment_V1beta2_GroupSpec {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var name: String = String()
var requirements: Akash_Base_V1beta2_PlacementRequirements {
get {return _requirements ?? Akash_Base_V1beta2_PlacementRequirements()}
set {_requirements = newValue}
}
/// Returns true if `requirements` has been explicitly set.
var hasRequirements: Bool {return self._requirements != nil}
/// Clears the value of `requirements`. Subsequent reads from it will return its default value.
mutating func clearRequirements() {self._requirements = nil}
var resources: [Akash_Deployment_V1beta2_Resource] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _requirements: Akash_Base_V1beta2_PlacementRequirements? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "akash.deployment.v1beta2"
extension Akash_Deployment_V1beta2_GroupSpec: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GroupSpec"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "requirements"),
3: .same(proto: "resources"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.name) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._requirements) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.resources) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if let v = self._requirements {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if !self.resources.isEmpty {
try visitor.visitRepeatedMessageField(value: self.resources, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Deployment_V1beta2_GroupSpec, rhs: Akash_Deployment_V1beta2_GroupSpec) -> Bool {
if lhs.name != rhs.name {return false}
if lhs._requirements != rhs._requirements {return false}
if lhs.resources != rhs.resources {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 40.395833 | 146 | 0.746261 |
206ccb5f9356f5de243e96d5c269d074df971d22 | 5,015 | //
// AVNotifications.swift
// Copyright © 2019 NBC News Digital. All rights reserved.
//
import AVFoundation
public typealias AudioSessionInterruptionObserver = NotificationObserver<AudioSessionInterruption>
public struct AudioSessionInterruption: ObservableNotification {
public static let name = AVAudioSession.interruptionNotification
public let interruptionType: AVAudioSession.InterruptionType
public let interruptionOptions: AVAudioSession.InterruptionOptions
public init?(_ n: Notification) {
guard let userInfo = n.userInfo,
let typeInt = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruptionType = AVAudioSession.InterruptionType(rawValue: typeInt)
else {
return nil
}
self.interruptionType = interruptionType
let optionsInt = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt
self.interruptionOptions = AVAudioSession.InterruptionOptions(rawValue: optionsInt ?? 0)
}
}
public struct AudioSessionRouteChange: ObservableNotification {
public static let name = AVAudioSession.routeChangeNotification
public let reason: AVAudioSession.RouteChangeReason
public let previousRoute: AVAudioSessionRouteDescription
public init?(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue),
let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription
else {
return nil
}
self.reason = reason
self.previousRoute = previousRoute
}
}
public struct MediaServicesWereLost: DecodableNotification {
public static let name = AVAudioSession.mediaServicesWereLostNotification
}
public struct MediaServicesWereReset: DecodableNotification {
public static let name = AVAudioSession.mediaServicesWereResetNotification
}
public struct SilenceSecondaryAudioHint: ObservableNotification {
public static let name = AVAudioSession.silenceSecondaryAudioHintNotification
public let hint: AVAudioSession.SilenceSecondaryAudioHintType
public init?(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey] as? UInt,
let hint = AVAudioSession.SilenceSecondaryAudioHintType(rawValue: typeValue) else {
return nil
}
self.hint = hint
}
}
public typealias PlayerItemPlaybackStalledObserver = NotificationObserver<PlayerItemPlaybackStalled>
public struct PlayerItemPlaybackStalled: ObservableNotification {
public static let name = Notification.Name.AVPlayerItemPlaybackStalled
public let playerItem: AVPlayerItem?
public init(_ n: Notification) {
playerItem = n.object as? AVPlayerItem
}
}
public typealias PlayerItemFailedToPlayToEndTimeObserver = NotificationObserver<PlayerItemFailedToPlayToEndTime>
public struct PlayerItemFailedToPlayToEndTime: ObservableNotification {
public static let name = Notification.Name.AVPlayerItemFailedToPlayToEndTime
public let playerItem: AVPlayerItem
public let error: NSError
public init?(_ n: Notification) {
guard let error = n.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? NSError,
let item = n.object as? AVPlayerItem else {
return nil
}
playerItem = item
self.error = error
}
}
public typealias PlayerItemDidPlayToEndTimeObserver = NotificationObserver<PlayerItemDidPlayToEndTime>
public struct PlayerItemDidPlayToEndTime: ObservableNotification {
public static let name = NSNotification.Name.AVPlayerItemDidPlayToEndTime
public let playerItem: AVPlayerItem
public init?(_ n: Notification) {
guard let playerItem = n.object as? AVPlayerItem else { return nil }
self.playerItem = playerItem
}
}
public typealias PlayerItemNewErrorLogEntryObserver = NotificationObserver<PlayerItemNewErrorLogEntry>
public struct PlayerItemNewErrorLogEntry: ObservableNotification {
public static let name = NSNotification.Name.AVPlayerItemNewErrorLogEntry
public let playerItem: AVPlayerItem
public init?(_ n: Notification) {
guard let playerItem = n.object as? AVPlayerItem else { return nil }
self.playerItem = playerItem
}
}
public typealias PlayerItemNewAccessLogEntryObserver = NotificationObserver<PlayerItemNewAccessLogEntry>
public struct PlayerItemNewAccessLogEntry: ObservableNotification {
public static let name = NSNotification.Name.AVPlayerItemNewAccessLogEntry
public let playerItem: AVPlayerItem
public init?(_ n: Notification) {
guard let playerItem = n.object as? AVPlayerItem else { return nil }
self.playerItem = playerItem
}
}
| 36.875 | 118 | 0.756331 |
9b196559c0682562321f5721ceb060d8a9d261dc | 1,294 | // MockableStub.swift
/*
MIT License
Copyright (c) 2019 Jordhan Leoture
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
@testable import MockSwift
extension Mockable {
static func stub() -> Mockable<ReturnType> {
Mockable(FunctionBehaviourRegister(), .stub(), [])
}
}
| 38.058824 | 79 | 0.777434 |
18471b426d1758478d0010c584ed8d59ca0dd858 | 2,975 | import Foundation
import UIKit
import IBMAdaptiveKit
class OnetimePasscodeViewController: UIViewController, AssessmentResultDelegate {
@IBOutlet weak var buttonEvaluate: UIButton!
@IBOutlet weak var textfieldOtp: UITextField!
@IBOutlet weak var labelTitle: UILabel!
var transactionId: String?
var correlationId: String?
var otp: OneTimePasscodeType = .emailotp
var assessmentResult: AdaptiveResult?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
buttonEvaluate.layer.cornerRadius = 5
textfieldOtp.layer.addSublayer(createBottomBorder(width: textfieldOtp.frame.width - 40, height: textfieldOtp.frame.height))
if let prefix = correlationId {
labelTitle.text! += " \(prefix)"
}
// Hides the keyboard
textfieldOtp.delegate = self
}
// MARK: Control events
@IBAction func onEvaluateClick(_ sender: UIButton) {
guard let value = textfieldOtp.text, !value.isEmpty else {
let alertController = UIAlertController(title: "Evaluation", message: "Code is empty.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true)
return
}
// Construct a new Otp evaluation instance.
let evaluation = OneTimePasscodeEvaluation(transactionId!, code: value, otp: otp)
buttonEvaluate.setActivity(true)
// Attempt the evaluation of the username and password.
AdaptiveService().evaluate(using: evaluation) { result in
DispatchQueue.main.async {
self.buttonEvaluate.setActivity(false)
switch result {
case .success(let assessmentResult):
self.assessmentResult = assessmentResult
if assessmentResult is AllowAssessmentResult || assessmentResult is DenyAssessmentResult {
self.performSegue(withIdentifier: "UnwindOnetimePasscode", sender: self)
}
else {
self.performSegue(withIdentifier: "ShowSecondFactor", sender: self)
}
case .failure(let error):
let alertController = UIAlertController(title: "Evaluation", message: error.localizedDescription, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
self.assessmentResult = DenyAssessmentResult()
self.performSegue(withIdentifier: "UnwindOnetimePasscode", sender: self)
}))
self.present(alertController, animated: true)
}
}
}
}
}
| 41.319444 | 141 | 0.606723 |
76fe5bf0fd63557734ac4ba2287b22f14d89e4c5 | 2,189 | //
// AppDelegate.swift
// Project6
//
// Created by Rodrigo F. Fernandes on 7/20/17.
// Copyright © 2017 Rodrigo F. Fernandes. 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.574468 | 285 | 0.755139 |
fb720072ec622711712f206fe0e0e9a73879ae9a | 492 | //
// ImageSaver.swift
// Instafilter
//
// Created by Ataias Pereira Reis on 22/07/20.
// Copyright © 2020 ataias. All rights reserved.
//
import Foundation
import UIKit
class ImageSaver: NSObject {
func writeToPhotoAlbum(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
}
@objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
print("Save finished")
}
}
| 23.428571 | 115 | 0.703252 |
504a3c0fdc62195ca289b239e3008cbca2b9b9c3 | 3,005 | //
// Uris.swift
// Mi Salud
//
// Created by ITMED on 6/8/18.
// Copyright © 2018 ITMED. All rights reserved.
//
import Foundation
class Uris{
let dominio : String = "https://appwebsv.com/misalud/API/"
let dominioExamenesLaboratorio : String = "https://appwebsv.com/labmisalud/examenes/"
func url_validar_usuario() -> String {
return dominio + "ValidateUser"
}
func url_restaurar_contrasenia() -> String {
return dominio + "RestaurarContrasenia"
}
func url_obtener_citas() -> String {
return dominio + "FetchCitas"
}
func url_reservar_citas_datos_iniciales() -> String{
return dominio + "ReservarCitas"
}
func url_obtener_horas_disponibles() -> String{
return dominio + "ObtenerHorasDisponibles"
}
func url_guardar_cita() -> String{
return dominio + "GuardarCita"
}
func url_obtener_detalles_cita() -> String{
return dominio + "ObtenerDetallesCita"
}
func url_cancelar_cita() -> String{
return dominio + "CancelarCita"
}
func url_contactanos() -> String{
return dominio + "SaveMensajeContactanos"
}
func url_obtener_datos_generales() -> String{
return dominio + "ObtenerDatosGenerales"
}
func url_actualizar_datos_generales() -> String{
return dominio + "ActualizarDatosGenerales"
}
func url_cambiar_contrasenia() -> String{
return dominio + "CambiarContrasenia"
}
func url_obtener_documentos_internos() -> String{
return dominio + "ObtenerDocumentosInternos"
}
func url_obtener_documentos_internos_detalles(idExpediente : Int, idDocumento : Int) -> String{
return dominio + "ObtenerDocumentosInternosDetalles?idExpediente=\(idExpediente)&idDocumento=\(idDocumento)"
}
func url_obtener_examenes_laboratorio() -> String{
return dominio + "ObtenerExamenesLaboratorio"
}
func url_obtener_detalles_examen_laboratorio(nombreArchivo : String, idExamenLaboratorio : Int, idExpediente : Int) -> String{
return dominioExamenesLaboratorio + "\(nombreArchivo)?id=\(idExamenLaboratorio)&ide=\(idExpediente)"
}
func url_obtener_consultas() -> String{
return dominio + "ObtenerConsultas"
}
func url_obtener_detalles_consulta() -> String{
return dominio + "ObtenerDetallesConsulta"
}
func url_obtener_recetas() -> String{
return dominio + "ObtenerRecetas"
}
func url_obtener_detalles_recetas() -> String{
return dominio + "ObtenerDetallesReceta"
}
func url_obtener_cuentas() -> String{
return dominio + "ObtenerCuentas"
}
func url_obtener_detalles_cuenta() -> String{
return dominio + "ObtenerDetallesCuenta"
}
func url_obtener_detalles_cuenta_consumo() -> String{
return dominio + "ObtenerDetallesCuentaConsumo"
}
}
| 27.824074 | 130 | 0.651581 |
03d4b0dc11921ace2d4a099c91a63ce53a0d8686 | 955 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
re g{ enum b = c("))
let a{}()
}class A {
a
B<T where g:b(")
class d>(_ = c{
import Foundation
func f.C{let:T? = [Void{
class A {
class d<f<T : {
init()
var b<T : T
if true{
T] {
init()
class A{
if tocol c(){
struct S <T.c
var a
struct Q<T where H:T.c()
class A : {enum b {
class B:P{
end " ( 1 ]
var a{
struct c(){
class B<C<d<d<d<T{}struct S< C {
func c(_ = F>()
struct A<
class C<T {
struct S< {
class B< g<T where T.e: {let v{{}
b{{
var b:T.c{ enum b<T{
let c{
var b(_ = 0
B
func f<T : T.c{ enum b = e
class A : a {
if true {}class B:P{
class C{
struct
| 19.1 | 79 | 0.643979 |
67a038ecbed42f58936d8df9e3780980456cc82b | 19,817 | //
// PhotoPickerController+Internal.swift
// HXPHPicker
//
// Created by Slience on 2021/8/25.
//
import UIKit
import AVFoundation
import Photos
// MARK: ViewControllers function
extension PhotoPickerController {
func finishCallback() {
#if HXPICKER_ENABLE_EDITOR
removeAllEditedPhotoAsset()
#endif
let result = PickerResult(
photoAssets: selectedAssetArray,
isOriginal: isOriginal
)
finishHandler?(result, self)
pickerDelegate?.pickerController(
self,
didFinishSelection: result
)
if isExternalPickerPreview {
disablesCustomDismiss = true
}
if autoDismiss {
dismiss(animated: true, completion: nil)
}
}
func singleFinishCallback(for photoAsset: PhotoAsset) {
#if HXPICKER_ENABLE_EDITOR
removeAllEditedPhotoAsset()
#endif
let result = PickerResult(
photoAssets: [photoAsset],
isOriginal: isOriginal
)
finishHandler?(result, self)
pickerDelegate?.pickerController(
self,
didFinishSelection: result
)
if isExternalPickerPreview {
disablesCustomDismiss = true
}
if autoDismiss {
dismiss(animated: true, completion: nil)
}
}
func cancelCallback() {
#if HXPICKER_ENABLE_EDITOR
for photoAsset in editedPhotoAssetArray {
photoAsset.photoEdit = photoAsset.initialPhotoEdit
photoAsset.videoEdit = photoAsset.initialVideoEdit
}
editedPhotoAssetArray.removeAll()
#endif
cancelHandler?(self)
pickerDelegate?.pickerController(didCancel: self)
if autoDismiss {
dismiss(animated: true, completion: nil)
}else {
if pickerDelegate == nil && cancelHandler == nil {
dismiss(animated: true, completion: nil)
}
}
}
func originalButtonCallback() {
pickerDelegate?.pickerController(
self,
didOriginalButton: isOriginal
)
}
func shouldPresentCamera() -> Bool {
if let shouldPresent = pickerDelegate?.pickerController(
shouldPresentCamera: self
) {
return shouldPresent
}
return true
}
func previewUpdateCurrentlyDisplayedAsset(
photoAsset: PhotoAsset,
index: Int
) {
pickerDelegate?.pickerController(
self,
previewUpdateCurrentlyDisplayedAsset: photoAsset,
atIndex: index
)
}
func shouldClickCell(
photoAsset: PhotoAsset,
index: Int
) -> Bool {
if let shouldClick = pickerDelegate?.pickerController(
self,
shouldClickCell: photoAsset,
atIndex: index
) {
return shouldClick
}
return true
}
func shouldEditAsset(
photoAsset: PhotoAsset,
atIndex: Int
) -> Bool {
if let shouldEditAsset = pickerDelegate?.pickerController(
self,
shouldEditAsset: photoAsset,
atIndex: atIndex
) {
return shouldEditAsset
}
return true
}
func didEditAsset(
photoAsset: PhotoAsset,
atIndex: Int
) {
pickerDelegate?.pickerController(
self,
didEditAsset: photoAsset,
atIndex: atIndex
)
}
func previewShouldDeleteAsset(
photoAsset: PhotoAsset,
index: Int
) -> Bool {
if let previewShouldDeleteAsset = pickerDelegate?.pickerController(
self,
previewShouldDeleteAsset: photoAsset,
atIndex: index
) {
return previewShouldDeleteAsset
}
return true
}
func previewDidDeleteAsset(
photoAsset: PhotoAsset,
index: Int
) {
pickerDelegate?.pickerController(
self,
previewDidDeleteAsset: photoAsset,
atIndex: index
)
}
func viewControllersWillAppear(_ viewController: UIViewController) {
pickerDelegate?.pickerController(
self,
viewControllersWillAppear: viewController
)
}
func viewControllersDidAppear(_ viewController: UIViewController) {
pickerDelegate?.pickerController(
self,
viewControllersDidAppear: viewController
)
}
func viewControllersWillDisappear(_ viewController: UIViewController) {
pickerDelegate?.pickerController(
self,
viewControllersWillDisappear: viewController
)
}
func viewControllersDidDisappear(_ viewController: UIViewController) {
pickerDelegate?.pickerController(
self,
viewControllersDidDisappear: viewController
)
}
/// 获取已选资源的总大小
/// - Parameters:
/// - isPreview: 是否是预览界面获取
/// - completion: 完成回调
func requestSelectedAssetFileSize(
isPreview: Bool,
completion: @escaping (Int, String) -> Void
) {
cancelRequestAssetFileSize(isPreview: isPreview)
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation] in
var totalFileSize = 0
var total: Int = 0
func calculationCompletion(_ totalSize: Int) {
DispatchQueue.main.async {
completion(
totalSize,
PhotoTools.transformBytesToString(
bytes: totalSize
)
)
}
}
for photoAsset in self.selectedAssetArray {
if operation.isCancelled {
return
}
if let fileSize = photoAsset.getPFileSize() {
totalFileSize += fileSize
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
continue
}
let requestId = photoAsset.checkAdjustmentStatus { (isAdjusted, asset) in
if isAdjusted {
if asset.mediaType == .photo {
asset.requestImageData(
iCloudHandler: nil,
progressHandler: nil
) { sAsset, result in
switch result {
case .success(let dataResult):
sAsset.updateFileSize(dataResult.imageData.count)
totalFileSize += sAsset.fileSize
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
case .failure(_):
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
}
}
}else {
asset.requestAVAsset(iCloudHandler: nil, progressHandler: nil) { (sAsset, avAsset, info) in
if let urlAsset = avAsset as? AVURLAsset {
totalFileSize += urlAsset.url.fileSize
}
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
} failure: { (sAsset, info, error) in
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
}
}
return
}else {
totalFileSize += asset.fileSize
}
total += 1
if total == self.selectedAssetArray.count {
calculationCompletion(totalFileSize)
}
}
photoAsset.adjustmentStatusId = requestId
}
}
if isPreview {
previewRequestAssetBytesQueue.addOperation(operation)
}else {
requestAssetBytesQueue.addOperation(operation)
}
}
/// 取消获取资源文件大小
/// - Parameter isPreview: 是否预览界面
func cancelRequestAssetFileSize(isPreview: Bool) {
for photoAsset in selectedAssetArray {
if let id = photoAsset.adjustmentStatusId {
photoAsset.phAsset?.cancelContentEditingInputRequest(id)
photoAsset.adjustmentStatusId = nil
}
}
if isPreview {
previewRequestAssetBytesQueue.cancelAllOperations()
}else {
requestAssetBytesQueue.cancelAllOperations()
}
}
/// 更新相册资源
/// - Parameters:
/// - coverImage: 封面图片
/// - count: 需要累加的数量
func updateAlbums(coverImage: UIImage?, count: Int) {
for assetCollection in assetCollectionsArray {
if assetCollection.realCoverImage != nil {
assetCollection.realCoverImage = coverImage
}
assetCollection.count += count
}
reloadAlbumData()
}
/// 添加根据本地资源生成的PhotoAsset对象
/// - Parameter photoAsset: 对应的PhotoAsset对象
func addedLocalCameraAsset(photoAsset: PhotoAsset) {
photoAsset.localIndex = localCameraAssetArray.count
localCameraAssetArray.append(photoAsset)
}
/// 添加PhotoAsset对象到已选数组
/// - Parameter photoAsset: 对应的PhotoAsset对象
/// - Returns: 添加结果
@discardableResult
func addedPhotoAsset(
photoAsset: PhotoAsset,
filterEditor: Bool = false
) -> Bool {
if singleVideo && photoAsset.mediaType == .video {
return false
}
if config.selectMode == .single {
// 单选模式不可添加
return false
}
if selectedAssetArray.contains(photoAsset) {
photoAsset.isSelected = true
return true
}
let canSelect = canSelectAsset(
for: photoAsset,
showHUD: true,
filterEditor: filterEditor
)
if canSelect {
pickerDelegate?.pickerController(
self,
willSelectAsset: photoAsset,
atIndex: selectedAssetArray.count
)
canAddAsset = false
photoAsset.isSelected = true
photoAsset.selectIndex = selectedAssetArray.count
if photoAsset.mediaType == .photo {
selectedPhotoAssetArray.append(photoAsset)
}else if photoAsset.mediaType == .video {
selectedVideoAssetArray.append(photoAsset)
}
selectedAssetArray.append(photoAsset)
pickerDelegate?.pickerController(
self,
didSelectAsset: photoAsset,
atIndex: selectedAssetArray.count - 1
)
}
return canSelect
}
/// 移除已选的PhotoAsset对象
/// - Parameter photoAsset: 对应PhotoAsset对象
/// - Returns: 移除结果
@discardableResult
func removePhotoAsset(photoAsset: PhotoAsset) -> Bool {
if selectedAssetArray.isEmpty || !selectedAssetArray.contains(photoAsset) {
return false
}
canAddAsset = false
pickerDelegate?.pickerController(
self,
willUnselectAsset: photoAsset,
atIndex: selectedAssetArray.count
)
photoAsset.isSelected = false
if photoAsset.mediaType == .photo {
selectedPhotoAssetArray.remove(
at: selectedPhotoAssetArray.firstIndex(of: photoAsset)!
)
}else if photoAsset.mediaType == .video {
selectedVideoAssetArray.remove(
at: selectedVideoAssetArray.firstIndex(of: photoAsset)!
)
}
selectedAssetArray.remove(at: selectedAssetArray.firstIndex(of: photoAsset)!)
for (index, asset) in selectedAssetArray.enumerated() {
asset.selectIndex = index
}
pickerDelegate?.pickerController(
self,
didUnselectAsset: photoAsset,
atIndex: selectedAssetArray.count
)
return true
}
/// 是否能够选择Asset
/// - Parameters:
/// - photoAsset: 对应的PhotoAsset
/// - showHUD: 是否显示HUD
/// - Returns: 结果
// swiftlint:disable cyclomatic_complexity
func canSelectAsset(
for photoAsset: PhotoAsset,
showHUD: Bool,
filterEditor: Bool = false
) -> Bool {
// swiftlint:enable cyclomatic_complexity
var canSelect = true
var text: String?
if photoAsset.mediaType == .photo {
if config.maximumSelectedPhotoFileSize > 0 {
if photoAsset.fileSize > config.maximumSelectedPhotoFileSize {
text = "照片大小超过最大限制".localized + PhotoTools.transformBytesToString(
bytes: config.maximumSelectedPhotoFileSize
)
canSelect = false
}
}
if !config.allowSelectedTogether {
if selectedVideoAssetArray.count > 0 {
text = "照片和视频不能同时选择".localized
canSelect = false
}
}
if config.maximumSelectedPhotoCount > 0 {
if selectedPhotoAssetArray.count >= config.maximumSelectedPhotoCount {
text = String.init(format: "最多只能选择%d张照片".localized, arguments: [config.maximumSelectedPhotoCount])
canSelect = false
}
}else {
if selectedAssetArray.count >= config.maximumSelectedCount && config.maximumSelectedCount > 0 {
text = String.init(format: "已达到最大选择数".localized, arguments: [config.maximumSelectedPhotoCount])
canSelect = false
}
}
}else if photoAsset.mediaType == .video {
if config.maximumSelectedVideoFileSize > 0 {
if photoAsset.fileSize > config.maximumSelectedVideoFileSize {
text = "视频大小超过最大限制".localized + PhotoTools.transformBytesToString(
bytes: config.maximumSelectedVideoFileSize
)
canSelect = false
}
}
if config.maximumSelectedVideoDuration > 0 {
if round(photoAsset.videoDuration) > Double(config.maximumSelectedVideoDuration) {
#if HXPICKER_ENABLE_EDITOR
if !config.editorOptions.contains(.video) || filterEditor {
text = String(
format: "视频最大时长为%d秒,无法选择".localized,
arguments: [config.maximumSelectedVideoDuration]
)
canSelect = false
}else {
if config.maximumVideoEditDuration > 0 &&
round(photoAsset.videoDuration) > Double(config.maximumVideoEditDuration) {
text = String(
format: "视频可编辑最大时长为%d秒,无法编辑".localized,
arguments: [config.maximumVideoEditDuration]
)
canSelect = false
}
}
#else
text = String(
format: "视频最大时长为%d秒,无法选择".localized,
arguments: [config.maximumSelectedVideoDuration]
)
canSelect = false
#endif
}
}
if config.minimumSelectedVideoDuration > 0 {
if round(photoAsset.videoDuration) < Double(config.minimumSelectedVideoDuration) {
text = String(
format: "视频最小时长为%d秒,无法选择".localized,
arguments: [config.minimumSelectedVideoDuration]
)
canSelect = false
}
}
if !config.allowSelectedTogether {
if selectedPhotoAssetArray.count > 0 {
text = "视频和照片不能同时选择".localized
canSelect = false
}
}
if config.maximumSelectedVideoCount > 0 {
if selectedVideoAssetArray.count >= config.maximumSelectedVideoCount {
text = String.init(format: "最多只能选择%d个视频".localized, arguments: [config.maximumSelectedVideoCount])
canSelect = false
}
}else {
if selectedAssetArray.count >= config.maximumSelectedCount && config.maximumSelectedCount > 0 {
text = String.init(format: "已达到最大选择数".localized, arguments: [config.maximumSelectedPhotoCount])
canSelect = false
}
}
}
if let shouldSelect = pickerDelegate?.pickerController(
self,
shouldSelectedAsset: photoAsset,
atIndex: selectedAssetArray.count
) {
if canSelect {
canSelect = shouldSelect
}
}
if let text = text, !canSelect, showHUD {
if DispatchQueue.isMain {
ProgressHUD.showWarning(addedTo: view, text: text, animated: true, delayHide: 1.5)
}else {
DispatchQueue.main.async {
ProgressHUD.showWarning(addedTo: self.view, text: text, animated: true, delayHide: 1.5)
}
}
}
return canSelect
}
/// 视频时长是否超过最大限制
/// - Parameter photoAsset: 对应的PhotoAsset对象
func videoDurationExceedsTheLimit(photoAsset: PhotoAsset) -> Bool {
if photoAsset.mediaType == .video {
if config.maximumSelectedVideoDuration > 0 {
if round(photoAsset.videoDuration) > Double(config.maximumSelectedVideoDuration) {
return true
}
}
}
return false
}
/// 选择数是否达到最大
func selectArrayIsFull() -> Bool {
if selectedAssetArray.count >= config.maximumSelectedCount && config.maximumSelectedCount > 0 {
return true
}
return false
}
#if HXPICKER_ENABLE_EDITOR
func addedEditedPhotoAsset(_ photoAsset: PhotoAsset) {
if editedPhotoAssetArray.contains(photoAsset) {
return
}
editedPhotoAssetArray.append(photoAsset)
}
func removeAllEditedPhotoAsset() {
if editedPhotoAssetArray.isEmpty {
return
}
for photoAsset in editedPhotoAssetArray {
photoAsset.initialPhotoEdit = nil
photoAsset.initialVideoEdit = nil
}
editedPhotoAssetArray.removeAll()
}
#endif
}
| 35.3875 | 119 | 0.522733 |
878dfa77c8db21839de6422ac0a383428d5e5182 | 2,978 | import Foundation
final class BondedState: BaseStashNextState {
private(set) var ledgerInfo: StakingLedger
private(set) var rewardEstimationAmount: Decimal?
init(
stateMachine: StakingStateMachineProtocol,
commonData: StakingStateCommonData,
stashItem: StashItem,
ledgerInfo: StakingLedger,
totalReward: TotalRewardItem?,
rewardEstimationAmount: Decimal? = nil,
payee: RewardDestinationArg?
) {
self.ledgerInfo = ledgerInfo
self.rewardEstimationAmount = rewardEstimationAmount
super.init(
stateMachine: stateMachine,
commonData: commonData,
stashItem: stashItem,
totalReward: totalReward,
payee: payee
)
}
override func accept(visitor: StakingStateVisitorProtocol) {
visitor.visit(state: self)
}
override func process(rewardEstimationAmount: Decimal?) {
self.rewardEstimationAmount = rewardEstimationAmount
stateMachine?.transit(to: self)
}
override func process(ledgerInfo: StakingLedger?) {
guard let stateMachine = stateMachine else {
return
}
let newState: StakingStateProtocol
if let ledgerInfo = ledgerInfo {
self.ledgerInfo = ledgerInfo
newState = self
} else {
newState = StashState(
stateMachine: stateMachine,
commonData: commonData,
stashItem: stashItem,
ledgerInfo: nil,
totalReward: totalReward
)
}
stateMachine.transit(to: newState)
}
override func process(nomination: Nomination?) {
guard let stateMachine = stateMachine else {
return
}
let newState: StakingStateProtocol
if let nomination = nomination {
newState = NominatorState(
stateMachine: stateMachine,
commonData: commonData,
stashItem: stashItem,
ledgerInfo: ledgerInfo,
nomination: nomination,
totalReward: totalReward,
payee: payee
)
} else {
newState = self
}
stateMachine.transit(to: newState)
}
override func process(validatorPrefs: ValidatorPrefs?) {
guard let stateMachine = stateMachine else {
return
}
let newState: StakingStateProtocol
if let prefs = validatorPrefs {
newState = ValidatorState(
stateMachine: stateMachine,
commonData: commonData,
stashItem: stashItem,
ledgerInfo: ledgerInfo,
prefs: prefs,
totalReward: totalReward,
payee: payee
)
} else {
newState = self
}
stateMachine.transit(to: newState)
}
}
| 26.828829 | 64 | 0.570181 |
22ba8119262f7556aec7500707c4ee6183e76d58 | 506 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "OrderedDictionary",
products: [
.library(
name: "OrderedDictionary",
targets: ["OrderedDictionary"]
)
],
dependencies: [],
targets: [
.target(
name: "OrderedDictionary",
dependencies: []
),
.testTarget(
name: "OrderedDictionaryTests",
dependencies: ["OrderedDictionary"]
)
]
)
| 20.24 | 47 | 0.521739 |
cc2d7e1ef7c8ab4cbde50d9742c69c38c3eebdb8 | 2,081 | //
// HalanButton+Configure.swift
// HalanUIComponents
//
// Created by Moamen Abd Elgawad on 25/01/2022.
//
import UIKit
/// This is the extension used to configure HalanButton.
extension HalanButton {
/**
Configure Halan Button Style
- Parameter buttonSize: Button size whether large = 1, medium = 2 , small = 3.
- Parameter buttonTheme: Button theme whether primary = 1, secondary = 2 , tertiary = 3.
- Parameter background: Button background whether blue = 1, danger = 2.
- Parameter cornerRadius: Button corner radius
- Parameter imageName: Button image name
*/
public func configureButtonStyle(
buttonSize: ButtonSize = .large,
buttonTheme: ButtonTheme = .primary,
buttonBackground: ButtonBackground = .blue,
cornerRadius: CGFloat = 6.0,
imageName: String = ""
) {
size = buttonSize
theme = buttonTheme
background = buttonBackground
self.cornerRadius = cornerRadius
self.imageName = imageName
}
/**
Configure Halan Button Animation
- Parameter animatedScaleWhenHighlighted: Scaling animation when button is highlighted
- Parameter animatedScaleDurationWhenHighlighted: Duration scaling animation when button is highlighted
- Parameter animatedScaleWhenSelected: Scaling animation when button is Selected
- Parameter animatedScaleDurationWhenSelected: Duration scaling animation when button is Selected
*/
public func configureButtonAnimation(
animatedScaleWhenHighlighted: CGFloat = 1.0,
animatedScaleDurationWhenHighlighted: CGFloat = 0.2,
animatedScaleWhenSelected: CGFloat = 1.0,
animatedScaleDurationWhenSelected: CGFloat = 0.2
) {
self.animatedScaleWhenHighlighted = animatedScaleWhenHighlighted
self.animatedScaleDurationWhenHighlighted = animatedScaleDurationWhenHighlighted
self.animatedScaleWhenSelected = animatedScaleWhenSelected
self.animatedScaleDurationWhenSelected = animatedScaleDurationWhenSelected
}
}
| 39.264151 | 108 | 0.716002 |
fbbcd717c1577cec6b435e62e7b82d6fa344050f | 2,141 | //
// DogsViewController.swift
// TareaDogsWithRealm
//
// Created by Local User on 5/27/17.
// Copyright © 2017 Local User. All rights reserved.
//
import UIKit
import RealmSwift
class DogsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dogs : Results<Dog>?
override func viewDidLoad()
{
super.viewDidLoad()
tableView.registerCustomCell(identifier: DogTableViewCell.getTableViewCellIdentifier())
createdAddButton()
self.title = "Perros"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
initializeDogs()
tableView.reloadData()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func initializeDogs()
{
dogs = RealmManager.getAllDogs()
}
func createdAddButton()
{
let addButton = UIBarButtonItem(barButtonSystemItem: .add , target: self, action: #selector(addAction))
navigationItem.rightBarButtonItem = addButton
}
func addAction()
{
let addDogViewController = storyboard!.instantiateViewController(withIdentifier: AddDogViewController.getViewControllerIdentifier())
navigationController?.pushViewController(addDogViewController, animated: true)
}
}
extension DogsViewController : UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
guard let dogs = dogs else
{
return 0
}
return dogs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = (tableView.dequeueReusableCell(withIdentifier: DogTableViewCell.getTableViewCellIdentifier())) as! DogTableViewCell
let dog = dogs![indexPath.row]
cell.setUpCell(dog: dog)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
}
| 25.795181 | 140 | 0.663709 |
0a182b296d6613c5753a3fd5db7ad10efc6faefe | 2,125 | //
// MenuHeader.swift
// uber-clone
//
// Created by Ted Hyeong on 27/10/2020.
//
import UIKit
class MenuHeader: UIView {
// MARK: - Properties
private let user: User
private lazy var profileImageView: UIView = {
let view = UIView()
view.backgroundColor = .darkGray
view.addSubview(initialLabel)
initialLabel.centerX(inView: view)
initialLabel.centerY(inView: view)
return view
}()
private lazy var initialLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 42)
label.textColor = .white
label.text = user.firstInitial
return label
}()
private lazy var fullnameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = .white
label.text = user.fullname
return label
}()
private lazy var emailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = .lightGray
label.text = user.email
return label
}()
// MARK: - Lifecycle
init(user: User, frame: CGRect) {
self.user = user
super.init(frame: frame)
backgroundColor = .backgroundColor
addSubview(profileImageView)
profileImageView.anchor(top: topAnchor, left: leftAnchor, paddingTop: 4, paddingLeft: 12,
width: 64, height: 64)
profileImageView.layer.cornerRadius = 64 / 2
let stack = UIStackView(arrangedSubviews: [fullnameLabel, emailLabel])
stack.distribution = .fillEqually
stack.spacing = 4
stack.axis = .vertical
addSubview(stack)
stack.centerY(inView: profileImageView,
leftAnchor: profileImageView.rightAnchor,
paddingLeft: 12)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Selectors
}
| 26.5625 | 97 | 0.576 |
335d621e4884f2bd3bfacd4a77637ebd2e531351 | 927 | //
// DexLastTradesModuleBuilder.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 8/16/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
struct DexLastTradesModuleBuilder: ModuleBuilderOutput {
weak var output: DexLastTradesModuleOutput?
func build(input: DexTraderContainer.DTO.Pair) -> UIViewController {
var interactor: DexLastTradesInteractorProtocol = DexLastTradesInteractor()
interactor.pair = input
var presenter: DexLastTradesPresenterProtocol = DexLastTradesPresenter()
presenter.interactor = interactor
presenter.moduleOutput = output
presenter.amountAsset = input.amountAsset
presenter.priceAsset = input.priceAsset
let vc = StoryboardScene.Dex.dexLastTradesViewController.instantiate()
vc.presenter = presenter
return vc
}
}
| 28.090909 | 83 | 0.701187 |
2044a3b19a125138e1ba4b4ed2cab542928f0174 | 228 | //
// RouterToPresenterInterface.swift
// Snek
//
// Created by Philip Niedertscheider on 30.01.20.
// Copyright © 2020 Philip Niedertscheider. All rights reserved.
//
public protocol RouterToPresenterInterface: class {
}
| 19 | 65 | 0.741228 |
67c31c00a7664717b3b64d4ef529c05e703ce641 | 1,404 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
import IrohaCrypto
enum DummySigningType {
case sr25519(secretKeyData: Data, publicKeyData: Data)
case ed25519(seed: Data)
case ecdsa(seed: Data)
}
final class DummySigner: SigningWrapperProtocol {
let type: DummySigningType
init(cryptoType: CryptoType, seed: Data = Data(repeating: 1, count: 32)) throws {
switch cryptoType {
case .sr25519:
let keypair = try SNKeyFactory().createKeypair(fromSeed: seed)
type = .sr25519(secretKeyData: keypair.privateKey().rawData(),
publicKeyData: keypair.publicKey().rawData())
case .ed25519:
type = .ed25519(seed: seed)
case .ecdsa:
type = .ecdsa(seed: seed)
}
}
func sign(_ originalData: Data) throws -> IRSignatureProtocol {
switch type {
case .sr25519(let secretKeyData, let publicKeyData):
return try signSr25519(originalData,
secretKeyData: secretKeyData,
publicKeyData: publicKeyData)
case .ed25519(let seed):
return try signEd25519(originalData, secretKey: seed)
case .ecdsa(let seed):
return try signEcdsa(originalData, secretKey: seed)
}
}
}
| 31.2 | 85 | 0.608262 |
fc4f038cebe18e1e3c059dd9239e8f2f56a7e806 | 7,128 | //
// ViewModel.swift
// Audio Source Selector
//
// Created by ASM on 7/28/19.
// Copyright © 2019 ASM. All rights reserved.
//
import Foundation
import AVFoundation
class ViewModel {
//MARK: Properties
let audioSession = AVAudioSession.sharedInstance()
var inputAudioSources = [AudioSource]()
var audioInputPorts: Set<AVAudioSession.Port> {
let inputPorts = inputAudioSources.map{$0.portInfo.description.portType}
return Set(inputPorts)
}
var outputAudioSources = [AudioSource]()
var audioOutputPorts: Set<AVAudioSession.Port> {
let outputPorts = outputAudioSources.map({$0.portInfo.description.portType})
return Set(outputPorts)
}
//In-use audio sources
var currentInput: AudioSource? {
willSet {
if let newAudioSource = newValue {
setInputAudioSource(newAudioSource)
}
} didSet {
previousInput = oldValue
print("\ncurrentInput is: \(String(describing: currentInput)), previousInput is: \(String(describing: previousInput))\n")
}
}
var currentOutput: AudioSource? {
willSet {
if let newAudioSource = newValue {
setOutputAudioSource(newAudioSource)
}
} didSet {
previousOutput = oldValue
print("\ncurrentOutput is: \(String(describing: currentOutput)), previousOutput is: \(String(describing: previousOutput))\n")
}
}
var previousInput: AudioSource?
var previousOutput: AudioSource?
//MARK: Methods
func populateAudioSources(with descriptions: [AVAudioSessionPortDescription]) -> [AudioSource] {
var audioSources = [AudioSource]()
for description in descriptions {
let portInfo = PortInfo(port: description)
if let dataSources = description.dataSources, !dataSources.isEmpty {
for dataSource in dataSources {
audioSources.append(AudioSource(portInfo: portInfo, dataSource: dataSource))
}
} else {
audioSources.append(AudioSource(portInfo: portInfo, dataSource: description.preferredDataSource))
}
}
return audioSources
}
func portThatChanged(among newPorts: [AVAudioSessionPortDescription]) -> AVAudioSessionPortDescription? {
for portDescription in newPorts {
switch (audioInputPorts.contains(portDescription.portType), audioOutputPorts.contains(portDescription.portType)) {
case (true, true):
print("Error! Input and output have the same port type!")
case (true, false): continue
case (false, true): continue
case (false, false): return portDescription
}
}
return nil
}
//MARK: Methods
func updateAudioSessionInfo(withNewInput newInput: AVAudioSessionPortDescription?, newOutput: AVAudioSessionPortDescription?) {
inputAudioSources = populateAudioSources(with: audioSession.availableInputs ?? audioSession.currentRoute.inputs)
outputAudioSources = populateAudioSources(with: audioSession.currentRoute.outputs)
if let newInput = newInput {
print("\nnewInput's data source(s): \(String(describing: newInput.dataSources))\n")
let newInputSources = convert(portDescription: newInput)
print("\nNew input source is: \(newInputSources)\n")
newInputSources.forEach { addInputAudioSource($0) }
currentInput = newInputSources.first
} else {
assignCurrentInputWhenUnplugged()
print("\naudioSession preferred input is: \(String(describing: audioSession.preferredInput))\n")
//TODO: if previousInput is nil, try to load the preferred input from UserDefaults. Otherwise, need to cache previous input of the previous input
}
if let newOutput = newOutput {
let newOutputSources = convert(portDescription: newOutput)
newOutputSources.forEach { addOutputAudioSource($0) }
currentOutput = newOutputSources.first
} else {
assignCurrentOutputWhenUnplugged()
}
// audioSourcesTableView.reloadData()
}
//set system's preferred source
func setInputAudioSource(_ audioSource: AudioSource) {
do {
try audioSession.setPreferredInput(audioSource.portInfo.description)
if let dataSource = audioSource.dataSource {
try audioSession.preferredInput?.setPreferredDataSource(dataSource)
}
} catch let error {
print("\nUnable to set input source: \(error.localizedDescription)\n")
}
}
func setOutputAudioSource(_ audioSource: AudioSource) {
do {
if let dataSource = audioSource.dataSource {
try audioSession.setOutputDataSource(dataSource)
}
} catch let error {
print("\nUnable to set output source: \(error.localizedDescription)\n")
}
}
//Adds non-duplicate input source
func addInputAudioSource(_ audioSource: AudioSource, possibleDataSource: AVAudioSessionDataSourceDescription? = nil) {
print("\nAdding audio source: \(audioSource)\n")
if !inputAudioSources.contains(audioSource) {
print("Adding input audio source")
inputAudioSources.append(audioSource)
}
}
//Adds non-duplicate output source
func addOutputAudioSource(_ audioSource: AudioSource, possibleDataSource: AVAudioSessionDataSourceDescription? = nil) {
if !outputAudioSources.contains(audioSource) {
outputAudioSources.append(audioSource)
}
}
func assignCurrentInputWhenUnplugged() {
if let _currentInput = currentInput {
if !inputAudioSources.contains(_currentInput) {
currentInput = previousInput
}
}
}
func assignCurrentOutputWhenUnplugged() {
if let _currentInput = currentInput {
if !inputAudioSources.contains(_currentInput) {
currentOutput = previousOutput
}
}
}
//use this to add source that changed (from notification) to array of AudioSources
func convert(portDescription: AVAudioSessionPortDescription) -> [AudioSource] {
var convertedAudioSources = [AudioSource]()
if let dataSources = portDescription.dataSources, !dataSources.isEmpty {
for dataSource in dataSources {
let audioSource = AudioSource(portInfo: PortInfo(port: portDescription), dataSource: dataSource)
convertedAudioSources.append(audioSource)
}
return convertedAudioSources
}
let audioSource = AudioSource(portInfo: PortInfo(port: portDescription), dataSource: nil)
convertedAudioSources.append(audioSource)
print("\nconvertedAudioSources: \(convertedAudioSources)\n")
return convertedAudioSources
}
}
| 39.164835 | 157 | 0.643659 |
1e0c457b34e125663879adbd223a894903251070 | 3,482 | //
// UserManager.swift
// FMIPractice
//
// Created by Spas Bilyarski on 31.10.19.
// Copyright © 2019 bilyarski. All rights reserved.
//
import UIKit
/// Модел за потребител.
struct User {
/// Потребителско име.
let username: String
/// Парола.
let password: String
}
/// Мениджър, който се занимава с регистрацията на нови потребители и тяхното съхранение, както и вход на потребители.
/// Класът е маркиран като `final` за да забраним наследяването.
final class UserManager {
/// Singleton константа за достъп до `UserManager`.
static let shared = UserManager()
/// Имитация на база данни от потребители.
private var users = [User]()
/// Забраняваме инициализацията на обекти от тип `UserManager. Това налага използването на константата `shared`.
private init() { }
}
/// Разширение на `UserManager` съдържащо методите за вход и регистрация.
extension UserManager {
/// Enum от тип `Error`, който ще бъде връщан като резултат от методите за вход и регистрация.
enum UserError: String, Error {
// Няма такъв потребител.
case noSuchUser
// Грешна парола.
case wrongPassword
// Потребителят вече съществува.
case alreadyExists
}
/// Метод за вход приемащ потребителско име, парола и клоужър, който ще ни върне резултат.
func logIn(username: String, password: String, completion: @escaping (Result<User, UserError>) -> Void) {
// Проверяваме дали има съществуващ потребител, като потърсим дали подаденото потребителско име вече съществува в `users` масивът ни.
if let user = users.first(where: { user in user.username == username }) {
// Забавяме резултатът от метода с 2 секунди.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// Проверяваме дали подадената парола съвпада и връщаме съответният резултат.
if user.password != password {
completion(.failure(.wrongPassword))
} else {
completion(.success(user))
}
}
} else {
// Забавяме резултатът от метода с 2 секунди.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// Връщаме грешка за несъществуващ потребител.
completion(.failure(.noSuchUser))
}
}
}
/// Метод за регистрация на потребител приемащ потребителско име, парола и клоужър, който ще ни върне резултат.
func register(username: String, password: String, completion: @escaping (User?) -> Void) {
// Проверяваме дали имаме потребител със същото потребителско име в `users` масива.
if users.contains(where: { user in user.username == username }) {
// Забавяме резултатът от метода с 1 секунда.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// Връщаме празен обект. Вече има потребител с това потребителско име.
completion(nil)
}
} else {
// Няма такъв потребител в масива и можем да го създадем.
let newUser = User(username: username, password: password)
// Добавяме го в "базата данни".
users.append(newUser)
// Връщаме новосъздаденият потребител като резултат от метода.
completion(newUser)
}
}
}
| 35.896907 | 141 | 0.612292 |
1e9641d783b949c4f801ee205f7dc7509cc5a6f3 | 13,083 | //
// TestsViewController.swift
//
// Created by Edwin Vermeer on 25-07-14.
// Copyright (c) 2014 EVICT BV. All rights reserved.
//
import CloudKit
import EVCloudKitDao
import EVReflection
class TestObject: NSObject {
var objectValue: String = ""
}
class TestsViewController: UIViewController {
var dao: EVCloudKitDao = EVCloudKitDao.publicDB
var userId: String = ""
var createdId = "";
@IBAction func runTest(_ sender: AnyObject) {
conflictTest()
getUserInfoTest() // will set the self.userId
ingnoreFieldTest()
subObjectTest()
removeAllSubscriptionsTest()
getAllContactsTest()
saveObjectsTest() // will set the self.createdId
saveAndDeleteTest()
queryRecordsTest()
subscriptionsTest()
deleteTest()
connectTest()
alternateContainerTest()
}
func conflictTest() {
let message = Message()
message.recordID = CKRecordID(recordName: "We use this twice")
message.Text = "This is the message text"
let message2 = Message()
message2.recordID = CKRecordID(recordName: "We use this twice")
message2.Text = "This is an other message text"
self.dao.saveItem(message, completionHandler: {record in
EVLog("saveItem Message: \(record.recordID.recordName)");
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message \(error)");
})
self.dao.saveItem(message, completionHandler: {record in
EVLog("saveItem Message: \(record.recordID.recordName)");
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message \(error)");
})
}
func getUserInfoTest() {
// retrieve our CloudKit user id. (made syncronous for this demo)
let sema = DispatchSemaphore(value: 0)
dao.discoverUserInfo({ (user) -> Void in
if #available(iOS 10.0, *) {
self.userId = (user as! CKUserIdentity).userRecordID?.recordName ?? ""
} else {
self.userId = (user as! CKDiscoveredUserInfo).userRecordID?.recordName ?? ""
}
EVLog("discoverUserInfo : \(showNameFor(user))");
sema.signal();
}) { (error) -> Void in
EVLog("<--- ERROR in getUserInfo");
sema.signal();
}
let _ = sema.wait(timeout: DispatchTime.distantFuture);
// Must be loged in to iCloud
if userId.isEmpty {
EVLog("You have to log in to your iCloud account. Open the Settings app, Go to iCloud and sign in with your account")
return
}
}
func removeAllSubscriptionsTest() {
dao.unsubscribeAll({ subscriptionCount in
EVLog("unsubscribeAll removed \(subscriptionCount) subscriptions");
}, errorHandler: { error in
EVLog("<--- ERROR in unsubscribeAll");
})
}
func getAllContactsTest() {
// Look who of our contact is also using this app.
// the To for the test message will be the last contact in the list
let sema = DispatchSemaphore(value: 0)
dao.allContactsUserInfo({ users in
EVLog("AllContactUserInfo count = \(users?.count ?? 0)");
for user in users! {
EVLog("\(showNameFor(user))")
}
sema.signal();
}, errorHandler: { error in
EVLog("<-- ERROR in allContactsUserInfo : \(error.localizedDescription)")
sema.signal();
})
let _ = sema.wait(timeout: DispatchTime.distantFuture);
}
func saveObjectsTest() {
let userIdTo: String = userId
// New message
let message = Message()
message.From = dao.referenceForId(userId)
message.To = dao.referenceForId(userIdTo)
message.Text = "This is the message text"
message.MessageType = MessageTypeEnum.Picture.rawValue
// The attachment
let asset = Asset()
asset.File = CKAsset(fileURL: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "png")!))
asset.FileName = "test"
asset.FileType = "png"
// Save the message
self.dao.saveItem(asset, completionHandler: {record in
EVLog("saveItem Asset: \(record.recordID.recordName)");
// Save the attached image
message.setAssetFields(record.recordID.recordName)
self.dao.saveItem(message, completionHandler: {record in
EVLog("saveItem Message: \(record.recordID.recordName)");
}, errorHandler: {error in
EVLog("<--- ERROR saveItem asset");
})
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message");
})
}
func saveAndDeleteTest() {
let userIdTo: String = userId
let message = Message()
message.setFromFields(userId)
message.setToFields(userIdTo)
message.Text = "This is the message text"
message.MessageType = MessageTypeEnum.Text.rawValue
let sema = DispatchSemaphore(value: 0);
message.MessageType = MessageTypeEnum.Text.rawValue
dao.saveItem(message, completionHandler: {record in
self.createdId = record.recordID.recordName
EVLog("saveItem Message: \(self.createdId)")
sema.signal()
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message")
sema.signal()
})
let _ = sema.wait(timeout: DispatchTime.distantFuture);
// Get the just created data item
dao.getItem(createdId
, completionHandler: { item in
EVLog("getItem: with the keys and values:")
EVReflection.logObject(item)
}, errorHandler: { error in
EVLog("<--- ERROR getItem")
})
}
func queryRecordsTest() {
// Get all records of a recordType
dao.query(Message(), completionHandler: { results, isFinished in
EVLog("query recordType : result count = \(results.count)")
return false
}, errorHandler: { error in
EVLog("<--- ERROR query Message")
})
// Get all user related record of a recordType
dao.query(Message(), referenceRecordName: userId, referenceField:"To"
, completionHandler: { results, isFinished in
EVLog("query recordType reference : result count = \(results.count)")
return false
}, errorHandler: { error in
EVLog("<--- ERROR query Message for user in To")
})
// Get all records of a recordType that are created by me using a predicate
let predicate = NSPredicate(format: "creatorUserRecordID == %@", CKRecordID(recordName: userId))
dao.query(Message(), predicate:predicate, completionHandler: { results, isFinished in
EVLog("query recordType created by: result count = \(results.count)")
return false
}, errorHandler: { error in
EVLog("<--- ERROR query Message created by user")
})
// Get all users containing some words
dao.query(Message(), tokens: "test the", completionHandler: { results, isFinished in
EVLog("query tokens: result count = \(results.count)")
return false
}, errorHandler: { error in
EVLog("<--- ERROR query Message for words")
})
}
func subscriptionsTest() {
// Subscribe for update notifications
dao.subscribe(Message(), configureNotificationInfo:{ notificationInfo in
notificationInfo.alertBody = "New Message record"
notificationInfo.shouldSendContentAvailable = true
}, errorHandler:{ error in
EVLog("<--- ERROR subscribeForRecordType")
})
// Unsubscribe for update notifications
dao.unsubscribe(Message(), errorHandler:{ error in
EVLog("<--- ERROR unsubscribeForRecordType")
})
// Subscribe for update notifications where you are in the To field
dao.subscribe(Message(), referenceRecordName: userId, referenceField:"To", configureNotificationInfo:{ notificationInfo in
notificationInfo.alertBody = "New Message record where To = \(self.userId)"
notificationInfo.shouldSendContentAvailable = true
}, errorHandler: { error in
EVLog("<--- ERROR subscribeForRecordType reference")
})
// Unsubscribe for update notifications where you are in the To field
dao.unsubscribe(Message(), referenceRecordName: userId, referenceField: "To", errorHandler: { error in
EVLog("<--- ERROR subscribeForRecordType reference")
})
}
func deleteTest() {
// Delete the just created data item
dao.deleteItem(self.createdId, completionHandler: { recordId in
EVLog("deleteItem : \(recordId)")
}, errorHandler: {error in
EVLog("<--- ERROR deleteItem")
})
}
func connectTest() {
// Creating a connection to the Message recordType in the public database
EVCloudData.publicDB.connect(Message()
, predicate: NSPredicate(value: true)
, filterId: "Message_all"
, configureNotificationInfo:{ notificationInfo in
notificationInfo.alertBody = "New Message record"
notificationInfo.shouldSendContentAvailable = true
}, completionHandler: { results, isFinished in
EVLog("results = \(results.count)")
return results.count < 200 // Continue reading if we have less than 200 records and if there are more.
}, insertedHandler: { item in
EVLog("inserted \(item)")
}, updatedHandler: { item, index in
EVLog("updated \(item)")
}, deletedHandler: { recordId, index in
EVLog("deleted : \(recordId)")
}, errorHandler: { error in
EVLog("<--- ERROR connect")
})
}
func alternateContainerTest() {
EVLog("===== WARNING : This will fail because you will probably not have this specific container! =====")
let userIdTo: String = userId
let message = Message()
message.From = dao.referenceForId(userId)
message.To = dao.referenceForId(userIdTo)
message.Text = "This is the message text"
message.MessageType = MessageTypeEnum.Text.rawValue
let dao2 = EVCloudKitDao.publicDBForContainer("iCloud.nl.evict.myapp")
dao2.saveItem(message, completionHandler: {record in
self.createdId = record.recordID.recordName;
EVLog("saveItem Message: \(self.createdId)");
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message, you probably need to fix the container id iCloud.nl.evict.myapp");
})
}
func subObjectTest() {
let invoice = Invoice()
invoice.InvoiceNumber = "A123"
invoice.DeliveryAddress = Address()
invoice.DeliveryAddress?.Street = "The street"
invoice.DeliveryAddress?.City = "The city"
invoice.InvoiceAddress = Address()
invoice.InvoiceAddress?.Street = "The invoice street"
invoice.InvoiceAddress?.City = "The invoice city"
invoice.PostalAddress = Address()
invoice.PostalAddress?.Street = "The postal street"
invoice.PostalAddress?.City = "The postal city"
// Save the invoice and wait for it to complete
let sema = DispatchSemaphore(value: 0);
self.dao.saveItem(invoice, completionHandler: {record in
EVLog("saveItem Invoice: \(record.recordID.recordName)");
sema.signal();
}, errorHandler: {error in
EVLog("<--- ERROR saveItem message");
sema.signal();
})
let _ = sema.wait(timeout: DispatchTime.distantFuture);
// Now see if we can query the invoice
// Get all records of a recordType
dao.query(Invoice(), completionHandler: { results, isFinished in
EVLog("query Invoice : result count = \(results.count), results = \(results)")
return false
}, errorHandler: { error in
EVLog("<--- ERROR query Invoice")
})
}
func ingnoreFieldTest() {
let myObj = testObject()
myObj.saveString = "save this"
myObj.ignoreString = "Forget about this"
let record = myObj.toCKRecord()
EVLog("record from object: \(record)")
}
}
open class testObject: CKDataObject {
fileprivate var ignoreString: String = ""
var saveString: String = ""
override open func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] {
return [("ignoreString", nil)]
}
}
| 37.273504 | 130 | 0.592754 |
8a5255e3c1c26852e5d682d29a89e5af3343c6d3 | 6,561 | // ZHRefreshStateHeader.swift
// Refresh
//
// Created by SummerHF on 27/04/2018.
//
//
// Copyright (c) 2018 SummerHF(https://github.com/summerhf)
//
// 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
typealias lastUpdatedTimeTextBlock = (Date) -> String
/// 带有状态文字的下拉刷新控件
class ZHRefreshStateHeader: ZHRefreshHeader {
// MARK: - 刷新时间相关
var lastUpdatedTimeTextBlcok: lastUpdatedTimeTextBlock?
private var _lastUpdatedTimeLable: UILabel?
/// 显示上一次刷新时间的lable
var lastUpdatedTimeLable: UILabel! {
if _lastUpdatedTimeLable == nil {
_lastUpdatedTimeLable = UILabel.zh_lable()
self.addSubview(_lastUpdatedTimeLable!)
}
return _lastUpdatedTimeLable
}
/// 显示刷新状态的lable
private var _stateLable: UILabel?
var stateLable: UILabel! {
if _stateLable == nil {
_stateLable = UILabel.zh_lable()
self.addSubview(_stateLable!)
}
return _stateLable
}
// MARK: - 状态相关
/// 文字距离圈圈, 箭头的距离
var lableLeftInset: CGFloat = 0.0
/// 所有状态对应的文字
private var stateTitles: [ZHRefreshState: String] = [ZHRefreshState: String]()
/// 设置state状态下的文字
func set(title: String?, for state: ZHRefreshState) {
if title == nil { return }
self.stateTitles[state] = title
self.stateLable.text = self.stateTitles[state]
}
// MARK: - Key的处理
override var lastUpdatedTimeKey: String {
didSet {
super.lastUpdatedTimeKey = lastUpdatedTimeKey
if self.lastUpdatedTimeLable.isHidden { return }
if let time = self.lastUpdatedTime {
/// 如果有block, 回调blcok并且return
if let lastUpdatedTextBlock = self.lastUpdatedTimeTextBlcok {
self.lastUpdatedTimeLable.text = lastUpdatedTextBlock(time)
return
}
let calendar = currentCalendar()
/// 存储的时间
let cmp1 = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: time)
/// 当前时间
let cmp2 = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: Date())
/// 格式化日期
let formatter = DateFormatter()
var isToday = false
/// 今天
if cmp1.day == cmp2.day {
formatter.dateFormat = " HH:mm"
isToday = true
} else if cmp1.year == cmp2.year {
/// 今年
formatter.dateFormat = "MM-dd HH:mm"
} else {
formatter.dateFormat = "yyyy-MM-dd HH:mm"
}
let timeStr = formatter.string(from: time)
printf(timeStr)
printf(isToday)
/// 显示日期
let desc: String = isToday ? Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerDateTodayText) : ""
self.lastUpdatedTimeLable.text = String(format: "%@%@%@", arguments: [Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerLastTimeText), desc, timeStr])
} else {
self.lastUpdatedTimeLable.text = String(format: "%@%@", arguments: [Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerLastTimeText), Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerNoneLastDateText)])
}
}
}
// MARK: - 日历获取方法
func currentCalendar() -> Calendar {
return Calendar.current
}
// MARK: - 重写父类的方法
override func prepare() {
super.prepare()
self.lableLeftInset = ZHRefreshKeys.lableLeftInset
self.set(title: Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerIdleText), for: .idle)
self.set(title: Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerPullingText), for: .pulling)
self.set(title: Bundle.zh_localizedString(forKey: ZHRefreshKeys.headerRefreshingText), for: .refreshing)
}
override func placeSubViews() {
super.placeSubViews()
if self.stateLable.isHidden { return }
let noConstraintOnStatusLable: Bool = self.stateLable.constraints.count == 0
if self.lastUpdatedTimeLable.isHidden {
/// 状态
if noConstraintOnStatusLable {
self.stateLable.frame = self.bounds
}
} else {
let stateLableH: CGFloat = self.zh_h * 0.5
/// 状态
if noConstraintOnStatusLable {
self.stateLable.zh_x = 0
self.stateLable.zh_y = 0
self.stateLable.zh_w = self.zh_w
self.stateLable.zh_h = stateLableH
}
/// 更新时间
if self.lastUpdatedTimeLable.constraints.count == 0 {
self.lastUpdatedTimeLable.zh_x = 0
self.lastUpdatedTimeLable.zh_y = stateLableH
self.lastUpdatedTimeLable.zh_w = self.zh_w
self.lastUpdatedTimeLable.zh_h = self.zh_h - stateLableH
}
}
}
override var state: ZHRefreshState {
/// check date
get {
return super.state
}
set {
guard check(newState: newValue, oldState: state) != nil else { return }
super.state = newValue
/// 设置状态文字
self.stateLable.text = self.stateTitles[newValue]
/// 重新设置key(重新显示时间)
self.lastUpdatedTimeKey = ZHRefreshKeys.headerLastUpdatedTimeKey
}
}
}
| 37.706897 | 226 | 0.608749 |
e429c9ba88080037cc108136a03471caaf2ed5f6 | 778 | //
// DQStatuses.swift
// SinaWeibo
//
// Created by admin on 2016/9/27.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
import YYModel
class DQStatuses: NSObject, YYModel {
//微博ID
var id: Int = 0
var text: String?
var created_at: String?
var source: String?
var user: DQUser?
var pic_urls: [DQStatusPictureInfo]?
//转发的数量
var reposts_count: Int = 0
//评论的数量
var comments_count: Int = 0
//点赞的数量
var attitudes_count: Int = 0
//转发微博
var retweeted_status: DQStatuses?
//实际上是告诉YYModel在转换字典数组的时候 需要将字典转成什么类型的模型对象
static func modelContainerPropertyGenericClass() -> [String : Any]? {
return ["pic_urls" : DQStatusPictureInfo.self]
}
}
| 18.093023 | 73 | 0.624679 |
762173ac010664f56917731fe33a570dd2cdf4f6 | 281 | //
// Comments.swift
// mArtian
//
// Created by Goran Obarcanin on 07/06/2020.
// Copyright © 2020 MartianAndMAchine. All rights reserved.
//
struct Comment: ApiParameter {
let postId: Int
let id: Int
let name: String
let email: String
let body: String
}
| 17.5625 | 60 | 0.658363 |
5d3ff9f02740dbf8ae8ab78b8bcc0deda83d17e7 | 1,142 | //
// ViewController.swift
// TipCalculator
//
// Created by Shrijan Aryal on २०१८-०८-२३.
// Copyright © २०१८ Shrijan Aryal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var tipPercent: UISegmentedControl!
@IBOutlet weak var billText: UITextField!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
let tipArray = [0.18,0.2,0.25]
let bill = Double(billText.text!) ?? 0
let tip = tipArray[tipPercent.selectedSegmentIndex]*bill
let total = bill + tip
tipLabel.text = String(format: "$%.2f",tip)
totalLabel.text = String(format: "$%.2f",total)
}
}
| 25.954545 | 80 | 0.644483 |
3350ff6785c80e419d9744224be8a2f90855f24c | 7,174 | //
// APIManager.swift
// twitter_alamofire_demo
//
// Created by Charles Hieger on 4/4/17.
// Copyright © 2017 Charles Hieger. All rights reserved.
//
import Foundation
import Alamofire
import OAuthSwift
import OAuthSwiftAlamofire
import KeychainAccess
class APIManager: SessionManager {
// MARK: TODO: Add App Keys
static let consumerKey = "LoAfQC7lA4VfXMkWpymJU2SyO"
static let consumerSecret = "OmBIzWdbLVstp6hZtPXutNOrTscLo7qGtThwFXPJP8JFmOciEN"
static let requestTokenURL = "https://api.twitter.com/oauth/request_token"
static let authorizeURL = "https://api.twitter.com/oauth/authorize"
static let accessTokenURL = "https://api.twitter.com/oauth/access_token"
static let callbackURLString = "alamoTwitter://"
// MARK: Twitter API methods
func login(success: @escaping () -> (), failure: @escaping (Error?) -> ()) {
// Add callback url to open app when returning from Twitter login on web
let callbackURL = URL(string: APIManager.callbackURLString)!
oauthManager.authorize(withCallbackURL: callbackURL, success: { (credential, _response, parameters) in
// Save Oauth tokens
self.save(credential: credential)
self.getCurrentAccount(completion: { (user, error) in
if let error = error {
failure(error)
} else if let user = user {
print("Welcome \(user.name)")
// MARK: TODO: set User.current, so that it's persisted
success()
}
})
}) { (error) in
failure(error)
}
}
func logout() {
clearCredentials()
// TODO: Clear current user by setting it to nil
NotificationCenter.default.post(name: NSNotification.Name("didLogout"), object: nil)
}
func getCurrentAccount(completion: @escaping (User?, Error?) -> ()) {
request(URL(string: "https://api.twitter.com/1.1/account/verify_credentials.json")!)
.validate()
.responseJSON { response in
switch response.result {
case .failure(let error):
completion(nil, error)
break;
case .success:
guard let userDictionary = response.result.value as? [String: Any] else {
completion(nil, JSONError.parsing("Unable to create user dictionary"))
return
}
completion(User(dictionary: userDictionary), nil)
}
}
}
func getHomeTimeLine(completion: @escaping ([Tweet]?, Error?) -> ()) {
// This uses tweets from disk to avoid hitting rate limit. Comment out if you want fresh
// tweets,
if let data = UserDefaults.standard.object(forKey: "hometimeline_tweets") as? Data {
let tweetDictionaries = NSKeyedUnarchiver.unarchiveObject(with: data) as! [[String: Any]]
let tweets = tweetDictionaries.flatMap({ (dictionary) -> Tweet in
Tweet(dictionary: dictionary)
})
completion(tweets, nil)
return
}
request(URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")!, method: .get)
.validate()
.responseJSON { (response) in
switch response.result {
case .failure(let error):
completion(nil, error)
return
case .success:
guard let tweetDictionaries = response.result.value as? [[String: Any]] else {
print("Failed to parse tweets")
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Failed to parse tweets"])
completion(nil, error)
return
}
let data = NSKeyedArchiver.archivedData(withRootObject: tweetDictionaries)
UserDefaults.standard.set(data, forKey: "hometimeline_tweets")
UserDefaults.standard.synchronize()
let tweets = tweetDictionaries.flatMap({ (dictionary) -> Tweet in
Tweet(dictionary: dictionary)
})
completion(tweets, nil)
}
}
}
// MARK: TODO: Favorite a Tweet
// MARK: TODO: Un-Favorite a Tweet
// MARK: TODO: Retweet
// MARK: TODO: Un-Retweet
// MARK: TODO: Compose Tweet
// MARK: TODO: Get User Timeline
//--------------------------------------------------------------------------------//
//MARK: OAuth
static var shared: APIManager = APIManager()
var oauthManager: OAuth1Swift!
// Private init for singleton only
private init() {
super.init()
// Create an instance of OAuth1Swift with credentials and oauth endpoints
oauthManager = OAuth1Swift(
consumerKey: APIManager.consumerKey,
consumerSecret: APIManager.consumerSecret,
requestTokenUrl: APIManager.requestTokenURL,
authorizeUrl: APIManager.authorizeURL,
accessTokenUrl: APIManager.accessTokenURL
)
// Retrieve access token from keychain if it exists
if let credential = retrieveCredentials() {
oauthManager.client.credential.oauthToken = credential.oauthToken
oauthManager.client.credential.oauthTokenSecret = credential.oauthTokenSecret
}
// Assign oauth request adapter to Alamofire SessionManager adapter to sign requests
adapter = oauthManager.requestAdapter
}
// MARK: Handle url
// OAuth Step 3
// Finish oauth process by fetching access token
func handle(url: URL) {
OAuth1Swift.handle(url: url)
}
// MARK: Save Tokens in Keychain
private func save(credential: OAuthSwiftCredential) {
// Store access token in keychain
let keychain = Keychain()
let data = NSKeyedArchiver.archivedData(withRootObject: credential)
keychain[data: "twitter_credentials"] = data
}
// MARK: Retrieve Credentials
private func retrieveCredentials() -> OAuthSwiftCredential? {
let keychain = Keychain()
if let data = keychain[data: "twitter_credentials"] {
let credential = NSKeyedUnarchiver.unarchiveObject(with: data) as! OAuthSwiftCredential
return credential
} else {
return nil
}
}
// MARK: Clear tokens in Keychain
private func clearCredentials() {
// Store access token in keychain
let keychain = Keychain()
do {
try keychain.remove("twitter_credentials")
} catch let error {
print("error: \(error)")
}
}
}
enum JSONError: Error {
case parsing(String)
}
| 34.657005 | 130 | 0.566769 |
14f8ff801e2129848ecac3e68f0c990a1d796660 | 889 | //
// PPrime.swift
// EquationFramework
//
// Created by Kristaps Brēmers on 24.04.19.
// Copyright © 2019. g. Chili. All rights reserved.
//
public protocol PPrime {
func checkPrime(number: Int, with completionHandler: @escaping (Bool) -> Void)
}
extension PPrime {
/// dslkmsldflds
///
/// - Parameters:
/// - number: lklkds
/// - completionHandler: kds
public func checkPrime(number: Int, with completionHandler: @escaping (Bool) -> Void) {
if number <= 1 {
completionHandler(false)
return
}
if number == 2 {
completionHandler(true)
return
}
for prime in 2...number - 1 {
if number % prime == 0 {
completionHandler(false)
return
}
}
completionHandler(true)
}
}
| 22.225 | 91 | 0.52306 |
14991f2b052f5966603a425dbc16b03a9d5940b7 | 961 | // Copyright © 2021 Andreas Link. All rights reserved.
import Combine
import Foundation
struct SettingsReducer: BlocReducer {
func reduce(
state: inout SettingsState,
action: SettingsAction,
environment: SettingsEnvironment
) -> Effect<SettingsAction, Never> {
switch action {
case .readIsAutomaticFetchEnabled:
state.isAutomaticFetchEnabled = environment.settingsDataSource.isAutomaticFetchEnabled
return .none
case .readToken:
state.token = environment.settingsDataSource.token
return .none
case let .didChangeIsAutomaticFetchEnabled(value):
environment.settingsDataSource.isAutomaticFetchEnabled = value
return Effect(value: .readIsAutomaticFetchEnabled)
case let .didChangeToken(value):
environment.settingsDataSource.token = value
return Effect(value: .readToken)
}
}
}
| 31 | 98 | 0.672216 |
e009151158f83ffe54f6875b949b147bdbd97d85 | 2,009 | import Foundation
import Combine
import SwiftUI
class ArtistSearchViewModel: ObservableObject {
// MARK: - Inner Types
enum ViewState {
case empty(text: String, action: (() -> Void)?)
case data(itemViewModels: [ArtistSearchItemViewModel])
}
// MARK: - Properties
// MARK: Immutable
private let networkKit: NetworkKitType
// MARK: Mutable
private var cancellables = Set<AnyCancellable>()
// MARK: Published
@Published private(set) var viewState: ViewState = .empty(text: "Search your favourite artists", action: nil)
@Published var searchText: String = ""
// MARK: - Initializers
init(networkKit: NetworkKitType) {
self.networkKit = networkKit
start()
}
// MARK: - Setups
func start() {
$searchText.debounce(for: .seconds(1), scheduler: DispatchQueue.main)
.filter { !$0.isEmpty }
.flatMap { [unowned self] in self.networkKit.searchArtists(searchKeyword: String($0)) }
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
switch completion {
case .failure(let error):
self?.viewState = ViewState.empty(text: "Network failed") {
self?.start()
}
print(error)
case .finished:
break
}
},
receiveValue: { [weak self] in self?.handleResponse($0) }
)
.store(in: &cancellables)
}
// MARK: - Helpers
// MARK: Handlers
private func handleResponse(_ response: ArtistSearchResponse) {
let itemViewModels = response.artists
.filter { $0.name != "(null)" && !$0.mbid.isEmpty }
.map { ArtistSearchItemViewModel(artist: $0) }
viewState = ViewState.data(itemViewModels: itemViewModels)
}
}
| 29.115942 | 113 | 0.554505 |
76a8e0a891461c0b9878dbdca8c78953a725860f | 710 | //
// RootNavigationViewController.swift
// BookOfDestiny
//
// Created by 王嘉宁 on 2019/4/18.
// Copyright © 2019 王嘉宁. All rights reserved.
//
import UIKit
class RootNavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.903226 | 106 | 0.677465 |
4bb334908567a2aaa962719d26f9290594c9181b | 1,177 | //
// IntentHandler.swift
// IkachanIntents
//
// Created by Sketch on 2021/2/2.
//
import Intents
class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
if intent is ScheduleIntent {
return ScheduleIntentHandler()
} else if intent is ShiftIntent {
return ShiftIntentHandler()
} else {
return self
}
}
static func gameModeConvertTo(gameMode: GameMode) -> Schedule.GameMode {
switch gameMode {
case .regular, .unknown:
return .regular
case .gachi:
return .gachi
case .league:
return .league
}
}
static func gameModeConvertFrom(gameMode: Schedule.GameMode) -> GameMode {
switch gameMode {
case .regular:
return .regular
case .gachi:
return .gachi
case .league:
return .league
}
}
static func rotationConvertTo(rotation: Rotation) -> Int {
switch rotation {
case .current, .unknown:
return 0
case .next:
return 1
}
}
}
| 22.634615 | 78 | 0.541206 |
ac21562c0cc3d510547ab60ad75151b9c02bedbc | 1,130 | //
// main.swift
// ModelSynchro
//
// Created by Jonathan Samudio on 11/27/17.
// Copyright © 2017 Jonathan Samudio. All rights reserved.
//
import Foundation
import ModelSynchroLibrary
print("############### ModelSynchro v0.3.0 ###############")
guard let config = ConfigurationParser().configFile else {
CommandError.configFile.displayError()
exit(1)
}
let modelParser = ModelParser(config: config)
let jsonParser = JsonParser(config: config, currentModels: modelParser.customComponents)
print("Fetching JSON...")
let requester = NetworkRequester(config: config, jsonParser: jsonParser)
requester.generateModels()
if config.containsLocalDirectory {
print("Parsing Local Files")
let localJSONParser = LocalJSONParser(config: config, jsonParser: jsonParser)
localJSONParser.parseLocalJSON()
}
if config.containsOutputApiDirectory {
print("Parsing API Template Files")
let templateParser = StencilParser(config: config, urlModelDict: jsonParser.urlModelDict)
templateParser.generateAPI()
}
print("Models Generated!")
print("############### ModelSynchro v0.3.0 ###############")
exit(0)
| 27.560976 | 93 | 0.719469 |
23980817f6736b3b7793a7ef2716255381dad9f2 | 1,255 | //
// AnchorGroup.swift
// DYZB
//
// Created by Jacksun on 2019/4/12.
// Copyright © 2019 Jacksun. All rights reserved.
//
import UIKit
@objcMembers class AnchorGroup: NSObject {
//显示的房间信息
var room_list : [[String : NSObject]]? {
didSet {
guard let room_list = room_list else {
return
}
for dict in room_list {
anchors.append(AnchorModel(dict: dict))
}
}
}
//显示的标题
var tag_name : String = ""
//显示的图标
var icon_name : String = "home_header_normal"
//添加游戏对应的图标
var icon_url : String = ""
//定义主播的模型对象数组
lazy var anchors : [AnchorModel] = [AnchorModel]()
override init() {
}
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
// override func setValue(_ value: Any?, forKey key: String) {
// if key == "room_list" {
// if let dataArray = value as? [[String: NSObject]] {
// for dict in dataArray {
// anchors.append(AnchorModel(dict: dict))
// }
// }
// }
// }
}
| 22.818182 | 72 | 0.516335 |
5b2c3b0d2adca6c39f978ef5cf85f2ebc8788fb5 | 922 | /*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
****
# Document Revision History
### June 5, 2017
Updated the playground for Swift 4.0.
### January 24, 2017
Updated the playground for Swift 3.1.
### October 20, 2016
Updated the playground for Swift 3.0.1.
### September 13, 2016
Updated the playground for Swift 3.\
Added [Creating a Generic Collection](Creating%20a%20Generic%20Collection).
### February 22, 2016
Removed the use of `var` from a function declaration in [Understanding Value Semantics](Understanding%20Value%20Semantics).\
Updated the format of [Table of Contents](Table%20of%20Contents).
### January 25, 2016
Updated for Swift 2.2.
### September 16, 2015
Updated for Swift 2.
### June 8, 2015
A new playground document that describes how to use the Swift standard library.
****
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
| 34.148148 | 124 | 0.733189 |
e874dc26995853faa6d3c608ee49b8ecccac6c70 | 198 | func fibonacci(n: Int) -> Int {
if n < 2 {
return n
}
var fibPrev = 1
var fib = 1
for num in 2...n {
(fibPrev, fib) = (fib, fib + fibPrev)
}
return fib
}
| 16.5 | 45 | 0.459596 |
219587162ada86ba83cfb36a26b15ed21643083d | 3,985 |
import Cocoa
// Chapter 1: Expresions, Variables & Constants
/*
Challenge 1: Variables
Declare a constant Int called myAge and set it equal to your age.
Also declare an Int variable called dogs and set it equal to the number of dogs you own.
Then imagine you bought a new puppy and increment the dogs variable by one.
*/
let myAge: Int = 30
var dogs: Int = 3
dogs += 1
/*
Challenge 2: Make it compile
Given the fallowing code:
age: Int = 16
print(age)
age = 30
print(age)
Modify the first line so that it compiles. Did you use var or let?
*/
var age: Int = 16
print(age)
age = 30
print(age)
/*
Challenge 3: Compute the answer
Consider the following code:
let x: Int = 46
let y: Int = 10
Work out what answer equals when you add the following lines of code:
// 1
let answer1: Int = (x * 100) + y
// 2
let answer2: Int = (x * 100) + (y * 100)
// 3
let answer3: Int = (x * 100) + (y / 10)
My answers:
answer1 == 4610
answer2 == 5600
answer3 == 4601
*/
/*
Challenge 4: Add parentheses
Add as many parentheses to the following calculation, ensuring that it doesn’t change the result of the calculation.
8 - 4 * 2 + 6 / 3 * 4
*/
((8 - (4 * 2)) + ((6 / 3) * 4))
/*
Challenge 5: Average rating
Declare three constants called rating1, rating2 and rating3 of type Double and assign each a value.
Calculate the average of the three and store the result in a constant named averageRating.
*/
let rating1: Double = 4.5
let rating2: Double = 3.0
let rating3: Double = 5.0
let averageRating: Double = (rating1 + rating2 + rating3) / 3
/*
Challenge 6: Electrical power
The power of an electrical appliance is calculated by multiplying the voltage by the current.
Declare a constant named voltage of type Double and assign it a value.
Then declare a constant called current of type Double and assign it a value.
Finally calculate the power of the electrical appliance you’ve just created
storing it in a constant called power of type Double.
*/
let voltage: Double = 230.0
let current: Double = 16.0
let power: Double = voltage * current
/*
Challenge 7: Electrical resistance
The resistance of such an appliance can then be calculated (in a long-winded way)
as the power divided by the current squared.
Calculate the resistance and store it in a constant called resistance of type Double.
*/
let resistance: Double = power / pow(current, 2.0)
/*
Challenge 8: Random integer
You can create a random integer number by using the function arc4random().
This picks a number anywhere between 0 and 4294967295.
You can use the modulo operator to truncate this random number to whatever range you want.
Declare a constant randomNumber and assign it a random number generated with arc4random().
Then calculate a constant called diceRoll and use the random number you just found
to create a random number between 1 and 6.
(Hint: You will need to include the line import Foundation to get access to arc4random().
If this method of creating a random number seems primative, you are right!
There is an easier, more clear and expressive way to generate random numbers
you will learn about in Chapter 4.)
*/
let randomNumber: Int = Int(arc4random())
let diceRoll: Int = randomNumber % 6 + 1
/*
Challenge 9: Quadratic equations
A quadratic equation is something of the form a⋅x² + b⋅x + c = 0.
The values of x which satisfy this can be solved by using the equation x = (-b ± sqrt(b² - 4⋅a⋅c)) / (2⋅a).
Declare three constants named a, b and c of type Double.
Then calculate the two values for x using the equation above
(noting that the ± means plus or minus — so one value of x for each).
Store the results in constants called root1 and root2 of type Double.
*/
let a: Double = 2.0
let b: Double = -1.5
let c: Double = -5.0
let delta: Double = sqrt(pow(b, 2.0) - 4.0 * a * c)
let root1: Double = (-b - delta) / (2.0 * a)
let root2: Double = (-b + delta) / (2.0 * a)
//: [Next](@Chapter 2)
| 26.744966 | 117 | 0.709912 |
eb30116f7785b5d5e5cfa9e8cd5e1aa0a2177a00 | 223 | //
// UIColor.swift
// Rainbow
//
// Created by Alex Zimin on 18/01/16.
// Copyright © 2016 Alex Zimin. All rights reserved.
//
import UIKit
extension UIColor {
var color: Color {
return Color(color: self)
}
} | 14.866667 | 53 | 0.64574 |
9c6be417c053de195f499876d2dfdee754674020 | 992 | //
// UIImage+Resize.swift
// PhotoGallery
//
// Created by Abdullah Bayraktar on 10.05.2020.
// Copyright © 2020 Abdullah Bayraktar. All rights reserved.
//
import UIKit
import Photos
extension UIImage {
func resizeImage(targetSize: CGSize) -> UIImage {
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| 28.342857 | 96 | 0.653226 |
1de67538af511bbd02245cd842ef9e224f0eeeae | 175 | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
// REQUIRES: swift_ast_verifier
{var f={{#^A^#}r
| 35 | 104 | 0.714286 |
fba41b1d1d1b7a8e9689d2cf31598c931cd0635f | 275 | //
// ViewController.swift
// Prework
//
// Created by Scarlett Lin on 9/10/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 13.75 | 58 | 0.643636 |
fc6ecd6adc53fba7db9b27c4d28c6b48b90518f3 | 3,292 | //
// MainTabRewardViewController.swift
// Cosmostation
//
// Created by yongjoo on 05/03/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
import Alamofire
class ValidatorListViewController: BaseViewController {
@IBOutlet weak var chainBg: UIImageView!
@IBOutlet weak var validatorSegment: UISegmentedControl!
@IBOutlet weak var myValidatorView: UIView!
@IBOutlet weak var allValidatorView: UIView!
@IBOutlet weak var otherValidatorView: UIView!
var mainTabVC: MainTabViewController!
@IBAction func switchView(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
myValidatorView.alpha = 1
allValidatorView.alpha = 0
otherValidatorView.alpha = 0
} else if sender.selectedSegmentIndex == 1 {
myValidatorView.alpha = 0
allValidatorView.alpha = 1
otherValidatorView.alpha = 0
} else {
myValidatorView.alpha = 0
allValidatorView.alpha = 0
otherValidatorView.alpha = 1
}
}
override func viewDidLoad() {
super.viewDidLoad()
myValidatorView.alpha = 1
allValidatorView.alpha = 0
otherValidatorView.alpha = 0
mainTabVC = (self.parent)?.parent as? MainTabViewController
chainType = WUtils.getChainType(mainTabVC.mAccount.account_base_chain)
if #available(iOS 13.0, *) {
validatorSegment.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
validatorSegment.setTitleTextAttributes([.foregroundColor: UIColor.gray], for: .normal)
if (chainType == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) {
validatorSegment.selectedSegmentTintColor = TRANS_BG_COLOR_COSMOS2
} else if (chainType == ChainType.SUPPORT_CHAIN_IRIS_MAIN) {
validatorSegment.selectedSegmentTintColor = TRANS_BG_COLOR_IRIS2
} else if (chainType == ChainType.SUPPORT_CHAIN_KAVA_MAIN || chainType == ChainType.SUPPORT_CHAIN_KAVA_TEST) {
validatorSegment.selectedSegmentTintColor = TRANS_BG_COLOR_KAVA2
}
} else {
if (chainType == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) {
validatorSegment.tintColor = COLOR_ATOM
} else if (chainType == ChainType.SUPPORT_CHAIN_IRIS_MAIN) {
validatorSegment.tintColor = COLOR_IRIS
} else if (chainType == ChainType.SUPPORT_CHAIN_KAVA_MAIN || chainType == ChainType.SUPPORT_CHAIN_KAVA_TEST) {
validatorSegment.tintColor = COLOR_KAVA
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
self.navigationController?.navigationBar.topItem?.title = NSLocalizedString("title_validator_list", comment: "");
self.navigationItem.title = NSLocalizedString("title_validator_list", comment: "");
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
}
}
| 40.641975 | 122 | 0.665249 |
09386c17bb08fca7e5e5c80c10d535380c21ecda | 679 | //
// ViewController.swift
// SPDateFormattor
//
// Created by spandey211 on 05/18/2020.
// Copyright (c) 2020 spandey211. All rights reserved.
//
import UIKit
import SPDateFormattor
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let dateParams = Date.getDateComponent()
let diff = Date.differenceBetweenDates()
print(diff)
print(dateParams)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 23.413793 | 80 | 0.674521 |
4aaf59cfa608b7bb552224f8a401f1ed8bda976f | 2,688 | //
// Copyright (c) 2019 Nathan E. Walczak
//
// 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
struct BlackboardViewController {
var className: String
var identifier: String?
var navigationControllerIdentifier: String?
var parameterName: String
var segues: [BlackboardSegue]
var shouldPerformSegues: [BlackboardSegue]
var tableViewCells: [BlackboardTableViewCell]
var collectionViewCells: [BlackboardCollectionViewCell]
}
extension BlackboardViewController {
init?(_ viewController: StoryboardViewController, storyboard: Storyboard, storyboards: [Storyboard]) {
guard let customClass = viewController.customClass else {
return nil
}
className = customClass
identifier = viewController.storyboardIdentifier
navigationControllerIdentifier = storyboard.navigationControllerFor(id: viewController.id)?.storyboardIdentifier
parameterName = customClass.firstCharacterLowercased
segues = viewController.segues
.compactMap { BlackboardSegue($0, storyboard: storyboard, storyboards: storyboards) }
.sorted { $0.name < $1.name }
shouldPerformSegues = segues.filter { $0.shouldPerformFuncName != nil }
tableViewCells = viewController.tableViewCells
.compactMap(BlackboardTableViewCell.init)
.sorted { $0.name < $1.name }
collectionViewCells = viewController.collectionViewCells
.compactMap(BlackboardCollectionViewCell.init)
.sorted { $0.name < $1.name }
}
}
| 38.4 | 120 | 0.71317 |
23002506910b36efde05a2b492375b7041b2f6f5 | 1,930 | //
// ViewController.swift
// TableViewExample
//
// Created by Wi on 18/10/2018.
// Copyright © 2018 Wi. All rights reserved.
//
import UIKit
class ViewController01: UIViewController {
@IBOutlet weak var tableView: UITableView!
var data = Array(1...20)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let refreshControl = UIRefreshControl()
refreshControl.tintColor = .blue
refreshControl.attributedTitle = NSAttributedString(string: "Refreshing")
refreshControl.addTarget(self, action: #selector(reloadData), for: .valueChanged)
tableView.refreshControl = refreshControl
}
@objc func reloadData(){
//수행할 코드
data = data.reversed()
if tableView.refreshControl!.isRefreshing {
tableView.refreshControl?.endRefreshing() //로딩끝내는거
}
tableView.reloadData() //데이타 다시 불러온다
}
}
extension ViewController01: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//미리 셀을 하나 만들어 두는 것 //코드로 했을때
// let cell = tableView.dequeueReusableCell(withIdentifier: <#T##String#>) //옵셔널 이기 떄문에 옵셔널 체크를 해야함
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)//스토리보드로 만들어 놨을때 셀이 무조건 있을때
cell.textLabel?.text = "\(data[indexPath.row])"
// let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
// cell.textLabel?.text = "MyCell"
return cell
}
}
extension ViewController01: UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
}
| 32.166667 | 115 | 0.659585 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.