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
|
---|---|---|---|---|---|
6903043a120143f0cd36d7a28a75f81ddcffa503 | 738 | //
// Customell.swift
// TableViewCellLifeCycle
//
// Created by Wi on 19/10/2018.
// Copyright © 2018 Wi. All rights reserved.
//
import UIKit
class Customell: UITableViewCell {
override func awakeFromNib() {//스토리보드로 할때 로드 될때 호출되는 함수
super.awakeFromNib()
// Initialization code
print("--------awakeFromNit")
}
override func prepareForReuse() {// 셀이 재사용 될때 호출 되는 함수
super.prepareForReuse()
print("--------prepareForReuse")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
deinit {
print("--------deinit")
}
}
| 21.705882 | 65 | 0.600271 |
3aeea3ba676ba73e73d996e088a37a2413d7614e | 2,529 | //
// PostDetailsInteractorTests.swift
// JSONPlaceHolderApp
//
// Created by Iván Díaz Molina on 17/2/21.
// Copyright (c) 2021 IDIAZM. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
@testable import JSONPlaceHolderApp
import XCTest
class PostDetailsInteractorTests: XCTestCase {
// MARK: Subject under test
var sut: PostDetailsInteractor!
// MARK: Test lifecycle
override func setUp() {
super.setUp()
setupPostDetailsInteractor()
}
override func tearDown() {
super.tearDown()
}
// MARK: Test setup
func setupPostDetailsInteractor() {
sut = PostDetailsInteractor()
}
// MARK: Test doubles
class PostDetailsPresentationLogicSpy: PostDetailsPresentationLogic {
var setupViewCalled = false
var displayLoadingCalled = false
var presentCommentsCalled = false
func setupView(response: PostDetails.SetupView.Response) {
setupViewCalled = true
}
func displayLoading(_ show: Bool) {
displayLoadingCalled = true
}
func presentComments() {
presentCommentsCalled = true
}
}
// MARK: Tests
func testSetupView() {
// Given
let spy = PostDetailsPresentationLogicSpy()
sut.presenter = spy
sut.selectedPost = Post()
// When
sut.setupView()
// Then
XCTAssertTrue(spy.setupViewCalled, "setupView should ask the presenter to setupViewCalled")
}
func testGetCommentsCount() {
// Given
let spy = PostDetailsPresentationLogicSpy()
sut.presenter = spy
// When
sut.comments = [Comment(), Comment()]
let count = sut.getCommentsCount()
// Then
XCTAssertEqual(sut.comments?.count, count, "Check if count is equal to array count")
}
func testGetCommentCellFor() {
// Given
let spy = PostDetailsPresentationLogicSpy()
sut.presenter = spy
// When
var comment = Comment()
comment.id = 1
sut.comments = [comment]
let cell = sut.getCommentCellFor(index: 0)
// Then
XCTAssertEqual(cell.comment?.id, 1, "Check if id is equal to 0")
}
}
| 24.794118 | 99 | 0.586793 |
f73cbebff207c78237a1d75edf18406ef0925631 | 1,254 | import XCTest
@testable import Kickstarter_Framework
@testable import Library
@testable import KsApi
import Prelude
internal final class ProfileDataSourceTests: XCTestCase {
let dataSource = ProfileDataSource()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewLayout())
func testDataSource() {
let liveProject = Project.template
let successfulProject = Project.template |> Project.lens.state .~ .successful
let failedProject = Project.template |> Project.lens.state .~ .failed
self.dataSource.load(projects: [liveProject, successfulProject, failedProject])
XCTAssertEqual(3, self.dataSource.collectionView(collectionView, numberOfItemsInSection: 0))
XCTAssertEqual(liveProject, self.dataSource[itemSection: (0, 0)] as? Project)
XCTAssertEqual("ProfileProjectCell", self.dataSource.reusableId(item: 0, section: 0))
XCTAssertEqual(successfulProject, self.dataSource[itemSection: (1, 0)] as? Project)
XCTAssertEqual("ProfileProjectCell", self.dataSource.reusableId(item: 1, section: 0))
XCTAssertEqual(failedProject, self.dataSource[itemSection: (2, 0)] as? Project)
XCTAssertEqual("ProfileProjectCell", self.dataSource.reusableId(item: 2, section: 0))
}
}
| 41.8 | 101 | 0.773525 |
222a4f6cbd51ff927b6595db22b2f7b3ba5b9daf | 5,121 | //
// DayView.swift
// DayView
//
// Created by Naveen Magatala on 1/31/19.
//
public protocol DayViewDelegate: UICollectionViewDelegate { }
open class DayView: UIView, NibLoadable {
@IBOutlet weak public var collectionView: UICollectionView!
@IBOutlet weak public var headerDate: UILabel!
public weak var delegate: DayViewDelegate?
lazy var dateController = DateController.shared
var twentyOneDays: [Date] {
return dateController.twentyOnedays
}
var selectedIndexPath: IndexPath?
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadView()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
collectionView.isPagingEnabled = true
let nib = UINib(nibName: "CollectionViewCell", bundle: Bundle(for: type(of: self)))
collectionView.register(nib, forCellWithReuseIdentifier: "CollectionViewCell")
setupCollectionViewInitialPosition()
}
func setupCollectionViewInitialPosition() {
let firstDayOfWeek = dateController.getFirstDayOfWeek()
let today = dateController.todayDate
if let scrollItem = twentyOneDays.index(of: firstDayOfWeek) {
let scrollIndexpath = IndexPath(row: scrollItem, section: 0)
DispatchQueue.main.async { [weak self] in
self?.collectionView.scrollToItem(at: scrollIndexpath, at: .left, animated: true)
}
}
if let selectionRow = twentyOneDays.index(of: today) {
let selectionIndexpath = IndexPath(row: selectionRow, section: 0)
highlightSelectedCell(selectionIndexpath)
}
}
}
extension DayView: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return twentyOneDays.count
}
public func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell",
for: indexPath) as? CollectionViewCell
else { fatalError("CollectionViewCell") }
cell.dayLabel.text = twentyOneDays[indexPath.row].shortday
cell.background.backgroundColor = indexPath == selectedIndexPath ? .lightGray : .clear
return cell
}
}
extension DayView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if indexPath.row == twentyOneDays.count - 6 {
dateController.fetchNextWeek()
DispatchQueue.main.async {
collectionView.reloadData()
}
}
delegate?.collectionView?(collectionView, willDisplay: cell, forItemAt: indexPath)
}
public func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
highlightSelectedCell(indexPath)
delegate?.collectionView?(collectionView, didSelectItemAt: indexPath)
}
func highlightSelectedCell(_ indexPath: IndexPath) {
selectedIndexPath = indexPath
collectionView.reloadData()
headerDate.text = twentyOneDays[indexPath.row].detailedDate
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
if offsetX < 0 {
let beforeContentSize = collectionView.contentSize
dateController.fetchPastWeek()
collectionView.reloadData()
selectedIndexPath = nil
let afterContentSize = collectionView.collectionViewLayout.collectionViewContentSize
let afterContentOffset = collectionView.contentOffset
let newContentOffset = CGPoint(x: afterContentOffset.x + afterContentSize.width - beforeContentSize.width,
y: afterContentOffset.y)
collectionView.contentOffset = newContentOffset
}
delegate?.scrollViewDidScroll?(scrollView)
}
}
extension DayView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/7,
height: collectionView.frame.height)
}
}
extension DayView {
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
delegate?.collectionView?(collectionView, didEndDisplaying: cell, forItemAt: indexPath)
}
}
| 37.379562 | 145 | 0.652802 |
5b9c5d130fbe23d06ff527a06f141ad27c94f8eb | 2,176 | //
// Copyright (c) 19.1.2020 Somia Reality Oy. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
import UIKit
enum ConfirmAction {
case confirm
case cancel
}
protocol ConfirmView where Self:UIView {
typealias OnViewAction = ((ConfirmAction) -> Void)
var onViewAction: OnViewAction? { get set }
var delegate: NINChatSessionInternalDelegate? { get set }
var sessionManager: NINChatSessionManager? { get set }
func showConfirmView(on view: UIView)
func hideConfirmView()
func overrideAssets()
}
final class FadeView: UIView {
var onViewAction: ((ConfirmAction) -> Void)?
}
extension ConfirmView {
func showConfirmView(on view: UIView) {
let fadeView = self.fadeView(on: view)
view.addSubview(fadeView)
fadeView
.fix(leading: (0, view), trailing: (0, view))
.fix(top: (0, view), bottom: (0, view))
view.addSubview(self)
self
.fix(top: (0, view))
.fix(leading: (0, view), trailing: (0, view))
self.transform = CGAffineTransform(translationX: 0, y: -bounds.height)
self.hide(false, withActions: { [weak self] in
fadeView.alpha = 1.0
self?.transform = .identity
})
}
/// Create a "fade" view to fade out the background a bit and constrain it to match the view
private func fadeView(on target: UIView) -> UIView {
let view = FadeView(frame: target.bounds)
view.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
view.onViewAction = self.onViewAction
return view
}
}
extension ConfirmView {
func hideConfirmView() {
let fadeView = self.superview?.subviews.compactMap { $0 as? FadeView }.first
self.hide(true, withActions: { [weak self] in
self?.transform = CGAffineTransform(translationX: 0, y: -(self?.bounds.height ?? 0))
fadeView?.alpha = 0.0
}, andCompletion: { [weak self] in
fadeView?.removeFromSuperview()
self?.removeFromSuperview()
})
}
}
| 30.647887 | 96 | 0.616728 |
756cb1b44ca8177d51554cfc6e5a2b9de81e2164 | 4,403 | //
// YMPush.swift
// YiMai
//
// Created by why on 2016/12/28.
// Copyright © 2016年 why. All rights reserved.
//
import Foundation
class YMNotificationType: NSObject {
static let NewAppointment = "appointment"
static let NewAdmissions = "admissions"
static let NewBroadCast = "radio"
static let AddFriend = "add-friend"
// static let NewAddmission = "NewAddmission"
// static let NewFriendApply = "NewFriend"
// static let YiMaiR1Changed = "YiMaiR1Changed"
}
typealias YMNotificationHandlerFunc = ((UINavigationController, AnyObject, Bool) -> Void)
class YMNotificationHandler: NSObject {
static var HandlerMap: [String: YMNotificationHandlerFunc] = [
YMNotificationType.NewAppointment: YMNotificationHandler.NewAppointment,
YMNotificationType.NewAdmissions: YMNotificationHandler.NewAddmission,
YMNotificationType.NewBroadCast: YMNotificationHandler.NewBroadcast,
YMNotificationType.AddFriend: YMNotificationHandler.AddNewFriend
]
static func AddNewFriend(nav: UINavigationController, data: AnyObject, isAppActive: Bool) {
YMBackgroundRefresh.ShowNewFriendFlag = true
if(!isAppActive) {
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_NEW_FRIEND_NAME)
}
}
static func NewBroadcast(nav: UINavigationController, data: AnyObject, isAppActive: Bool) {
if(!isAppActive) {
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_SYS_BROADCAST)
}
}
static func NewAppointment(nav: UINavigationController, data: AnyObject, isAppActive: Bool) {
if(!isAppActive) {
let realData = data as! [NSObject: AnyObject]
let id = realData["data-id"] as? String
if(nil != id) {
PageAppointmentDetailViewController.AppointmentID = id!
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_APPOINTMENT_DETAIL_NAME)
} else {
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_GET_APPOINMENT_MSG_LIST)
}
}
}
static func NewAddmission(nav: UINavigationController, data: AnyObject, isAppActive: Bool) {
if(!isAppActive) {
let realData = data as! [NSObject: AnyObject]
let id = realData["data-id"] as? String
let status = realData["status"] as? String
if(nil != id) {
if("wait-2" == status) {
PageAppointmentAcceptBodyView.AppointmentID = id!
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_APPOINTMENT_ACCEPT_NAME)
} else {
PageAppointmentProcessingBodyView.AppointmentID = id!
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_APPOINTMENT_PROCESSING_NAME)
}
} else {
PageJumpActions(navController: nav).DoJump(YMCommonStrings.CS_PAGE_GET_ADMISSSION_MSG_LIST)
}
}
}
}
class YMNotification: NSObject {
static func DoLocalNotification(content: String, userData: AnyObject?) {
// let localNotification: UILocalNotification = UILocalNotification()
//
// // 2.设置本地通知的内容
// // 2.1.设置通知发出的时间
// localNotification.fireDate = NSDate() //NSDate(timeInterval: NSDate().timeIntervalSinceNow) //[NSDate dateWithTimeIntervalSinceNow:3.0];
// // 2.2.设置通知的内容
// localNotification.alertBody = content
// // 2.3.设置滑块的文字(锁屏状态下:滑动来“解锁”)
// localNotification.alertAction = "解锁"
// // 2.4.决定alertAction是否生效
// localNotification.hasAction = false
// // 2.5.设置点击通知的启动图片
// localNotification.alertLaunchImage = ""
// // 2.6.设置alertTitle
// localNotification.alertTitle = "医者脉连";
// // 2.7.设置有通知时的音效
//// localNotification.soundName = @"buyao.wav";
// // 2.8.设置应用程序图标右上角的数字
// localNotification.applicationIconBadgeNumber = 1;
//
// // 2.9.设置额外信息
// if(nil != userData) {
// localNotification.userInfo = ["data": userData!]
// } else {
// localNotification.userInfo = ["data": ""]
// }
//
// UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
}
}
| 36.090164 | 146 | 0.642289 |
87108ae9e757eaf8e39d12261ca07847f19c6bbf | 4,958 | //
// NoteObj.swift
// SmartLife-App
//
// Created by thanhlt on 9/7/17.
// Copyright © 2017 thanhlt. All rights reserved.
//
import UIKit
class NoteCommentContentObj: NSObject {
var m_content: String? = nil
var m_image_path: String? = nil
var m_image_size: CGSize? = nil
}
class NoteObj: NSObject {
var m_id:String
var m_note_id:String
var m_title:String
var m_kabocha_building_id:String
var m_area_id:String
var m_jenre_id:String
var m_important:String
var m_public_range:String
var m_jenre:String
var m_comment_count:String
var m_counts_favorite:String
var m_time_stamp:String
var m_created:String
var m_updated:String
var m_disable:String
var m_list_note_comment_content: [NoteCommentContentObj] = []
override init() {
m_id = ""
m_note_id = ""
m_title = ""
m_kabocha_building_id = ""
m_area_id = ""
m_jenre_id = ""
m_important = ""
m_public_range = ""
m_jenre = ""
m_comment_count = ""
m_counts_favorite = ""
m_time_stamp = ""
m_created = ""
m_updated = ""
m_disable = ""
}
init(id:String,title:String, kabocha_building_id:String, area_id:String, jenre_id:String, important:String, public_range:String, jenre:String, comment_count:String, counts_favorite:String, time_stamp:String, created:String, updated:String, disable:String) {
m_id = id
m_note_id = ""
m_title = title
m_kabocha_building_id = kabocha_building_id
m_area_id = area_id
m_jenre_id = jenre_id
m_important = important
m_public_range = public_range
m_jenre = jenre
m_comment_count = comment_count
m_counts_favorite = counts_favorite
m_time_stamp = time_stamp
m_created = created
m_updated = updated
m_disable = disable
}
init(dict:NSDictionary) {
if let id = dict["id"] as? String {
m_id = id
} else {
m_id = ""
}
if let note_id = dict["note_id"] as? String {
m_note_id = note_id
} else {
m_note_id = ""
}
if let title = dict["title"] as? String {
m_title = title
} else {
m_title = ""
}
if let kabocha_building_id = dict["mikata_building_id"] as? String {
m_kabocha_building_id = kabocha_building_id
} else {
m_kabocha_building_id = ""
}
if let area_id = dict["area_id"] as? String {
m_area_id = area_id
} else {
m_area_id = ""
}
if let jenre_id = dict["jenre_id"] as? String {
m_jenre_id = jenre_id
} else {
m_jenre_id = ""
}
if let important = dict["important"] as? String {
m_important = important
} else {
m_important = ""
}
if let public_range = dict["public_range"] as? String {
m_public_range = public_range
} else {
m_public_range = ""
}
if let jenre = dict["jenre"] as? String {
m_jenre = jenre
} else {
m_jenre = ""
}
if let comment_count = dict["comment_count"] as? String {
m_comment_count = comment_count
} else {
m_comment_count = ""
}
if let counts_favorite = dict["counts_favorite"] as? String {
m_counts_favorite = counts_favorite
} else {
m_counts_favorite = ""
}
if let time_stamp = dict["time_stamp"] as? String {
m_time_stamp = time_stamp
} else {
m_time_stamp = ""
}
if let created = dict["created"] as? String {
m_created = created
} else {
m_created = ""
}
if let updated = dict["updated"] as? String {
m_updated = updated
} else {
m_updated = ""
}
if let disable = dict["disable"] as? String {
m_disable = disable
} else {
m_disable = ""
}
if let listContent: NSArray = dict["content"] as? NSArray {
for content in listContent {
if let contentDict: NSDictionary = content as? NSDictionary {
let noteCommentContent: NoteCommentContentObj = NoteCommentContentObj()
noteCommentContent.m_content = contentDict.object(forKey: "content") as? String
noteCommentContent.m_image_path = contentDict.object(forKey: "image_path") as? String
self.m_list_note_comment_content.append(noteCommentContent)
}
}
}
}
}
| 28.011299 | 261 | 0.538927 |
c15143d096ffe9bfdf00fb5711661548755a94ea | 3,260 | // MIT License
//
// Copyright (c) 2016 Spazstik Software, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Load the secrets required for the app
sharedSecrets()
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 throttle down OpenGL ES frame rates. 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 inactive 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:.
}
}
| 50.153846 | 285 | 0.753988 |
3a9b921a853ec09bb7297a5665cf2c52257e266a | 24,722 | //import Foundation
// MARK: - doMove
extension Creature {
enum MovementMode {
case normal
case flee
case maneuvre
case fall
}
enum MovementResult {
case success
case failure
case death
}
func doMove(context: CommandContext) {
let direction: Direction
switch context.subcommand {
case .north: direction = .north
case .east: direction = .east
case .south: direction = .south
case .west: direction = .west
case .up: direction = .up
case .down: direction = .down
default:
assertionFailure()
return
}
let finalDirection = checkSpins(direction: direction)
performMove(direction: finalDirection)
handlePostponedMovement(interactive: true)
}
func performMove(direction: Direction) {
if movementPath.isEmpty {
movementPathInitialRoom = inRoom?.vnum
}
movementPath.append(direction)
}
/*
func performMove(direction: Direction, mode: MovementMode) -> MovementResult {
let (movementResult, warnRooms) = mode == .normal ?
moveWithMountOrRiderAndFollowers(who: self, leader: self, direction: direction) :
moveWithMountOrRiderOnly(who: self, leader: self, direction: direction, mode: mode)
warnRooms.forEach { $0.warnMobiles() }
return movementResult
}
*/
private func checkSpins(direction: Direction) -> Direction {
if !isGodMode() && canGo(direction) {
guard let room = inRoom else { return direction }
if room.flags.contains(.spin) {
return pickRandomDirection(fallback: direction)
} /* else if room.flags.contains(.wilderness) && !orienting() {
return pickRandomDirection(fallback: direction, constrainedTo: Direction.horizontalDirections)
} */
}
return direction
}
private func pickRandomDirection(fallback: Direction, constrainedTo: Set<Direction> = Direction.allDirections) -> Direction {
var chosen: Direction?
for (index, direction) in constrainedTo.enumerated() {
guard canGo(direction) else { continue }
if Random.uniformInt(0...index) == 0 {
chosen = direction
}
}
return chosen ?? fallback
}
/*
// Try to move the character and his mount or rider if any
private func moveWithMountOrRiderOnly(who: Creature, leader: Creature, direction: Direction, mode: MovementMode) -> (result: MovementResult, warnRooms: [Room]) {
guard let needMovement = movementPointsNeededToMove(in: direction, mode: mode) else {
return (result: .failure, warnRooms: [])
}
if let riding = riding, riding.position != .standing {
riding.stand()
}
guard let oldRoom = inRoom else {
return (result: .failure, warnRooms: [])
}
guard let newRoom = oldRoom.exits[direction]?.toRoom() else {
return (result: .failure, warnRooms: [])
}
// if (!entry_mtrigger(ch) ||
// !enter_wtrigger(new_room, ch, dir, mode) ||
// !leave_mtrigger(ch, old_room, dir, mode))
// return WENT_FAILURE;
if oldRoom !== inRoom {
return (result: .failure, warnRooms: [])
}
if level < Level.hero && isPlayer {
movement = movement - needMovement
}
unhide(informRoom: false)
//Тут, до реального перемещения, будут вызваны триггеры
//с установленным MTRIG_BEFORE, и если возвращается 0, то перемещения не будет!
//if (!greet_mtrigger(ch, new_room, dir))
//return WENT_FAILURE;
showLeaveMessage(leader: leader, direction: direction, mode: mode)
teleportTo(room: newRoom)
lookAtRoom(ignoreBrief: false)
if isPlayer ||
(isRiding && riding!.isPlayer) ||
(isRiddenBy && riddenBy!.isPlayer) {
return ( result: .success, warnRooms: inRoom != nil ? [inRoom!] : [] )
}
return ( result: .success, warnRooms: [] )
}
private func moveWithMountOrRiderAndFollowers(who: Creature, leader: Creature, direction: Direction) -> (result: MovementResult, warnRooms: [Room]) {
guard let oldRoom = inRoom else { return (result: .failure, warnRooms: []) }
let (result, initialWarnRooms) = moveWithMountOrRiderOnly(who: who, leader: leader, direction: direction, mode: .normal)
var warnRooms = initialWarnRooms
if result == .success {
warnRooms += moveFollowers(who: who, leader: leader, direction: direction, oldRoom: oldRoom)
if let riding = who.riding {
warnRooms += moveFollowers(who: riding, leader: leader, direction: direction, oldRoom: oldRoom)
}
if let riddenBy = who.riddenBy {
warnRooms += moveFollowers(who: riddenBy, leader: leader, direction: direction, oldRoom: oldRoom)
}
// FIXME
//if who.isPlayer && who.isHunting() {
// do_track(ch, CMDARG_SKIP6, "", 0, SCMD_TCONT, "", "", "");
//}
}
return (result: result, warnRooms: warnRooms)
}
// Returns warnRoom
private func moveFollowers(who: Creature, leader: Creature, direction: Direction, oldRoom: Room) -> [Room] {
return []
}
private func movementPointsNeededToMove(in direction: Direction, mode: MovementMode) -> Int? {
verifyRiderAndMountInSameRoom()
// В случае падения все проверки должны быть сделаны в вызывающей функци
if mode == .fall {
return nil
}
// 1 - проверка возможности покинуть текущую комнату
/* TODO
* когда буду делать заклинание entangle, проверка на него
* должна быть до падения и в случае mode == MOVE_FALL может быть
* стоит выдавать специальное сообщение
* ? а может быть, и его проверять в вызывающей функции ? */
guard !cantLeaveRoom(isMount: false, fear: mode == .flee) else {
return nil
}
guard let inRoom = inRoom,
let exit = inRoom.exits[direction],
let toRoom = exit.toRoom() else {
sendCantGoThereMessage()
return nil
}
if handleClosedDoor(exit: exit) {
return nil
}
if exit.flags.contains(.barOut) {
send("Что-то препятствует Вашему движению в этом направлении.")
return nil
}
let inTerrain = inRoom.terrain
let toTerrain = toRoom.terrain
let isFlying = isAffected(by: .fly)
let isWaterOnlyMobile = mobile?.flags.contains(.waterOnly) ?? false
// 2 - проверка наличия прохода и возможности туда пройти
if !isFlying && isWaterOnlyMobile && !toTerrain.isWater {
send("Вы можете перемещаться только в воде.")
return nil
}
if toTerrain == .waterNoSwim {
if let riding = riding, !riding.isAffected(by: .fly) && !riding.hasBoat() {
act("2и не может везти Вас в этом направлении.", .toCreature(self), .excludingCreature(riding))
return nil
}
else if !isRiding && !isFlying && !hasBoat() {
send("Чтобы передвигаться в этом направлении, Вам необходимо иметь лодку.")
return nil
}
}
//arilou: внимание! для ухода под воду мобу не достаточно флага MOB_WATER_ONLY,
//надо ещё и подводное дыхание - и это правильно, это позоляет делать надводных
//мобов, коорые не выходят на сушу.
if toTerrain == .underwater && !isAffected(by: .waterbreath) && level < Level.lesserGod {
send("Чтобы передвигаться в этом направлении, Вам необходимо уметь дышать под водой.")
return nil
}
if direction == .up && toTerrain == .air {
if let riding = riding, !riding.isAffected(by: .fly) {
act("2и не умеет летать.", .toCreature(self), .excludingCreature(riding))
return nil
}
if !isRiding && !isFlying {
send("Чтобы передвигаться в этом направлении, Вы должны уметь летать.")
return nil
}
}
let isMountable = mobile?.flags.contains(.mountable) ?? false
if let riding = riding { // вообще-то in_sect должен проверяться в другом месте...
if toTerrain == .jungle {
sendNoRideInJungleMessage()
return nil
}
if toTerrain == .tree && !riding.isAffected(by: .fly) {
act("Чтобы везти Вас туда, 2и долж2(ен,на,но) уметь летать.", .toCreature(self), .excludingCreature(riding))
return nil
}
} else if isMountable && toTerrain == .tree && !isFlying {
send("Вы не можете идти в этом направлении.")
return nil
}
if toRoom.flags.contains(.nomount) || toRoom.flags.contains(.indoors) {
if let mobile = mobile, mobile.flags.contains(.mountable) {
send("Вам не разрешено передвигаться в этом направлении.")
return nil
} else if let riding = riding, let ridingMobile = riding.mobile, ridingMobile.flags.contains(.mountable) && level < Level.hero {
act("2и отказывается передвигаться в этом направлении.", .toCreature(self), .excludingCreature(riding))
return nil
}
}
if toRoom.flags.contains(.tunnel) {
if (isRiding || isRiddenBy) && !toRoom.creatures.isEmpty {
act("Вы не помещаетесь туда вместе с 2т.", .toCreature(self), .excludingCreature(isRiding ? riding! : riddenBy!))
return nil
}
let count: Int
if isCharmed() {
count = toRoom.creatures.count(where: { $0 != following })
} else if isPlayer {
count = toRoom.creatures.count(where: { $0.isPlayer })
} else {
count = toRoom.creatures.count
}
if count > 0 {
send("Там не хватает места для двоих.")
return nil
}
}
if let riding = riding, riding.isFighting {
act("2и не может Вас везти, пока не закончит бой!", .toCreature(self), .excludingCreature(riding))
return nil
}
// 3 - подсчёт расхода бодрости
var needMovement = (inTerrain.movementLoss + toTerrain.movementLoss) / 2
if mode == .normal && runtimeFlags.contains(.orienting) {
needMovement += 1
}
if runtimeFlags.contains(.sneaking) || runtimeFlags.contains(.doublecrossing) {
needMovement *= 2
}
switch mode {
case .flee:
needMovement = 3 * needMovement / 2
case .maneuvre:
needMovement = 2 * needMovement
default:
break
}
// arilou:
// при выходе из вроды на поверхность полёт облегчает движение,
// поэтому проверяю только, чтобы подводной не была точка прибытия
if isFlying && toTerrain != .underwater {
let nm = needMovement
needMovement = max(1, needMovement / 3)
if nm > 3 && (nm % 3) != 0 && (nm % 3) > Random.uniformInt(0...2) {
needMovement += 1
}
} else if isRiding {
// arilou: проверка && riding.inRoom == inRoom нам не нужна -
// мы проверяем это в самом начале
needMovement = max(1, needMovement / 2)
}
//FIXME
//arilou: вот тут мы не проверяем специфику того, кто несет,
if let riding = riding, riding.isPlayer && riding.movement < needMovement {
act("2и сильно устал2(,а,о,и), и не может везти Вас дальше.", .toCreature(self), .excludingCreature(riding))
return nil
}
// чтобы "усталость" действовала на мобов - проверяем и у них
if /* isPlayer && */ movement < needMovement {
switch mode {
case .normal:
send("Вы слишком устали.")
case .flee:
send("Вы слишком устали, и не смогли убежать!")
case .maneuvre:
send("Вы слишком устали, и не смогли выполнить маневр!")
default:
break
}
return nil
}
return needMovement
}
private func cantLeaveRoom(isMount: Bool = false, fear: Bool = false) -> Bool {
guard let inRoom = inRoom else { return true }
// Если мы в падении и ничего не изменилось - не ходить никуда
if runtimeFlags.contains(.falling) {
if willFallHere() {
return true
} else {
runtimeFlags.remove(.falling)
}
}
if isHeld() {
if isMount {
if let master = following {
act(spells.message(.holdPerson, "ПАРАЛИЗОВАН"), .excludingCreature(self), .toCreature(master))
}
} else {
act(spells.message(.holdPerson, "ПАРАЛИЧ"), .toSleeping, .toCreature(self))
}
return true
}
let inTerrain = inRoom.terrain
let flying = isAffected(by: .fly)
if inTerrain == .waterNoSwim && !flying && !hasBoat() && !isRiding {
// а если верхом - то достаточно лодки или полёта у mount'а
if isMount {
if let master = following {
act("2и не может увезти Вас отсюда.", .toCreature(master), .excludingCreature(self))
}
} else {
send("Чтобы уйти отсюда, Вам необходимо иметь лодку.")
}
return true
}
if isMount {
if inTerrain == .jungle {
sendNoRideInJungleMessage()
return true
}
} else { // for 'if (mount)'
if let mobile = mobile, mobile.flags.contains(.tethered) {
send("Вы привязаны, и не можете сдвинуться с места.")
return true
}
if !fear && isCharmed(),
let master = following,
let masterInRoom = master.inRoom,
inRoom === masterInRoom {
act(spells.message(.charmPerson, "НЕ_УЙДЕШЬ"), .toCreature(self), .excludingCreature(master))
if runtimeFlags.contains(.order) {
act(spells.message(.charmPerson, "НЕ_УЙДЕТ"), .excludingCreature(self), .toCreature(master))
act(spells.message(.charmPerson, "НЕ_УЙДУ"), .toRoom, .excludingCreature(self), .excludingCreature(master))
}
return true
}
if let riding = riding, riding.cantLeaveRoom(isMount: true) {
return true
}
}
return false
}
private func verifyRiderAndMountInSameRoom() {
if riding != nil && riding!.inRoom !== inRoom {
logError("verifyRiderAndMountInSameRoom: rider '\(nameNominative)' and mount '\(riding!.nameNominative)' are in different rooms")
dismount()
}
if riddenBy != nil && riddenBy!.inRoom !== inRoom {
logError("verifyRiderAndMountInSameRoom: mount '\(nameNominative)' %s and rider '\(riddenBy!.nameNominative)' are in different rooms")
dismount()
}
}
private func unhide(informRoom: Bool) {
if (runtimeFlags.contains(.hiding) || runtimeFlags.contains(.failedHide)) &&
!runtimeFlags.contains(.sneaking) {
runtimeFlags.remove(.hiding)
runtimeFlags.remove(.failedHide)
send("Вы прекратили прятаться.")
if informRoom {
act("1*и прекратил1(,а,о,и) прятаться.", .toRoom, .excludingCreature(self))
}
}
}
private func sneakSuccessful(victim: Creature) -> (success: Bool, victimIsImmune: Bool) {
if !runtimeFlags.contains(.sneaking) {
return (success: false, victimIsImmune: false)
}
if isAffected(by: .senseLife) || (preferenceFlags?.contains(.holylight) ?? false) {
return (success: false, victimIsImmune: true)
}
// let baseSkill = skill_eff_val(ch, SKILL_SNEAK) +
// dex_app_skill[CH_DEX(ch)].sneak +
// ch->level
// let probability = rogueCarryingSkillModifier(baseSkill: baseSkill)
// let percent = Random.uniformInt(1 ... 101 + victim.level)
//
// return probability >= percent
return (success: false, victimIsImmune: false) // FIXME
}
private func showLeaveMessage(leader: Creature, direction: Direction, mode: MovementMode) {
var rider = self
var mount = self
let isMounted = isRiding || isRiddenBy
if let riding = riding {
mount = riding
}
if let riddenBy = riddenBy {
rider = riddenBy
}
guard mode != .fall else {
send("Вы упали вниз!")
act("1и упал1(,а,о,и) вниз.", .toRoom, .excludingCreature(self))
return
}
guard mode == .normal else {
if isMounted {
act("1и с 2т на спине убежал1(,а,о,и) &.", .toRoom, .excludingCreature(rider), .excludingCreature(mount), .text(direction.whereTo))
if let riding = riding {
act("2и быстро убежал2(,а,о,и), унося Вас подальше от боя.", .toCreature(self), .excludingCreature(riding))
} else if let riddenBy = riddenBy {
act("Вы быстро убежали, унося 2в подальше от боя.", .toCreature(self), .excludingCreature(riddenBy))
}
} else if mode == .maneuvre {
// FIXME: isAllowed not checked
let event = inRoom!.override(eventId: .maneuvre)
let toActor = event.toActor ??
"Вы выполнили обманный маневр и убежали &."
let toRoom = event.toRoomExcludingActor ??
"1и выполнил1(,а,о,и) обманный маневр и убежал1(,а,о,и) &."
act(toActor, .toCreature(self), .text(direction.whereTo))
act(toRoom, .toRoom, .excludingCreature(self), .text(direction.whereTo))
} else {
act("1и запаниковал1(,а,о,и) и убежал1(,а,о,и) &.", .toRoom, .excludingCreature(self), .text(direction.whereTo))
send("Вы быстро убежали из боя.")
}
return
}
guard let peopleInRoom = inRoom?.creatures else { return }
// It is possible to merge these two cycles into one, but since this
// function is called very often, it is better to keep them separate.
if isMounted {
let message = "2+и с 3+т на спине \(mount.leavingVerb(2)) &."
for creature in peopleInRoom {
let masterIsMountOrRider = creature.following == mount || creature.following == rider
guard creature.canSee(mount) || creature.canSee(rider) else {
if masterIsMountOrRider {
creature.runtimeFlags.remove(.follow)
}
continue
}
if masterIsMountOrRider {
creature.runtimeFlags.insert(.follow)
}
guard creature != mount && creature != rider else { continue }
let (success, _) = mount.sneakSuccessful(victim: creature)
if !success {
if mount.shouldShowMovement(to: creature, leader: leader) {
act(message, .toCreature(creature), .excludingCreature(mount), .excludingCreature(rider), .text(direction.whereTo))
}
} else if masterIsMountOrRider {
creature.runtimeFlags.remove(.follow)
}
}
} else {
let message = "2*и \(leavingVerb(2)) &."
for creature in peopleInRoom {
let masterIsMountOrRider = creature.following == self
guard creature.canSee(self) else {
if masterIsMountOrRider {
creature.runtimeFlags.remove(.follow)
}
continue
}
if masterIsMountOrRider {
creature.runtimeFlags.insert(.follow)
}
guard creature != self else { continue }
let (success, _) = mount.sneakSuccessful(victim: creature)
if !success {
if shouldShowMovement(to: creature, leader: leader) {
act(message, .toCreature(creature), .excludingCreature(self), .text(direction.whereTo))
} else if masterIsMountOrRider {
creature.runtimeFlags.remove(.follow)
}
}
}
}
}
private func shouldShowMovement(to creature: Creature, leader: Creature) -> Bool {
guard let creaturePreferenceFlags = creature.preferenceFlags else {
// It's mobile not controlled by a player
return true
}
guard creaturePreferenceFlags.contains(.hideTeamMovement) else { return true }
return !isSameTeam(with: creature) ||
self == leader ||
(creature != leader && creature.following != leader)
}
private func arrivalVerb(_ index: Int) -> String {
guard !isAffected(by: .fly) else {
return "прилетел\(index)(,а,о,и)"
}
if let mobile = mobile {
return mobile.movementType.arrivalVerb(index)
} else {
return MovementType.walk.arrivalVerb(index)
}
}
private func leavingVerb(_ index: Int) -> String {
guard !isAffected(by: .fly) else {
return "улетел\(index)(,а,о,и)"
}
if let mobile = mobile {
return mobile.movementType.leavingVerb(index)
} else {
return MovementType.walk.leavingVerb(index)
}
}
private func sendCantGoThereMessage() {
send("Увы, Вы не можете идти в этом направлении.")
}
private func sendNoRideInJungleMessage() {
send("Густые заросли не позволяют проехать верхом.")
}
private func handleClosedDoor(exit: RoomExit) -> Bool {
if exit.flags.contains(.closed) {
if exit.flags.contains(.hidden) {
sendCantGoThereMessage()
} else {
act("&1 закрыт&2.", .toCreature(self), .text(exit.type.nominative), .text(exit.type.adjunctiveEnd))
}
return true
}
return false
}
*/
}
// MARK: - doFollow
extension Creature {
func doFollow(context: CommandContext) {
guard let creature = context.creature1 else {
if let following = following {
act("Вы следуете за 2т.", .toSleeping,
.toCreature(self), .excludingCreature(following))
} else {
send("Вы ни за кем не следуете.")
}
return
}
guard following != creature else {
act("Вы уже следуете за 2т.", .toSleeping,
.toCreature(self), .excludingCreature(creature))
return
}
//guard !isCharmed() else {
// act("Вы хотите следовать только за 2т!", .toSleeping,
// .toCreature(self), .excludingCreature(following))
// return
//}
if creature == self {
if !isFollowing {
send("Вы уже ни за кем не следуете.")
} else {
stopFollowing()
}
} else {
if isFollowing {
stopFollowing()
}
follow(leader: creature, silent: false)
}
}
}
| 38.26935 | 165 | 0.542513 |
eb8b1f6c2d4df24af0469481206baeed5ee7a475 | 4,147 | //
// StoreDispatchTests.swift
// ReSwift
//
// Created by Karl Bowden on 20/07/2016.
// Copyright © 2016 Benjamin Encz. All rights reserved.
//
import XCTest
@testable import ReSwift
class StoreDispatchTests: XCTestCase {
typealias TestSubscriber = TestStoreSubscriber<TestAppState>
typealias CallbackSubscriber = CallbackStoreSubscriber<TestAppState>
var store: Store<TestAppState>!
var reducer: TestReducer!
override func setUp() {
super.setUp()
reducer = TestReducer()
store = Store(reducer: reducer.handleAction, state: TestAppState())
}
/**
it throws an exception when a reducer dispatches an action
*/
func testThrowsExceptionWhenReducersDispatch() {
// Expectation lives in the `DispatchingReducer` class
let reducer = DispatchingReducer()
store = Store(reducer: reducer.handleAction, state: TestAppState())
reducer.store = store
store.dispatch(SetValueAction(10))
}
/**
it accepts action creators
*/
@available(*, deprecated, message: "Deprecated in favor of https://github.com/ReSwift/ReSwift-Thunk")
func testAcceptsActionCreators() {
store.dispatch(SetValueAction(5))
let doubleValueActionCreator: Store<TestAppState>.ActionCreator = { state, store in
return SetValueAction(state.testValue! * 2)
}
store.dispatch(doubleValueActionCreator)
XCTAssertEqual(store.state.testValue, 10)
}
/**
it accepts async action creators
*/
@available(*, deprecated, message: "Deprecated in favor of https://github.com/ReSwift/ReSwift-Thunk")
func testAcceptsAsyncActionCreators() {
let asyncExpectation = futureExpectation(
withDescription: "It accepts async action creators")
let asyncActionCreator: Store<TestAppState>.AsyncActionCreator = { _, _, callback in
dispatchAsync {
// Provide the callback with an action creator
callback { _, _ in
return SetValueAction(5)
}
}
}
let subscriber = CallbackSubscriber { [unowned self] state in
if self.store.state.testValue != nil {
XCTAssertEqual(self.store.state.testValue, 5)
asyncExpectation.fulfill()
}
}
store.subscribe(subscriber)
store.dispatch(asyncActionCreator)
waitForFutureExpectations(withTimeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
/**
it calls the callback once state update from async action is complete
*/
@available(*, deprecated, message: "Deprecated in favor of https://github.com/ReSwift/ReSwift-Thunk")
func testCallsCalbackOnce() {
let asyncExpectation = futureExpectation(withDescription:
"It calls the callback once state update from async action is complete")
let asyncActionCreator: Store<TestAppState>.AsyncActionCreator = { _, _, callback in
dispatchAsync {
// Provide the callback with an action creator
callback { _, _ in
return SetValueAction(5)
}
}
}
store.dispatch(asyncActionCreator) { newState in
XCTAssertEqual(self.store.state.testValue, 5)
if newState.testValue == 5 {
asyncExpectation.fulfill()
}
}
waitForFutureExpectations(withTimeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
}
// Needs to be class so that shared reference can be modified to inject store
class DispatchingReducer: XCTestCase {
var store: Store<TestAppState>?
func handleAction(action: Action, state: TestAppState?) -> TestAppState {
expectFatalError {
self.store?.dispatch(SetValueAction(20))
}
return state ?? TestAppState()
}
}
| 31.9 | 105 | 0.625271 |
09c1ae76936e2279ae9dd7f3ce41fbe87acefef7 | 1,710 | //
// ViewController.swift
// homework_UITableView_200526
//
// Created by 김광수 on 2020/05/26.
// Copyright © 2020 김광수. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate {
var dataArray = Array(1...50)
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
}
func setTableView() {
tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), style: .plain)
tableView.register(CustomCell.self, forCellReuseIdentifier: "CellID")
tableView.rowHeight = 60
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! CustomCell
cell.textLabel?.text = "\(dataArray[indexPath.row])"
cell.plusButton.addTarget(self, action: #selector(tabplusButton), for: .touchUpInside)
return cell
}
@objc func tabplusButton(sender:UIButton) {
if let cell = sender.superview?.superview as? CustomCell,
let row = tableView.indexPath(for: cell)?.row {
let addedNumber = dataArray[row] + 1
dataArray[row] = addedNumber
cell.textLabel?.text = "\(addedNumber)"
}
}
}
| 31.090909 | 135 | 0.652047 |
203e1645cfa2ac91824dd30f221d9decfe48e2c2 | 1,188 | //
// Fonts.swift
// doordeck-sdk-swift
//
// Copyright © 2019 Doordeck. All rights reserved.
//
import Foundation
import UIKit
/// Fonts used by Doordeck
///
/// - doorRegularFont: Regular
/// - doorBoldFont: Bold
/// - doorMediumFont: Medium
/// - doorLightFont: Light
/// - doorCondensedBlackFont: Condensed Black
/// - doorCondensedBoldFont: Condensed Bold
/// - doorLightItalicFont: Light Italic
/// - doorUltraLightItalicFont: Ultra Light Italic
/// - doorUltraLightFont: Ultra Light
/// - doorBoldItalicFont: Bold Italic
/// - doorItalicFont: Italic
enum Fonts: String {
case doorRegularFont = "HelveticaNeue"
case doorBoldFont = "HelveticaNeue-Bold"
case doorMediumFont = "HelveticaNeue-Medium"
case doorLightFont = "HelveticaNeue-Light"
case doorCondensedBlackFont = "HelveticaNeue-CondensedBlack"
case doorCondensedBoldFont = "HelveticaNeue-CondensedBold"
case doorLightItalicFont = "HelveticaNeue-LightItalic"
case doorUltraLightItalicFont = "HelveticaNeue-UltraLightItalic"
case doorUltraLightFont = "HelveticaNeue-UltraLight"
case doorBoldItalicFont = "HelveticaNeue-BoldItalic"
case doorItalicFont = "HelveticaNeue-Italic"
}
| 32.108108 | 68 | 0.748316 |
6431349b33ca2023e84319c8d12a9b904e48ab2b | 1,672 | //
// Package.swift
// Backtrack
//
// Created by ggl on 2020/8/21.
// Copyright © 2020 ggl. All rights reserved.
// 0-1背包问题(回溯算法)
import Foundation
/** 问题描述
* 我们有一个背包,背包总的承载重量是 Wkg。
* 现在我们有 n 个物品,每个物品的重量不等,并且不可分割。我们现在期望选择几件物品,装载到背包中。
* 在不超过背包所能装载重量的前提下,如何让背包中物品的总重量最大?
*
*/
// 存储背包中物品总重量的最大值
private var maxW = Int.min
// 最终存储的物品数组
private var finalItems = [Int]()
// 递归过程中的物品数组
private var resultItems = [Int]()
/// 0-1背包问题求解
///
/// - Parameters:
/// - items: 物品数组
/// - loadBearing: 背包总的承重
func find(items: [Int], loadBearing: Int) -> (weight: Int, items: [Int]) {
resultItems = [Int](repeating: 0, count: items.count)
recurFind(curIndex: 0, items: items, curW: 0, loadBearing: loadBearing)
return (maxW, finalItems)
}
/// 递归计算背包问题
///
/// - Parameters:
/// - curIndex: 当前考察到的物品的索引
/// - items: 物品数组
/// - curW: 当前物品总重量
/// - loadBearing: 背包总承重
private func recurFind(curIndex: Int, items: [Int], curW: Int, loadBearing: Int) {
// 物品已装满或者已经考察完所有的物品了
if curW == loadBearing || curIndex == items.count {
if curW > maxW {
maxW = curW
print("背包物品: \(resultItems), 总重量: \(resultItems.reduce(0) { $0 + $1 })")
finalItems = resultItems
}
return
}
// 如果未超过背包可以承受的重量,则加入背包
if curW + items[curIndex] <= loadBearing {
resultItems[curIndex] = items[curIndex]
recurFind(curIndex: curIndex+1, items: items, curW: curW+items[curIndex], loadBearing: loadBearing)
}
// 加入背包的情况走完了,再走不加入背包的情况,注意不能加else,否则会漏掉很多情况
resultItems[curIndex] = 0
recurFind(curIndex: curIndex+1, items: items, curW: curW, loadBearing: loadBearing)
}
| 25.723077 | 107 | 0.633373 |
eb88b20232c6fa597b67eb3af4acde841cafc871 | 1,595 | /*
* ResetHappnPasswordAction.swift
* OfficeKit
*
* Created by François Lamboley on 18/09/2018.
*/
import Foundation
import NIO
import SemiSingleton
import ServiceKit
public final class ResetHappnPasswordAction : Action<HappnUser, String, Void>, ResetPasswordAction, SemiSingleton {
public static func additionalInfo(from services: Services) throws -> HappnConnector {
return try (services.semiSingleton(forKey: services.make()))
}
public typealias SemiSingletonKey = HappnUser
public typealias SemiSingletonAdditionalInitInfo = HappnConnector
public required init(key id: HappnUser, additionalInfo: HappnConnector, store: SemiSingletonStore) {
deps = Dependencies(connector: additionalInfo)
super.init(subject: id)
}
public override func unsafeStart(parameters newPassword: String, handler: @escaping (Result<Void, Swift.Error>) -> Void) throws {
let eventLoop = MultiThreadedEventLoopGroup(numberOfThreads: 1).next()
let f = deps.connector.connect(scope: ModifyHappnUserOperation.scopes, eventLoop: eventLoop)
.map{ _ -> EventLoopFuture<Void> in
var happnUser = self.subject.cloneForPatching()
happnUser.password = .set(newPassword)
let modifyUserOperation = ModifyHappnUserOperation(user: happnUser, connector: self.deps.connector)
return EventLoopFuture<Void>.future(from: modifyUserOperation, on: eventLoop)
}
f.whenSuccess{ _ in handler(.success(())) }
f.whenFailure{ err in handler(.failure(err)) }
}
private struct Dependencies {
var connector: HappnConnector
}
private let deps: Dependencies
}
| 27.982456 | 130 | 0.758621 |
752502a820b32db28feb9c735bb04b2b2b5d62c7 | 2,393 | //
// APIController.swift
// PersonSwift
//
// Created by RYPE on 26/04/2015.
// Copyright (c) 2015 weareopensource. All rights reserved.
//
import Foundation
import Alamofire
/**************************************************************************************************/
// Protocol
/**************************************************************************************************/
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
}
/**************************************************************************************************/
// Class
/**************************************************************************************************/
class APIController {
/*************************************************/
// Main
/*************************************************/
// Var
/*************************/
var delegate: APIControllerProtocol
// init
/*************************/
init(delegate: APIControllerProtocol) {
self.delegate = delegate
}
/*************************************************/
// Functions
/*************************************************/
// actions
/*************************/
func get(path: String) {
Alamofire.request(.GET, path)
.responseJSON { (_, _, JSON, error) in
if(error != nil) {
println("JSON Error \(error)")
}
if let results: NSArray = JSON as? NSArray {
self.delegate.didReceiveAPIResults(results)
}
}
}
func post(path: String, push: [String: AnyObject]?) {
Alamofire.request(.POST, path, parameters: push, encoding: .JSON)
.responseJSON { (_, _, JSON, error) in
if(error != nil) {
println("JSON Error \(error)")
}
else{
self.delegate.didReceiveAPIResults(["ok"])
}
}
}
// requests
/*************************/
func getModel(model: String) {
let urlPath = "http://localhost:3000/api/\(model)"
get(urlPath)
}
func postModel(model: String, data: [String: AnyObject]?) {
let urlPath = "http://localhost:3000/api/\(model)"
post(urlPath, push: data)
}
} | 29.54321 | 100 | 0.359382 |
bb76e1aeb57ede7f0c7ce23582a30211ad8eefcc | 6,957 | //
// MiniPlayer.swift
// Youtube Transition
//
// Created by 王庆华 on 2021/10/8.
//
import SwiftUI
struct MiniPlayer: View {
@EnvironmentObject var player: VideoPlayerViewMode
@Binding var video : Video
var body: some View {
VStack(spacing: 0){
HStack {
VidePlayerView(video: video.url)
.frame(width: player.isMiniPlayer ? 150 : player.width, height: player.isMiniPlayer ? 70 : getFrame())
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(
// Controls...
VideoControls(video: $video)
)
.onTapGesture {
if player.isMiniPlayer{
withAnimation {
player.width = UIScreen.main.bounds.width
player.isMiniPlayer.toggle()
}
}
}
GeometryReader(){ reader in
ScrollView {
VStack(spacing: 18){
VStack(alignment: .leading, spacing: 8){
Text(video.title)
.font(.callout)
.frame(maxWidth: .infinity, alignment: .leading)
// .frame(width: 500)
.padding(.trailing, 15)
Text("1.2M Views")
.font(.caption)
.fontWeight(.bold)
.foregroundColor(.gray)
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
// Buttons...
ScrollView(.horizontal, showsIndicators:false) {
HStack(){
PlayBackVideoButtons(image: "hand.thumbsup", text: "123K")
PlayBackVideoButtons(image: "hand.thumbsdown", text: "1K")
PlayBackVideoButtons(image: "square.and.arrow.up", text: "Share")
PlayBackVideoButtons(image: "square.and.arrow.down", text: "Download")
PlayBackVideoButtons(image: "message", text: "Live Chat")
}
}
Divider()
VStack(spacing: 15){
ForEach(videos){ video in
// video card view
VideoCardView(video: video)
}
}
}
}
.onAppear {
player.height = reader.frame(in: .global)
.height + 250
}
}
.background(Color.white)
.opacity(player.isMiniPlayer ? 0: getOpacity())
.frame(height: player.isMiniPlayer ? 0 : nil)
}
.background(
Color.white
.ignoresSafeArea()
.onTapGesture {
withAnimation {
player.width = UIScreen.main.bounds.width
player.isMiniPlayer.toggle()
}
})
}
func getFrame() -> CGFloat{
let progress = player.offset/(player.height - 100)
if (1 - progress) <= 1.0 {
let videoHeight : CGFloat = (1 - progress) * 250
if videoHeight <= 70{
let precent = videoHeight / 70
let videoWiedth: CGFloat = precent * UIScreen.main.bounds.width
DispatchQueue.main.async {
if videoWiedth >= 150{
player.width = videoWiedth
}
}
return 70
}
DispatchQueue.main.async {
player.width = UIScreen.main.bounds.width
}
return videoHeight
}
print(progress)
return 250
}
func getOpacity() -> Double{
let progress = player.offset / (player.height)
if progress <= 1{
return Double( 1 - progress)
}
return 1
}
}
struct MiniPlayer_Previews: PreviewProvider {
static var previews: some View {
// Home()
MiniPlayer( video: .constant(videos[0]))
.environmentObject(VideoPlayerViewMode())
}
}
struct PlayBackVideoButtons: View {
var image: String
var text: String
var body: some View {
Button {
} label: {
VStack(spacing: 8){
Image(systemName: image)
.font(.title3)
Text(text)
.fontWeight(.semibold)
.font(.caption)
}
.foregroundColor(.black)
.frame(maxWidth: .infinity)
}
.padding(.horizontal,15)
}
}
struct VideoControls: View{
@EnvironmentObject var player: VideoPlayerViewMode
@Binding var video: Video
var body: some View{
HStack(spacing: 8){
Rectangle()
.fill(Color.clear)
.frame(width: 150,height :70)
VStack(alignment: .leading, spacing: 6) {
Text(video.title)
.font(.callout)
.foregroundColor(.black)
.lineLimit(1)
Text(video.author)
.font(.caption)
.foregroundColor(.gray)
}
Button {
} label: {
Image(systemName: "pause.fill")
.font(.title2)
.foregroundColor(.black)
}
Button {
print("---")
player.showPlayer.toggle()
player.offset = 0
player.isMiniPlayer.toggle()
} label: {
Image(systemName: "xmark")
.font(.title2)
.foregroundColor(.black)
}
}
.padding(.trailing)
}
}
| 29.987069 | 122 | 0.383499 |
26b95f090bbf44d48511852870958a46a4d6afa5 | 939 | //
// BLViewController.swift
// BLStatusBarStyleDemo
//
// Created by bailun on 2018/2/27.
// Copyright © 2018年 bailun. All rights reserved.
//
import UIKit
class BLViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
modalPresentationCapturesStatusBarAppearance = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setNeedsStatusBarAppearanceUpdate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| 24.076923 | 74 | 0.680511 |
f71bc99daf1bf61d63802b3d25d175992b2e5ebe | 530 | //
// ViewController.swift
// Calculator
//
// Created by Guillermo Alcalá Gamero on 29/7/17.
// Copyright © 2017 Guillermo Alcalá Gamero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.384615 | 80 | 0.679245 |
5d13a2d550e49ad204fc48bf357e10b0ab8c860b | 3,152 | //
// Team.swift
// HotBox
//
// Created by Mark Evans on 12/5/18.
// Copyright © 2018 Mark Evans. All rights reserved.
//
import Foundation
import FirebaseFirestore
import FirebaseAuth
import FirebaseDatabase
struct Team {
var id: String?
var name: String
var mascot: String
var primaryColor: String?
var secondaryColor: String?
var textColor: String?
var representation: [String : Any] {
var rep: [String : Any] = [
"name": name,
"mascot": mascot,
]
if let id = id {
rep["id"] = id
}
if let primaryColor = primaryColor {
rep["primaryColor"] = primaryColor
}
if let secondaryColor = secondaryColor {
rep["secondaryColor"] = secondaryColor
}
if let textColor = textColor {
rep["textColor"] = textColor
}
return rep
}
init(name: String, mascot: String, primaryColor: String?, secondaryColor: String?, textColor: String?) {
self.id = nil
self.name = name
self.mascot = mascot
self.primaryColor = primaryColor
self.secondaryColor = secondaryColor
self.textColor = textColor
}
init?(document: QueryDocumentSnapshot) {
let data = document.data()
self.id = document.documentID
guard let name = data["name"] as? String else {
return nil
}
guard let mascot = data["mascot"] as? String else {
return nil
}
if let primaryColor = data["primaryColor"] as? String {
self.primaryColor = primaryColor
}
if let secondaryColor = data["secondaryColor"] as? String {
self.secondaryColor = secondaryColor
}
if let textColor = data["textColor"] as? String {
self.textColor = textColor
}
self.name = name
self.mascot = mascot
}
}
extension Team: Comparable {
static func == (lhs: Team, rhs: Team) -> Bool {
return lhs.name == rhs.name
}
static func < (lhs: Team, rhs: Team) -> Bool {
return lhs.name < rhs.name
}
}
extension Team {
static func findTeam(name: String, completion: @escaping CompletionHandler) {
let teamReference = Constants.shared.db.collection("teams")
teamReference.whereField("name", isEqualTo: name).limit(to: 1).getDocuments(completion: { (teamQuerySnap, error) in
guard let teamQuerySnap = teamQuerySnap else {
DispatchQueue.main.async {
completion(nil, NSError(domain: "\(error?.localizedDescription ?? "No error")", code: 400, userInfo: nil))
}
return
}
if let doc = teamQuerySnap.documents.first, let team = Team(document: doc) {
DispatchQueue.main.async {
completion(team, nil)
}
return
}
DispatchQueue.main.async {
completion(nil, NSError(domain: Constants.DEFAULT_ERROR_MSG, code: 400, userInfo: nil))
}
})
}
}
| 27.893805 | 126 | 0.564404 |
508c6c233a72fec15d6caa3840109c7b9e1ee82d | 18,622 | /*
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
Delegate for events that occur on `NumberPad`.
*/
@objc(BKYNumberPadDelegate)
public protocol NumberPadDelegate: class {
/**
Event that is fired if the number pad text has changed.
- parameter numberPad: The `NumberPad` that triggered this event.
- parameter text: The current text of the `numberPad`.
*/
func numberPad(_ numberPad: NumberPad, didChangeText text: String)
/**
Event that is fired if the user pressed the return key (from a connected physical keyboard).
- parameter numberPad: The `NumberPad` that triggered this event.
*/
func numberPadDidPressReturnKey(_ numberPad: NumberPad)
}
/**
UI control for typing numbers.
*/
@objc(BKYNumberPad)
@objcMembers public class NumberPad: UIView {
// MARK: - Constants
/**
Options for configuring the behavior of the number pad.
*/
public struct Options {
/// The color to use for the backspace button.
public var backspaceButtonColor: UIColor = ColorPalette.green.tint300
/// The corner radius to use for the non-backspace buttons.
public var buttonCornerRadius: CGFloat = 4
/// The text color to use for non-backspace buttons.
public var buttonTextColor: UIColor = ColorPalette.grey.tint900
/// The background color to use for non-backspace buttons.
public var buttonBackgroundColor: UIColor = ColorPalette.grey.tint300
/// The border color to use for non-backspace buttons.
public var buttonBorderColor: UIColor = ColorPalette.grey.tint300
/// The color to use for the main number text field.
public var textFieldColor: UIColor = ColorPalette.grey.tint900
}
// MARK: - Properties
/// Button for the "0" value.
@IBOutlet public weak var button0: UIButton?
/// Button for the "1" value.
@IBOutlet public weak var button1: UIButton?
/// Button for the "2" value.
@IBOutlet public weak var button2: UIButton?
/// Button for the "3" value.
@IBOutlet public weak var button3: UIButton?
/// Button for the "4" value.
@IBOutlet public weak var button4: UIButton?
/// Button for the "5" value.
@IBOutlet public weak var button5: UIButton?
/// Button for the "6" value.
@IBOutlet public weak var button6: UIButton?
/// Button for the "7" value.
@IBOutlet public weak var button7: UIButton?
/// Button for the "8" value.
@IBOutlet public weak var button8: UIButton?
/// Button for the "9" value.
@IBOutlet public weak var button9: UIButton?
/// Button for the minus sign symbol.
@IBOutlet public weak var buttonMinusSign: UIButton?
/// Button for the decimal symbol.
@IBOutlet public weak var buttonDecimal: UIButton?
/// Button for deleting a character.
@IBOutlet public weak var buttonBackspace: UIButton?
/// Text field that holds the current number.
@IBOutlet public weak var textField: NumberPadTextField? {
didSet {
// Prevent keyboard from appearing.
_dummyKeyboardView.removeFromSuperview()
textField?.inputView = _dummyKeyboardView
if #available(iOS 9.0, *) {
// Prevent shortcut toolbar from appearing at the bottom.
textField?.inputAssistantItem.leadingBarButtonGroups = []
textField?.inputAssistantItem.trailingBarButtonGroups = []
}
textField?.numberPad = self
}
}
/// Empty view used to prevent the virtual keyboard from appearing when editing the number pad
/// text field (we still want to enable use of a connected physical keyboard though, which
/// is why the text field is still editable).
private let _dummyKeyboardView = UIView()
/// Flag that determines if this view is using the default number pad.
public let isDefault: Bool
/// Allows use of the minus sign button. Defaults to `true`.
public var allowMinusSign: Bool = true {
didSet { updateState() }
}
/// Allows use of the decimal button. Defaults to `true`.
public var allowDecimal: Bool = true {
didSet { updateState() }
}
/// Returns the displayed text of the number pad.
public var text: String {
get { return textField?.text ?? "" }
set {
textField?.text = newValue
updateState()
}
}
/// The font to use within the number pad.
public var font: UIFont? {
didSet {
if let font = self.font {
// Use a slightly larger font size for the number.
textField?.font = font.withSize(font.pointSize + 2)
}
button0?.titleLabel?.font = font
button1?.titleLabel?.font = font
button2?.titleLabel?.font = font
button3?.titleLabel?.font = font
button4?.titleLabel?.font = font
button5?.titleLabel?.font = font
button6?.titleLabel?.font = font
button7?.titleLabel?.font = font
button8?.titleLabel?.font = font
button9?.titleLabel?.font = font
buttonMinusSign?.titleLabel?.font = font
buttonDecimal?.titleLabel?.font = font
updateState()
}
}
/// Configurable options of the number pad.
/// - note: These values are not used if a custom UI is provided for this control.
public let options: Options
/// Delegate for events that occur on this instance.
public weak var delegate: NumberPadDelegate?
/// Number formatter used for converting values to localized text.
fileprivate let _localizedNumberFormatter = NumberFormatter()
// MARK: - Initializers
public init(frame: CGRect, useDefault: Bool = true, options: Options) {
self.options = options
self.isDefault = useDefault
super.init(frame: frame)
if isDefault {
createDefaultControls()
}
updateState()
}
public required init?(coder aDecoder: NSCoder) {
self.isDefault = false
self.options = Options()
super.init(coder: aDecoder)
updateState()
}
private func createDefaultControls() {
// Create buttons
button0 = addButton(text: _localizedNumberFormatter.string(from: 0))
button1 = addButton(text: _localizedNumberFormatter.string(from: 1))
button2 = addButton(text: _localizedNumberFormatter.string(from: 2))
button3 = addButton(text: _localizedNumberFormatter.string(from: 3))
button4 = addButton(text: _localizedNumberFormatter.string(from: 4))
button5 = addButton(text: _localizedNumberFormatter.string(from: 5))
button6 = addButton(text: _localizedNumberFormatter.string(from: 6))
button7 = addButton(text: _localizedNumberFormatter.string(from: 7))
button8 = addButton(text: _localizedNumberFormatter.string(from: 8))
button9 = addButton(text: _localizedNumberFormatter.string(from: 9))
buttonMinusSign = addButton(
text: _localizedNumberFormatter.plusSign + "/" + _localizedNumberFormatter.minusSign)
buttonDecimal = addButton(text: _localizedNumberFormatter.decimalSeparator)
buttonBackspace = addButton()
if let image = ImageLoader.loadImage(named: "backspace", forClass: NumberPad.self) {
buttonBackspace?.setImage(image, for: .normal)
buttonBackspace?.imageView?.contentMode = .scaleAspectFit
buttonBackspace?.contentHorizontalAlignment = .fill
buttonBackspace?.contentVerticalAlignment = .fill
buttonBackspace?.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
buttonBackspace?.layer.borderWidth = 0
buttonBackspace?.sizeToFit()
buttonBackspace?.tintColor = options.backspaceButtonColor
buttonBackspace?.backgroundColor = .clear
}
// Create text field
let textField = NumberPadTextField()
textField.adjustsFontSizeToFitWidth = false
textField.textAlignment = .natural
textField.rightViewMode = .always
textField.delegate = self
textField.numberPad = self
textField.inputView = _dummyKeyboardView // Prevent keyboard from appearing.
textField.textColor = options.textFieldColor
if let font = self.font {
// Use a slightly larger font size for the number.
textField.font = font.withSize(font.pointSize + 2)
}
if #available(iOS 9.0, *) {
// Prevent shortcut toolbar from appearing at the bottom.
textField.inputAssistantItem.leadingBarButtonGroups = []
textField.inputAssistantItem.trailingBarButtonGroups = []
}
self.textField = textField
addSubview(textField)
}
// MARK: - Super
public override func layoutSubviews() {
super.layoutSubviews()
// Only run this layout code for the default number pad controls.
guard isDefault else { return }
let rows = [
[textField, buttonBackspace],
[button1, button2, button3],
[button4, button5, button6],
[button7, button8, button9],
[buttonMinusSign, button0, buttonDecimal]
] as [[UIView?]]
let padding = min(bounds.width, bounds.height) * 0.03 // Use the same spacing for x & y axes
let numRows = CGFloat(rows.count)
let rowHeight = (bounds.height - padding * (numRows - 1)) / numRows
var x: CGFloat = 0
var y: CGFloat = 0
for (row, views) in rows.enumerated() {
x = 0
if row == 0 {
// The first row is special in that the text field should use as much space as possible.
let backspaceWidth = rowHeight
textField?.frame =
CGRect(x: x, y: y, width: bounds.width - backspaceWidth - padding, height: rowHeight)
x += (textField?.bounds.width ?? 0) + padding
buttonBackspace?.frame = CGRect(x: x, y: y, width: backspaceWidth, height: rowHeight)
} else {
// Evenly distribute the buttons across the row.
let numColumns = CGFloat(views.count)
let columnWidth = (bounds.width - padding * (numColumns - 1)) / numColumns
for view in views {
view?.frame = CGRect(x: x, y: y, width: columnWidth, height: rowHeight)
x += columnWidth + padding
}
}
y += rowHeight + padding
}
}
// MARK: - Button Configuration
private func addButton(text: String? = nil) -> UIButton {
let button = UIButton(type: .roundedRect)
if let text = text {
button.setTitle(text, for: .normal)
}
button.autoresizingMask = []
button.addTarget(self, action: #selector(didPressButton(_:)), for: .touchUpInside)
button.contentMode = .center
button.layer.borderWidth = 1.0
button.layer.cornerRadius = options.buttonCornerRadius
button.titleLabel?.font = self.font
button.tintColor = options.buttonTextColor
button.layer.borderColor = options.buttonBorderColor.cgColor
button.backgroundColor = options.buttonBackgroundColor
addSubview(button)
return button
}
/**
Method that is called when the user presses a button.
- parameter button: The button that triggered the event.
*/
public func didPressButton(_ button: UIButton) {
var buttonText: String?
if button == button0 {
buttonText = _localizedNumberFormatter.string(from: 0) ?? "0"
} else if button == button1 {
buttonText = _localizedNumberFormatter.string(from: 1) ?? "1"
} else if button == button2 {
buttonText = _localizedNumberFormatter.string(from: 2) ?? "2"
} else if button == button3 {
buttonText = _localizedNumberFormatter.string(from: 3) ?? "3"
} else if button == button4 {
buttonText = _localizedNumberFormatter.string(from: 4) ?? "4"
} else if button == button5 {
buttonText = _localizedNumberFormatter.string(from: 5) ?? "5"
} else if button == button6 {
buttonText = _localizedNumberFormatter.string(from: 6) ?? "6"
} else if button == button7 {
buttonText = _localizedNumberFormatter.string(from: 7) ?? "7"
} else if button == button8 {
buttonText = _localizedNumberFormatter.string(from: 8) ?? "8"
} else if button == button9 {
buttonText = _localizedNumberFormatter.string(from: 9) ?? "9"
} else if button == buttonMinusSign {
buttonText = _localizedNumberFormatter.minusSign
} else if button == buttonDecimal {
buttonText = _localizedNumberFormatter.decimalSeparator
} else if button == buttonBackspace {
buttonText = ""
}
if let text = buttonText {
handleText(text, replacement: false)
}
}
// MARK: - Text Handling
/**
Handles the insertion of given text into `textField`.
- parameter text: The text to insert into the text field. If it is a deletion, then this value
should be `""`.
- parameter replacement: `true` if the entire `textField.text` should be replaced. `false` if
the given text should be inserted at the current cursor position.
*/
fileprivate func handleText(_ text: String, replacement: Bool) {
guard let textField = self.textField,
var currentText = textField.text else {
return
}
guard allowMinusSign || !text.contains(_localizedNumberFormatter.minusSign) else {
return
}
guard allowDecimal || !text.contains(_localizedNumberFormatter.decimalSeparator) else {
return
}
let oldText = currentText
if text.isEmpty && !currentText.isEmpty {
// Empty text means the backspace key was pressed. Remove last character.
textField.deleteBackward()
} else if text == _localizedNumberFormatter.minusSign {
// Toggle "-"
if currentText.contains(text) {
currentText = currentText.replacingOccurrences(of: text, with: "")
} else {
currentText = text + currentText
}
textField.text = currentText
} else if text == _localizedNumberFormatter.plusSign &&
currentText.contains(_localizedNumberFormatter.minusSign) {
// "+" button was pressed, remove the "-".
textField.text = currentText.replacingOccurrences(
of: _localizedNumberFormatter.minusSign, with: "")
} else if text == _localizedNumberFormatter.decimalSeparator && !currentText.contains(text) {
// Add "." since it's not present yet.
insertText(text)
} else if text.count == 1 && !replacement {
// This is the equivalent of a button press (either from the number pad or physical keyboard).
if _localizedNumberFormatter.number(from: text) != nil {
// The text entered is a localized digit. Figure out how to insert it into the text field.
if let zero = _localizedNumberFormatter.string(from: 0),
_localizedNumberFormatter.number(from: currentText) == 0 &&
!currentText.contains(_localizedNumberFormatter.decimalSeparator) {
// Special case where current text is "0" or "-0" (or equivalent for RTL).
// Replace "0" in the current text with the new number (while preserving the minus sign).
textField.text = currentText.replacingOccurrences(of: zero, with: text)
} else {
// Simply add the number to the text field.
insertText(text)
}
}
} else if text.count > 1 || replacement {
// This must be a pasted string. Completely replace the current text if it's a valid number.
if _localizedNumberFormatter.number(from: text) != nil {
textField.text = text
}
}
updateState()
if oldText != textField.text {
delegate?.numberPad(self, didChangeText: self.text)
}
}
fileprivate func insertText(_ text: String) {
guard let textField = self.textField,
let selectedTextRange = textField.selectedTextRange,
let currentText = textField.text else {
return
}
// Check that inserting the text isn't before the minus sign.
let offset = textField.offset(from: textField.beginningOfDocument, to: selectedTextRange.start)
if offset == 0 && currentText.contains(_localizedNumberFormatter.minusSign) {
// Move the cursor position to the end, so nothing is inserted before the minus sign
let cursorPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: cursorPosition, to: cursorPosition)
}
textField.insertText(text)
}
// MARK: - State Update
fileprivate func updateState() {
let text = textField?.text ?? ""
buttonBackspace?.isEnabled = !text.isEmpty
buttonDecimal?.isEnabled = !text.contains(_localizedNumberFormatter.decimalSeparator)
buttonDecimal?.isHidden = !allowDecimal
buttonMinusSign?.isHidden = !allowMinusSign
}
}
// MARK: - UITextFieldDelegate Implementation
extension NumberPad: UITextFieldDelegate {
public func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// Manually handle text insertion/replacement/deletion.
handleText(string, replacement: false)
return false
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Remove focus from the text field.
textField.resignFirstResponder()
// Notify the delegate.
delegate?.numberPadDidPressReturnKey(self)
return true
}
}
/**
Specialized text field used for `NumberPad`.
*/
public class NumberPadTextField: UITextField {
fileprivate weak var numberPad: NumberPad? = nil
// MARK: - Text Field Rendering
public override func selectionRects(for range: UITextRange) -> [Any] {
// Disable selection ranges.
return []
}
// MARK: - Copy/Paste Actions
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(copy(_:)) {
// Only allow copy if there's something to copy.
return (text?.count ?? 0) > 0
} else if action == #selector(paste(_:)) {
// Only allow paste if there's a valid number in the pasteboard.
if let numberPad = self.numberPad,
let text = UIPasteboard.general.string, !text.isEmpty {
return numberPad._localizedNumberFormatter.number(from: text) != nil
}
}
return false
}
public override func copy(_ sender: Any?) {
// Always copy the entire number
UIPasteboard.general.string = text
}
public override func paste(_ sender: Any?) {
// Paste the text into number pad
if let text = UIPasteboard.general.string, !text.isEmpty {
numberPad?.handleText(text, replacement: true)
}
}
}
| 35.335863 | 100 | 0.687091 |
f9f0ce0a2342364a250a6106caf17e5c9723c625 | 2,299 | //
// SceneDelegate.swift
// Mapbox-Testin
//
// Created by Daniel Bachar on 22/10/2020.
//
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 necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.377358 | 147 | 0.713354 |
467db2be7dd00ce1f7f74d4e7158a5ca8f77244d | 578 | //
// PKHUDAnimatingContentView.swift
// PKHUD
//
// Created by Philip Kluz on 9/27/15.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
@objc public protocol PKHUDAnimating {
func startAnimation()
func stopAnimation()
//修改标题颜色
func changeTitleLabelTextColor(textColor:UIColor)
//修改标题字体
func changeTitleLabelTextFont(textFont:UIFont)
//修改副标题颜色
func changeSubTitleLabelTextColor(textColor:UIColor)
//修改副标题字体
func changeSubTitleLabelTextFont(textFont:UIFont)
}
| 22.230769 | 58 | 0.717993 |
23c1045b67dddb1bcd4be7ce688e37ceb5f52484 | 253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func < {
struct Q {
{
}
let a {
for in {
for {
case
let {
protocol A {
class
case ,
| 14.882353 | 87 | 0.70751 |
8a6c19ecdfb35b95a7d19557a8e37efc2f816120 | 6,076 | //
// BodyDate.swift
// azureSwiftRuntimeTests
//
// Created by Vladimir Shcherbakov on 12/27/17.
//
import Foundation
import XCTest
import azureSwiftRuntime
class BodyDateTests: XCTestCase {
let timeout: TimeInterval = 102.0
var azureClient: AzureClient!
override func setUp() {
continueAfterFailure = false
let env = AuzureEnvironment(endpoints:[
.resourceManager : "http://localhost:3000"
])
let atc = AzureTokenCredentials(environment: env, tenantId: "", subscriptionId: "")
self.azureClient = AzureClient(atc: atc)
.withRequestInterceptor(LogRequestInterceptor(showOptions: .all))
.withResponseInterceptor(LogResponseInterceptor(showOptions: .all))
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_date_getNull() {
print("\n=================== #1 date_getNull\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetNullCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
XCTAssertNil(result)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_getInvalidDate() {
print("\n=================== #2 date_getInvalidDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetInvalidDateCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
//"201O-18-90"
XCTAssertNil(result)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_getOverflowDate() {
print("\n=================== #3 date_getOverflowDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetOverflowDateCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
//"10000000000-12-31"
XCTAssertNil(result)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_getUnderflowDate() {
print("\n=================== #4 date_getUnderflowDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetUnderflowDateCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
//"0000-00-00"
XCTAssertNil(result)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_putMaxDate() {
print("\n=================== #4 date_putMaxDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.PutMaxDateCommand()
cmd.dateBody = Date(fromString: "9999-12-31", format: .date)
XCTAssertNotNil(cmd.dateBody)
cmd.execute(client: self.azureClient) { (error) in
defer { e.fulfill() }
XCTAssertNil(error)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_getMaxDate() {
print("\n=================== #4 date_getMaxDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetMaxDateCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
//"9999-12-31"
XCTAssertNotNil(result)
let date = result!
XCTAssertNotNil(date)
let calendar = Calendar.current
let components = calendar.dateComponents(in: TimeZone(identifier: "GMT")!, from: date)
XCTAssertEqual(9999, components.year)
XCTAssertEqual(12, components.month)
XCTAssertEqual(31, components.day)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_putMinDate() {
print("\n=================== #4 date_putMinDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.PutMinDateCommand()
cmd.dateBody = Date(fromString: "0001-01-01", format: .date)
XCTAssertNotNil(cmd.dateBody)
cmd.execute(client: self.azureClient) { (error) in
defer { e.fulfill() }
XCTAssertNil(error)
}
waitForExpectations(timeout: timeout, handler: nil)
}
func test_date_getMinDate() {
print("\n=================== #4 date_getMinDate\n")
let e = expectation(description: "Wait for HTTP request to complete")
let cmd = DateNamespace.GetMinDateCommand()
cmd.execute(client: self.azureClient) { (result, error) in
defer { e.fulfill() }
XCTAssertNil(error)
XCTAssertNotNil(result)
let date = result!
XCTAssertNotNil(date)
let calendar = Calendar.current
let components = calendar.dateComponents(in: TimeZone(identifier: "GMT")!, from: date)
XCTAssertEqual(1, components.year)
XCTAssertEqual(1, components.month)
XCTAssertEqual(1, components.day)
}
waitForExpectations(timeout: timeout, handler: nil)
}
}
| 32.319149 | 111 | 0.562212 |
b9ecb76003a5ca54453d6d84c20ec97015465683 | 2,319 | //
// SendMoneyVC+TableViewExtensions.swift
// Franklin
//
// Created by Anton on 21/02/2019.
// Copyright © 2019 Matter Inc. All rights reserved.
//
import UIKit
extension SendMoneyController {
func emptyContactsList() {
contactsList = []
emptyAttention(enabled: true)
DispatchQueue.main.async { [unowned self] in
self.tableView?.reloadData()
}
}
func updateContactsList(with list: [Contact]) {
DispatchQueue.main.async { [unowned self] in
self.contactsList = list
self.emptyAttention(enabled: list.isEmpty)
self.tableView?.reloadData()
}
}
func searchContact(string: String) {
guard let list = try? ContactsService().getFullContactsList(for: string) else {
emptyContactsList()
return
}
updateContactsList(with: list)
}
func emptyAttention(enabled: Bool) {
DispatchQueue.main.async { [unowned self] in
self.emptyContactsView.alpha = enabled ? 1 : 0
}
}
}
extension SendMoneyController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if contactsList.isEmpty {
return 0
} else {
return contactsList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if !contactsList.isEmpty {
guard let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier,
for: indexPath) as? ContactTableCell else {
return UITableViewCell()
}
cell.configure(with: contactsList[indexPath.row])
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let contact = contactsList[indexPath.row]
showConfirmScreen(animated: true, for: contact)
}
}
| 30.92 | 102 | 0.593359 |
01d08671b61d55ea60500405984051ef0508f71c | 1,932 | import UIKit
public extension UIAlertController {
/// Add a textField
///
/// - Parameters:
/// - height: textField height
/// - hInset: right and left margins to AlertController border
/// - vInset: bottom margin to button
/// - configuration: textField
public func addOneTextField(configuration: TextField.Config?) {
let textField = OneTextFieldViewController(vInset: preferredStyle == .alert ? 12 : 0, configuration: configuration)
let height: CGFloat = OneTextFieldViewController.ui.height + OneTextFieldViewController.ui.vInset
set(vc: textField, height: height)
}
}
final class OneTextFieldViewController: UIViewController {
fileprivate lazy var textField: TextField = TextField()
struct ui {
static let height: CGFloat = 44
static let hInset: CGFloat = 12
static var vInset: CGFloat = 12
}
init(vInset: CGFloat = 12, configuration: TextField.Config?) {
super.init(nibName: nil, bundle: nil)
view.addSubview(textField)
ui.vInset = vInset
/// have to set textField frame width and height to apply cornerRadius
textField.height = ui.height
textField.width = view.width
configuration?(textField)
preferredContentSize.height = ui.height + ui.vInset
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
Log("has deinitialized")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textField.width = view.width - ui.hInset * 2
textField.height = ui.height
textField.center.x = view.center.x
textField.center.y = view.center.y - ui.vInset / 2
}
}
| 28.835821 | 123 | 0.624224 |
50852ad7837f4567f06e0164a988b12ed7c50ea8 | 2,412 | //
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
import Foundation
/// Represents distinct cases of FluentKit (version: 1.12.0) property wrappers
public enum FluentPropertyType: String, TypeInformationElement, CaseIterable {
/// @Enum
case enumProperty
/// @OptionalEnum
case optionalEnumProperty
/// @Children
case childrenProperty
/// @Field
case fieldProperty
/// @ID
case iDProperty
/// @OptionalChild
case optionalChildProperty
/// @OptionalField
case optionalFieldProperty
/// @OptionalParent
case optionalParentProperty
/// @Parent
case parentProperty
/// @Siblings
case siblingsProperty
/// @Timestamp
case timestampProperty
/// @Group
case groupProperty
// MARK: - Encodable
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
// MARK: - Decodable
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container
.decode(String.self)
.replacingOccurrences(of: "@", with: "")
.lowerFirst
+ "Property"
guard let instance = FluentPropertyType(rawValue: string) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Failed to decode \(Self.self)")
}
self = instance
}
/// Indicates whether the type of the property is get-only. Such fluent properties represent some kind of relationship among db tables
public var isGetOnly: Bool {
[.childrenProperty, .optionalChildProperty, .optionalParentProperty, .parentProperty, .siblingsProperty].contains(self)
}
}
// MARK: - CustomStringConvertible + CustomDebugStringConvertible
extension FluentPropertyType: CustomStringConvertible, CustomDebugStringConvertible {
/// String representation, e.g. `@ID`
public var description: String {
"@" + rawValue.upperFirst.replacingOccurrences(of: "Property", with: "")
}
public var debugDescription: String {
description
}
}
| 30.923077 | 138 | 0.670398 |
09e39c980637aa2351a61d9ad728322b4dcc4ba1 | 2,969 | //
// UploadedViewController.swift
// SampleApp
//
// Created by Nitzan Jaitman on 27/08/2017.
// Copyright © 2017 Cloudinary. All rights reserved.
//
import Foundation
import UIKit
class InProgressViewController: BaseCollectionViewController {
static let progressChangedNotification = NSNotification.Name(rawValue: "com.cloudinary.sample.progress.notification")
// MARK: Properties
@IBOutlet weak var collectionView: UICollectionView!
var progressMap: [String: Progress] = [:]
// MARK: ViewController
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(InProgressViewController.progressChanged(notification:)), name: InProgressViewController.progressChangedNotification, object: nil)
}
override func getReuseIdentifier() -> String {
return "ResourceInProgressCell"
}
override func getItemsPerRow() -> CGFloat {
return CGFloat(2);
}
override func getCollectionView() -> UICollectionView! {
return collectionView
}
override func reloadData() {
PersistenceHelper.fetch(statuses: [PersistenceHelper.UploadStatus.queued, PersistenceHelper.UploadStatus.uploading]) { fetchedResources in
var oldResources = Set(self.resources)
self.resources = fetchedResources as! [CLDResource]
self.collectionView.reloadData()
let newResources = Set(self.resources)
oldResources.subtract(newResources)
// if something was here before and it's gone now, clean it up from the progress map as well
for res in oldResources {
self.progressMap.removeValue(forKey: res.localPath!)
}
}
}
@objc func progressChanged(notification: NSNotification) {
// update progress in map
let name = notification.userInfo?["name"] as? String
let progress = notification.userInfo?["progress"] as? Progress
if (name != nil && progress != nil) {
progressMap[name!] = progress!
}
// refresh views
collectionView.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: getReuseIdentifier(), for: indexPath) as! ResourceInProgressCell
let resource = resources[indexPath.row]
setLocalImage(imageView: cell.imageView, resource: resource)
cell.overlayView.isHidden = true
if let progress = progressMap[resource.localPath!] {
cell.overlayView.isHidden = false
cell.progressView.isHidden = false
cell.progressView.progress = Float(progress.fractionCompleted)
} else {
cell.overlayView.isHidden = true
cell.progressView.isHidden = true
}
return cell
}
}
| 35.345238 | 203 | 0.677669 |
91cf4baef70da15d62f3805a7c9cd7bee9517cf9 | 2,254 | //
// CarTrackTests.swift
// CarTrackTests
//
// Created by Avin More on 3/5/21.
//
import XCTest
import Moya
@testable import CarTrack
class CarTrackTests: XCTestCase {
var viewModel = AuthenticationViewModel()
let dashboardViewModel = DashboardViewModel()
let mockDashboardService = BaseProvider<DashboardService>(
stubClosure: MoyaProvider.immediatelyStub, //This enables mocking to avoid internet call for testing APIs
manager: BaseProvider<DashboardService>.customManager()
)
func testCountryList() {
XCTAssertFalse(viewModel.countryList.isEmpty, "Country names are unavailable")
}
func testValidateInput() {
viewModel.userName = "[email protected]"
_ = viewModel.validateInput(textfiledType: .userName)
viewModel.password = "testtest"
_ = viewModel.validateInput(textfiledType: .password)
viewModel.selectedCountry = "Singapore"
_ = viewModel.validateInput(textfiledType: .selection)
XCTAssertTrue(viewModel.loginButtonStatus.filter({ !$0.isValid }).first == nil, "Invalid input")
}
func testValidUserId() {
XCTAssertTrue("[email protected]".isValidUserName(), "is valid user function has issue")
XCTAssertFalse("test@test".isValidUserName(), "is valid user function has issue")
}
func testUpdateButtonStatus() {
viewModel.updateLoginButtonStatus = { result in
XCTAssertTrue(result.last?.isValid == true, "Login could not be enabled")
}
viewModel.userName = "[email protected]"
_ = viewModel.validateInput(textfiledType: .userName)
viewModel.password = "testtest"
_ = viewModel.validateInput(textfiledType: .password)
viewModel.selectedCountry = "Singapore"
_ = viewModel.validateInput(textfiledType: .selection)
}
func testFetchUsers() {
let exp = expectation(description: "Fetch mock user data")
dashboardViewModel.service = mockDashboardService
dashboardViewModel.users?.removeAll()
dashboardViewModel.fetchUsers() { [weak self] in
if self?.dashboardViewModel.users?.count == 10 {
exp.fulfill()
}
}
waitForExpectations(timeout: 2)
}
}
| 40.25 | 113 | 0.679237 |
01e9b44eaccc52e2b837163304c1360da756e10e | 1,338 | //
// ConnectPacketTests.swift
// NIOMQTT
//
// Created by Bofei Zhu on 8/24/19.
// Copyright © 2019 HealthTap Inc. All rights reserved.
//
import XCTest
@testable import NIOMQTT
class ConnectPacketTests: XCTestCase {
func testVariableHeaderByteCount() {
let connectFlags = ConnectPacket.ConnectFlags(rawValue: 0)!
let properties = PropertyCollection()
let variableHeader = ConnectPacket.VariableHeader(
connectFlags: connectFlags,
keepAlive: 120,
properties: properties)
XCTAssertEqual(variableHeader.mqttByteCount, 11)
}
func testPayloadByteCount() {
let bytes: [UInt8] = [0, 0]
let willMessage = ConnectPacket.WillMessage(
properties: PropertyCollection(),
topic: "abc",
payload: Data(bytes))
XCTAssertEqual(willMessage.mqttByteCount, 10)
var payload = ConnectPacket.Payload(
clientId: "abc",
willMessage: nil,
username: nil,
password: nil)
XCTAssertEqual(payload.mqttByteCount, 5)
payload = ConnectPacket.Payload(
clientId: "abc",
willMessage: willMessage,
username: "foo",
password: Data(bytes))
XCTAssertEqual(payload.mqttByteCount, 24)
}
}
| 23.892857 | 67 | 0.613602 |
6122a4759033dda0e428450acd426e38e85b51a1 | 2,587 | //
// FirestoreManager.swift
// Weather
//
// Created by Olesya Nikolaeva on 22.12.2021.
// Copyright © 2021 Olesya Nikolaeva. All rights reserved.
//
import FirebaseFirestore
protocol FirestoreManagerProtocol: AnyObject {
func read(completion: @escaping (Result<[CityItem], Error>) -> Void)
func addItem(
_ item: CityItem,
merge: Bool,
completion: @escaping (Result<Bool, Error>) -> Void
)
func deleteItem(
_ item: CityItem,
completion: @escaping (Result<Bool, Error>) -> Void
)
}
final class FirestoreManager: FirestoreManagerProtocol {
enum Collection: String {
case city = "City"
}
private let db = Firestore.firestore()
private let collection: Collection
init(_ collection: Collection) {
self.collection = collection
}
func read(completion: @escaping (Result<[CityItem], Error>) -> Void) {
// if let items = UserDefaults.standard.value(forKey: collection.rawValue) as? [ToDoListItem] {
// completion(.success(items))
// }
db.collection(collection.rawValue).getDocuments { [weak self] snapshot, error in
if let error = error {
DispatchQueue.main.async { completion(.failure(error)) }
}
let items = snapshot?.documents.compactMap { document -> CityItem? in
try? document.data(as: CityItem.self)
}
//UserDefaults.standard.set(items, forKey: self?.collection.rawValue ?? "")
DispatchQueue.main.async { completion(.success(items ?? [])) }
}
}
func addItem(_ item: CityItem, merge: Bool, completion: @escaping (Result<Bool, Error>) -> Void) {
do {
try db.collection(collection.rawValue).document(item.id ?? "").setData(from: item, merge: merge) { error in
if let error = error {
DispatchQueue.main.async { completion(.failure(error)) }
}
DispatchQueue.main.async { completion(.success(true)) }
}
} catch let error {
DispatchQueue.main.async { completion(.failure(error)) }
}
}
func deleteItem(_ item: CityItem, completion: @escaping (Result<Bool, Error>) -> Void) {
db.collection(collection.rawValue).document(item.id ?? "").delete() { error in
if let error = error {
DispatchQueue.main.async { completion(.failure(error)) }
}
DispatchQueue.main.async { completion(.success(true)) }
}
}
}
| 34.039474 | 119 | 0.590646 |
1a8e5fcd3b808418e344a04342fdec1f6b13b2ed | 2,319 | //
// ArtistOrLabelBookmarkOrderViewController.swift
// Metal Archives
//
// Created by Thanh-Nhon Nguyen on 11/04/2020.
// Copyright © 2020 Thanh-Nhon Nguyen. All rights reserved.
//
import UIKit
final class ArtistOrLabelBookmarkOrderViewController: BaseViewController {
enum BookmarkType {
case artist, label
}
@IBOutlet private weak var tableView: UITableView!
var currentOrder: ArtistOrLabelBookmarkOrder = .lastModifiedDescending
var selectedArtistOrLabelBookmarkOrder: ((ArtistOrLabelBookmarkOrder) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
SimpleTableViewCell.register(with: tableView)
tableView.tableFooterView = UIView(frame: .zero)
tableView.backgroundColor = Settings.currentTheme.bodyTextColor
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
preferredContentSize = tableView.contentSize
}
}
extension ArtistOrLabelBookmarkOrderViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
currentOrder = ArtistOrLabelBookmarkOrder(rawValue: indexPath.row) ?? .nameAscending
selectedArtistOrLabelBookmarkOrder?(currentOrder)
dismiss(animated: false, completion: nil)
}
}
extension ArtistOrLabelBookmarkOrderViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ArtistOrLabelBookmarkOrder.allCases.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SimpleTableViewCell.dequeueFrom(tableView, forIndexPath: indexPath)
cell.selectionStyle = .none
cell.displayAsBodyText()
cell.inverseColors()
let order = ArtistOrLabelBookmarkOrder.allCases[indexPath.row]
cell.fill(with: order.description)
if order == currentOrder {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
}
| 32.208333 | 100 | 0.699871 |
d72f082b1da3be0a9b926cbe39588e825805e505 | 451 | //
// ModelConvertible.swift
// CoreDataCodable
//
// Created by Andrea Prearo on 12/29/21.
// Copyright © 2021 Andrea Prearo. All rights reserved.
//
import Foundation
/// Protocol to provide functionality for data model converion.
protocol ModelConvertible {
associatedtype Model
/// Converts a conforming instance to a data model instance.
///
/// - Returns: The converted data model instance.
func toModel() -> Model?
}
| 22.55 | 64 | 0.700665 |
21fcab2d1ec804ac6ac5e582c7b8bfb2db38281f | 185 | //
// KeyType.swift
//
//
// Created by Joseph Hinkle on 5/10/21.
//
enum KeyType: String, CaseIterable, Identifiable {
var id: String { self.rawValue }
case RSA = "RSA"
}
| 15.416667 | 50 | 0.616216 |
08431124c7b95388574be9a34356b06994d4819f | 1,850 | //
// Copyright (c) 2019 KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RxSwift
/*:
# window
*/
// window 연사자도 buffer와 같이 2가지 조건이 있다. interval 시간, 방출할 최대 이벤트 갯수
// 버퍼는 이벤트를 모아서 배열 형태로 방출하는 반면, 이벤트를 바로 방출하는 옵저버블을 구독자에게 전달한다.
let disposeBag = DisposeBag()
Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.window(timeSpan: .seconds(2), count: 3, scheduler: MainScheduler.instance)
.take(5)
.subscribe {
print($0)
if let observable = $0.element {
observable.subscribe {
print($0)
}
.disposed(by: disposeBag)
}
}
.disposed(by: disposeBag)
Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
| 33.035714 | 81 | 0.698378 |
90bdb9f59bfff1f6a2379a714fe9696f68288558 | 1,547 | //
// AssetLiveView.swift
// Pickery
//
// Created by Okan Arikan on 11/11/16.
//
//
import Foundation
import PhotosUI
import ReactiveSwift
/// An image view that displays an asset live photo view
class AssetLiveView : PHLivePhotoView {
/// The disposibles we are listenning
let disposibles = ScopedDisposable(CompositeDisposable())
/// The content we are displaying
var asset : Asset? {
didSet {
requestLivePhoto()
}
}
/// Ctor
override init(frame: CGRect) {
super.init(frame: frame)
// The view hierarchy
// When we get network connectivity, re-request the asset
disposibles += Network
.sharedInstance
.gotNetwork
.signal
.observe(on: UIScheduler()).observeValues { [ unowned self ] gotConnection in
if gotConnection {
self.requestLivePhoto()
}
}
}
// Request the live photo
func requestLivePhoto() {
asset?
.requestLivePhoto(pixelSize: bounds.size)
.observe(on: UIScheduler())
.on(failed: { error in
},value: { photo in
self.livePhoto = photo
})
.start()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Reset the animations
func reset() {
asset = nil
}
}
| 23.439394 | 89 | 0.530058 |
e284538c3cae4365b44199d11950614ac31e1cc6 | 3,117 | //
// MIT License
//
// Copyright (c) 2018-2019 Open Zesame (https://github.com/OpenZesame)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Zesame
struct KeystoreValidator: InputValidator {
typealias Input = String
typealias Output = Keystore
enum Error: InputError {
case stringToDataConversionFailed
case badJSON(Swift.DecodingError)
case incorrectPassword
init?(walletImportError: Zesame.Error.WalletImport) {
switch walletImportError {
case .incorrectPassword: self = .incorrectPassword
default: return nil
}
}
init?(error: Swift.Error) {
guard
let zesameError = error as? Zesame.Error,
case .walletImport(let walletImportError) = zesameError
else { return nil }
self.init(walletImportError: walletImportError)
}
}
func validate(input: Input) -> Validation<Output, Error> {
func validate() throws -> Keystore {
guard let json = input.data(using: .utf8) else {
throw Error.stringToDataConversionFailed
}
do {
return try JSONDecoder().decode(Keystore.self, from: json)
} catch let jsonDecoderError as Swift.DecodingError {
throw Error.badJSON(jsonDecoderError)
} catch {
incorrectImplementation("DecodingError should cover all errors")
}
}
do {
return .valid(try validate())
} catch let error as Error {
return .invalid(.error(error))
} catch {
incorrectImplementation("All errors should have been covered")
}
}
}
extension KeystoreValidator.Error {
var errorMessage: String {
let Message = L10n.Error.Input.Keystore.self
switch self {
case .badJSON, .stringToDataConversionFailed: return Message.badFormatOrInput
case .incorrectPassword: return Message.incorrectPassword
}
}
}
| 35.420455 | 85 | 0.657363 |
67e7ad4d13a524d47b84fe525a1cff5ac91c460c | 2,010 | //
// BaseAbstractTextLogger.swift
// LogsManager
//
// Created by Anton Plebanovich on 3/2/18.
// Copyright © 2018 Anton Plebanovich. All rights reserved.
//
import Foundation
import CocoaLumberjack
/// Abstract base class inherited from DDAbstractLogger that represents text logger.
/// Override process(message:) in child classes
open class BaseAbstractTextLogger: DDAbstractLogger, BaseLogger {
// ******************************* MARK: - BaseLogger
public let logLevel: DDLogLevel
public let mode: LoggerMode
public let dateFormatter: DateFormatter?
required public init(mode: LoggerMode,
logLevel: DDLogLevel,
dateFormatter: DateFormatter? = BaseLogFormatter.dateFormatter) {
self.mode = mode
self.logLevel = logLevel
self.dateFormatter = dateFormatter
super.init()
setup()
}
private func setup() {
logFormatter = BaseLogFormatter(mode: mode, dateFormatter: dateFormatter)
}
// ******************************* MARK: - DDLogger Overrides
override open func log(message logMessage: DDLogMessage) {
guard shouldLog(message: logMessage) else { return }
let formattedMessage: String
if let logFormatter = value(forKey: "_logFormatter") as? DDLogFormatter {
formattedMessage = logFormatter.format(message: logMessage) ?? logMessage.message
} else {
formattedMessage = logMessage.message
}
process(message: logMessage, formattedMessage: formattedMessage)
}
// ******************************* MARK: - Open Methods
/// Abstract method that should be overridden. Message validation already done. You shouldn't call super in your implementation.
open func process(message logMessage: DDLogMessage, formattedMessage: String) {
assertionFailure("Should be overrided in child class")
}
}
| 31.904762 | 132 | 0.624876 |
91a3862b7f405def982118d3086925cb56dbd271 | 147 | import Foundation
protocol BookRepositoryProtocol {
func list(title: String, completion: @escaping ([Book]?, ApiErrorResponse?) -> Void )
}
| 18.375 | 89 | 0.727891 |
48b794de602f0407ca606a68560055e292086423 | 1,074 | import Foundation
import lzlib
public enum Lzip { }
extension Lzip {
public enum CompressionLevel {
case lvl0
case lvl1
case lvl2
case lvl3
case lvl4
case lvl5
case lvl6
case lvl7
case lvl8
case lvl9
}
}
extension Data {
public var isLzipped: Bool {
return self.starts(with: [0x4c, 0x5a, 0x49, 0x50])
}
public func lzipped(level: Lzip.CompressionLevel) throws -> Data? {
let compressor = Lzip.Compress(level: level)
var destination = Data(capacity: self.count * 4)
try compressor.compress(input: self,
output: &destination)
compressor.finish(output: &destination)
return destination
}
public func lunzipped() throws -> Data? {
let decompressor = Lzip.Decompress()
var destination = Data(capacity: self.count / 2)
try decompressor.decompress(input: self,
output: &destination)
return destination
}
}
| 23.866667 | 71 | 0.570764 |
762e5e37b08a3dad58e7b4aebf2b9983ae37fb1c | 824 | //
// CGSSNotification.swift
// DereGuide
//
// Created by zzk on 2017/5/1.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
extension Notification.Name {
static let updateEnd = Notification.Name.init("CGSS_UPDATE_END")
static let gameResoureceProcessedEnd = Notification.Name.init("CGSS_PROCESS_END")
static let saveEnd = Notification.Name.init("CGSS_SAVE_END")
static let favoriteCardsChanged = Notification.Name.init("CGSS_FAVORITE_CARD_CHANGED")
static let favoriteCharasChanged = Notification.Name.init("CGSS_FAVORITE_CHARA_CHANGED")
static let favoriteSongsChanged = Notification.Name(rawValue: "CGSS_FAVORITE_SONG_CHANGED")
static let dataRemoved = Notification.Name.init("CGSS_DATA_REMOVED")
static let unitModified = Notification.Name.init("CGSS_UNIT_MODIFIED")
}
| 39.238095 | 95 | 0.774272 |
285392b4d4d153419afd4c2d519d709ba4ed7d7b | 4,248 | //
// ViewController.swift
// Example App
//
// Created by Emil Karimov on 27/03/2019.
// Copyright © 2019 Emil Karimov. All rights reserved.
//
import UIKit
import CoreLocation
import AstrologyCalc
class ViewController: UIViewController {
let location = CLLocation(latitude: 55.751244, longitude: 37.618423)
var moonPhaseManager: MoonCalculatorManager!
weak var container: UIStackView!
override func loadView() {
super.loadView()
let container = self.stackView(orientation: .vertical, distribution: .fillProportionally, spacing: 10)
self.view.addSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints([
NSLayoutConstraint(item: container, attribute: .topMargin, relatedBy: .equal, toItem: self.view, attribute: .topMargin, multiplier: 1.0, constant: 64),
NSLayoutConstraint(item: container, attribute: .leftMargin, relatedBy: .equal, toItem: self.view, attribute: .leftMargin, multiplier: 1.0, constant: 16),
NSLayoutConstraint(item: container, attribute: .rightMargin, relatedBy: .equal, toItem: self.view, attribute: .rightMargin, multiplier: 1.0, constant: -16),
])
self.container = container
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.moonPhaseManager = MoonCalculatorManager(location: location)
let info = self.moonPhaseManager.getInfo(date: Date())
self.addInfo(param: "=== Current localtion ===", value: "", on: self.container, textAlignment: .center)
self.addInfo(param: "Latitude", value: "\(info.location.coordinate.latitude)", on: self.container, textAlignment: .left)
self.addInfo(param: "Longitude", value: "\(info.location.coordinate.longitude)", on: self.container, textAlignment: .left)
self.addInfo(param: "=== Current date ===", value: "", on: self.container, textAlignment: .center)
self.addInfo(param: "", value: "\(info.date)", on: self.container, textAlignment: .left)
info.moonModels.forEach {
self.addInfo(param: "=== Moon day", value: "\($0.age) ===", on: self.container, textAlignment: .center)
self.addInfo(param: "Moon rise", value: $0.moonRise == nil ? "Yesterday" : "\($0.moonRise!)", on: self.container, textAlignment: .left)
self.addInfo(param: "Moon set", value: $0.moonSet == nil ? "Tomorrow" : "\($0.moonSet!)", on: self.container, textAlignment: .left)
}
self.addInfo(param: "Moon phase", value: "\(info.phase)", on: self.container, textAlignment: .left)
self.addInfo(param: "Moon trajectory", value: "\(info.trajectory)", on: self.container, textAlignment: .left)
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
}
// MARK: - Privates
extension ViewController {
private func addInfo(param: String, value: String, on stackView: UIStackView, textAlignment: NSTextAlignment) {
let container = UILabel()
container.textAlignment = textAlignment
container.text = param + " " + value
container.backgroundColor = UIColor.yellow.withAlphaComponent(0.4)
stackView.addArrangedSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([container.heightAnchor.constraint(equalToConstant: 35)])
}
private func stackView(orientation: NSLayoutConstraint.Axis = .vertical, distribution: UIStackView.Distribution = .fill, spacing: CGFloat = 0) -> UIStackView {
let stackView = UIStackView()
stackView.axis = orientation
stackView.distribution = distribution
stackView.alignment = UIStackView.Alignment.fill
stackView.spacing = spacing
return stackView
}
}
| 40.075472 | 168 | 0.65725 |
482fda3aa3fa85e68cbcdc3996d1c93170e7ff2c | 57,864 | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment
// swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity
// -- Generated Code; do not edit --
//
// AppConfigModelOperations.swift
// AppConfigModel
//
import Foundation
/**
Operation enumeration for the AppConfigModel.
*/
public enum AppConfigModelOperations: String, Hashable, CustomStringConvertible {
case createApplication = "CreateApplication"
case createConfigurationProfile = "CreateConfigurationProfile"
case createDeploymentStrategy = "CreateDeploymentStrategy"
case createEnvironment = "CreateEnvironment"
case createHostedConfigurationVersion = "CreateHostedConfigurationVersion"
case deleteApplication = "DeleteApplication"
case deleteConfigurationProfile = "DeleteConfigurationProfile"
case deleteDeploymentStrategy = "DeleteDeploymentStrategy"
case deleteEnvironment = "DeleteEnvironment"
case deleteHostedConfigurationVersion = "DeleteHostedConfigurationVersion"
case getApplication = "GetApplication"
case getConfiguration = "GetConfiguration"
case getConfigurationProfile = "GetConfigurationProfile"
case getDeployment = "GetDeployment"
case getDeploymentStrategy = "GetDeploymentStrategy"
case getEnvironment = "GetEnvironment"
case getHostedConfigurationVersion = "GetHostedConfigurationVersion"
case listApplications = "ListApplications"
case listConfigurationProfiles = "ListConfigurationProfiles"
case listDeploymentStrategies = "ListDeploymentStrategies"
case listDeployments = "ListDeployments"
case listEnvironments = "ListEnvironments"
case listHostedConfigurationVersions = "ListHostedConfigurationVersions"
case listTagsForResource = "ListTagsForResource"
case startDeployment = "StartDeployment"
case stopDeployment = "StopDeployment"
case tagResource = "TagResource"
case untagResource = "UntagResource"
case updateApplication = "UpdateApplication"
case updateConfigurationProfile = "UpdateConfigurationProfile"
case updateDeploymentStrategy = "UpdateDeploymentStrategy"
case updateEnvironment = "UpdateEnvironment"
case validateConfiguration = "ValidateConfiguration"
public var description: String {
return rawValue
}
public var operationPath: String {
switch self {
case .createApplication:
return "/applications"
case .createConfigurationProfile:
return "/applications/{ApplicationId}/configurationprofiles"
case .createDeploymentStrategy:
return "/deploymentstrategies"
case .createEnvironment:
return "/applications/{ApplicationId}/environments"
case .createHostedConfigurationVersion:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}/hostedconfigurationversions"
case .deleteApplication:
return "/applications/{ApplicationId}"
case .deleteConfigurationProfile:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}"
case .deleteDeploymentStrategy:
return "/deployementstrategies/{DeploymentStrategyId}"
case .deleteEnvironment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}"
case .deleteHostedConfigurationVersion:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}/hostedconfigurationversions/{VersionNumber}"
case .getApplication:
return "/applications/{ApplicationId}"
case .getConfiguration:
return "/applications/{Application}/environments/{Environment}/configurations/{Configuration}"
case .getConfigurationProfile:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}"
case .getDeployment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}/deployments/{DeploymentNumber}"
case .getDeploymentStrategy:
return "/deploymentstrategies/{DeploymentStrategyId}"
case .getEnvironment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}"
case .getHostedConfigurationVersion:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}/hostedconfigurationversions/{VersionNumber}"
case .listApplications:
return "/applications"
case .listConfigurationProfiles:
return "/applications/{ApplicationId}/configurationprofiles"
case .listDeploymentStrategies:
return "/deploymentstrategies"
case .listDeployments:
return "/applications/{ApplicationId}/environments/{EnvironmentId}/deployments"
case .listEnvironments:
return "/applications/{ApplicationId}/environments"
case .listHostedConfigurationVersions:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}/hostedconfigurationversions"
case .listTagsForResource:
return "/tags/{ResourceArn}"
case .startDeployment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}/deployments"
case .stopDeployment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}/deployments/{DeploymentNumber}"
case .tagResource:
return "/tags/{ResourceArn}"
case .untagResource:
return "/tags/{ResourceArn}"
case .updateApplication:
return "/applications/{ApplicationId}"
case .updateConfigurationProfile:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}"
case .updateDeploymentStrategy:
return "/deploymentstrategies/{DeploymentStrategyId}"
case .updateEnvironment:
return "/applications/{ApplicationId}/environments/{EnvironmentId}"
case .validateConfiguration:
return "/applications/{ApplicationId}/configurationprofiles/{ConfigurationProfileId}/validators"
}
}
}
/**
Structure to encode the path input for the CreateConfigurationProfile
operation.
*/
public struct CreateConfigurationProfileOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension CreateConfigurationProfileRequest {
func asAppConfigModelCreateConfigurationProfileOperationInputPath() -> CreateConfigurationProfileOperationInputPath {
return CreateConfigurationProfileOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the body input for the CreateConfigurationProfile
operation.
*/
public struct CreateConfigurationProfileOperationInputBody: Codable, Equatable {
public var description: Description?
public var locationUri: Uri
public var name: Name
public var retrievalRoleArn: RoleArn?
public var tags: TagMap?
public var validators: ValidatorList?
public init(description: Description? = nil,
locationUri: Uri,
name: Name,
retrievalRoleArn: RoleArn? = nil,
tags: TagMap? = nil,
validators: ValidatorList? = nil) {
self.description = description
self.locationUri = locationUri
self.name = name
self.retrievalRoleArn = retrievalRoleArn
self.tags = tags
self.validators = validators
}
enum CodingKeys: String, CodingKey {
case description = "Description"
case locationUri = "LocationUri"
case name = "Name"
case retrievalRoleArn = "RetrievalRoleArn"
case tags = "Tags"
case validators = "Validators"
}
public func validate() throws {
try description?.validateAsDescription()
try locationUri.validateAsUri()
try name.validateAsName()
try retrievalRoleArn?.validateAsRoleArn()
try validators?.validateAsValidatorList()
}
}
public extension CreateConfigurationProfileRequest {
func asAppConfigModelCreateConfigurationProfileOperationInputBody() -> CreateConfigurationProfileOperationInputBody {
return CreateConfigurationProfileOperationInputBody(
description: description,
locationUri: locationUri,
name: name,
retrievalRoleArn: retrievalRoleArn,
tags: tags,
validators: validators)
}
}
/**
Structure to encode the path input for the CreateEnvironment
operation.
*/
public struct CreateEnvironmentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension CreateEnvironmentRequest {
func asAppConfigModelCreateEnvironmentOperationInputPath() -> CreateEnvironmentOperationInputPath {
return CreateEnvironmentOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the body input for the CreateEnvironment
operation.
*/
public struct CreateEnvironmentOperationInputBody: Codable, Equatable {
public var description: Description?
public var monitors: MonitorList?
public var name: Name
public var tags: TagMap?
public init(description: Description? = nil,
monitors: MonitorList? = nil,
name: Name,
tags: TagMap? = nil) {
self.description = description
self.monitors = monitors
self.name = name
self.tags = tags
}
enum CodingKeys: String, CodingKey {
case description = "Description"
case monitors = "Monitors"
case name = "Name"
case tags = "Tags"
}
public func validate() throws {
try description?.validateAsDescription()
try monitors?.validateAsMonitorList()
try name.validateAsName()
}
}
public extension CreateEnvironmentRequest {
func asAppConfigModelCreateEnvironmentOperationInputBody() -> CreateEnvironmentOperationInputBody {
return CreateEnvironmentOperationInputBody(
description: description,
monitors: monitors,
name: name,
tags: tags)
}
}
/**
Structure to encode the path input for the CreateHostedConfigurationVersion
operation.
*/
public struct CreateHostedConfigurationVersionOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension CreateHostedConfigurationVersionRequest {
func asAppConfigModelCreateHostedConfigurationVersionOperationInputPath() -> CreateHostedConfigurationVersionOperationInputPath {
return CreateHostedConfigurationVersionOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the body input for the CreateHostedConfigurationVersion
operation.
*/
public struct CreateHostedConfigurationVersionOperationInputAdditionalHeaders: Codable, Equatable {
public var contentType: StringWithLengthBetween1And255
public var description: Description?
public var latestVersionNumber: Integer?
public init(contentType: StringWithLengthBetween1And255,
description: Description? = nil,
latestVersionNumber: Integer? = nil) {
self.contentType = contentType
self.description = description
self.latestVersionNumber = latestVersionNumber
}
enum CodingKeys: String, CodingKey {
case contentType = "Content-Type"
case description = "Description"
case latestVersionNumber = "Latest-Version-Number"
}
public func validate() throws {
try contentType.validateAsStringWithLengthBetween1And255()
try description?.validateAsDescription()
}
}
public extension CreateHostedConfigurationVersionRequest {
func asAppConfigModelCreateHostedConfigurationVersionOperationInputAdditionalHeaders() -> CreateHostedConfigurationVersionOperationInputAdditionalHeaders {
return CreateHostedConfigurationVersionOperationInputAdditionalHeaders(
contentType: contentType,
description: description,
latestVersionNumber: latestVersionNumber)
}
}
/**
Structure to encode the body input for the CreateHostedConfigurationVersion
operation.
*/
public struct CreateHostedConfigurationVersionOperationOutputHeaders: Codable, Equatable {
public var applicationId: Id?
public var configurationProfileId: Id?
public var contentType: StringWithLengthBetween1And255?
public var description: Description?
public var versionNumber: Integer?
public init(applicationId: Id? = nil,
configurationProfileId: Id? = nil,
contentType: StringWithLengthBetween1And255? = nil,
description: Description? = nil,
versionNumber: Integer? = nil) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
self.contentType = contentType
self.description = description
self.versionNumber = versionNumber
}
enum CodingKeys: String, CodingKey {
case applicationId = "Application-Id"
case configurationProfileId = "Configuration-Profile-Id"
case contentType = "Content-Type"
case description = "Description"
case versionNumber = "Version-Number"
}
public func validate() throws {
try applicationId?.validateAsId()
try configurationProfileId?.validateAsId()
try contentType?.validateAsStringWithLengthBetween1And255()
try description?.validateAsDescription()
}
}
public extension HostedConfigurationVersion {
func asAppConfigModelCreateHostedConfigurationVersionOperationOutputHeaders() -> CreateHostedConfigurationVersionOperationOutputHeaders {
return CreateHostedConfigurationVersionOperationOutputHeaders(
applicationId: applicationId,
configurationProfileId: configurationProfileId,
contentType: contentType,
description: description,
versionNumber: versionNumber)
}
}
/**
Structure to encode the path input for the DeleteApplication
operation.
*/
public struct DeleteApplicationOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension DeleteApplicationRequest {
func asAppConfigModelDeleteApplicationOperationInputPath() -> DeleteApplicationOperationInputPath {
return DeleteApplicationOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the path input for the DeleteConfigurationProfile
operation.
*/
public struct DeleteConfigurationProfileOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension DeleteConfigurationProfileRequest {
func asAppConfigModelDeleteConfigurationProfileOperationInputPath() -> DeleteConfigurationProfileOperationInputPath {
return DeleteConfigurationProfileOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the path input for the DeleteDeploymentStrategy
operation.
*/
public struct DeleteDeploymentStrategyOperationInputPath: Codable, Equatable {
public var deploymentStrategyId: DeploymentStrategyId
public init(deploymentStrategyId: DeploymentStrategyId) {
self.deploymentStrategyId = deploymentStrategyId
}
enum CodingKeys: String, CodingKey {
case deploymentStrategyId = "DeploymentStrategyId"
}
public func validate() throws {
try deploymentStrategyId.validateAsDeploymentStrategyId()
}
}
public extension DeleteDeploymentStrategyRequest {
func asAppConfigModelDeleteDeploymentStrategyOperationInputPath() -> DeleteDeploymentStrategyOperationInputPath {
return DeleteDeploymentStrategyOperationInputPath(
deploymentStrategyId: deploymentStrategyId)
}
}
/**
Structure to encode the path input for the DeleteEnvironment
operation.
*/
public struct DeleteEnvironmentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var environmentId: Id
public init(applicationId: Id,
environmentId: Id) {
self.applicationId = applicationId
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension DeleteEnvironmentRequest {
func asAppConfigModelDeleteEnvironmentOperationInputPath() -> DeleteEnvironmentOperationInputPath {
return DeleteEnvironmentOperationInputPath(
applicationId: applicationId,
environmentId: environmentId)
}
}
/**
Structure to encode the path input for the DeleteHostedConfigurationVersion
operation.
*/
public struct DeleteHostedConfigurationVersionOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public var versionNumber: Integer
public init(applicationId: Id,
configurationProfileId: Id,
versionNumber: Integer) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
self.versionNumber = versionNumber
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
case versionNumber = "VersionNumber"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension DeleteHostedConfigurationVersionRequest {
func asAppConfigModelDeleteHostedConfigurationVersionOperationInputPath() -> DeleteHostedConfigurationVersionOperationInputPath {
return DeleteHostedConfigurationVersionOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId,
versionNumber: versionNumber)
}
}
/**
Structure to encode the path input for the GetApplication
operation.
*/
public struct GetApplicationOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension GetApplicationRequest {
func asAppConfigModelGetApplicationOperationInputPath() -> GetApplicationOperationInputPath {
return GetApplicationOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the path input for the GetConfiguration
operation.
*/
public struct GetConfigurationOperationInputPath: Codable, Equatable {
public var application: StringWithLengthBetween1And64
public var configuration: StringWithLengthBetween1And64
public var environment: StringWithLengthBetween1And64
public init(application: StringWithLengthBetween1And64,
configuration: StringWithLengthBetween1And64,
environment: StringWithLengthBetween1And64) {
self.application = application
self.configuration = configuration
self.environment = environment
}
enum CodingKeys: String, CodingKey {
case application = "Application"
case configuration = "Configuration"
case environment = "Environment"
}
public func validate() throws {
try application.validateAsStringWithLengthBetween1And64()
try configuration.validateAsStringWithLengthBetween1And64()
try environment.validateAsStringWithLengthBetween1And64()
}
}
public extension GetConfigurationRequest {
func asAppConfigModelGetConfigurationOperationInputPath() -> GetConfigurationOperationInputPath {
return GetConfigurationOperationInputPath(
application: application,
configuration: configuration,
environment: environment)
}
}
/**
Structure to encode the query input for the GetConfiguration
operation.
*/
public struct GetConfigurationOperationInputQuery: Codable, Equatable {
public var clientConfigurationVersion: Version?
public var clientId: StringWithLengthBetween1And64
public init(clientConfigurationVersion: Version? = nil,
clientId: StringWithLengthBetween1And64) {
self.clientConfigurationVersion = clientConfigurationVersion
self.clientId = clientId
}
enum CodingKeys: String, CodingKey {
case clientConfigurationVersion = "client_configuration_version"
case clientId = "client_id"
}
public func validate() throws {
try clientConfigurationVersion?.validateAsVersion()
try clientId.validateAsStringWithLengthBetween1And64()
}
}
public extension GetConfigurationRequest {
func asAppConfigModelGetConfigurationOperationInputQuery() -> GetConfigurationOperationInputQuery {
return GetConfigurationOperationInputQuery(
clientConfigurationVersion: clientConfigurationVersion,
clientId: clientId)
}
}
/**
Structure to encode the body input for the GetConfiguration
operation.
*/
public struct GetConfigurationOperationOutputHeaders: Codable, Equatable {
public var configurationVersion: Version?
public var contentType: String?
public init(configurationVersion: Version? = nil,
contentType: String? = nil) {
self.configurationVersion = configurationVersion
self.contentType = contentType
}
enum CodingKeys: String, CodingKey {
case configurationVersion = "Configuration-Version"
case contentType = "Content-Type"
}
public func validate() throws {
try configurationVersion?.validateAsVersion()
}
}
public extension Configuration {
func asAppConfigModelGetConfigurationOperationOutputHeaders() -> GetConfigurationOperationOutputHeaders {
return GetConfigurationOperationOutputHeaders(
configurationVersion: configurationVersion,
contentType: contentType)
}
}
/**
Structure to encode the path input for the GetConfigurationProfile
operation.
*/
public struct GetConfigurationProfileOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension GetConfigurationProfileRequest {
func asAppConfigModelGetConfigurationProfileOperationInputPath() -> GetConfigurationProfileOperationInputPath {
return GetConfigurationProfileOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the path input for the GetDeployment
operation.
*/
public struct GetDeploymentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var deploymentNumber: Integer
public var environmentId: Id
public init(applicationId: Id,
deploymentNumber: Integer,
environmentId: Id) {
self.applicationId = applicationId
self.deploymentNumber = deploymentNumber
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case deploymentNumber = "DeploymentNumber"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension GetDeploymentRequest {
func asAppConfigModelGetDeploymentOperationInputPath() -> GetDeploymentOperationInputPath {
return GetDeploymentOperationInputPath(
applicationId: applicationId,
deploymentNumber: deploymentNumber,
environmentId: environmentId)
}
}
/**
Structure to encode the path input for the GetDeploymentStrategy
operation.
*/
public struct GetDeploymentStrategyOperationInputPath: Codable, Equatable {
public var deploymentStrategyId: DeploymentStrategyId
public init(deploymentStrategyId: DeploymentStrategyId) {
self.deploymentStrategyId = deploymentStrategyId
}
enum CodingKeys: String, CodingKey {
case deploymentStrategyId = "DeploymentStrategyId"
}
public func validate() throws {
try deploymentStrategyId.validateAsDeploymentStrategyId()
}
}
public extension GetDeploymentStrategyRequest {
func asAppConfigModelGetDeploymentStrategyOperationInputPath() -> GetDeploymentStrategyOperationInputPath {
return GetDeploymentStrategyOperationInputPath(
deploymentStrategyId: deploymentStrategyId)
}
}
/**
Structure to encode the path input for the GetEnvironment
operation.
*/
public struct GetEnvironmentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var environmentId: Id
public init(applicationId: Id,
environmentId: Id) {
self.applicationId = applicationId
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension GetEnvironmentRequest {
func asAppConfigModelGetEnvironmentOperationInputPath() -> GetEnvironmentOperationInputPath {
return GetEnvironmentOperationInputPath(
applicationId: applicationId,
environmentId: environmentId)
}
}
/**
Structure to encode the path input for the GetHostedConfigurationVersion
operation.
*/
public struct GetHostedConfigurationVersionOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public var versionNumber: Integer
public init(applicationId: Id,
configurationProfileId: Id,
versionNumber: Integer) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
self.versionNumber = versionNumber
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
case versionNumber = "VersionNumber"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension GetHostedConfigurationVersionRequest {
func asAppConfigModelGetHostedConfigurationVersionOperationInputPath() -> GetHostedConfigurationVersionOperationInputPath {
return GetHostedConfigurationVersionOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId,
versionNumber: versionNumber)
}
}
/**
Structure to encode the query input for the ListApplications
operation.
*/
public struct ListApplicationsOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListApplicationsRequest {
func asAppConfigModelListApplicationsOperationInputQuery() -> ListApplicationsOperationInputQuery {
return ListApplicationsOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the path input for the ListConfigurationProfiles
operation.
*/
public struct ListConfigurationProfilesOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension ListConfigurationProfilesRequest {
func asAppConfigModelListConfigurationProfilesOperationInputPath() -> ListConfigurationProfilesOperationInputPath {
return ListConfigurationProfilesOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the query input for the ListConfigurationProfiles
operation.
*/
public struct ListConfigurationProfilesOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListConfigurationProfilesRequest {
func asAppConfigModelListConfigurationProfilesOperationInputQuery() -> ListConfigurationProfilesOperationInputQuery {
return ListConfigurationProfilesOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the query input for the ListDeploymentStrategies
operation.
*/
public struct ListDeploymentStrategiesOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListDeploymentStrategiesRequest {
func asAppConfigModelListDeploymentStrategiesOperationInputQuery() -> ListDeploymentStrategiesOperationInputQuery {
return ListDeploymentStrategiesOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the path input for the ListDeployments
operation.
*/
public struct ListDeploymentsOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var environmentId: Id
public init(applicationId: Id,
environmentId: Id) {
self.applicationId = applicationId
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension ListDeploymentsRequest {
func asAppConfigModelListDeploymentsOperationInputPath() -> ListDeploymentsOperationInputPath {
return ListDeploymentsOperationInputPath(
applicationId: applicationId,
environmentId: environmentId)
}
}
/**
Structure to encode the query input for the ListDeployments
operation.
*/
public struct ListDeploymentsOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListDeploymentsRequest {
func asAppConfigModelListDeploymentsOperationInputQuery() -> ListDeploymentsOperationInputQuery {
return ListDeploymentsOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the path input for the ListEnvironments
operation.
*/
public struct ListEnvironmentsOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension ListEnvironmentsRequest {
func asAppConfigModelListEnvironmentsOperationInputPath() -> ListEnvironmentsOperationInputPath {
return ListEnvironmentsOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the query input for the ListEnvironments
operation.
*/
public struct ListEnvironmentsOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListEnvironmentsRequest {
func asAppConfigModelListEnvironmentsOperationInputQuery() -> ListEnvironmentsOperationInputQuery {
return ListEnvironmentsOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the path input for the ListHostedConfigurationVersions
operation.
*/
public struct ListHostedConfigurationVersionsOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension ListHostedConfigurationVersionsRequest {
func asAppConfigModelListHostedConfigurationVersionsOperationInputPath() -> ListHostedConfigurationVersionsOperationInputPath {
return ListHostedConfigurationVersionsOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the query input for the ListHostedConfigurationVersions
operation.
*/
public struct ListHostedConfigurationVersionsOperationInputQuery: Codable, Equatable {
public var maxResults: MaxResults?
public var nextToken: NextToken?
public init(maxResults: MaxResults? = nil,
nextToken: NextToken? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
enum CodingKeys: String, CodingKey {
case maxResults = "max_results"
case nextToken = "next_token"
}
public func validate() throws {
try maxResults?.validateAsMaxResults()
try nextToken?.validateAsNextToken()
}
}
public extension ListHostedConfigurationVersionsRequest {
func asAppConfigModelListHostedConfigurationVersionsOperationInputQuery() -> ListHostedConfigurationVersionsOperationInputQuery {
return ListHostedConfigurationVersionsOperationInputQuery(
maxResults: maxResults,
nextToken: nextToken)
}
}
/**
Structure to encode the path input for the ListTagsForResource
operation.
*/
public struct ListTagsForResourceOperationInputPath: Codable, Equatable {
public var resourceArn: Arn
public init(resourceArn: Arn) {
self.resourceArn = resourceArn
}
enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
}
public func validate() throws {
try resourceArn.validateAsArn()
}
}
public extension ListTagsForResourceRequest {
func asAppConfigModelListTagsForResourceOperationInputPath() -> ListTagsForResourceOperationInputPath {
return ListTagsForResourceOperationInputPath(
resourceArn: resourceArn)
}
}
/**
Structure to encode the path input for the StartDeployment
operation.
*/
public struct StartDeploymentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var environmentId: Id
public init(applicationId: Id,
environmentId: Id) {
self.applicationId = applicationId
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension StartDeploymentRequest {
func asAppConfigModelStartDeploymentOperationInputPath() -> StartDeploymentOperationInputPath {
return StartDeploymentOperationInputPath(
applicationId: applicationId,
environmentId: environmentId)
}
}
/**
Structure to encode the body input for the StartDeployment
operation.
*/
public struct StartDeploymentOperationInputBody: Codable, Equatable {
public var configurationProfileId: Id
public var configurationVersion: Version
public var deploymentStrategyId: DeploymentStrategyId
public var description: Description?
public var tags: TagMap?
public init(configurationProfileId: Id,
configurationVersion: Version,
deploymentStrategyId: DeploymentStrategyId,
description: Description? = nil,
tags: TagMap? = nil) {
self.configurationProfileId = configurationProfileId
self.configurationVersion = configurationVersion
self.deploymentStrategyId = deploymentStrategyId
self.description = description
self.tags = tags
}
enum CodingKeys: String, CodingKey {
case configurationProfileId = "ConfigurationProfileId"
case configurationVersion = "ConfigurationVersion"
case deploymentStrategyId = "DeploymentStrategyId"
case description = "Description"
case tags = "Tags"
}
public func validate() throws {
try configurationProfileId.validateAsId()
try configurationVersion.validateAsVersion()
try deploymentStrategyId.validateAsDeploymentStrategyId()
try description?.validateAsDescription()
}
}
public extension StartDeploymentRequest {
func asAppConfigModelStartDeploymentOperationInputBody() -> StartDeploymentOperationInputBody {
return StartDeploymentOperationInputBody(
configurationProfileId: configurationProfileId,
configurationVersion: configurationVersion,
deploymentStrategyId: deploymentStrategyId,
description: description,
tags: tags)
}
}
/**
Structure to encode the path input for the StopDeployment
operation.
*/
public struct StopDeploymentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var deploymentNumber: Integer
public var environmentId: Id
public init(applicationId: Id,
deploymentNumber: Integer,
environmentId: Id) {
self.applicationId = applicationId
self.deploymentNumber = deploymentNumber
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case deploymentNumber = "DeploymentNumber"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension StopDeploymentRequest {
func asAppConfigModelStopDeploymentOperationInputPath() -> StopDeploymentOperationInputPath {
return StopDeploymentOperationInputPath(
applicationId: applicationId,
deploymentNumber: deploymentNumber,
environmentId: environmentId)
}
}
/**
Structure to encode the path input for the TagResource
operation.
*/
public struct TagResourceOperationInputPath: Codable, Equatable {
public var resourceArn: Arn
public init(resourceArn: Arn) {
self.resourceArn = resourceArn
}
enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
}
public func validate() throws {
try resourceArn.validateAsArn()
}
}
public extension TagResourceRequest {
func asAppConfigModelTagResourceOperationInputPath() -> TagResourceOperationInputPath {
return TagResourceOperationInputPath(
resourceArn: resourceArn)
}
}
/**
Structure to encode the body input for the TagResource
operation.
*/
public struct TagResourceOperationInputBody: Codable, Equatable {
public var tags: TagMap
public init(tags: TagMap) {
self.tags = tags
}
enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
public func validate() throws {
}
}
public extension TagResourceRequest {
func asAppConfigModelTagResourceOperationInputBody() -> TagResourceOperationInputBody {
return TagResourceOperationInputBody(
tags: tags)
}
}
/**
Structure to encode the path input for the UntagResource
operation.
*/
public struct UntagResourceOperationInputPath: Codable, Equatable {
public var resourceArn: Arn
public init(resourceArn: Arn) {
self.resourceArn = resourceArn
}
enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
}
public func validate() throws {
try resourceArn.validateAsArn()
}
}
public extension UntagResourceRequest {
func asAppConfigModelUntagResourceOperationInputPath() -> UntagResourceOperationInputPath {
return UntagResourceOperationInputPath(
resourceArn: resourceArn)
}
}
/**
Structure to encode the query input for the UntagResource
operation.
*/
public struct UntagResourceOperationInputQuery: Codable, Equatable {
public var tagKeys: TagKeyList
public init(tagKeys: TagKeyList) {
self.tagKeys = tagKeys
}
enum CodingKeys: String, CodingKey {
case tagKeys
}
public func validate() throws {
try tagKeys.validateAsTagKeyList()
}
}
public extension UntagResourceRequest {
func asAppConfigModelUntagResourceOperationInputQuery() -> UntagResourceOperationInputQuery {
return UntagResourceOperationInputQuery(
tagKeys: tagKeys)
}
}
/**
Structure to encode the path input for the UpdateApplication
operation.
*/
public struct UpdateApplicationOperationInputPath: Codable, Equatable {
public var applicationId: Id
public init(applicationId: Id) {
self.applicationId = applicationId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
}
public func validate() throws {
try applicationId.validateAsId()
}
}
public extension UpdateApplicationRequest {
func asAppConfigModelUpdateApplicationOperationInputPath() -> UpdateApplicationOperationInputPath {
return UpdateApplicationOperationInputPath(
applicationId: applicationId)
}
}
/**
Structure to encode the body input for the UpdateApplication
operation.
*/
public struct UpdateApplicationOperationInputBody: Codable, Equatable {
public var description: Description?
public var name: Name?
public init(description: Description? = nil,
name: Name? = nil) {
self.description = description
self.name = name
}
enum CodingKeys: String, CodingKey {
case description = "Description"
case name = "Name"
}
public func validate() throws {
try description?.validateAsDescription()
try name?.validateAsName()
}
}
public extension UpdateApplicationRequest {
func asAppConfigModelUpdateApplicationOperationInputBody() -> UpdateApplicationOperationInputBody {
return UpdateApplicationOperationInputBody(
description: description,
name: name)
}
}
/**
Structure to encode the path input for the UpdateConfigurationProfile
operation.
*/
public struct UpdateConfigurationProfileOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension UpdateConfigurationProfileRequest {
func asAppConfigModelUpdateConfigurationProfileOperationInputPath() -> UpdateConfigurationProfileOperationInputPath {
return UpdateConfigurationProfileOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the body input for the UpdateConfigurationProfile
operation.
*/
public struct UpdateConfigurationProfileOperationInputBody: Codable, Equatable {
public var description: Description?
public var name: Name?
public var retrievalRoleArn: RoleArn?
public var validators: ValidatorList?
public init(description: Description? = nil,
name: Name? = nil,
retrievalRoleArn: RoleArn? = nil,
validators: ValidatorList? = nil) {
self.description = description
self.name = name
self.retrievalRoleArn = retrievalRoleArn
self.validators = validators
}
enum CodingKeys: String, CodingKey {
case description = "Description"
case name = "Name"
case retrievalRoleArn = "RetrievalRoleArn"
case validators = "Validators"
}
public func validate() throws {
try description?.validateAsDescription()
try name?.validateAsName()
try retrievalRoleArn?.validateAsRoleArn()
try validators?.validateAsValidatorList()
}
}
public extension UpdateConfigurationProfileRequest {
func asAppConfigModelUpdateConfigurationProfileOperationInputBody() -> UpdateConfigurationProfileOperationInputBody {
return UpdateConfigurationProfileOperationInputBody(
description: description,
name: name,
retrievalRoleArn: retrievalRoleArn,
validators: validators)
}
}
/**
Structure to encode the path input for the UpdateDeploymentStrategy
operation.
*/
public struct UpdateDeploymentStrategyOperationInputPath: Codable, Equatable {
public var deploymentStrategyId: DeploymentStrategyId
public init(deploymentStrategyId: DeploymentStrategyId) {
self.deploymentStrategyId = deploymentStrategyId
}
enum CodingKeys: String, CodingKey {
case deploymentStrategyId = "DeploymentStrategyId"
}
public func validate() throws {
try deploymentStrategyId.validateAsDeploymentStrategyId()
}
}
public extension UpdateDeploymentStrategyRequest {
func asAppConfigModelUpdateDeploymentStrategyOperationInputPath() -> UpdateDeploymentStrategyOperationInputPath {
return UpdateDeploymentStrategyOperationInputPath(
deploymentStrategyId: deploymentStrategyId)
}
}
/**
Structure to encode the body input for the UpdateDeploymentStrategy
operation.
*/
public struct UpdateDeploymentStrategyOperationInputBody: Codable, Equatable {
public var deploymentDurationInMinutes: MinutesBetween0And24Hours?
public var description: Description?
public var finalBakeTimeInMinutes: MinutesBetween0And24Hours?
public var growthFactor: GrowthFactor?
public var growthType: GrowthType?
public init(deploymentDurationInMinutes: MinutesBetween0And24Hours? = nil,
description: Description? = nil,
finalBakeTimeInMinutes: MinutesBetween0And24Hours? = nil,
growthFactor: GrowthFactor? = nil,
growthType: GrowthType? = nil) {
self.deploymentDurationInMinutes = deploymentDurationInMinutes
self.description = description
self.finalBakeTimeInMinutes = finalBakeTimeInMinutes
self.growthFactor = growthFactor
self.growthType = growthType
}
enum CodingKeys: String, CodingKey {
case deploymentDurationInMinutes = "DeploymentDurationInMinutes"
case description = "Description"
case finalBakeTimeInMinutes = "FinalBakeTimeInMinutes"
case growthFactor = "GrowthFactor"
case growthType = "GrowthType"
}
public func validate() throws {
try deploymentDurationInMinutes?.validateAsMinutesBetween0And24Hours()
try description?.validateAsDescription()
try finalBakeTimeInMinutes?.validateAsMinutesBetween0And24Hours()
try growthFactor?.validateAsGrowthFactor()
}
}
public extension UpdateDeploymentStrategyRequest {
func asAppConfigModelUpdateDeploymentStrategyOperationInputBody() -> UpdateDeploymentStrategyOperationInputBody {
return UpdateDeploymentStrategyOperationInputBody(
deploymentDurationInMinutes: deploymentDurationInMinutes,
description: description,
finalBakeTimeInMinutes: finalBakeTimeInMinutes,
growthFactor: growthFactor,
growthType: growthType)
}
}
/**
Structure to encode the path input for the UpdateEnvironment
operation.
*/
public struct UpdateEnvironmentOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var environmentId: Id
public init(applicationId: Id,
environmentId: Id) {
self.applicationId = applicationId
self.environmentId = environmentId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case environmentId = "EnvironmentId"
}
public func validate() throws {
try applicationId.validateAsId()
try environmentId.validateAsId()
}
}
public extension UpdateEnvironmentRequest {
func asAppConfigModelUpdateEnvironmentOperationInputPath() -> UpdateEnvironmentOperationInputPath {
return UpdateEnvironmentOperationInputPath(
applicationId: applicationId,
environmentId: environmentId)
}
}
/**
Structure to encode the body input for the UpdateEnvironment
operation.
*/
public struct UpdateEnvironmentOperationInputBody: Codable, Equatable {
public var description: Description?
public var monitors: MonitorList?
public var name: Name?
public init(description: Description? = nil,
monitors: MonitorList? = nil,
name: Name? = nil) {
self.description = description
self.monitors = monitors
self.name = name
}
enum CodingKeys: String, CodingKey {
case description = "Description"
case monitors = "Monitors"
case name = "Name"
}
public func validate() throws {
try description?.validateAsDescription()
try monitors?.validateAsMonitorList()
try name?.validateAsName()
}
}
public extension UpdateEnvironmentRequest {
func asAppConfigModelUpdateEnvironmentOperationInputBody() -> UpdateEnvironmentOperationInputBody {
return UpdateEnvironmentOperationInputBody(
description: description,
monitors: monitors,
name: name)
}
}
/**
Structure to encode the path input for the ValidateConfiguration
operation.
*/
public struct ValidateConfigurationOperationInputPath: Codable, Equatable {
public var applicationId: Id
public var configurationProfileId: Id
public init(applicationId: Id,
configurationProfileId: Id) {
self.applicationId = applicationId
self.configurationProfileId = configurationProfileId
}
enum CodingKeys: String, CodingKey {
case applicationId = "ApplicationId"
case configurationProfileId = "ConfigurationProfileId"
}
public func validate() throws {
try applicationId.validateAsId()
try configurationProfileId.validateAsId()
}
}
public extension ValidateConfigurationRequest {
func asAppConfigModelValidateConfigurationOperationInputPath() -> ValidateConfigurationOperationInputPath {
return ValidateConfigurationOperationInputPath(
applicationId: applicationId,
configurationProfileId: configurationProfileId)
}
}
/**
Structure to encode the query input for the ValidateConfiguration
operation.
*/
public struct ValidateConfigurationOperationInputQuery: Codable, Equatable {
public var configurationVersion: Version
public init(configurationVersion: Version) {
self.configurationVersion = configurationVersion
}
enum CodingKeys: String, CodingKey {
case configurationVersion = "configuration_version"
}
public func validate() throws {
try configurationVersion.validateAsVersion()
}
}
public extension ValidateConfigurationRequest {
func asAppConfigModelValidateConfigurationOperationInputQuery() -> ValidateConfigurationOperationInputQuery {
return ValidateConfigurationOperationInputQuery(
configurationVersion: configurationVersion)
}
}
| 32.308208 | 159 | 0.716905 |
648686de3aca72af9cdc6cf9b458fb311f0fab4d | 1,315 | //
// Xcodebuild.swift
//
//
// Created by Stefan Herold on 23.09.20.
//
import Foundation
import SwiftShell
public struct Xcodebuild {
}
public extension Xcodebuild {
enum Command: String {
case buildForTesting = "build-for-testing"
case testWithoutBuilding = "test-without-building"
}
static func execute(cmd: Command,
workspace: String,
schemes: [String],
deviceIds: [String],
testPlan: String? = nil,
resultsBundleURL: URL? = nil) throws {
let destinations = deviceIds.map { "platform=iOS Simulator,id=\($0)" }
for scheme in schemes {
var args = ["xcodebuild", cmd.rawValue, "-workspace", workspace, "-scheme", scheme]
destinations.forEach { args += ["-destination", $0] }
if let testPlan = testPlan {
args += ["-testPlan", testPlan]
}
if let resultBundleURL = resultsBundleURL {
args += ["-resultBundlePath", resultBundleURL.path]
}
let out = run("xcrun", args)
if let error = out.error {
Logger.shared.error(out.stderror)
throw error
}
}
}
}
| 25.784314 | 95 | 0.518631 |
5629baea77c3c4cad8a497abded40d980e1feaee | 10,284 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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
@testable import Beagle
import BeagleSchema
final class CacheManagerDefaultTests: XCTestCase {
private let dependencies = BeagleScreenDependencies()
// swiftlint:disable force_unwrapping
private let jsonData = """
{
"_beagleType_": "beagle:component:text",
"text": "cache",
"style": {
"backgroundColor": "#4000FFFF"
}
}
""".data(using: .utf8)!
// swiftlint:enable force_unwrapping
private let cacheHashHeader = "beagle-hash"
private let serviceMaxCacheAge = "cache-control"
private let defaultHash = "123"
private let defaultURL = "urlTeste"
private let url1 = "urlTeste1"
private let url2 = "urlTeste2"
private let url3 = "urlTeste3"
func test_whenHaveDefaultValue_itShouldAffectIsValid() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 10))
let reference = CacheReference(identifier: "", data: jsonData, hash: "")
let isValid = sut.isValid(reference: reference)
XCTAssert(isValid, "Should not need revalidation")
}
func testMaxAgeDefaultExpired() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 1))
let reference = CacheReference(identifier: "", data: jsonData, hash: "")
let timeOutComponent = expectation(description: "timeOutComponent")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
let isValid = sut.isValid(reference: reference)
timeOutComponent.fulfill()
XCTAssert(isValid == false, "Should need revalidation")
}
waitForExpectations(timeout: 5, handler: nil)
}
func testMaxAgeFromServer() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 0))
let cacheReference = CacheReference(identifier: defaultURL, data: jsonData, hash: defaultHash, maxAge: 5)
let isValid = sut.isValid(reference: cacheReference)
XCTAssert(isValid, "Should not need revalidation")
}
func testMaxAgeFromServerExpired() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 1))
let cacheReference = CacheReference(identifier: defaultURL, data: jsonData, hash: defaultHash, maxAge: 2)
let timeOutComponent = expectation(description: "timeOutComponent")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) {
let isValid = sut.isValid(reference: cacheReference)
XCTAssert(isValid == false, "Should need revalidation")
timeOutComponent.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testMemoryLRU_deletingSecondRecord() {
let memoryCapacity = 2
let diskCapacity = 1
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: memoryCapacity, diskMaximumCapacity: diskCapacity, cacheMaxAge: 10))
let cacheReference1 = CacheReference(identifier: url1, data: jsonData, hash: defaultHash)
let cacheReference2 = CacheReference(identifier: url2, data: jsonData, hash: defaultHash)
let cacheReference3 = CacheReference(identifier: url3, data: jsonData, hash: defaultHash)
sut.addToCache(cacheReference1)
sut.addToCache(cacheReference2)
sut.addToCache(cacheReference3)
if sut.getReference(identifiedBy: url1) != nil {
XCTFail("Should not find the cached reference.")
}
if sut.getReference(identifiedBy: url2) == nil ||
sut.getReference(identifiedBy: url3) == nil {
XCTFail("Could not find the cached reference.")
}
}
func testMemoryLRU_deletingFirstRecord() {
let memoryCapacity = 2
let diskCapacity = 0
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: memoryCapacity, diskMaximumCapacity: diskCapacity, cacheMaxAge: 10))
sut.clear()
let cacheReference1 = CacheReference(identifier: url1, data: jsonData, hash: defaultHash)
let cacheReference2 = CacheReference(identifier: url2, data: jsonData, hash: defaultHash)
let cacheReference3 = CacheReference(identifier: url3, data: jsonData, hash: defaultHash)
sut.addToCache(cacheReference1)
sut.addToCache(cacheReference2)
_ = sut.getReference(identifiedBy: url1)
sut.addToCache(cacheReference3)
if sut.getReference(identifiedBy: url2) != nil {
XCTFail("Should not find the cached reference.")
}
if sut.getReference(identifiedBy: url1) == nil ||
sut.getReference(identifiedBy: url3) == nil {
XCTFail("Could not find the cached reference.")
}
}
func testDiskLRU_deletingSecondRecord() {
let memoryCapacity = 1
let diskCapacity = 2
struct CacheManagerDependenciesLocal: CacheManagerDefault.Dependencies {
var logger: BeagleLoggerType = BeagleLoggerDefault()
var cacheDiskManager: CacheDiskManagerProtocol = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
var decoder: ComponentDecoding = ComponentDecoder()
}
let manager = CacheManagerDefault(dependencies: CacheManagerDependenciesLocal(), config: .init(memoryMaximumCapacity: memoryCapacity, diskMaximumCapacity: diskCapacity, cacheMaxAge: 10))
manager.clear()
let cacheReference1 = CacheReference(identifier: url1, data: jsonData, hash: defaultHash)
let cacheReference2 = CacheReference(identifier: url2, data: jsonData, hash: defaultHash)
let cacheReference3 = CacheReference(identifier: url3, data: jsonData, hash: defaultHash)
manager.addToCache(cacheReference1)
manager.addToCache(cacheReference2)
_ = manager.getReference(identifiedBy: url1)
manager.addToCache(cacheReference3)
if manager.getReference(identifiedBy: url2) != nil {
XCTFail("Should not find the cached reference.")
}
if manager.getReference(identifiedBy: url1) == nil ||
manager.getReference(identifiedBy: url3) == nil {
XCTFail("Could not find the cached reference.")
}
}
func testDiskLRU_deletingFirstRecord() {
let memoryCapacity = 0
let diskCapacity = 2
struct CacheManagerDependenciesLocal: CacheManagerDefault.Dependencies {
var logger: BeagleLoggerType = BeagleLoggerDefault()
var cacheDiskManager: CacheDiskManagerProtocol = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
var decoder: ComponentDecoding = ComponentDecoder()
}
let sut = CacheManagerDefault(dependencies: CacheManagerDependenciesLocal(), config: .init(memoryMaximumCapacity: memoryCapacity, diskMaximumCapacity: diskCapacity, cacheMaxAge: 10))
let cacheReference1 = CacheReference(identifier: url1, data: jsonData, hash: defaultHash)
let cacheReference2 = CacheReference(identifier: url2, data: jsonData, hash: defaultHash)
let cacheReference3 = CacheReference(identifier: url3, data: jsonData, hash: defaultHash)
sut.addToCache(cacheReference1)
sut.addToCache(cacheReference2)
sut.addToCache(cacheReference3)
if sut.getReference(identifiedBy: url1) != nil {
XCTFail("Should not find the cached reference.")
}
if sut.getReference(identifiedBy: url2) == nil ||
sut.getReference(identifiedBy: url3) == nil {
XCTFail("Could not find the cached reference.")
}
}
func testGetExistingReference() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 10))
addDefaultComponent(manager: sut)
if getDefaultReference(manager: sut) == nil {
XCTFail("Could not retrieve reference.")
}
}
func testGetInexistentReference() {
let sut = CacheManagerDefault(dependencies: CacheManagerDependencies(), config: .init(memoryMaximumCapacity: 2, diskMaximumCapacity: 2, cacheMaxAge: 10))
sut.clear()
if getDefaultReference(manager: sut) != nil {
XCTFail("Should not retrieve reference.")
}
}
private func addDefaultComponent(manager: CacheManagerDefault) {
let cacheReference = CacheReference(identifier: defaultURL, data: jsonData, hash: defaultHash)
manager.addToCache(cacheReference)
}
private func getDefaultReference(manager: CacheManagerDefault) -> CacheReference? {
return manager.getReference(identifiedBy: defaultURL)
}
}
struct CacheManagerDependencies: CacheManagerDefault.Dependencies {
var logger: BeagleLoggerType = BeagleLoggerDefault()
}
struct CacheDiskManagerDummy: CacheDiskManagerProtocol {
func removeLastUsed() { }
func saveChanges() { }
func update(_ reference: CacheReference) { }
func getReference(for key: String) -> CacheReference? {
return nil
}
func numberOfReferences() -> Int {
return 0
}
func clear() { }
}
| 46.533937 | 194 | 0.689518 |
1eed0e67dd17eb94d9a1ad394f4a9dde438c63e7 | 2,422 | //
// AppDelegate.swift
// SFAPPRealTimeLogCaughter
//
// Created by [email protected] on 08/24/2021.
// Copyright (c) 2021 [email protected]. 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.
self.window = UIWindow()
let nvc = UINavigationController.init(rootViewController: ViewController());
self.window?.rootViewController = nvc;
self.window?.makeKeyAndVisible()
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 throttle down OpenGL ES frame rates. 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 inactive 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.576923 | 285 | 0.744426 |
674f759ad9723c030952d4af907520de3aea1540 | 1,820 | @testable import SexpyJSON
import XCTest
final class ArraySyntaxTests: XCTestCase {
func testEmpty() throws {
let (element, remainder) = buildParser().run("[]")
XCTAssertEqual(element, SexpyJSONElement.array([]))
XCTAssertEqual(remainder, ""[...])
}
func testOneElement() throws {
let (element, remainder) = buildParser().run("[1]")
XCTAssertEqual(element, SexpyJSONElement.array([.number("1")]))
XCTAssertEqual(remainder, ""[...])
}
func testOneSymbolElement() throws {
let (element, remainder) = buildParser().run("[blep]")
XCTAssertEqual(try XCTUnwrap(element), SexpyJSONElement.array([SexpyJSONElement.symbol(.init("blep"))]))
XCTAssertEqual(remainder, ""[...])
}
func testStringsNumbers() throws {
let (element, remainder) = buildParser().run(#"[1, "first", 42, "second"]"#)
let actualElement = try XCTUnwrap(element)
XCTAssertEqual(actualElement, SexpyJSONElement.array([
.number("1"),
.string("first"),
.number("42"),
.string("second"),
]))
XCTAssertEqual(remainder, ""[...])
}
func testNested() throws {
let (element, remainder) = buildParser().run(#"[1, "first", 42, "second", [11, [], 6, ["deep"]]]"#)
let actualElement = try XCTUnwrap(element)
XCTAssertEqual(actualElement, SexpyJSONElement.array([
.number("1"),
.string("first"),
.number("42"),
.string("second"),
.array([
.number("11"),
.array([]),
.number("6"),
.array([
.string("deep"),
]),
]),
]))
XCTAssertEqual(remainder, ""[...])
}
}
| 33.090909 | 112 | 0.532418 |
72df057f1a53b62543a3bf826c8c816287f83fd9 | 1,910 | //
// AkuratecoSaleSuccess.swift
// AkuratecoSDK
//
// Created by Bodia on 09.03.2021.
//
import Foundation
/// The SALE success result of the *AkuratecoSaleResult*.
///
/// See *AkuratecoSaleResponse*
public struct AkuratecoSaleSuccess: DetailsAkuratecoResultProtocol {
public let action: AkuratecoAction
public let result: AkuratecoResult
public let status: AkuratecoStatus
public let orderId: String
public let transactionId: String
public let transactionDate: Date
public let descriptor: String?
public let orderAmount: Double
public let orderCurrency: String
}
extension AkuratecoSaleSuccess: Decodable {
enum CodingKeys: String, CodingKey {
case action, result, status, descriptor
case orderId = "order_id"
case transactionId = "trans_id"
case transactionDate = "trans_date"
case orderAmount = "amount"
case orderCurrency = "currency"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
action = try container.decode(AkuratecoAction.self, forKey: .action)
result = try container.decode(AkuratecoResult.self, forKey: .result)
status = try container.decode(AkuratecoStatus.self, forKey: .status)
orderId = try container.decode(String.self, forKey: .orderId)
transactionId = try container.decode(String.self, forKey: .transactionId)
orderCurrency = try container.decode(String.self, forKey: .orderCurrency)
orderAmount = Double(try container.decode(String.self, forKey: .orderAmount)) ?? 0
transactionDate = AkuratecoDateFormatter.date(from: try container.decode(String.self, forKey: .transactionDate)) ?? Date()
descriptor = try container.decodeIfPresent(String.self, forKey: .descriptor)
}
}
| 31.833333 | 130 | 0.688482 |
de256b600d439f0e9459a333c06599747f48be4d | 2,549 | // Copyright (c) 2021 梁大红 <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public extension Chain where Base: UISwitch {
@discardableResult
@available(iOS 5.0, *)
func onTintColor(_ onTintColor: UIColor?) -> Chain {
base.onTintColor = onTintColor
return self
}
@discardableResult
@available(iOS 6.0, *)
func thumbTintColor(_ thumbTintColor: UIColor?) -> Chain {
base.thumbTintColor = thumbTintColor
return self
}
@discardableResult
@available(iOS 6.0, *)
func onImage(_ onImage: UIImage?) -> Chain {
base.onImage = onImage
return self
}
@discardableResult
@available(iOS 6.0, *)
func offImage(_ offImage: UIImage?) -> Chain {
base.offImage = offImage
return self
}
@discardableResult
@available(iOS 14.0, *)
func title(_ title: String?) -> Chain {
base.title = title
return self
}
@discardableResult
@available(iOS 14.0, *)
func preferredStyle(_ preferredStyle: UISwitch.Style) -> Chain {
base.preferredStyle = preferredStyle
return self
}
@discardableResult
func isOn(_ isOn: Bool) -> Chain {
base.isOn = isOn
return self
}
@discardableResult
func setOn(_ on: Bool, animated: Bool) -> Chain {
base.setOn(on, animated: animated)
return self
}
}
| 31.469136 | 83 | 0.655159 |
b94d769340faadda77a5ae05e1b55f607de2ecc5 | 1,161 | //
// tipcalcDUITests.swift
// tipcalcDUITests
//
// Created by KimNgan Nguyen on 3/31/19.
// Copyright © 2019 Derek Ye. All rights reserved.
//
import XCTest
class tipcalcDUITests: XCTestCase {
override func 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.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.171429 | 182 | 0.689922 |
cc31cda5f878086d256e4adc4a80db85bc0157ba | 1,086 | //
// Array+Extensions.swift
// MexicanTrain
//
// Created by Ceri on 10/05/2020.
//
import Foundation
extension Array {
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
@inlinable func anySatisfies(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
for item in self {
if try predicate(item) {
return true
}
}
return false
}
}
extension Array where Element: Equatable {
func with(_ element: Element) -> [Element] {
self + [element]
}
func without(_ element: Element) -> [Element]? {
guard let firstIndex = firstIndex(of: element) else {
return nil
}
var array = self
_ = array.remove(at: firstIndex)
return array
}
func removing(_ element: Element) -> [Element] {
guard let firstIndex = firstIndex(of: element) else {
return self
}
var array = self
_ = array.remove(at: firstIndex)
return array
}
}
| 22.625 | 90 | 0.558932 |
21159c7865703dc7f1e7cb1c57a4438fe87e790b | 211 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
protocol DefaultRouterInput {
}
| 17.583333 | 73 | 0.734597 |
72b0255dc1e191eece81890043fb86e30c1f790f | 291 | import Foundation
public class KuwaharaFilter: BasicOperation {
@objc open var radius:Int = 3 { didSet { uniformSettings["radius"] = radius } }
public init() {
super.init(fragmentShader:KuwaharaFragmentShader, numberOfInputs:1)
({radius = 3})()
}
}
| 26.454545 | 83 | 0.639175 |
017ce7f54f911d090d87a42f25388dd20943a222 | 358 | import XCTest
@testable import BatteryWidget
final class BatteryWidgetTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(BatteryWidget().text, "Hello, World!")
}
}
| 29.833333 | 87 | 0.689944 |
4b449bdcc81995a8ff64c4c2e069b78a2eb9a896 | 93 | //
// JacobTheme.swift
// Context
//
// Created by mac on 2021/4/4.
//
import Foundation
| 10.333333 | 31 | 0.623656 |
622a0ad9c98054c75ddbf5f4b1885a4b86af2c42 | 3,248 | import ComScore
import BitmovinPlayer
public final class ComScoreAnalytics {
private static let serialQueue = DispatchQueue(label: "com.bitmovin.player.integrations.comscore.ComScoreAnalytics")
private static var started: Bool = false
private static var configuration: ComScoreConfiguration?
/**
Start ComScoreAnalytics app level tracking
- Parameters:
- configuration: The ComScoreConfiguration that contains application specific information
*/
public static func start(configuration: ComScoreConfiguration) {
serialQueue.sync {
if !started {
ComScoreAnalytics.configuration = configuration
let publisherConfig = SCORPublisherConfiguration(builderBlock: { builder in
builder?.publisherId = configuration.publisherId
})
SCORAnalytics.configuration().addClient(with: publisherConfig)
SCORAnalytics.configuration().applicationName = configuration.applicationName
if configuration.userConsent != .unknown {
SCORAnalytics.configuration().setPersistentLabelWithName(
"cs_ucfr",
value: configuration.userConsent.rawValue
)
}
if configuration.childDirectedAppMode {
SCORAnalytics.configuration().enableChildDirectedApplicationMode()
}
SCORAnalytics.start()
started = true
} else {
BitLog.d("ComScoreAnalytics has already been started. Ignoring call to start")
}
}
}
/**
Set a persistent label on the ComScore PublisherConfiguration
- Parameters:
- label: The label name
- value: The label value
*/
public static func setPersistentLabel(label: String, value: String) {
serialQueue.sync {
if started {
notifyHiddenEvent(publisherId: ComScoreAnalytics.configuration?.publisherId, label: label, value: value)
BitLog.d("ComScore persistent label set: [\(label):\(value)]")
}
}
}
/**
Set persistent labels on the ComScore PublisherConfiguration
- Parameters:
- label: The labels to set
*/
public static func setPersistentLabels(labels: [String: String]) {
serialQueue.sync {
if started {
notifyHiddenEvents(publisherId: ComScoreAnalytics.configuration?.publisherId, labels: labels)
BitLog.d("ComScore persistent labels set: [\(labels.map { "\($0.key):\($0.value)"})]")
}
}
}
public static func createComScoreStreamingAnalytics(bitmovinPlayer: Player, metadata: ComScoreMetadata) throws -> ComScoreStreamingAnalytics? {
if started {
return ComScoreStreamingAnalytics(bitmovinPlayer: bitmovinPlayer, configuration: ComScoreAnalytics.configuration!, metadata: metadata)
} else {
throw ComScoreError.notStarted
}
}
public static func isActive() -> Bool {
return ComScoreAnalytics.started
}
}
@frozen
public enum ComScoreError: Error {
case notStarted
}
| 37.767442 | 147 | 0.62931 |
03f173509df4dcd2aff72c071305632d7e62e2c3 | 1,404 | //
// AppDelegate.swift
// Notare
//
// Created by Bree Jeune on 3/2/20.
// Copyright © 2020 Young. 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.
}
}
| 36.947368 | 179 | 0.745726 |
2ff23b59d67fcb60f2bd39db455536c1770c2a87 | 1,549 |
import UIKit
@IBDesignable class DesignView: UIView {
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet{
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth:CGFloat = 0 {
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor:UIColor = .white {
didSet{
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable
override var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
layer.masksToBounds = false
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
}
| 20.381579 | 53 | 0.490639 |
64a8deb7102d4e40987c69fb02c7e740f1438cdf | 2,656 | //
// WindowsClass.swift
// Car
//
// Created by Mikk Rätsep on 27/09/2017.
// Copyright © 2017 High-Mobility GmbH. All rights reserved.
//
import AutoAPI
import Foundation
public class WindowClass {
public let isOpen: Bool
public let location: Location
let position: AAWindowLocation
init(open: AAWindowPosition) {
isOpen = open.position == .open
location = Location(position: open.location)
position = open.location
}
}
public class WindowsCommand: CommandClass {
public private(set) var open: Bool = false
public private(set) var windows: [WindowClass] = []
}
extension WindowsCommand: Parser {
}
extension WindowsCommand: CapabilityParser {
func update(from capability: AASupportedCapability) {
guard capability.capabilityID == AAWindows.identifier,
capability.supportsAllProperties(for: AAWindows.PropertyIdentifier.self) else {
return
}
isAvailable = true
}
}
extension WindowsCommand: ResponseParser {
@discardableResult func update(from response: AACapability) -> CommandType? {
guard let windows = response as? AAWindows,
let positions = windows.positions else {
return nil
}
open = positions.compactMap {
$0.value
}.filter {
$0.location == .hatch
}.contains {
$0.position == .open
}
self.windows = positions.compactMap {
$0.value
}.map {
WindowClass(open: $0)
}
return .other(self)
}
}
public class WindowsStatusCommand: CommandClass {
public private(set) var windows: [WindowClass] = []
}
extension WindowsStatusCommand: Parser {
}
extension WindowsStatusCommand: CapabilityParser {
func update(from capability: AASupportedCapability) {
guard capability.capabilityID == AAWindows.identifier,
capability.supports(propertyIDs: AAWindows.PropertyIdentifier.openPercentages.rawValue,
AAWindows.PropertyIdentifier.positions.rawValue) else {
return
}
isAvailable = true
}
}
extension WindowsStatusCommand: ResponseParser {
@discardableResult func update(from response: AACapability) -> CommandType? {
guard let windows = response as? AAWindows,
let positions = windows.positions else {
return nil
}
self.windows = positions.compactMap {
$0.value
}.map {
WindowClass(open: $0)
}
return .other(self)
}
}
| 22.508475 | 99 | 0.61634 |
38fe3ff8a77fb0cdf36dbb75f6a0b468e2a10bf6 | 2,172 | //
// AppDelegate.swift
// iOS_Practical_Naman
//
// Created by naman on 02/02/19.
// Copyright © 2019 naman. 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
}
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.212766 | 285 | 0.755525 |
7117dce7e9a5b07589b1be553b12c59c0e60f23f | 42,474 | //
// ResponseModels.swift
// EosioSwift
//
// Created by Steve McCoole on 2/21/19.
// Copyright (c) 2017-2019 block.one and its contributors. All rights reserved.
//
import Foundation
/// Response struct for the `get_info` RPC endpoint.
public struct EosioRpcInfoResponse: EosioRpcInfoResponseProtocol, EosioRpcResponseProtocol, Decodable {
public var _rawResponse: Any?
public let serverVersion: String
public let chainId: String
public let headBlockNum: EosioUInt64
public let lastIrreversibleBlockNum: EosioUInt64
public let lastIrreversibleBlockId: String
public let headBlockId: String
public let headBlockTime: String
public let headBlockProducer: String
public let virtualBlockCpuLimit: EosioUInt64
public let virtualBlockNetLimit: EosioUInt64
public let blockCpuLimit: EosioUInt64
public let blockNetLimit: EosioUInt64
public let serverVersionString: String
enum CodingKeys: String, CodingKey {
case serverVersion = "server_version"
case chainId = "chain_id"
case headBlockNum = "head_block_num"
case lastIrreversibleBlockNum = "last_irreversible_block_num"
case lastIrreversibleBlockId = "last_irreversible_block_id"
case headBlockId = "head_block_id"
case headBlockTime = "head_block_time"
case headBlockProducer = "head_block_producer"
case virtualBlockCpuLimit = "virtual_block_cpu_limit"
case virtualBlockNetLimit = "virtual_block_net_limit"
case blockCpuLimit = "block_cpu_limit"
case blockNetLimit = "block_net_limit"
case serverVersionString = "server_version_string"
}
public init(serverVersion: String = "",
chainId: String,
headBlockNum: EosioUInt64,
lastIrreversibleBlockNum: EosioUInt64,
lastIrreversibleBlockId: String,
headBlockId: String,
headBlockTime: String,
headBlockProducer: String = "",
virtualBlockCpuLimit: EosioUInt64 = EosioUInt64.uint64(0),
virtualBlockNetLimit: EosioUInt64 = EosioUInt64.uint64(0),
blockCpuLimit: EosioUInt64 = EosioUInt64.uint64(0),
blockNetLimit: EosioUInt64 = EosioUInt64.uint64(0),
serverVersionString: String = "") {
self.serverVersion = serverVersion
self.chainId = chainId
self.headBlockNum = headBlockNum
self.lastIrreversibleBlockNum = lastIrreversibleBlockNum
self.lastIrreversibleBlockId = lastIrreversibleBlockId
self.headBlockId = headBlockId
self.headBlockTime = headBlockTime
self.headBlockProducer = headBlockProducer
self.virtualBlockCpuLimit = virtualBlockCpuLimit
self.virtualBlockNetLimit = virtualBlockNetLimit
self.blockCpuLimit = blockCpuLimit
self.blockNetLimit = blockNetLimit
self.serverVersionString = serverVersionString
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
serverVersion = try container.decodeIfPresent(String.self, forKey: .serverVersion) ?? ""
chainId = try container.decode(String.self, forKey: .chainId)
headBlockNum = try container.decode(EosioUInt64.self, forKey: .headBlockNum)
lastIrreversibleBlockNum = try container.decode(EosioUInt64.self, forKey: .lastIrreversibleBlockNum)
lastIrreversibleBlockId = try container.decode(String.self, forKey: .lastIrreversibleBlockId)
headBlockId = try container.decode(String.self, forKey: .headBlockId)
headBlockTime = try container.decode(String.self, forKey: .headBlockTime)
headBlockProducer = try container.decodeIfPresent(String.self, forKey: .headBlockProducer) ?? ""
virtualBlockCpuLimit = try container.decodeIfPresent(EosioUInt64.self, forKey: .virtualBlockCpuLimit) ?? EosioUInt64.uint64(0)
virtualBlockNetLimit = try container.decodeIfPresent(EosioUInt64.self, forKey: .virtualBlockNetLimit) ?? EosioUInt64.uint64(0)
blockCpuLimit = try container.decodeIfPresent(EosioUInt64.self, forKey: .blockCpuLimit) ?? EosioUInt64.uint64(0)
blockNetLimit = try container.decodeIfPresent(EosioUInt64.self, forKey: .blockNetLimit) ?? EosioUInt64.uint64(0)
serverVersionString = try container.decodeIfPresent(String.self, forKey: .serverVersionString) ?? ""
}
}
/// Response struct for the `get_block` RPC endpoint.
public struct EosioRpcBlockResponse: EosioRpcBlockResponseProtocol, EosioRpcResponseProtocol, Decodable {
public var _rawResponse: Any?
public let timestamp: String
public let producer: String
public let confirmed: UInt
public let previous: String
public let transactionMroot: String
public let actionMroot: String
public let scheduleVersion: UInt
public let newProducers: String?
public let headerExtensions: [String]
public let producerSignature: String
public let transactions: [Any]
public let blockExtensions: [Any]
public let id: String
public let blockNum: EosioUInt64
public let refBlockPrefix: EosioUInt64
enum CodingKeys: String, CodingKey {
case timestamp
case producer
case confirmed
case previous
case transactionMroot = "transaction_mroot"
case actionMroot = "action_mroot"
case scheduleVersion = "schedule_version"
case newProducers = "new_producers"
case headerExtensions = "header_extensions"
case producerSignature = "producer_signature"
case transactions
case blockExtensions = "block_extensions"
case id
case blockNum = "block_num"
case refBlockPrefix = "ref_block_prefix"
}
public init(timestamp: String, producer: String = "", confirmed: UInt = 0, previous: String = "", transactionMroot: String = "",
actionMroot: String = "", scheduleVersion: UInt = 0, newProducers: String?, headerExtensions: [String] = [],
producerSignature: String = "", transactions: [Any] = [Any](),
blockExtensions: [Any] = [Any](),
id: String, blockNum: EosioUInt64, refBlockPrefix: EosioUInt64) {
self.timestamp = timestamp
self.producer = producer
self.confirmed = confirmed
self.previous = previous
self.transactionMroot = transactionMroot
self.actionMroot = actionMroot
self.scheduleVersion = scheduleVersion
self.newProducers = newProducers
self.headerExtensions = headerExtensions
self.producerSignature = producerSignature
self.transactions = transactions
self.blockExtensions = blockExtensions
self.id = id
self.blockNum = blockNum
self.refBlockPrefix = refBlockPrefix
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
timestamp = try container.decode(String.self, forKey: .timestamp)
producer = try container.decodeIfPresent(String.self, forKey: .producer) ?? ""
confirmed = try container.decodeIfPresent(UInt.self, forKey: .confirmed) ?? 0
previous = try container.decodeIfPresent(String.self, forKey: .previous) ?? ""
transactionMroot = try container.decodeIfPresent(String.self, forKey: .transactionMroot) ?? ""
actionMroot = try container.decodeIfPresent(String.self, forKey: .actionMroot) ?? ""
scheduleVersion = try container.decodeIfPresent(UInt.self, forKey: .scheduleVersion) ?? 0
newProducers = try container.decodeIfPresent(String.self, forKey: .newProducers)
headerExtensions = try container.decodeIfPresent([String].self, forKey: .headerExtensions) ?? [String]()
producerSignature = try container.decodeIfPresent(String.self, forKey: .producerSignature) ?? ""
var nestedTrx = try? container.nestedUnkeyedContainer(forKey: .transactions)
transactions = nestedTrx?.decodeDynamicValues() ?? [Any]()
var nestedBlx = try? container.nestedUnkeyedContainer(forKey: .blockExtensions)
blockExtensions = nestedBlx?.decodeDynamicValues() ?? [Any]()
id = try container.decode(String.self, forKey: .id)
blockNum = try container.decode(EosioUInt64.self, forKey: .blockNum)
refBlockPrefix = try container.decode(EosioUInt64.self, forKey: .refBlockPrefix)
}
}
/// Response struct for the `get_raw_abi` RPC endpoint.
public struct EosioRpcRawAbiResponse: EosioRpcRawAbiResponseProtocol, EosioRpcResponseProtocol, Decodable {
public var _rawResponse: Any?
public var accountName: String
public var codeHash: String
public var abiHash: String
public var abi: String
enum CodingKeys: String, CodingKey {
case accountName = "account_name"
case codeHash = "code_hash"
case abiHash = "abi_hash"
case abi
}
public init(accountName: String, codeHash: String, abiHash: String, abi: String) {
self.accountName = accountName
self.codeHash = codeHash
self.abiHash = abiHash
self.abi = abi
}
}
/// Response struct for the `get_required_keys` RPC endpoint.
public struct EosioRpcRequiredKeysResponse: EosioRpcRequiredKeysResponseProtocol, EosioRpcResponseProtocol, Decodable {
public var _rawResponse: Any?
public var requiredKeys: [String]
enum CodingKeys: String, CodingKey {
case requiredKeys = "required_keys"
}
public init(requiredKeys: [String]) {
self.requiredKeys = requiredKeys
}
}
/// Response struct for the `push_transaction` RPC endpoint.
public struct EosioRpcTransactionResponse: EosioRpcTransactionResponseProtocol, EosioRpcResponseProtocol, Decodable {
public var _rawResponse: Any?
public var transactionId: String
public var processed: [String: Any]?
enum CodingKeys: String, CodingKey {
case transactionId = "transaction_id"
case processed
}
public init(transactionId: String) {
self.transactionId = transactionId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
transactionId = try container.decode(String.self, forKey: .transactionId)
let processedContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .processed)
processed = processedContainer?.decodeDynamicKeyValues()
}
}
/// Response struct for the `get_key_accounts` RPC endpoint
public struct EosioRpcKeyAccountsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var accountNames: [String] = [String]()
enum CodingKeys: String, CodingKey {
case accountNames = "account_names"
}
}
/// Reponse type for `wait_weight` in RPC endpoint responses.
public struct WaitWeight: Decodable {
public var waitSec: EosioUInt64
public var weight: EosioUInt64
enum CodingKeys: String, CodingKey {
case waitSec = "wait_sec"
case weight
}
}
/// Response type for `permission_level` in RPC endpoint responses.
public struct PermissionLevel: Decodable {
public var actor: String
public var permission: String
enum CodingKeys: String, CodingKey {
case actor
case permission
}
}
/// Response type for `permission_level_weight in RPC endpoint responses.
public struct PermissionLevelWeight: Decodable {
public var weight: EosioUInt64
public var permission: PermissionLevel
enum CodingKeys: String, CodingKey {
case weight
case permission
}
}
/// Response type for `key_weight` structure in RPC endpoint responses.
public struct KeyWeight: Decodable {
public var key: String
public var weight: EosioUInt64
enum CodingKeys: String, CodingKey {
case key
case weight
}
}
/// Response type for `authority` structure in RPC endpoint responses.
public struct Authority: Decodable {
public var threshold: EosioUInt64
public var keys: [KeyWeight]
public var waits: [WaitWeight]
public var accounts: [PermissionLevelWeight]
enum CodingKeys: String, CodingKey {
case threshold
case keys
case waits
case accounts
}
}
/// Response type for `permission` structure in RPC endpoint responses.
public struct Permission: Decodable {
public var permName: String
public var parent: String
public var requiredAuth: Authority
enum CodingKeys: String, CodingKey {
case permName = "perm_name"
case parent
case requiredAuth = "required_auth"
}
}
/// Response type for the `get_account` RPC endpoint.
public struct EosioRpcAccountResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var accountName: String
public var headBlockNum: EosioUInt64 = EosioUInt64.uint64(0)
public var headBlockTime: String = ""
public var privileged: Bool = false
public var lastCodeUpdate: String = ""
public var created: String = ""
public var coreLiquidBalance: String = ""
public var ramQuota: EosioInt64 = EosioInt64.int64(0)
public var netWeight: EosioInt64 = EosioInt64.int64(0)
public var cpuWeight: EosioInt64 = EosioInt64.int64(0)
public var netLimit: [String: Any]
public var cpuLimit: [String: Any]
public var ramUsage: EosioInt64 = EosioInt64.int64(0)
public var permissions: [Permission]
public var totalResources: [String: Any]?
public var selfDelegatedBandwidth: [String: Any]?
public var refundRequest: [String: Any]?
public var voterInfo: [String: Any]?
enum CodingKeys: String, CodingKey {
case accountName = "account_name"
case headBlockNum = "head_block_num"
case headBlockTime = "head_block_time"
case privileged
case lastCodeUpdate = "last_code_update"
case created
case coreLiquidBalance = "core_liquid_balance"
case ramQuota = "ram_quota"
case netWeight = "net_weight"
case cpuWeight = "cpu_weight"
case netLimit = "net_limit"
case cpuLimit = "cpu_limit"
case ramUsage = "ram_usage"
case permissions
case totalResources = "total_resources"
case selfDelegatedBandwidth = "self_delegated_bandwidth"
case refundRequest = "refund_request"
case voterInfo = "voter_info"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
accountName = try container.decode(String.self, forKey: .accountName)
headBlockNum = try container.decodeIfPresent(EosioUInt64.self, forKey: .headBlockNum) ?? EosioUInt64.uint64(0)
headBlockTime = try container.decodeIfPresent(String.self, forKey: .headBlockTime) ?? ""
privileged = try container.decodeIfPresent(Bool.self, forKey: .privileged) ?? false
lastCodeUpdate = try container.decodeIfPresent(String.self, forKey: .lastCodeUpdate) ?? ""
created = try container.decodeIfPresent(String.self, forKey: .created) ?? ""
coreLiquidBalance = try container.decodeIfPresent(String.self, forKey: .coreLiquidBalance) ?? ""
ramQuota = try container.decodeIfPresent(EosioInt64.self, forKey: .ramQuota) ?? EosioInt64.int64(0)
netWeight = try container.decodeIfPresent(EosioInt64.self, forKey: .netWeight) ?? EosioInt64.int64(0)
cpuWeight = try container.decodeIfPresent(EosioInt64.self, forKey: .cpuWeight) ?? EosioInt64.int64(0)
// netLimit = try container.decodeIfPresent(JSONValue.self, forKey: .netLimit)?.toDictionary() ?? [String: Any]()
let netLimitContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .netLimit)
netLimit = netLimitContainer?.decodeDynamicKeyValues() ?? [String: Any]()
let cpuLimitContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .cpuLimit)
cpuLimit = cpuLimitContainer?.decodeDynamicKeyValues() ?? [String: Any]()
ramUsage = try container.decodeIfPresent(EosioInt64.self, forKey: .ramUsage) ?? EosioInt64.int64(0)
permissions = try container.decodeIfPresent([Permission].self, forKey: .permissions) ?? [Permission]()
let totalResourcesContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .totalResources)
totalResources = totalResourcesContainer?.decodeDynamicKeyValues()
let selfDelegatedBandwidthContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .selfDelegatedBandwidth)
selfDelegatedBandwidth = selfDelegatedBandwidthContainer?.decodeDynamicKeyValues()
let refundRequestContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .refundRequest)
refundRequest = refundRequestContainer?.decodeDynamicKeyValues()
let voterInfoContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .voterInfo)
voterInfo = voterInfoContainer?.decodeDynamicKeyValues()
}
}
/// Response type for the `get_transaction` RPC endpoint.
public struct EosioRpcGetTransactionResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var id: String
public var trx: [String: Any]
public var blockTime: String
public var blockNum: EosioUInt64
public var lastIrreversibleBlock: EosioUInt64
public var traces: [String: Any]?
enum CodingKeys: String, CodingKey {
case id
case trx
case blockTime = "block_time"
case blockNum = "block_num"
case lastIrreversibleBlock = "last_irreversible_block"
case traces
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
let trxContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .trx)
trx = trxContainer?.decodeDynamicKeyValues() ?? [String: Any]()
blockTime = try container.decode(String.self, forKey: .blockTime)
blockNum = try container.decode(EosioUInt64.self, forKey: .blockNum)
lastIrreversibleBlock = try container.decode(EosioUInt64.self, forKey: .lastIrreversibleBlock)
let tracesContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .traces)
traces = tracesContainer?.decodeDynamicKeyValues() ?? [String: Any]()
}
}
/// Response struct for the `get_currency_balance` RPC endpoint
public struct EosioRpcCurrencyBalanceResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var currencyBalance: [String]
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
currencyBalance = try container.decode([String].self)
}
}
/// Response type for the `Currency` RPC endpoint.
public struct CurrencyStats: Decodable {
public var supply: String
public var maxSupply: String
public var issuer: String
enum CodingKeys: String, CodingKey {
case supply
case maxSupply = "max_supply"
case issuer
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
supply = try container.decode(String.self, forKey: .supply)
maxSupply = try container.decode(String.self, forKey: .maxSupply)
issuer = try container.decode(String.self, forKey: .issuer)
}
}
/// Response type for the `get_currency_stats` RPC endpoint.
public struct EosioRpcCurrencyStatsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var symbol: String
public var currencyStats: CurrencyStats
private struct CustomCodingKeys: CodingKey { // to decode custom symbol key (i.e. "EOS")
var stringValue: String
init?(stringValue: String) { self.stringValue = stringValue }
var intValue: Int?
init?(intValue: Int) { return nil }
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
symbol = container.allKeys.first?.stringValue ?? "EOS"
currencyStats = try container.decode(CurrencyStats.self, forKey: CustomCodingKeys(stringValue: symbol)!)
}
}
/// Response type for the `get_raw_code_and_abi` RPC endpoint.
public struct EosioRpcRawCodeAndAbiResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var accountName: String
public var wasm: String
public var abi: String
enum CustomCodingKeys: String, CodingKey {
case accountName = "account_name"
case wasm
case abi
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
accountName = try container.decode(String.self, forKey: .accountName)
wasm = try container.decode(String.self, forKey: .wasm)
abi = try container.decode(String.self, forKey: .abi)
}
}
/// Response type for the `get_code` RPC endpoint.
public struct EosioRpcCodeResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var accountName: String
public var codeHash: String
public var wast: String
public var wasm: String
public var abi: [String: Any]?
enum CustomCodingKeys: String, CodingKey {
case accountName = "account_name"
case codeHash = "code_hash"
case wast
case wasm
case abi
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
accountName = try container.decode(String.self, forKey: .accountName)
codeHash = try container.decode(String.self, forKey: .codeHash)
wast = try container.decode(String.self, forKey: .wast)
wasm = try container.decode(String.self, forKey: .wasm)
let abiContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .abi)
abi = abiContainer?.decodeDynamicKeyValues()
}
}
/// Response type for the `get_abi` RPC endpoint.
public struct EosioRpcAbiResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var accountName: String
public var abi: [String: Any]
enum CustomCodingKeys: String, CodingKey {
case accountName = "account_name"
case abi
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
accountName = try container.decode(String.self, forKey: .accountName)
let abiContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .abi)
abi = abiContainer?.decodeDynamicKeyValues() ?? [String: Any]()
}
}
/// Response struct for the rows returned in the `get_producers` RPC endpoint response.
public struct ProducerRows: Decodable {
public var owner: String
public var totalVotes: String
public var producerKey: String
public var isActive: Int
public var url: String
public var unpaidBlocks: EosioUInt64
public var lastClaimTime: String
public var location: UInt16
enum CustomCodingKeys: String, CodingKey {
case owner
case totalVotes = "total_votes"
case producerKey = "producer_key"
case isActive = "is_active"
case url
case unpaidBlocks = "unpaid_blocks"
case lastClaimTime = "last_claim_time"
case location
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
owner = try container.decode(String.self, forKey: .owner)
totalVotes = try container.decode(String.self, forKey: .totalVotes)
producerKey = try container.decode(String.self, forKey: .producerKey)
isActive = try container.decode(Int.self, forKey: .isActive)
url = try container.decodeIfPresent(String.self, forKey: .url) ?? ""
unpaidBlocks = try container.decodeIfPresent(EosioUInt64.self, forKey: .unpaidBlocks) ?? EosioUInt64.uint64(0)
lastClaimTime = try container.decodeIfPresent(String.self, forKey: .lastClaimTime) ?? ""
location = try container.decodeIfPresent(UInt16.self, forKey: .location) ?? 0
}
}
/// Response type for the `get_producers` RPC endpoint.
public struct EosioRpcProducersResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var rows: [ProducerRows]
public var totalProducerVoteWeight: String
public var more: String
enum CustomCodingKeys: String, CodingKey {
case rows
case totalProducerVoteWeight = "total_producer_vote_weight"
case more
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
rows = try container.decodeIfPresent([ProducerRows].self, forKey: .rows) ?? [ProducerRows]()
totalProducerVoteWeight = try container.decode(String.self, forKey: .totalProducerVoteWeight)
more = try container.decodeIfPresent(String.self, forKey: .more) ?? ""
}
}
/// Response type for the `push_transactions` RPC endpoint.
public struct EosioRpcPushTransactionsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var transactionResponses: [EosioRpcTransactionResponse]
public init(from decoder: Decoder) throws {
transactionResponses = [EosioRpcTransactionResponse]()
if var container = try? decoder.unkeyedContainer() {
while container.isAtEnd == false {
transactionResponses.append(try container.decode(EosioRpcTransactionResponse.self))
}
}
}
}
/// Response struct for `header` struct returned in the `get_block_header_state` RPC endpoint response.
public struct EosioRpcBlockHeaderStateResponseHeader: Decodable {
public let timestamp: String
public let producer: String
public let confirmed: UInt
public let previous: String
public let transactionMroot: String
public let actionMroot: String
public let scheduleVersion: UInt
public let headerExtensions: [String]
public let producerSignature: String
enum CustomCodingKeys: String, CodingKey {
case timestamp
case producer
case confirmed
case previous
case transactionMroot = "transaction_mroot"
case actionMroot = "action_mroot"
case scheduleVersion = "schedule_version"
case headerExtensions = "header_extensions"
case producerSignature = "producer_signature"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
timestamp = try container.decode(String.self, forKey: .timestamp)
producer = try container.decode(String.self, forKey: .producer)
confirmed = try container.decode(UInt.self, forKey: .confirmed)
previous = try container.decode(String.self, forKey: .previous)
transactionMroot = try container.decode(String.self, forKey: .transactionMroot)
actionMroot = try container.decode(String.self, forKey: .actionMroot)
scheduleVersion = try container.decode(UInt.self, forKey: .scheduleVersion)
headerExtensions = try container.decode([String].self, forKey: .headerExtensions)
producerSignature = try container.decode(String.self, forKey: .producerSignature)
}
}
/// Response type for the `get_block_header_state` RPC endpoint.
public struct EosioRpcBlockHeaderStateResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var id: String
public var blockNumber: EosioUInt64
public var header: EosioRpcBlockHeaderStateResponseHeader
public var dposProposedIrreversibleBlockNumber: EosioUInt64
public var dposIrreversibleBlockNumber: EosioUInt64
public var bftIrreversibleBlockNumber: EosioUInt64
public var pendingScheduleLibNumber: EosioUInt64
public var pendingScheduleHash: String
public var pendingSchedule: [String: Any]
public var activeSchedule: [String: Any]
public var blockRootMerkle: [String: Any]
public var blockSigningKey: String
public var confirmCount: [EosioUInt64]
public var confirmations: [EosioUInt64]
public var producerToLastProduced: [Any]
public var producerToLastImpliedIrb: [Any]
enum CustomCodingKeys: String, CodingKey {
case id
case blockNumber = "block_num"
case header
case dposProposedIrreversibleBlockNumber = "dpos_proposed_irreversible_blocknum"
case dposIrreversibleBlockNumber = "dpos_irreversible_blocknum"
case bftIrreversibleBlockNumber = "bft_irreversible_blocknum"
case pendingScheduleLibNumber = "pending_schedule_lib_num"
case pendingScheduleHash = "pending_schedule_hash"
case pendingSchedule = "pending_schedule"
case activeSchedule = "active_schedule"
case blockRootMerkle = "blockroot_merkle"
case blockSigningKey = "block_signing_key"
case confirmCount = "confirm_count"
case confirmations
case producerToLastProduced = "producer_to_last_produced"
case producerToLastImpliedIrb = "producer_to_last_implied_irb"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
id = try container.decode(String.self, forKey: .id)
blockNumber = try container.decode(EosioUInt64.self, forKey: .blockNumber)
header = try container.decode(EosioRpcBlockHeaderStateResponseHeader.self, forKey: .header)
dposProposedIrreversibleBlockNumber = try container.decode(EosioUInt64.self, forKey: .dposProposedIrreversibleBlockNumber)
dposIrreversibleBlockNumber = try container.decode(EosioUInt64.self, forKey: .dposIrreversibleBlockNumber)
bftIrreversibleBlockNumber = try container.decode(EosioUInt64.self, forKey: .bftIrreversibleBlockNumber)
pendingScheduleLibNumber = try container.decode(EosioUInt64.self, forKey: .pendingScheduleLibNumber)
pendingScheduleHash = try container.decode(String.self, forKey: .pendingScheduleHash)
let pendingScheduleContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .pendingSchedule)
pendingSchedule = pendingScheduleContainer?.decodeDynamicKeyValues() ?? [String: Any]()
let activeScheduleContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .activeSchedule)
activeSchedule = activeScheduleContainer?.decodeDynamicKeyValues() ?? [String: Any]()
let blockRootMerkleContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .blockRootMerkle)
blockRootMerkle = blockRootMerkleContainer?.decodeDynamicKeyValues() ?? [String: Any]()
blockSigningKey = try container.decode(String.self, forKey: .blockSigningKey)
confirmCount = try container.decode([EosioUInt64].self, forKey: .confirmCount)
confirmations = try container.decode([EosioUInt64].self, forKey: .confirmations)
var nestedProducerToLast = try? container.nestedUnkeyedContainer(forKey: .producerToLastProduced)
producerToLastProduced = nestedProducerToLast?.decodeDynamicValues() ?? [Any]()
var nestedProducerToLastImply = try? container.nestedUnkeyedContainer(forKey: .producerToLastImpliedIrb)
producerToLastImpliedIrb = nestedProducerToLastImply?.decodeDynamicValues() ?? [Any]()
}
}
/* History Endpoints */
/// Response type for the `get_actions` RPC endpoint.
public struct EosioRpcActionsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var actions: [EosioRpcActionsResponseAction]
public var lastIrreversibleBlock: EosioUInt64
public var timeLimitExceededError: Bool
enum CustomCodingKeys: String, CodingKey {
case actions
case lastIrreversibleBlock = "last_irreversible_block"
case timeLimitExceededError = "time_limit_exceeded_error"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
actions = try container.decode([EosioRpcActionsResponseAction].self, forKey: .actions)
lastIrreversibleBlock = try container.decode(EosioUInt64.self, forKey: .lastIrreversibleBlock)
timeLimitExceededError = try container.decodeIfPresent(Bool.self, forKey: .timeLimitExceededError) ?? false
}
}
public struct EosioRpcActionsResponseAction: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var globalActionSequence: EosioUInt64
public var accountActionSequence: Int32
public var blockNumber: UInt32
public var blockTime: String
public var actionTrace: EosioRpcActionsResponseActionTrace
enum CustomCodingKeys: String, CodingKey {
case globalActionSequence = "global_action_seq"
case accountActionSequence = "account_action_seq"
case blockNumber = "block_num"
case blockTime = "block_time"
case actionTrace = "action_trace"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
globalActionSequence = try container.decode(EosioUInt64.self, forKey: .globalActionSequence)
accountActionSequence = try container.decode(Int32.self, forKey: .accountActionSequence)
blockNumber = try container.decode(UInt32.self, forKey: .blockNumber)
blockTime = try container.decode(String.self, forKey: .blockTime)
actionTrace = try container.decode(EosioRpcActionsResponseActionTrace.self, forKey: .actionTrace)
}
}
public struct EosioRpcActionsResponseActionTrace: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var receipt: EosioRpcActionsResponseActionTrReceipt
public var action: EosioRpcActionsResponseActionTraceAction
public var contextFree: Bool
public var elapsed: EosioUInt64
public var console: String
public var transactionId: String
public var blockNumber: EosioUInt64
public var blockTime: String
public var producerBlockId: String?
public var accountRamDeltas: [EosioRpcActionsResponseActionTrActDeltas]
public var exception: [String: Any]?
enum CustomCodingKeys: String, CodingKey {
case receipt
case action = "act"
case contextFree = "context_free"
case elapsed = "elapsed"
case console = "console"
case transactionId = "trx_id"
case blockNumber = "block_num"
case blockTime = "block_time"
case producerBlockId = "producer_block_id"
case accountRamDeltas = "account_ram_deltas"
case exception = "except"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
receipt = try container.decode(EosioRpcActionsResponseActionTrReceipt.self, forKey: .receipt)
action = try container.decode(EosioRpcActionsResponseActionTraceAction.self, forKey: .action)
contextFree = try container.decode(Bool.self, forKey: .contextFree)
elapsed = try container.decode(EosioUInt64.self, forKey: .elapsed)
console = try container.decode(String.self, forKey: .console)
transactionId = try container.decode(String.self, forKey: .transactionId)
blockNumber = try container.decode(EosioUInt64.self, forKey: .blockNumber)
blockTime = try container.decode(String.self, forKey: .blockTime)
producerBlockId = try container.decodeIfPresent(String.self, forKey: .producerBlockId)
accountRamDeltas = try container.decode([EosioRpcActionsResponseActionTrActDeltas].self, forKey: .accountRamDeltas)
let exceptionContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .exception)
exception = exceptionContainer?.decodeDynamicKeyValues() ?? [String: Any]()
}
}
public struct EosioRpcActionsResponseActionTrReceipt: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var receiver: String
public var actionDigest: String
public var globalSequence: EosioUInt64
public var receiverSequence: EosioUInt64
public var authorizationSequence: [Any]
public var codeSequence: EosioUInt64
public var abiSequence: EosioUInt64
enum CustomCodingKeys: String, CodingKey {
case receiver
case actionDigest = "act_digest"
case globalSequence = "global_sequence"
case receiveSequence = "recv_sequence"
case authorizationSequence = "auth_sequence"
case codeSequence = "code_sequence"
case abiSequence = "abi_sequence"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
receiver = try container.decode(String.self, forKey: .receiver)
actionDigest = try container.decode(String.self, forKey: .actionDigest)
globalSequence = try container.decode(EosioUInt64.self, forKey: .globalSequence)
receiverSequence = try container.decode(EosioUInt64.self, forKey: .receiveSequence)
var authorizationSequenceContainer = try? container.nestedUnkeyedContainer(forKey: .authorizationSequence)
authorizationSequence = authorizationSequenceContainer?.decodeDynamicValues() ?? [Any]()
codeSequence = try container.decode(EosioUInt64.self, forKey: .codeSequence)
abiSequence = try container.decode(EosioUInt64.self, forKey: .abiSequence)
}
}
public struct EosioRpcActionsResponseActionTraceAction: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var account: String
public var name: String
public var authorization: [EosioRpcActionsResponseActionTraceAuth]
public var data: [String: Any]
public var hexData: String?
enum CustomCodingKeys: String, CodingKey {
case account
case name
case authorization
case data
case hexData = "hex_data"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
account = try container.decode(String.self, forKey: .account)
name = try container.decode(String.self, forKey: .name)
authorization = try container.decode([EosioRpcActionsResponseActionTraceAuth].self, forKey: .authorization)
let dataContainer = try? container.nestedContainer(keyedBy: DynamicKey.self, forKey: .data)
data = dataContainer?.decodeDynamicKeyValues() ?? [String: Any]()
hexData = try? container.decode(String.self, forKey: .hexData)
}
}
public struct EosioRpcActionsResponseActionTraceAuth: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var actor: String
public var permission: String
enum CustomCodingKeys: String, CodingKey {
case actor
case permission
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
actor = try container.decode(String.self, forKey: .actor)
permission = try container.decode(String.self, forKey: .permission)
}
}
public struct EosioRpcActionsResponseActionTrActDeltas: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var account: String
public var delta: EosioInt64
enum CustomCodingKeys: String, CodingKey {
case account
case delta
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
account = try container.decode(String.self, forKey: .account)
delta = try container.decode(EosioInt64.self, forKey: .delta)
}
}
/// Response struct for the `get_controlled_accounts` RPC endpoint
public struct EosioRpcControlledAccountsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var controlledAccounts: [String] = [String]()
enum CodingKeys: String, CodingKey {
case controlledAccounts = "controlled_accounts"
}
}
/// Response type for the `get_table_rows` RPC endpoint.
public struct EosioRpcTableRowsResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var rows: [Any] = [Any]()
public var more: Bool
enum CustomCodingKeys: String, CodingKey {
case rows
case more
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
var rowsContainer = try? container.nestedUnkeyedContainer(forKey: .rows)
rows = rowsContainer?.decodeDynamicValues() ?? [Any]()
more = try container.decodeIfPresent(Bool.self, forKey: .more) ?? false
}
}
/// Response struct for the rows returned from get_table_by_scope
public struct TableByScopeRows: Decodable {
public var code: String
public var scope: String
public var table: String
public var payer: String
public var count: UInt32
}
/// Response type for the `get_table_by_scope` RPC endpoint.
public struct EosioRpcTableByScopeResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
public var rows: [TableByScopeRows] = [TableByScopeRows]()
public var more: String
enum CustomCodingKeys: String, CodingKey {
case rows
case more
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
rows = try container.decode([TableByScopeRows].self, forKey: .rows)
more = try container.decodeIfPresent(String.self, forKey: .more) ?? ""
}
}
/* Responses without response models */
/// Struct for response types which do not have models created for them. For those, we simply provide the `_rawResponse`.
public struct RawResponse: Decodable, EosioRpcResponseProtocol {
public var _rawResponse: Any?
enum CodingKeys: CodingKey {
}
}
/* History Endpoints */
| 41.928924 | 135 | 0.715567 |
0909e5fa80b0a97cbf94f3dbfecd13196d409551 | 1,758 | //
// AppDelegate.swift
// BonMot
//
// Created by Brian King on 7/20/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
import BonMot
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
style()
window?.makeKeyAndVisible()
application.enableAdaptiveContentSizeMonitor()
return true
}
func style() {
guard let traitCollection = window?.traitCollection else {
fatalError("There should be a traitCollection available before calling this method.")
}
let titleStyle = StringStyle(
.font(UIFont.appFont(ofSize: 20)),
.adapt(.control)
)
UINavigationBar.appearance().titleTextAttributes = titleStyle.attributes(adaptedTo: traitCollection)
let barStyle = StringStyle(
.font(UIFont.appFont(ofSize: 17)),
.adapt(.control)
)
UIBarButtonItem.appearance().setTitleTextAttributes(barStyle.attributes(adaptedTo: traitCollection), for: .normal)
}
}
extension UIColor {
static var raizlabsRed: UIColor {
return UIColor(hex: 0xEC594D)
}
convenience init(hex: UInt32, alpha: CGFloat = 1) {
self.init(
red: CGFloat((hex >> 16) & 0xff) / 255.0,
green: CGFloat((hex >> 8) & 0xff) / 255.0,
blue: CGFloat(hex & 0xff) / 255.0,
alpha: alpha)
}
}
extension UIFont {
static func appFont(ofSize pointSize: CGFloat) -> UIFont {
return UIFont(name: "Avenir-Roman", size: pointSize)!
}
}
| 27.46875 | 151 | 0.636519 |
3a7175075cba49e56b4fba73d593852f862336b5 | 17,457 | //
// HeadingIndicatorView.swift
// MentalCrosswind
//
// Created by Brice Rosenzweig on 13/02/2022.
//
import UIKit
import RZFlight
extension NSString {
func draw(centeredAt center : CGPoint, angle : CGFloat, withAttribute attr: [NSAttributedString.Key : Any]?){
if let context = UIGraphicsGetCurrentContext() {
let size : CGSize = self.size(withAttributes: attr )
let translation :CGAffineTransform = CGAffineTransform(translationX: center.x, y: center.y)
let rotation : CGAffineTransform = CGAffineTransform(rotationAngle: angle)
context.concatenate(translation)
context.concatenate(rotation)
let drawPoint = CGPoint(x: size.width / 2.0 * -1.0, y: size.height / 2.0 * -1.0)
self.draw(at: drawPoint, withAttributes: attr)
context.concatenate(rotation.inverted())
context.concatenate(translation.inverted())
}
}
static func mergeAttribute(attr : [NSAttributedString.Key:Any]?, with : [NSAttributedString.Key:Any] ) -> [NSAttributedString.Key:Any]{
if var attr = attr {
attr.merge(with, uniquingKeysWith: { return $1 })
return attr
}else{
return with
}
}
}
extension CGFloat {
var radianFromDegree : CGFloat { return self * .pi / 180.0 }
var degreeFromRadian : CGFloat { return self / .pi * 180.0 }
}
extension CGPoint {
func distance(to : CGPoint) -> CGFloat {
let square = (to.x - self.x) * (to.x - self.x) + (to.y - self.y) * (to.y - self.y)
return sqrt(square)
}
var rounded : CGPoint { return CGPoint(x: round(self.x), y: round(self.y)) }
/**
* angle with 0 on x axis, positive for y negative to 180, negative for y positive to 180
*/
func angle(to : CGPoint) -> CGFloat {
return atan2(to.y-self.y,to.x-self.x).degreeFromRadian
}
}
class HeadingIndicatorView: UIView {
enum DisplayWind {
case hidden
case wind
case windAndGust
var enabled : Bool { return self != .hidden }
}
enum DisplayCrossWindComponent {
case hidden
case speed
case hint
var enabled : Bool { return self != .hidden }
}
var model : RunwayWindModel {
get { return self.headingIndicatorLayer.model }
set { self.headingIndicatorLayer.model = newValue }
}
var displayWind : DisplayWind {
get { return self.headingIndicatorLayer.displayWind }
set { self.headingIndicatorLayer.displayWind = newValue }
}
var displayCrossWind : DisplayCrossWindComponent {
get { return self.headingIndicatorLayer.displayCrossWind }
set { self.headingIndicatorLayer.displayCrossWind = newValue }
}
var geometry : HeadingIndicatorGeometry { return self.headingIndicatorLayer.geometry }
var circleColor : UIColor = UIColor.label { didSet { self.headingIndicatorLayer.circleColor = circleColor }}
var compassPointColor : UIColor = UIColor.label { didSet { self.headingIndicatorLayer.compassPointColor = compassPointColor }}
var windConeColor : UIColor = UIColor.systemRed { didSet { self.headingIndicatorLayer.windConeColor = windConeColor }}
var labelAttribute : [NSAttributedString.Key : Any]? = nil { didSet { self.headingIndicatorLayer.labelAttribute = labelAttribute }}
override class var layerClass : AnyClass {
return HeadingIndicatorLayer.self
}
var headingIndicatorLayer : HeadingIndicatorLayer {
return self.layer as! HeadingIndicatorLayer
}
override func draw(_ rect: CGRect) {
self.headingIndicatorLayer.setNeedsDisplay()
}
//MARK: - element check
/**
return angle if in circle, nil otherwise
*/
func headingInCircle(point : CGPoint) -> CGFloat? {
let distance = point.distance(to: geometry.center)
if distance > (geometry.baseRadius * 0.95 - geometry.margin ) {
return self.heading(point: point)
}
return nil
}
func headingInWindCone(point : CGPoint) -> CGFloat? {
if displayWind.enabled {
let heading = self.heading(point: point)
if abs( heading - headingIndicatorLayer.windHeading ) < 10 {
return heading
}
}
return nil
}
func heading(point : CGPoint) -> CGFloat {
let angle = geometry.center.angle(to: point)
// + 90 to rotate north up, +360 to get rid of negative with the modulo and plus heading to rotate
return (angle + 90.0 + 360.0 + headingIndicatorLayer.heading).truncatingRemainder(dividingBy: 360.0)
}
func rotateHeading(degree : CGFloat){
// minus sign because rotation in screen is opposite
self.model.rotateHeading(degree: -Int(degree))
}
func rotateWind(degree : CGFloat){
if displayWind.enabled {
//self.model.windHeading.rotate(degree: Int(degree))
self.model.rotateWind(degree: Int(degree))
}
}
func increaseWindSpeed(percent : CGFloat){
// for now just
self.model.increaseWind(speed: Int(percent))
//self.model.windSpeed.increase(speed: Int(percent))
}
func radius(point : CGPoint) -> CGFloat {
return geometry.center.distance(to: point)
}
func radiusPercent(point : CGPoint) -> CGFloat {
return geometry.center.distance(to: point) / geometry.baseRadius * 100.0
}
}
class HeadingIndicatorLayer : CALayer {
var model : RunwayWindModel = RunwayWindModel()
var displayWind : HeadingIndicatorView.DisplayWind = .wind
var displayCrossWind : HeadingIndicatorView.DisplayCrossWindComponent = .hidden
var geometry : HeadingIndicatorGeometry = HeadingIndicatorGeometry(rect: CGRect.zero, heading: 0.0)
var circleColor : UIColor = UIColor.label
var compassPointColor : UIColor = UIColor.label
var windConeColor : UIColor = UIColor.systemRed
var labelAttribute : [NSAttributedString.Key : Any]? = nil
// for now keep heading and runway consistent
var windHeading : CGFloat { return self.model.windHeading.heading }
var heading : CGFloat { CGFloat(self.model.runwayHeading.heading)}
private var runwayDescription : String { self.model.runwayHeading.runwayDescription }
private var windSpeed : CGFloat { return self.model.windSpeed.speed }
private var windSizePercent : CGFloat { min(50.0,max(10.0, windSpeed)) }
override class func needsDisplay(forKey key: String) -> Bool {
if key == "model" {
return true
}
return super.needsDisplay(forKey: key)
}
//MARK: - draw elements
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
UIGraphicsPushContext(ctx)
self.geometry = HeadingIndicatorGeometry(rect: bounds, heading: self.heading)
self.drawCompass(bounds)
self.drawWindCone(bounds)
self.drawRunway(bounds)
UIGraphicsPopContext()
}
func drawRunway(_ rect : CGRect){
let center = geometry.center
let runwayTargetWidth = geometry.runwayTargetWidth
let runwayTargetLength = geometry.runwayTargetLength
// Fit center line + 3 stripe in each side: stripes or 16 units (stripe + space) + 1 for left
let stripeEachSideCount : Int = 3
// how many unit of stripe space to fit
let stripeSpaceUnitcount : Int = (2/*two sides*/ * 2/*stripe + space*/ * stripeEachSideCount + 2 /*centerline*/ + 1 /*first offset*/)
let stripeWidth : CGFloat = ceil(runwayTargetWidth / CGFloat(stripeSpaceUnitcount) )
let stripeOffset : CGFloat = stripeWidth // same as stripe
let runwayWidth = CGFloat(stripeSpaceUnitcount) * stripeWidth
let centerLineStripeCount = 5
// space between line is XX percent of centerline height
let centerLineOffsetPercent = 20.0
let stripeHeight = ceil(runwayTargetLength / CGFloat(centerLineStripeCount) * ( 1.0 - centerLineOffsetPercent / 100.0))
let stripeHeightOffset = stripeHeight * centerLineOffsetPercent / 100.0
let runwayLength = (stripeHeight + stripeHeightOffset) * CGFloat(centerLineStripeCount) + stripeHeightOffset
let runwayTopLeft = CGPoint(x: center.x - runwayWidth/2.0 , y: center.y-runwayLength/2.0)
let runwayTopRight = CGPoint(x: center.x + runwayWidth/2.0 , y: center.y-runwayLength/2.0)
let runwayBottomLeft = CGPoint(x: center.x - runwayWidth/2.0 , y: center.y+runwayLength/2.0)
let runwayBottomRight = CGPoint(x: center.x + runwayWidth/2.0 , y: center.y+runwayLength/2.0)
let path = UIBezierPath()
path.move(to: runwayTopLeft)
path.addLine(to: runwayBottomLeft)
path.addLine(to: runwayBottomRight)
path.addLine(to: runwayTopRight)
path.stroke()
// Center Line
let centerLineWidth = 1.0
let x = center.x - centerLineWidth / 2.0
for i in 2..<centerLineStripeCount {
let y = runwayBottomLeft.y - CGFloat(i+1) * (stripeHeightOffset + stripeHeight)
let centerLineRect = CGRect(x: x, y: y, width: centerLineWidth, height: stripeHeight)
let stripePath = UIBezierPath(roundedRect: centerLineRect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 0.0, height: 0.0))
stripePath.fill()
}
let runwayNumber = runwayDescription as NSString
let numberCenter = CGPoint(x: runwayBottomLeft.x + runwayWidth/2.0,
y: runwayBottomLeft.y - (2*stripeHeightOffset + stripeHeight * 1.5) )
runwayNumber.draw(centeredAt: numberCenter, angle: 0, withAttribute: self.labelAttribute)
// Each Side Stripe
for i in 0..<(2*stripeEachSideCount+1) {
// left side
for (xbase,xmult) : (CGFloat,Double) in [(runwayBottomLeft.x,1.0)/*, (runwayBottomRight.x-stripeOffset, -1.0)*/] {
let x = xbase + xmult * (stripeOffset + CGFloat(i) * (stripeWidth+stripeOffset));
let stripeRect = CGRect(x: x, y: runwayBottomLeft.y-stripeHeightOffset-stripeHeight, width: stripeWidth, height: stripeHeight)
let stripePath = UIBezierPath(roundedRect: stripeRect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 0.0, height: 0.0))
stripePath.fill()
}
}
// Landing Stripe
let y = runwayBottomLeft.y - (stripeHeightOffset + (stripeHeightOffset + stripeHeight) * 3.5)
for i in [-1,1] {
let x = center.x + 2 * stripeOffset * CGFloat(i) - stripeOffset/2.0
let stripeRect = CGRect(x: x, y: y, width: stripeWidth, height: stripeHeight)
let stripePath = UIBezierPath(roundedRect: stripeRect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 0.0, height: 0.0))
stripePath.fill()
}
}
func drawCompass(_ rect : CGRect){
let outCircle = UIBezierPath(arcCenter: geometry.center, radius: geometry.baseRadius,
startAngle: 0.0,
endAngle: .pi * 2.0,
clockwise: true)
self.circleColor.setStroke()
outCircle.stroke()
let cardinalPoint : [String] = ["N", "E", "S", "W"]
for headingPoint in 0..<36 {
let angle : CGFloat = CGFloat(headingPoint) * 10.0
var label : String? = nil
var length : CGFloat = geometry.smallLength
var width : CGFloat = geometry.smallWidth
if headingPoint % 9 == 0 {
length = geometry.regularLength
width = geometry.regularWidth
label = cardinalPoint[ headingPoint/9 ]
}
else if headingPoint % 3 == 0 {
length = geometry.regularLength
width = geometry.regularWidth
label = "\(headingPoint)"
}else{
label = ""
}
let radiusStart = geometry.baseRadius - length
let radiusEnd = geometry.baseRadius
let startPoint = geometry.point(angle: angle, radius: radiusStart)
let endPoint = geometry.point(angle: angle, radius: radiusEnd)
let tick = UIBezierPath()
tick.lineWidth = width
tick.move(to: startPoint)
tick.addLine(to: endPoint)
tick.close()
tick.stroke()
if let label = label {
let string = label as NSString
let size = string.size(withAttributes: self.labelAttribute)
let textAngle = geometry.viewCoordinateAngle(heading: angle) + 90.0
let textPoint = geometry.point(angle: angle, radius: radiusStart - geometry.textMargin - size.height/2.0 )
string.draw(centeredAt: textPoint, angle: textAngle.radianFromDegree, withAttribute: self.labelAttribute)
}
let headingString = "\(Int(round(geometry.heading)))" as NSString
let headingSize = headingString.size(withAttributes: self.labelAttribute)
let headLength : CGFloat = geometry.headingHeadLength
let headWidth : CGFloat = 10.0
let headingPoint = geometry.point(angle: heading, radius: geometry.baseRadius + headLength + geometry.textMargin + headingSize.height / 2.0)
self.drawCone(degree: self.heading, width: headWidth, radiusHead: geometry.baseRadius, headLength: headLength, shaftLength: 0.0,
strokeColor: self.compassPointColor, fillColor: self.compassPointColor)
headingString.draw(centeredAt: headingPoint, angle: 0, withAttribute: self.labelAttribute)
}
}
func drawWindCone(_ rect : CGRect){
if self.displayWind.enabled {
// Compute first as cheat to estimate height to go below heading string
let windHeadingString = "\(Int(round(windHeading))) @ \(Int(round(windSpeed)))" as NSString
let windHeadingSize = windHeadingString.size(withAttributes: self.labelAttribute)
let windStartRadius = geometry.windStartRadius(speed: self.windSpeed )
let windEndRadius = geometry.baseRadius
let coneWidth : CGFloat = geometry.windWidth(speed: self.windSpeed )
self.drawCone(degree: windHeading,
width: coneWidth,
radiusHead: windStartRadius-geometry.headLength,
headLength: geometry.headLength,
shaftLength: windEndRadius-windStartRadius+geometry.headingHeadLength,
strokeColor: self.windConeColor, fillColor: self.windConeColor)
let textAngle = geometry.viewCoordinateAngle(heading: windHeading) + 90.0
let windHeadingPoint = geometry.point(angle: windHeading, radius: windStartRadius - geometry.headLength - geometry.textMargin - windHeadingSize.height/2.0)
windHeadingString.draw(centeredAt: windHeadingPoint, angle: textAngle.radianFromDegree, withAttribute: self.labelAttribute)
}
}
//MARK: - draw helper
/// Draw a cone
/// - Parameters:
/// - degree: degree (in heading degree)
/// - width: in degree
/// - radiusHead: radius at end of point of head
/// - headLength: size of the head
/// - shaftLength: size of shaft (total size is headLength + shaftLength
/// - strokeColor: color for outside stroke
/// - fillColor: fill color wil be with 50% alpha
func drawCone(degree : CGFloat, width : CGFloat, radiusHead : CGFloat, headLength : CGFloat, shaftLength : CGFloat, strokeColor : UIColor = .label, fillColor : UIColor = .systemFill) {
let angleCenter = degree
let angleLeft = angleCenter - (width / 2.0 )
let angleRight = angleCenter + (width / 2.0 )
let shaftStartRadius = radiusHead + headLength
let shaftEndRadius = shaftStartRadius + shaftLength
let leftTopShaftPoint = geometry.point(angle: angleLeft, radius: shaftEndRadius)
let rightTopShaftPoint = geometry.point(angle: angleRight, radius: shaftEndRadius)
let leftBottomShaftPoint = geometry.point(angle: angleLeft, radius: shaftStartRadius)
let rightBottomShaftPoint = geometry.point(angle: angleRight, radius: shaftStartRadius)
let centerBottomHeadPoint = geometry.point(angle: angleCenter, radius: radiusHead)
let cone = UIBezierPath()
cone.move(to: leftTopShaftPoint)
cone.addLine(to: rightTopShaftPoint)
cone.addLine(to: rightBottomShaftPoint)
cone.addLine(to: centerBottomHeadPoint)
cone.addLine(to: leftBottomShaftPoint)
cone.close()
strokeColor.setStroke()
cone.stroke()
fillColor.setFill()
cone.fill(with: .darken, alpha: 0.5)
}
}
| 41.075294 | 188 | 0.623418 |
0e44086b21c1571719995d227e684b706f97de20 | 1,038 | ////
// 🦠 Corona-Warn-App
//
import XCTest
@testable import ENA
class AntigenTestInformationTests: CWATestCase {
func testGIVEN_AntigenTestInformationPayload_WHEN_Parse_THEN_WillBeEqual() throws {
let dateString = "2010-08-01"
let date = ISO8601DateFormatter.justUTCDateFormatter.date(from: dateString)
// GIVEN
let antigenTestInformation = AntigenTestQRCodeInformation(
hash: "asbf3242",
timestamp: 123456789,
firstName: "Thomase",
lastName: "Mustermann",
dateOfBirth: date,
testID: "123",
cryptographicSalt: "456",
certificateSupportedByPointOfCare: false
)
let encoder = JSONEncoder()
let payloadData = try encoder.encode(antigenTestInformation).base64EncodedData()
let payload = try XCTUnwrap(String(data: payloadData, encoding: .utf8))
// WHEN
let checkTestInformation = try XCTUnwrap(AntigenTestQRCodeInformation(payload: payload))
// THEN
XCTAssertEqual(checkTestInformation, antigenTestInformation)
XCTAssertEqual(checkTestInformation.dateOfBirthString, "2010-08-01")
}
}
| 28.054054 | 90 | 0.767823 |
deb665cb221736f6579731d8ab68f77c0a7fa5bf | 195 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a<T where B:A}()as a | 39 | 87 | 0.758974 |
764a66f7478c580a9fc51dcecc6f11bbb2808ef7 | 3,570 | //
// ThemedUIAlertController.swift
// iTorrent
//
// Created by Daniil Vinogradov on 24/06/2018.
// Copyright © 2018 XITRIX. All rights reserved.
//
import Foundation
import UIKit
class ThemedUIAlertController : UIAlertController, Themed {
private var visualEffectView: [UIVisualEffectView] {
if let presentationController = presentationController, presentationController.responds(to: Selector(("popoverView"))), let view = presentationController.value(forKey: "popoverView") as? UIView // We're on an iPad and visual effect view is in a different place.
{
return view.recursiveSubviews.compactMap({$0 as? UIVisualEffectView})
}
return view.recursiveSubviews.compactMap({$0 as? UIVisualEffectView})
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
visualEffectView.forEach({$0.effect = UIBlurEffect(style: Themes.current().blurEffect)})
}
func themeUpdate() {
visualEffectView.forEach({$0.effect = UIBlurEffect(style: Themes.current().blurEffect)})
//_UIDimmingKnockoutBackdropView
// if let back = NSClassFromString("_UIDimmingKnockoutBackdropView") as? UIView.Type {
// back.appearance().subviewsBackgroundColorNonVisualEffect = Theme.current.backgroundColor
// }
if let cancelBackgroundViewType = NSClassFromString("_UIAlertControlleriOSActionSheetCancelBackgroundView") as? UIView.Type {
cancelBackgroundViewType.appearance().subviewsBackgroundColor = Themes.current().actionCancelButtonColor
}
if let title = title {
let titleFont:[NSAttributedString.Key : Any] = [ .foregroundColor : preferredStyle == .alert ? Themes.current().mainText : Themes.current().secondaryText,
NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)]
let attributedTitle = NSMutableAttributedString(string: title, attributes: titleFont)
setValue(attributedTitle, forKey: "attributedTitle")
}
if let message = message {
let messageFont:[NSAttributedString.Key : Any] = [ .foregroundColor : preferredStyle == .alert ? Themes.current().mainText : Themes.current().secondaryText ]
let attributedMessage = NSMutableAttributedString(string: message, attributes: messageFont)
setValue(attributedMessage, forKey: "attributedMessage")
}
view.tintColor = Themes.current().actionButtonColor
//actions.forEach({$0})
}
override func viewDidLoad() {
super.viewDidLoad()
themeUpdate()
}
}
fileprivate extension UIView {
private struct AssociatedKey {
static var subviewsBackgroundColor = "subviewsBackgroundColor"
}
@objc dynamic var subviewsBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self, &AssociatedKey.subviewsBackgroundColor) as? UIColor
}
set {
objc_setAssociatedObject(self,
&AssociatedKey.subviewsBackgroundColor,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
subviews.forEach { $0.backgroundColor = newValue }
}
}
@objc dynamic var subviewsBackgroundColorNonVisualEffect: UIColor? {
get {
return objc_getAssociatedObject(self, &AssociatedKey.subviewsBackgroundColor) as? UIColor
}
set {
objc_setAssociatedObject(self,
&AssociatedKey.subviewsBackgroundColor,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
subviews.forEach { if !($0 is UIVisualEffectView) {$0.backgroundColor = newValue} }
}
}
}
extension UIView {
var recursiveSubviews: [UIView] {
var subviews = self.subviews.compactMap({$0})
subviews.forEach { subviews.append(contentsOf: $0.recursiveSubviews) }
return subviews
}
}
| 34.660194 | 263 | 0.746779 |
3a4b4ea493008fa9e38530dade712524b511183c | 484 | //
// NORBaseRevealViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 11/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import SWRevealViewController
class BaseRevealViewController: SWRevealViewController, UIAlertViewDelegate {
func ShowAbout(message aMessage : String){
let alertView = UIAlertView(title: "About", message: aMessage, delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
}
| 25.473684 | 111 | 0.731405 |
e2a338b7420efb1ef86e38953785bf3bc9b3ec7c | 2,711 | //
// Audio.swift
// Media
//
// Created by Christian Elies on 21.11.19.
// Copyright © 2019 Christian Elies. All rights reserved.
//
import Photos
/// Wrapper type for around `PHAsset`s of type `audio`
///
public struct Audio: MediaProtocol {
public typealias MediaSubtype = Audio.Subtype
public typealias MediaFileType = Audio.FileType
private var phAsset: PHAsset? { phAssetWrapper.value }
/// Box type internally used to store a reference
/// to the underlying `PHAsset`
public let phAssetWrapper: PHAssetWrapper
/// `PHAssetMediaType` for the `Audio` type
///
/// Used for the implementation of some generic
/// property wrappers
public static let type: MediaType = .audio
/// Locally available metadata of the `Audio`
public var metadata: Metadata? {
guard let phAsset = phAsset else { return nil }
return Metadata(
type: phAsset.mediaType,
subtypes: phAsset.mediaSubtypes,
sourceType: phAsset.sourceType,
creationDate: phAsset.creationDate,
modificationDate: phAsset.modificationDate,
location: phAsset.location,
isFavorite: phAsset.isFavorite,
isHidden: phAsset.isHidden)
}
/// Initializes an `Audio` using the given asset
/// - Parameter phAsset: an `PHAsset` which represents the audio
public init(phAsset: PHAsset) {
self.phAssetWrapper = PHAssetWrapper(value: phAsset)
}
}
extension Audio: Equatable {
public static func == (lhs: Audio, rhs: Audio) -> Bool {
lhs.identifier == rhs.identifier && lhs.phAsset == rhs.phAsset
}
}
extension Audio: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
hasher.combine(phAsset)
}
}
public extension Audio {
/// Fetches the audio with the given identifier if it exists
///
/// Alternative:
/// @FetchAsset(filter: [.localIdentifier("1234")])
/// private var audio: Audio?
///
/// - Parameter identifier: the identifier of the media
///
static func with(identifier: Media.Identifier<Self>) throws -> Audio? {
let options = PHFetchOptions()
let mediaTypeFilter: Media.Filter<Audio.Subtype> = .localIdentifier(identifier.localIdentifier)
let predicate = NSPredicate(format: "mediaType = %d", MediaType.audio.rawValue)
options.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, mediaTypeFilter.predicate])
let audio = try PHAssetFetcher.fetchAsset(options: options) { $0.localIdentifier == identifier.localIdentifier && $0.mediaType == .audio } as Audio?
return audio
}
}
| 33.060976 | 156 | 0.666175 |
0997dd6e123879e73a1ff731efd6e9a1d3999f8d | 1,775 | //
// BusinessTableViewCell.swift
// Yelp
//
// Created by Zhia Chong on 10/22/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
import AFNetworking
class BusinessTableViewCell: UITableViewCell {
@IBOutlet weak var thumbImageView: UIImageView!
@IBOutlet weak var ratingImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var categoriesLabel: UILabel!
@IBOutlet weak var reviewsCountLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
var business: Business! {
didSet {
titleLabel.text = business.name
if business.imageURL != nil {
thumbImageView.setImageWith(business.imageURL!)
}
ratingImageView.setImageWith(business.ratingImageURL!)
addressLabel.text = business.address
categoriesLabel.text = business.categories
reviewsCountLabel.text = "\(business.reviewCount!) Reviews"
distanceLabel.text = business.distance
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
thumbImageView.layer.cornerRadius = 3
thumbImageView.clipsToBounds = true
// Because sometimes it's out of sync.
titleLabel.preferredMaxLayoutWidth = titleLabel.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.preferredMaxLayoutWidth = titleLabel.frame.size.width
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 30.084746 | 72 | 0.657465 |
f5d7634953f43e65fed05c464aa8fd26f987fae2 | 6,399 | //
// SharedManagerLogicTests.swift
// Mitra
//
// Created by Serge Bouts on 5/12/20.
// Copyright © 2020 iRiZen.com. All rights reserved.
//
import XCTest
import XConcurrencyKit
@testable
import Mitra
final class SharedManagerLogicTests: XCTestCase {
let queue = DispatchQueue(label: "TestQueue", qos: .userInteractive, attributes: .concurrent)
var sut: SharedManager!
let foo = Property(value: 0)
let bar = Property(value: "")
override func setUp() {
super.setUp()
sut = SharedManager()
sut.borrow(foo.rw, bar.rw) { foo, bar in
foo.value = 0
bar.value = ""
}
}
func test_shared_modified() {
// Given
sut.borrow(foo.ro, bar.ro) { foo, bar in
XCTAssertEqual(foo.value, 0)
XCTAssertEqual(bar.value, "")
}
// When
sut.borrow(foo.rw, bar.rw) { foo, bar in
foo.value = 1
bar.value = "foo"
}
// Then
sut.borrow(foo.ro) { foo in
XCTAssertEqual(foo.value, 1)
}
sut.borrow(bar.ro) { bar in
XCTAssertEqual(bar.value, "foo")
}
}
func test_1prop_that_thread_borrows_and_this_thread_waits() {
// Given
let barrier = DispatchSemaphore(value: 0)
// When
queue.async {
self.sut.borrow(self.foo.rw) { foo in
barrier.signal()
Thread.sleep(until: Date() + 1)
foo.value = 1
}
}
// Then
barrier.wait()
var tm = MachExecutionTimeMeter()
tm.measure {
sut.borrow(foo.ro) { foo in
XCTAssertEqual(foo.value, 1)
}
}
XCTAssertGreaterThanOrEqual(tm.executionTime, 1 - 0.1)
}
func test_2pros_that_thread_borrows_and_this_thread_waits() {
// Given
let barrier = DispatchSemaphore(value: 0)
queue.async {
self.sut.borrow(self.foo.rw, self.bar.rw) { foo, bar in
barrier.signal()
Thread.sleep(until: Date() + 1)
foo.value = 1
bar.value = "foo"
}
}
// When
barrier.wait()
var tm = MachExecutionTimeMeter()
tm.measure {
sut.borrow(bar.ro) { bar in
// Then
XCTAssertEqual(bar.value, "foo")
}
}
// Then
XCTAssertGreaterThanOrEqual(tm.executionTime, 1 - 0.1)
}
func test_2props_that_thread_borrows_and_this_thread_waits2() {
// Given
let barrier = DispatchSemaphore(value: 0)
queue.async {
self.sut.borrow(self.foo.ro, self.bar.rw) { foo, bar in
barrier.signal()
Thread.sleep(until: Date() + 1)
bar.value = "foo"
}
}
// When
barrier.wait()
var tm = MachExecutionTimeMeter()
tm.measure {
sut.borrow(bar.ro) { bar in
// Then
XCTAssertEqual(bar.value, "foo")
}
}
// Then
XCTAssertGreaterThanOrEqual(tm.executionTime, 1 - 0.1)
}
func test_2props_that_thread_borrows_and_this_thread_waits3() {
// Given
let barrier = DispatchSemaphore(value: 0)
queue.async {
self.sut.borrow(self.foo.ro, self.bar.rw) { foo, bar in
barrier.signal()
Thread.sleep(until: Date() + 1)
bar.value = "foo"
}
}
// When
barrier.wait()
var tm = MachExecutionTimeMeter()
tm.measure {
sut.borrow(foo.ro, bar.ro) { foo, bar in
// Then
XCTAssertEqual(foo.value, 0)
XCTAssertEqual(bar.value, "foo")
}
}
// Then
XCTAssertGreaterThanOrEqual(tm.executionTime, 1 - 0.1)
}
func test_2props_that_thread_borrows_and_this_thread_doesnt_wait() {
// Given
let barrier = DispatchSemaphore(value: 0)
queue.async {
self.sut.borrow(self.foo.ro, self.bar.rw) { foo, bar in
barrier.signal()
Thread.sleep(until: Date() + 1)
bar.value = "foo"
}
}
// When
barrier.wait()
var tm = MachExecutionTimeMeter()
tm.measure {
sut.borrow(foo.ro) { bar in
// Then
XCTAssertEqual(bar.value, 0)
}
}
// Then
XCTAssertLessThan(tm.executionTime, 1)
}
func test_1prop_2those_threads_wait_while_this_thread_borrows() {
// Given
let barrier1 = DispatchSemaphore.init(value: 0)
let barrier2 = DispatchSemaphore(value: 0)
let group = DispatchGroup()
var tm1 = MachExecutionTimeMeter()
var tm2 = MachExecutionTimeMeter()
sut.borrow(foo.ro) { foo in
XCTAssertEqual(foo.value, 0)
}
// When
group.enter()
queue.async {
self.sut.borrow(self.foo.ro) { foo in
XCTAssertEqual(foo.value, 0)
}
barrier1.signal()
barrier2.wait()
tm1.measure {
self.sut.borrow(self.foo.ro) { foo in
// Then
XCTAssertEqual(foo.value, 123)
}
}
group.leave()
}
group.enter()
queue.async {
self.sut.borrow(self.foo.ro) { foo in
// Then
XCTAssertEqual(foo.value, 0)
}
barrier1.signal()
barrier2.wait()
tm2.measure {
// Then
self.sut.borrow(self.foo.ro) { foo in
XCTAssertEqual(foo.value, 123)
}
}
group.leave()
}
barrier1.wait()
barrier1.wait()
sut.borrow(foo.rw) { foo in
barrier2.signal()
barrier2.signal()
Thread.sleep(until: Date() + 1)
foo.value = 123
}
group.wait()
// Then
XCTAssertGreaterThanOrEqual(tm1.executionTime, 1 - 0.1)
XCTAssertGreaterThanOrEqual(tm2.executionTime, 1 - 0.1)
}
}
| 24.056391 | 97 | 0.494765 |
f7f34833d3db1a85d7b0ac14cdb5e8b19c6e7a2c | 8,444 | //
// QuizSetupViewController.swift
// KnowYourAngles
//
// Created by iPad App Dev on 7/7/18.
// Copyright © 2018 Iolani School. All rights reserved.
//
import Foundation
class QuizSetupViewController: UIViewController {
//label for the problemSlider to display how many problems the user wants to complete
@IBOutlet weak var totalNumOfProblems: UILabel!
//reference to a slider used to choose the number of problems the user wants to complete
@IBOutlet weak var problemSlider: UISlider!
//timerSwitch controls whether a time limit is set on how long the user has to complete the desired number of problems
@IBOutlet weak var timerSwitch: UISwitch!
//timerLabel displays the time limit currently set (can be 30 seconds, 1 min, 1 min 30 sec, 2 min, 2 min 30 seconds, or 3 min)
@IBOutlet weak var timerLabel: UILabel!
//timerSlider lets the user change the time limit
@IBOutlet weak var timerSlider: UISlider!
//grab the previously saved settings (if any)
let defaultSettings = UserDefaults.standard
//when the view loads...
override open func viewDidLoad() {
//call on the super class viewDidLoad method
super.viewDidLoad()
/**********SETTINGS FOR MAX NUM OF PROBLEMS**********/
//if there are previously saved settings for the max number of problems, use them
if (defaultSettings.object(forKey: "maxNumOfProblems") != nil)
{
problemSlider.maximumValue = defaultSettings.value(forKey: "maxNumOfProblems") as! Float;
}
// if there are no pre-existing settings, then use 48
else
{
problemSlider.maximumValue = 48.0;
defaultSettings.setValue(problemSlider.maximumValue, forKey: "maxNumOfProblems");
}
/**********SETTINGS FOR NUM OF PROBLEMS**********/
//if there are previously saved settings for the number of problems, use them
if (defaultSettings.object(forKey: "numOfProblems") != nil) {
if(defaultSettings.value(forKey: "numOfProblems") as! Float > defaultSettings.value(forKey: "maxNumOfProblems") as! Float)
{
defaultSettings.setValue(defaultSettings.value(forKey: "maxNumOfProblems"), forKey: "numOfProblems");
}
problemSlider.value = defaultSettings.value(forKey: "numOfProblems") as! Float;
}
//if there are no pre-existing settings, then...
else
{
//set the default number of problems to 10 or the max num of problems, whichever is smaller
problemSlider.value = min(10, defaultSettings.value(forKey: "maxNumOfProblems") as! Float)
defaultSettings.setValue(problemSlider.value, forKey: "numOfProblems");
}
// set the text on the settings page
totalNumOfProblems.text = "\(lroundf(problemSlider.value))";
/**********SETTINGS FOR TIMER**********/
// if there are previously saved settings for whether the timer is on or off, then use them
if(defaultSettings.object(forKey: "isTimerOn") != nil)
{
timerSwitch.setOn(defaultSettings.object(forKey: "isTimerOn") as! Bool, animated: true);
timerSlider.isHidden = !timerSwitch.isOn;
timerLabel.isHidden = !timerSwitch.isOn;
}
// if there are no pre-existing settings, then set default value to off.
else
{
timerSwitch.setOn(false, animated: true);
timerSlider.isHidden = true;
timerLabel.isHidden = true;
defaultSettings.setValue(timerSwitch.isOn, forKey: "isTimerOn");
}
// if there are already settings for the amount of time allowed, then use them
if(defaultSettings.object(forKey: "amtTimeMin") != nil && defaultSettings.object(forKey: "amtTimeSec") != nil)
{
// get the minutes & seconds stored in settings and convert to a slider value
let minutes = defaultSettings.object(forKey: "amtTimeMin") as! Float;
let seconds = defaultSettings.object(forKey: "amtTimeSec") as! Float;
timerSlider.value = (minutes) + (seconds/60);
// change the timer label
if(minutes == 0)
{
timerLabel.text = "\(Int(seconds)) seconds";
}
else if(seconds == 0)
{
timerLabel.text = "\(Int(minutes)) minutes";
}
else
{
timerLabel.text = "\(Int(minutes)) minutes \(Int(seconds)) seconds";
}
}
// if there are no pre-existing settings for amount of time allowed, then set default values
else
{
// if the timer is on, set to 30 seconds
if(defaultSettings.object(forKey: "isTimerOn") as! Bool)
{
timerLabel.text = "30 seconds";
timerSlider.value = 0.5;
defaultSettings.setValue(0, forKey: "amtTimeMin");
defaultSettings.setValue(30, forKey: "amtTimeSec");
}
// if the timer is off, set timer to 0
else{
defaultSettings.setValue(0, forKey: "amtTimeMin");
defaultSettings.setValue(0, forKey: "amtTimeSec");
}
}
}
//sliderChanged is called when the slider is moved to change the number of problems
@IBAction func sliderChanged(_ sender: UISlider) {
totalNumOfProblems.text = "\(lroundf(sender.value))";
//save the number of problems in settings
defaultSettings.setValue(lroundf(sender.value), forKey: "numOfProblems");
}
//timerSwitchChanged is called when the user turns on or off the timer.
@IBAction func timerSwitchChanged(_ sender: UISwitch) {
//get the previously set minutes and seconds
let minutes = defaultSettings.object(forKey: "amtTimeMin") as! Int;
let seconds = defaultSettings.object(forKey: "amtTimeSec") as! Int;
//if the timer gets turned on...
if(sender.isOn)
{
//show the timer slider and timer label
timerSlider.isHidden = false;
timerLabel.isHidden = false;
//if there was no previously saved time, change the time to 30 seconds
if(minutes == 0 && seconds == 0)
{
timerLabel.text = "30 seconds";
defaultSettings.setValue(30, forKey: "amtTimeSec");
}
else if(minutes == 0)
{
timerLabel.text = "\(seconds) seconds";
}
else if(seconds == 0)
{
timerLabel.text = "\(minutes) minutes";
}
else
{
timerLabel.text = "\(minutes) minutes \(seconds) seconds";
}
}
// if the timer gets turned off
else
{
//hide the slider and label
timerSlider.isHidden = true;
timerLabel.isHidden = true;
//change the text
timerLabel.text = "Timer: Off";
}
//save the state of the timer switch in settings
defaultSettings.setValue(sender.isOn, forKey: "isTimerOn");
}
//function is called when the timerSlider is changed
@IBAction func timerSliderChanged(_ sender: UISlider) {
//get the value from the slider and round it to the nearest half
let newValue = Double(lroundf(((sender.value - 0.25)/0.5)))*0.5;
//from the newValue, extract the number of minutes and number of seconds for the time limit.
let minutes = newValue - (newValue.truncatingRemainder(dividingBy: 1));
let seconds = 60 * (newValue.truncatingRemainder(dividingBy: 1));
if(minutes == 0)
{
timerLabel.text = "\(Int(seconds)) seconds";
}
else if(seconds == 0)
{
timerLabel.text = "\(Int(minutes)) minutes";
}
else
{
timerLabel.text = "\(Int(minutes)) minutes \(Int(seconds)) seconds";
}
//set new values for the time limit in the settings
defaultSettings.setValue(minutes, forKey: "amtTimeMin");
defaultSettings.setValue(seconds, forKey: "amtTimeSec");
}
}
| 41.80198 | 134 | 0.58882 |
efdd02f6a84f1492930ef2d0c6b38765cfe39924 | 953 | //
// FixedMatrixGate.swift
// SwiftQuantumComputing
//
// Created by Enrique de la Torre on 11/11/2020.
// Copyright © 2020 Enrique de la Torre. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// MARK: - Main body
struct FixedMatrixGate {
// MARK: - Internal properties
let matrix: Matrix
let inputs: [Int]
}
// MARK: - Hashable methods
extension FixedMatrixGate: Hashable {}
| 26.472222 | 75 | 0.720881 |
debe6b3bc8134e388e889d171aedee72b8de978e | 3,227 | //
// OfflineMap.swift
// anti-piracy-iOS-app
//
import Foundation
import MapKit
class OfflineMap {
let path = Bundle.main.path(forResource: "ne_50m_land.simplify0.2", ofType: "geojson")
var polygons: [MKPolygon] = [];
init()
{
let geoJson: NSDictionary = self.generateDictionaryFromGeoJson()
let features: NSArray = geoJson["features"] as! NSArray
generateExteriorPolygons(features)
}
func generateDictionaryFromGeoJson() -> NSDictionary
{
var jsonDict: NSDictionary = ["empty":"empty"]
let fileContent = try? Data(contentsOf: URL(fileURLWithPath: path!))
do {
jsonDict = (try JSONSerialization.jsonObject(with: fileContent!, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
} catch _ {
//Do nothing
}
return jsonDict
}
func generateExteriorPolygons(_ features: NSArray) {
//add ocean polygons
var ocean1Coordinates = [
CLLocationCoordinate2DMake(90, 0),
CLLocationCoordinate2DMake(90, -180.0),
CLLocationCoordinate2DMake(-90.0, -180.0),
CLLocationCoordinate2DMake(-90.0, 0)]
var ocean2Coordinates = [
CLLocationCoordinate2DMake(90, 0),
CLLocationCoordinate2DMake(90, 180.0),
CLLocationCoordinate2DMake(-90.0, 180.0),
CLLocationCoordinate2DMake(-90.0, 0)
]
let ocean1 = MKPolygon(coordinates: &ocean1Coordinates, count: ocean1Coordinates.count)
let ocean2 = MKPolygon(coordinates: &ocean2Coordinates, count: ocean2Coordinates.count)
ocean1.title = "ocean"
ocean2.title = "ocean"
polygons.append(ocean1)
polygons.append(ocean2)
//add feature polygons
for feature in features {
let aFeature = feature as! [String:Any]
let geometry = aFeature["geometry"] as! NSDictionary
let geometryType = geometry["type"]! as! String
if "MultiPolygon" == geometryType {
let subPolygons = geometry["coordinates"] as! NSArray
for subPolygon in subPolygons
{
let subPolygon = generatePolygon(subPolygon as! NSArray)
polygons.append(subPolygon)
}
}
}
}
func generatePolygon(_ coordinates: NSArray) -> MKPolygon {
let exteriorPolygonCoordinates = coordinates[0] as! [[Double]];
var exteriorCoordinates: [CLLocationCoordinate2D] = [];
//build out Array of coordinates
for coordinate in exteriorPolygonCoordinates {
let y = coordinate[0];
let x = coordinate[1];
let exteriorCoordinate = CLLocationCoordinate2DMake(x, y);
exteriorCoordinates.append(exteriorCoordinate)
}
//build Polygon
let exteriorPolygon = MKPolygon(coordinates: &exteriorCoordinates, count: exteriorCoordinates.count)
exteriorPolygon.title = "land"
return exteriorPolygon
}
}
| 32.928571 | 155 | 0.59591 |
ef93fa7d08697808d3d25de2a8013c64cbf03c17 | 378 | //
// AccountInfo.swift
// TongueTwister.Swift
//
// Created by Assassin on 23/5/20.
// Copyright © 2020 Dan Gerchcovich. All rights reserved.
//
import Foundation
import UIKit;
public struct AccountInfo {
public var Id : Int = 0;
public var Username : String = "";
public var Password : String = "";
public var Creation : NSDate = NSDate.now as NSDate;
}
| 21 | 58 | 0.669312 |
09b268e2c0e136753d58183df9f1dae555038cc6 | 289 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{var f={class B<T where g:a{struct d{class g{func b{let a{func g{e=b
| 36.125 | 87 | 0.737024 |
338cf053bb10546c3949dffa5a6a82d320ae20e1 | 8,610 | //
// Copyright © FINN.no AS, Inc. All rights reserved.
//
import Foundation
protocol FilterSelectionStoreDelegate: AnyObject {
func filterSelectionStoreDidChange(_ selectionStore: FilterSelectionStore)
}
final class FilterSelectionStore {
// MARK: - Internal properties
var isEmpty: Bool {
return queryItems.isEmpty
}
weak var delegate: FilterSelectionStoreDelegate?
// MARK: - Private properties
private var queryItems: Set<URLQueryItem>
// MARK: - Init
init(queryItems: Set<URLQueryItem> = []) {
self.queryItems = queryItems
}
func set(selection: Set<URLQueryItem>) {
queryItems = selection
}
// MARK: - Values
func value<T: LosslessStringConvertible>(for filter: Filter) -> T? {
return queryItem(for: filter)?.value.flatMap { T($0) }
}
func clear() {
queryItems.removeAll()
}
private func queryItem(for filter: Filter) -> URLQueryItem? {
if let value = filter.value {
return queryItems.first(where: { $0.name == filter.key && $0.value == value })
} else if filter.subfilters.isEmpty {
return queryItems.first(where: { $0.name == filter.key })
} else {
return nil
}
}
}
// MARK: - Selection
extension FilterSelectionStore {
func setValue(from filter: Filter) {
_setValue(filter.value, for: filter)
delegate?.filterSelectionStoreDidChange(self)
}
func setValue<T: LosslessStringConvertible>(_ value: T?, for filter: Filter) {
_setValue(value, for: filter)
delegate?.filterSelectionStoreDidChange(self)
}
func removeValues(for filter: Filter) {
_removeValues(for: filter)
delegate?.filterSelectionStoreDidChange(self)
}
func removeValues(for filters: [Filter]) {
for filter in filters {
_removeValues(for: filter)
}
delegate?.filterSelectionStoreDidChange(self)
}
@discardableResult
func toggleValue(for filter: Filter) -> Bool {
let isSelected = self.isSelected(filter)
_removeValues(for: filter)
if !isSelected {
_setValue(filter.value, for: filter)
}
delegate?.filterSelectionStoreDidChange(self)
return !isSelected
}
func isSelected(_ filter: Filter) -> Bool {
switch filter.kind {
case let .map(_, _, radiusFilter, _):
return isSelected(radiusFilter)
case .range:
return filter.subfilters.contains(where: { isSelected($0) })
default:
return queryItem(for: filter) != nil
}
}
}
private extension FilterSelectionStore {
func _setValue<T: LosslessStringConvertible>(_ value: T?, for filter: Filter) {
_removeValues(for: filter)
if let value = value.map(String.init), value != "" {
let queryItem = URLQueryItem(name: filter.key, value: value)
queryItems.insert(queryItem)
}
}
func _removeValues(for filter: Filter, withSubfilters: Bool = true) {
if let queryItem = queryItem(for: filter) {
queryItems.remove(queryItem)
}
if withSubfilters {
filter.subfilters.forEach {
_removeValues(for: $0)
}
}
}
}
// MARK: - Helpers
extension FilterSelectionStore {
func queryItems(for filter: Filter) -> [URLQueryItem] {
if let queryItem = queryItem(for: filter) {
return [queryItem]
}
return filter.subfilters.reduce([]) { $0 + queryItems(for: $1) }
}
func queryItems(for filterContainer: FilterContainer) -> [URLQueryItem] {
return queryItems(for: filterContainer.allFilters)
}
func queryItems(for filters: [Filter]) -> [URLQueryItem] {
return filters.reduce([]) { $0 + queryItems(for: $1) }
}
func titles(for filter: Filter) -> [SelectionTitle] {
switch filter.kind {
case let .range(lowValueFilter, highValueFilter, config):
let formatter = RangeFilterValueFormatter(unit: config.unit)
let suffix = config.unit.value.isEmpty ? "" : " \(config.unit.value)"
let accessibilitySuffix = " " + config.unit.accessibilityValue
func formattedValue(for filter: Filter) -> String? {
return (self.value(for: filter) as Int?).flatMap { formatter.string(from: $0) }
}
let value: String?
switch (formattedValue(for: lowValueFilter), formattedValue(for: highValueFilter)) {
case (.none, .none):
value = nil
case let (.some(lowValue), .none):
value = "\(config.unit.fromValueText) \(lowValue)"
case let (.none, .some(highValue)):
value = "\(config.unit.toValueText) \(highValue)"
case let (.some(lowValue), .some(highValue)):
value = lowValue == highValue ? "\(lowValue)" : "\(lowValue) - \(highValue)"
}
if let value = value {
let title = SelectionTitle(
value: "\(value)\(suffix)",
accessibilityLabel: "\(value.accessibilityLabelForRanges)\(accessibilitySuffix)"
)
return [title]
} else {
return []
}
case .stepper:
if let lowValue: Int = value(for: filter) {
return [SelectionTitle(value: "\(lowValue)+")]
} else {
return []
}
case let .map(_, _, radiusFilter, _):
if let radius: Int = value(for: radiusFilter) {
let value = MapDistanceValueFormatter().title(for: radius)
return [SelectionTitle(value: value)]
} else {
return []
}
default:
if isSelected(filter) {
return [SelectionTitle(value: filter.title)]
} else {
return filter.subfilters.reduce([]) { $0 + titles(for: $1) }
}
}
}
func isValid(_ filter: Filter) -> Bool {
switch filter.kind {
case let .range(lowValueFilter, highValueFilter, _):
let lowValue: Int? = value(for: lowValueFilter)
let highValue: Int? = value(for: highValueFilter)
if let lowValue = lowValue, let highValue = highValue {
return lowValue <= highValue
} else {
return true
}
default:
return true
}
}
func hasSelectedSubfilters(for filter: Filter, where predicate: ((Filter) -> Bool) = { _ in true }) -> Bool {
if isSelected(filter), predicate(filter) {
return true
}
return filter.subfilters.reduce(false) { $0 || hasSelectedSubfilters(for: $1, where: predicate) }
}
func selectedSubfilters(for filter: Filter, where predicate: ((Filter) -> Bool) = { _ in true }) -> [Filter] {
if isSelected(filter), predicate(filter) {
return [filter]
}
return filter.subfilters.reduce([]) { $0 + selectedSubfilters(for: $1, where: predicate) }
}
func syncSelection(with filterContainer: FilterContainer) {
let keys = filterContainer.allFilters.reduce(Set<String>()) { result, filter in
result.union(syncSelection(with: filter))
}
queryItems = queryItems.filter { keys.contains($0.name) }
}
/**
Cleans up selected values based on filter hierarchy (e.g. deselect filters with selected subfilters).
- Parameter filter: The root filter.
- Returns: Keys of all processed filters.
**/
private func syncSelection(with filter: Filter) -> Set<String> {
var isSelected = self.isSelected(filter)
var keys = Set([filter.key])
for subfilter in filter.subfilters {
if isSelected, hasSelectedSubfilters(for: subfilter) {
_removeValues(for: filter, withSubfilters: false)
isSelected = false
}
let subfilterKeys = syncSelection(with: subfilter)
keys = keys.union(subfilterKeys)
}
return keys
}
}
private extension String {
var accessibilityLabelForRanges: String {
if contains("-") {
let formattedAccessibilityLabel = replacingOccurrences(of: "-", with: "upTo".localized())
return "from".localized() + " " + formattedAccessibilityLabel
} else {
return self
}
}
}
| 31.195652 | 114 | 0.579443 |
ff2f4f019b566d3dcb9f4d752e27aa5ba699d9c4 | 2,780 | //
// SceneDelegate.swift
// SwiftUIDividerTutorial
//
// Created by Arthur Knopper on 08/12/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not 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.
}
}
| 42.769231 | 147 | 0.707914 |
e64875ea34771624d2c788afc936576e38732530 | 399 | //
// NotificationView.swift
// WatchLandmarks WatchKit Extension
//
// Created by Gospodi on 31.12.2021.
// Copyright © 2021 Apple. All rights reserved.
//
import SwiftUI
struct NotificationView: View {
var body: some View {
Text("Hello, World!")
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
NotificationView()
}
}
| 18.136364 | 51 | 0.671679 |
0e06eac7ee0afdf736572e129cdfdfb3b6a536d4 | 3,172 | //
// ViewController.swift
// TipCalculator
//
// Created by sheen vempeny on 3/6/17.
// Copyright © 2017 sheen vempeny. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lblBillCurrency:UILabel!
@IBOutlet weak var txtFieldBill:UITextField!
@IBOutlet weak var txtFieldTip:UILabel!
@IBOutlet weak var txtFieldNewBill:UILabel!
@IBOutlet weak var segCntl:UISegmentedControl!
var tipUpdater:TipUpdator = TipUpdator()
deinit{
NotificationCenter.default.removeObserver(self)
}
func updateUIColors(){
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.lightGray.cgColor, UIColor.darkGray.cgColor]
view.layer.insertSublayer(gradient, at: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateUIColors()
}
@IBAction func tipChanged(segCntl:UISegmentedControl){
self.txtFieldNewBill.resignFirstResponder()
SettingsController.sharedInstance.selTipIndex =
segCntl.selectedSegmentIndex
self.tipUpdater.updateValues()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updateUI()
self.txtFieldNewBill.perform(#selector(becomeFirstResponder), with: nil, afterDelay: 3)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.txtFieldNewBill.text = String(SettingsController.sharedInstance.lastBillAmount())
tipUpdater.txtNewBill = self.txtFieldNewBill
tipUpdater.txtTip = self.txtFieldTip
tipUpdater.txtFieldBill = self.txtFieldBill
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.saveAppData(notification:)), name: Notification.Name("saveAppData"), object: nil)
}
func saveAppData(notification:NSNotification){
SettingsController.sharedInstance.saveLastBillAmount(amount: Float(self.txtFieldNewBill.text!)!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateUI(){
let selIndex:Int = SettingsController.sharedInstance.selTipIndex
let minVal = SettingsController.sharedInstance.minTip
let maxVal = SettingsController.sharedInstance.maxTip
let midVal = SettingsController.sharedInstance.midTip
self.segCntl.setTitle(String(format: "%d%@", minVal!,"%"), forSegmentAt: 0)
self.segCntl.setTitle(String(format: "%d%@", midVal!,"%"), forSegmentAt: 1)
self.segCntl.setTitle(String(format: "%d%@", maxVal!,"%"), forSegmentAt: 2)
self.segCntl.selectedSegmentIndex = selIndex
self.tipUpdater.updateValues()
let locale = Locale.current
let currencySymbol = locale.currencySymbol
self.lblBillCurrency.text = currencySymbol
}
}
| 32.701031 | 169 | 0.677806 |
723b0d02d9ea345fc76bacb2ffa57d955feba9e7 | 21,441 | import XCTest
@testable import day02
final class day02Tests: XCTestCase {
func testPart1Sample() throws {
let validRecordCount = day02.solvePart1(input: sampleInput)
let expected = 2
XCTAssertEqual(validRecordCount, expected)
}
func testPart1Real() throws {
let validRecordCount = day02.solvePart1(input: realInput)
let expected = 500
XCTAssertEqual(validRecordCount, expected)
}
func testPart2Sample() throws {
let validRecordCount = day02.solvePart2(input: sampleInput)
let expected = 1
XCTAssertEqual(validRecordCount, expected)
}
func testPart2Real() throws {
let validRecordCount = day02.solvePart2(input: realInput)
let expected = 313
XCTAssertEqual(validRecordCount, expected)
}
}
// MARK: - Input
let sampleInput = """
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
"""
let realInput = """
1-7 q: qqqqxvqrkbqqztlqlzq
1-3 q: cqbm
15-16 h: hhhhhhhhhhhhhhbsh
4-16 x: xvbxswpnvxtnfjrxxx
6-7 v: kbbvnswp
17-18 h: hhhvhhhhhhhhhhhhhh
1-7 w: twftdrb
4-5 t: wcjtfpt
3-9 f: mbfvfptbfq
3-10 x: xfxxxxxxxv
5-11 p: ppvhkgpmwfjp
5-8 c: cbhhrtsbpf
13-14 t: ttttltttgttttvht
11-16 m: mmmmmmmrmmdmmmmxmmm
3-13 b: bbbbbgbbbbbkkbvd
7-10 d: ndddwdmdddhddv
4-7 d: gcndnddkwhd
14-18 z: zzzzzzzzzzzzzvzzzzzz
5-6 c: mfcwccckdccfmzc
9-14 p: bppzpwhzdgnpnh
11-19 q: jqhqqqqqqqmfqqqqqqqq
5-6 h: kqhpgl
15-18 w: wwwwwwwwwwwwwwqwwqw
2-10 m: qmmmmtphbrw
10-20 k: jxlnkxnkhlkgkzhxbdvg
8-9 c: ccccccccc
12-19 k: vlkkkkklkzkkzkkckkfk
13-14 s: bsfssqsscsssdj
11-13 p: rmpdppplgcnpwxd
9-16 c: ccccccccrclccqcgcc
3-8 s: snsssmssdns
13-19 t: ttttttttttttttttttwt
7-8 q: dqqqdqqqqnqdq
10-11 w: wwwvwwvhwtvwwwmw
3-6 b: bbsnbpbckbb
1-4 g: gggjg
6-8 b: jvrqbbmb
2-6 t: cvdtzn
3-4 v: vvmd
2-8 z: vmwhtskz
2-6 b: jbrbjbs
1-2 d: ndzwd
17-20 r: xjfmlrrjcnnrmkvhrpwr
8-10 q: qqqwqqqqqdl
2-5 p: phppxpppppppp
9-10 z: zzzzzznzzz
8-9 k: phgksffkrfgp
11-13 w: wwwwwwwwwwnwz
9-11 k: krkkkkqkkkkskkk
19-20 d: dmcwfddgdddvdffdhdld
8-11 f: bflfqsffvfdffmfpfqf
6-10 v: wwqvvvjvrd
4-5 v: vvdvw
3-4 h: hdhh
9-10 d: dndfdddddd
3-13 n: nnfnnnnnnnnnnnnnnmnn
5-12 b: zwqcbkfcbbnbb
5-15 q: qqrdqqqmqqnqqnjkqqqw
6-8 l: vfllklxllclll
3-4 h: hchh
12-16 b: bbbbbbbbbbbhwbbtgbs
4-10 p: ppwxplpppp
4-5 s: szhss
8-10 w: tvdtvbwnlfvkspxp
4-9 z: zzznnkzwdzrz
5-14 p: pppppppppppjpp
6-7 n: hnnnnqnn
1-4 q: qqdqqq
7-8 w: wwwwwwbpww
3-10 x: xfxxnxjxxxpx
5-19 m: kmqhgpjdszvgrfrdlhm
10-12 k: kqqzkkkkkkkk
4-7 l: llpqcgmll
4-5 p: rwppp
2-6 q: mqqhrsdk
7-10 m: cmmvscmmkm
9-18 k: kkkkkzkkqdpkdlkjpgk
2-7 m: xmglcvmkmln
8-12 n: nnnnnnnfjnnbn
4-5 n: nnnnn
13-17 z: zzzzzzzzzzzzkzzzz
1-5 t: mfftmn
2-3 n: nskh
11-18 s: sjssgsssfstzsbhnsw
14-16 d: pgxrmlxdthpdndfdt
2-3 h: hhhhh
3-4 s: hssn
7-9 f: fffffcmff
2-4 s: srwbvhnlqssdpsssx
3-4 v: vvvvvsvxvvh
12-13 x: xxxxsxsxxdxmpjxlxxf
15-16 m: cjcmmmmgdmbnmcmm
8-11 l: hsjlnlvlfchgjlrdl
9-11 k: kkknkkdkdkkk
5-6 q: qgqqfpq
16-19 w: wwwwfwwwwwwwvlwwwtw
2-13 n: nnnjngnwgldsnrnrr
5-6 x: qwbpxx
4-5 x: xxxhx
11-13 t: ctpskdtbwbtkstfj
2-8 z: jwznsgln
17-18 r: rrrrrrrrrrrrrrrrwnr
7-12 v: bkpvwzzsdnsd
5-7 h: hxxnpzh
7-8 z: zzzzzzxs
3-7 z: hzstpkrlht
7-10 p: ppgkppnpdppj
10-11 g: gghhgvgggwf
9-11 q: qqqqxqqqqpqqqq
2-3 r: qrrfr
3-8 x: xvxzsxtxgxb
11-14 q: fbqtzvjdqqhqqrqjrqq
11-16 c: cccpccccccscwccfccn
9-11 m: snmmmcmmsmmmmkm
2-11 m: mmmczqsmclmrvmbzlv
10-15 z: zzzzzzzzzjzzzzkjzzm
3-13 j: jjxjjjjwjjjjbjjjdjjd
7-10 j: sjjqjjvzjjcjrh
8-9 x: xxxxxxxzxxx
4-11 n: nnmnmndfnhqnhnn
16-19 v: kntvxvvvvpvvvvghkzp
6-9 b: pbbbxxjfqvngbvbb
16-17 j: jjjjjjjjmjjjjjjjjj
2-3 t: wttttttt
10-15 c: cccccccccgpcccccc
7-10 j: jjjjjjqjjrj
1-7 f: cffffftfff
8-14 r: rrnrrrrrfrrgscrmr
1-12 b: jbbbjbkwbgbb
13-16 m: mmxmmmmmwmmwmfmmmhbm
1-9 s: fsssssssqs
8-15 q: pxqqqqvbqqsbqzjngkv
3-4 w: wkspxwm
1-7 h: gkfhhhjhhhch
1-4 w: sqrnwwgwqdw
2-6 d: dpdwdld
2-3 m: mmmmm
4-6 p: pppspp
2-7 c: ctcglxx
11-13 x: xxqxxxxxxxxxxd
7-9 c: cgccccbcrc
6-9 p: xspppkppprp
4-5 v: vvfqrv
15-19 l: llwllllllfllllglllcl
10-17 v: vvvvvvvvvgvvvvvvk
11-14 s: sstngtbhsfsgds
3-4 c: dxklc
6-7 l: lllllll
8-10 w: wwwwwwxtwkwnw
3-4 l: sgllkmdpzgzvllzv
7-17 w: zdfsdmwbphwhzwrxww
2-12 l: rbwfpnmzgtsl
3-6 s: qssdwlfbnm
5-16 f: fffffffffffffffzff
12-14 l: lllfllllldlllljll
14-19 x: pxxxxxxxqxxxxxxxkxwx
12-14 b: bbbbbbbbbbbrbnbbbb
2-12 j: trjqljjgrjjq
1-10 q: qqqqqqqqqqqqq
1-6 t: jttttrtt
1-2 v: rpvfcxhcgx
4-5 r: frsrr
1-6 v: jvvvvqvvvv
2-4 v: tvvb
4-5 h: hhchhzhqhcvh
8-9 c: ccphccccccc
13-15 c: cccbccccccxccxclcscc
5-6 b: bbkbpczbs
10-16 g: gdgggggggggggggggg
1-11 f: fmffxfffgcfwfffbzff
3-13 m: mzmmkmntbmmmmcz
1-2 g: xkgq
10-12 r: rbrmrrrrrwrrhrqvkr
7-8 m: wbbmmmmmfmm
3-4 l: dsnt
4-5 k: kkkkkkk
16-17 r: rrrrcrgrrmqwjrpwmtr
15-17 z: zzzzzzzzzzzzzzzzzzz
13-15 b: zbbbbbbbbbbttbbb
8-13 w: twrwwwlwtwwww
10-11 w: wwwwwwwwwwwwwwwwww
4-6 b: pxvqbb
5-8 n: wnnnznngw
4-9 q: njjqqkrlq
10-15 c: cckhfccdhfccccj
10-15 c: ccrktcccgccgccz
1-5 s: dvssx
2-3 w: wwnw
3-4 n: nnnnc
7-16 n: tdlhmgsqknfnwgnnwmn
9-11 z: zgdzzzzwfgjwzzzm
4-5 f: ffpffff
3-6 f: fvgfcff
5-6 f: fkffhhlhrfg
7-13 g: gtflglggggwbg
4-5 w: wwdwrw
8-10 w: hwpzzwwwjbqfww
5-11 f: ftgfffffffpqffffffff
6-7 f: fffffml
6-12 j: jjtjjtjjjzjzjh
4-6 h: phwtrn
10-14 l: lllllllllcllll
6-7 d: hdwxdsk
13-18 w: kwwwwwwwwwwwwwwjwww
3-8 q: bpqtzmqqljll
1-3 c: cccds
4-5 m: mmmmzd
4-7 c: cccjcck
4-6 t: ctdvts
3-10 x: xsxrxshzjxrt
3-6 j: wljvmxqzrjhctx
4-5 v: vwvvcld
8-9 l: blllllvllglllll
4-14 j: jjjjjjjxxsjmjjjjj
8-12 v: bvvvvvvqvvvbvv
2-6 g: pgsgcglt
1-4 g: qggs
7-9 h: phchhpxhqhhh
5-7 z: czzjzrnq
3-4 k: kkkw
2-3 v: vjfv
7-11 v: slrrxhrhnvvk
7-10 t: czhvlfwthc
2-17 m: zmmmmtbmzlwmmmmslbm
1-4 m: fmjz
6-8 d: sdddddddddw
2-5 h: pnfkhrwchvc
2-4 r: brsrktfkqdlhzvvsfhf
3-4 n: qnknnn
7-10 f: rvnzfmfzrfdqkffc
2-5 x: hxxqxkxxw
1-7 w: wwqzwkww
2-3 s: ssps
8-16 d: ddjdddddddddbddddd
10-12 d: dddxddddwldfsd
1-6 v: skcvcwjf
2-7 g: ggggzlggjgwg
2-5 j: rjzfjqjzjtjkfp
15-17 f: bqslszncqcvrpfrff
2-13 d: xcddddddddwdzdmddzd
1-9 l: lllmllxlljlxhll
10-17 p: msbwpcprpppnsbpppzk
2-13 v: vwdvvrsjrvvvpcvvv
5-9 c: xscgtfxjbchcp
4-6 g: jghgfg
7-8 v: vvvvnvvv
10-12 z: zzzzzmzzhbxz
11-17 b: fknnqwzpgbbqnxkckj
1-3 h: zgbpdwdnmmhbnqxm
4-6 t: httsznfnx
5-10 f: fflfffrfvxvgdq
1-3 r: zrrrrrrrrnrr
5-7 k: kkkkkkkkkkk
6-7 r: rrrrrfgrrrz
3-12 s: sssssssssssssss
3-5 t: ttjdtt
3-4 s: zzhslfrtwsj
5-6 d: dddpddv
1-7 q: bqqqdqpqq
10-13 s: ssstscpsslsrsssds
7-8 r: lrrrrrrr
5-10 z: jzfwzlzjlz
3-8 g: grpggggg
1-7 c: jccccjvcc
12-13 n: nnnnnnnnnnnhn
1-5 t: ztwwnt
8-9 z: zszzzzzbzzzz
1-5 p: pppppp
8-9 j: jjjjjbjkcjgj
5-6 x: xwhxlx
5-8 d: ddddwddx
5-17 l: lllztxdllwblllllv
9-18 m: mmgmmzmrmzchvrhqmm
17-18 c: wzsjwnccrgbcwhrmgc
10-17 f: fbdmffffchfcfkfft
17-18 r: rzbzrszcnnrmlrrrzk
1-9 p: cppppppppppp
1-9 t: ttptqthtttct
5-7 c: ncwnhmswscrqgtjtdgcr
5-10 f: dffsfffpffhzf
8-19 n: mnscfmjnnlvznnvlktn
7-8 z: zzzzxzzd
8-18 z: lzzbzbczzhdkzzwzgzz
1-9 x: rxxsxxxxxxxfxxxx
5-10 w: kjrwwptbww
12-13 z: zzzfzzzrzzzzz
5-6 g: gghggg
16-18 q: qqqqqqqqqqqlqqqqqxqq
5-9 c: lmcsxccccqjhmtcq
1-3 x: xxtnxfqzxxx
13-15 w: wddxxwwgqwwxwwww
12-16 r: mrrjmrrrhrrrrrrrrr
18-19 j: nmfjvcjljptwjnjjjjj
1-13 g: ggggggggggggggg
11-15 p: tpldppcbbbpzpvppw
2-11 x: hbxdxxgnqxbxxxxjjxx
9-11 s: nsnsksshzsqss
1-16 k: knkkfkkqkhhbkppvkk
2-4 x: tlwd
5-7 h: npmhclh
15-17 t: ttttttttttttttsttt
5-6 d: dxddrkddhdl
8-12 d: bddjdffdddtkgdhddd
7-8 z: dkxzgbzzlw
3-4 z: pzzz
5-6 t: ttttqvv
2-7 d: tpsdkqds
18-19 c: cccccccccccccccccbcc
2-3 c: hcmj
5-6 l: llllwl
2-6 t: tqtttx
11-12 r: rrrfrrrvrrrcrrrrrrr
9-12 s: dspssssshssssss
1-3 d: ddddc
4-5 t: tbpttzvtqr
4-6 j: jjgjdjj
2-4 t: tbtb
4-5 w: wbwbwwvww
10-11 s: dwsspssssssss
1-8 s: tssssssl
6-8 k: kksgmgkq
6-11 p: pppppppjcpq
7-8 c: ggcccpcclr
13-14 h: hhhhhhhhhhhhbfh
14-15 n: hsnnnnnnnnbnnwmnnn
11-13 k: xxmqpkkcqkkjn
12-14 w: qwkwwwxqwwzwcw
1-17 n: nnnnnfnnvnnnnnnrpnn
2-3 b: xbsgcgnrh
4-5 v: ckpfvkvvswdnh
6-7 q: qqqfqqf
8-10 m: vntcbkgmmm
9-13 m: bvxrzxbmlnmxcvmrwrc
4-5 j: fjjlj
1-3 k: lkskjkkc
8-14 d: ftbhrdxmmfdbkwrsqr
1-6 q: qrwcqqmtsqqhq
16-17 h: zlmjqfbxhhhfmpvsdg
3-8 v: bpwnbflvsljdzfkdmv
8-18 m: mskwllxmbgbrdjmhwmn
9-10 h: hhhhhzhhhq
6-8 t: jttttztv
2-4 m: xmmm
15-17 f: ffffffffffffffjfwfff
3-5 q: xrqqq
1-4 h: hhqfmhhh
14-15 f: ffffffffffhfcffd
2-11 w: fjjnmtswwwbhwcrgjwgd
4-9 q: qqqqqhqxqqxqt
8-11 g: gggggggcggggggggg
1-5 s: dbstvs
2-4 z: zzzgz
10-13 r: rrrrrrrrrrrrr
3-4 r: wrzr
5-9 c: cccddcrfccc
2-8 k: vkkvlgvvsqzzkkvnk
8-9 d: djdxdddwxdqrd
5-7 j: cjjpjggqhjwtth
5-15 n: nmnbnmnrxnrkznnvnn
3-13 j: cjjjjvgjqdjjdqjr
6-7 r: rzkrrvr
3-5 v: nvczvzgrnk
6-7 x: xxxxxdv
2-5 c: hccpcw
9-16 d: ddddddddddddddddd
6-9 c: ccfccdpcqccccp
4-5 q: kqtqq
1-2 z: zzzk
9-13 d: ddddddddddddd
5-8 q: prfjgqvzqbqqqq
2-6 h: rhrvghkfx
3-10 d: rddszpfmrdfgqt
7-11 w: wwvwwwkwwwlwwwwwww
7-9 b: bbbbbbbbm
1-2 r: ffnppzhtrkj
1-10 m: mxnmfmlkwmwpkj
3-10 n: nnwmnxnxnnl
14-16 p: pppppppppppppfppp
1-2 m: mmgn
11-12 p: hpppppkpppppp
6-14 l: lfvlllscxnlpll
11-12 r: rrrbrdrrrrrm
3-6 w: wwwcgw
9-12 b: rbfhbqblnbbbbdb
5-6 m: hmmkmmqmkm
4-6 q: qclhqjqq
4-16 l: lllnpllllllllllblllr
4-5 m: nxcmmtmr
3-5 q: qmblr
4-5 m: mmmmm
16-17 b: bbbbbbbbbbbbbbbcbb
1-7 p: tjppppppppp
5-6 k: kkkksf
2-10 x: cxjbfjkwjxqwzjxcbq
2-5 t: tsjkfn
4-7 g: xgbcrst
4-5 x: xxxxxx
2-5 s: sszxb
4-12 k: wcrkhkgkzklkqkh
8-10 b: bbbbbbbnbn
2-7 k: fkzfkkkkkklk
4-8 w: wwwwwwwww
4-8 h: hhhhhhhjh
4-11 h: tgbhnnrzpshbjhq
6-7 b: bsbdqbbb
2-6 t: sqvtbgttbftt
2-7 c: mctjgnn
3-8 m: ktthpgrfmrqkcj
5-7 x: whcxpgxvfq
5-14 w: wwwwwwwwwwwwwww
2-14 m: nmbxjbsmfjhdxmswks
7-11 b: jbbprkhndbqclbb
5-7 f: ffbfhfq
6-10 z: zzzzzzzzzzzz
4-7 d: mkdddgdhdh
2-4 d: pkjd
5-7 c: ccctqptcccccc
15-16 h: hshfjthnhssrvdhb
4-5 b: bbbxb
5-12 l: llllmllllllnl
3-4 t: tbgt
5-9 w: wwvzwblwgwwwwvwww
3-4 g: mmggfggg
8-14 j: jnjjvjcjtmpjtjjxcpw
8-9 h: hhhhwhhpch
5-7 v: vvdzhcvv
16-17 v: vvvvvvvvvvvvvvvtq
12-18 s: sdcvjsfqtgnhcsmmsm
6-13 n: hnqglmrjfgdnnpvtjr
12-13 q: qmqqvqqqtqqvqqq
1-9 z: nzzzzzzzzzzzzzz
1-4 l: lllllll
15-17 j: jjjjjjjjjjqjjjpjhj
2-3 t: bttb
3-4 q: qqqx
1-3 t: wtjt
18-19 x: xgnmxxljxwxxztxjvxx
2-4 n: pkpf
17-19 s: sssvssssssssssssssss
13-14 l: llqlllllllllll
5-9 m: mxgnmmrdmzll
3-5 m: mmcmmmmwmmm
4-8 b: bbbbbmplb
4-6 x: xxxxvx
1-2 m: lvfb
9-10 n: npnnnnnpnnnn
3-5 m: mmnmwmmmm
15-20 r: mwrrrrrrrwrrrrrrnrrr
1-2 l: rzlll
9-11 s: sssdssnssts
3-5 c: lccncc
13-14 v: vvvvvvvvvvvvvv
2-12 g: vshnfnhkzgjgkqn
6-9 k: kqskrckkwg
18-19 v: xzwbgvvnwlprqdxvshl
16-17 v: vvvvvvvvvvvvvvvzv
6-13 m: vkmmclmmwjfcvnmmm
5-11 j: sjjjqwjjrjjqj
5-7 q: djqhqcqhlz
8-9 f: fffmcfftw
12-14 x: xqpnjxjxlpxwxxb
7-16 h: hhhglhnhbcxhvhhxhh
12-13 v: vcvxvvvvvvvvvvv
12-13 g: ggdngtlxwlrtsgcgmtgm
5-6 n: nhnnhcn
3-4 n: nnngwk
9-10 k: kkkkkkpkkk
6-11 r: rrrrrkrrmrtr
3-9 d: dwdwdddqnfdddddddd
8-15 q: qvqqxqqwqrqqqfjq
6-7 f: ffffflf
4-9 m: rpmsmphdmmbpdmmhmpr
3-9 q: qqqqqqqqcq
3-4 d: hddds
2-4 f: rcfj
3-4 k: kkhn
6-9 n: npnnnnnlj
1-6 k: tvspqddqktkkqkvk
11-12 x: slxrptmpfqtp
12-14 l: jjvwhlldtlllllh
13-14 g: ngggggggggggks
14-15 z: zzzzzzzzzzzzzjvzz
5-6 l: vbsnvllnhlchblllc
7-13 z: zgczzbzgzlpnczzz
17-18 v: vvvvvvvvrvvvvvvvvvv
15-16 h: hhhhhhhhhghhhhhh
1-5 n: snnqv
6-7 m: mmmmmmmm
15-17 p: pppppppppppspqpppxp
12-14 w: wwwwwhwwwwwwwwwww
4-8 s: fssltbzbsrn
5-7 g: gkxgbggg
15-16 s: ssssssssssssssss
2-4 l: lxtswwg
5-6 p: plppzkpp
9-10 r: srrrprgrhrrrvrr
1-2 d: ddlhchdfll
3-4 j: jjwg
7-11 b: bkfbvbdvzlbz
7-13 q: qgvwkzkrkvvks
2-7 c: ccjtcbccccgv
2-3 q: fqqq
3-4 b: btssh
6-7 m: mnmmmmm
3-4 n: nrnn
5-14 n: fcsxngnnkqxnjnn
14-19 x: rmxcxxxxwxzxxhxxxlc
3-13 q: qqqqqgqmdshrqnqlqlqt
14-16 v: vvpvvvvvjvvnvvvvvvvv
15-16 c: cccccccccclcccch
4-6 v: hvvcvv
7-9 d: dcdmddxdld
16-18 x: rxxxxxxxzxxxxxxxdx
11-14 l: llcsqllgvfmhlvtvb
7-10 h: hhhhhdmhhwhhhh
5-17 g: ggggggggggggggggg
4-6 q: fbsnmzqdsqsqfpdr
12-16 n: fnnlvnflmcnndtfnlw
8-13 c: cpwshcvbccbjmlch
7-9 l: sfhcltwlc
9-13 w: xwwwwxwwwwwgwwkw
5-6 q: kqqqqqjqqqqqqk
14-17 k: kkkkkkkkcvbkkqxtkkkk
8-9 h: qjhxhjhzl
3-6 l: jlllvl
10-11 q: shkxnqwfrhhznlb
3-9 l: dwbvfgngtzcbhzlft
16-20 b: qstrwcrclxzbwtlbpnwb
8-10 n: ndhpptnnnjnnnbnn
4-8 l: lllnlllw
1-3 v: vdfxksvvn
14-17 b: blbbmbbbbbbbbbxbbbb
9-10 t: tttrkltgfbtth
10-12 n: njhnnnznnnnn
8-9 w: hfwwdwwww
4-5 c: scrcccwc
17-18 t: ttttttttttttttttmp
10-11 t: tttttttttvjtttttt
1-3 m: mdlrc
8-9 r: zrnjxkbrrppzgvf
3-4 d: sqddksgdjmd
3-5 m: mmmmmmm
1-8 h: nhclfdhlqwhhczn
2-7 c: bbcbccgxhcwn
4-6 l: zldqlgl
9-11 n: pqbxnxfzhtd
2-15 r: drmrjfxlqvmlcnwlbn
14-15 k: kkkskkkkkkkkktk
4-5 x: mxxzsxxxxx
1-2 p: hhfwz
6-13 b: mbdbkbpbjbbcb
12-16 t: tthfzkrqvhltzhlttwtw
6-11 h: hhhhhhhhhchzh
3-8 q: knndgrkmnqqxjj
5-7 v: svkvhfvv
6-9 r: rrrrrwrrrrr
3-10 p: pspxqhpxfqp
3-9 z: xfzzmjgqzgjzczqpnj
6-10 n: nnnncrnnnqnnnnn
1-7 k: kkkkkkkkk
2-4 m: mhmj
3-7 j: qjtjjmbjjkfjjrj
2-7 r: nrdxvnr
1-2 l: wrrr
3-4 t: ttjktt
9-13 l: lllllllclslllll
12-19 p: cpplpppphpppppdpntp
10-12 p: dnpppppppwpgpppp
2-4 z: pzzb
1-2 k: kpkt
4-7 r: rrrrrrq
1-7 t: xttwtnqttd
1-4 g: zngs
4-6 d: qszrkcxxdt
1-6 b: cpbhfm
3-4 m: knmn
9-11 c: lpdbchcckwnrc
3-4 r: rrrrr
12-18 q: qzqqwqqqqxrqqwqqqdqq
6-9 v: wvvvvpvbq
6-7 g: sggxxdhl
12-17 b: mbsgqwvzlnjskhxctt
4-5 f: rsfkc
9-12 h: hhhhhhhhshhhhhh
4-5 p: nppcn
3-5 g: ggwsmggsgggfg
4-6 p: gppfpsh
13-14 v: fvftvjtqvxsqhzrv
2-3 l: jlmbl
2-4 v: wwjvv
4-8 l: lllhlhllmlplg
1-14 f: znvtwnmslnfhjrds
3-10 z: zzhzkhzzlkdxzzz
17-19 r: rrrrrrrrrrrrrrrrrrrr
15-16 q: qpvqdgqkqqqqqqqq
5-12 k: wkkkkknkszpkkrk
3-8 j: jjhjjjjwj
2-12 s: qvknfbrpsrfsp
11-12 j: jjjjjjlfjjcrzjtj
3-13 m: mmmmglpmhtrfvmfmmmx
6-17 l: lllllblllllllllldll
4-5 q: rqqnqqqqq
8-9 p: fppppnspp
11-17 q: pqqqqqqqqqjqlqqqqd
3-4 l: lslll
1-10 r: bgrrrrrrrprrr
12-17 g: gggwjnxgmggngggrgpg
14-16 z: zxzzzzzzzzzzzpzgz
4-12 t: sttttttttttttwtz
6-7 x: xlzxxxxg
3-4 g: ggcg
3-11 c: zblkwrxvcnl
3-16 l: lhlljbljsllfhlklrlv
8-9 v: vvvvvvvvtp
2-5 f: fpbqcglx
3-15 g: cwmgbgntbgwccqggpv
4-11 m: mwwfhdgxdsmxckqcqvpg
12-14 v: vvpvvvvvvvvfnwvv
2-4 b: bbsxbwqbbx
4-7 s: knsnxlsmg
3-4 z: zzzzz
1-4 x: mxxxxxxx
2-7 w: pxwmtbkskmmfcddczqd
9-12 b: bbbbbqlbgbbb
3-4 l: mlqrlchqn
2-3 b: bbbb
13-15 x: lxxfjvqxhxhlxxx
5-8 m: mtmnkvmcm
3-7 v: xvwvvvwbtvs
2-16 x: wsbhsvzxbjfjwlzlzr
3-4 d: dzrd
5-7 l: llllllml
14-15 d: dddddddddddddwb
6-7 t: ttttfbttg
11-12 v: vvvvvvvvvvvvvvvv
11-14 z: zzzzzlzzzzdfvjtzk
4-20 b: jfnnqxxvxwhbfmbxqdxq
6-9 d: dddddzdddd
1-2 s: rnwsscss
2-3 q: kqkrhq
8-16 r: krlrxhrchrrrrvrkr
5-7 r: svcrrfq
2-13 b: bbbbbbbbbbbbbbs
3-7 k: pdxkstw
9-16 w: wwwwwwwwvwwwgwwww
3-5 g: gbgkggpcmjgrc
13-15 d: dddmdddmdddmldg
3-17 t: tkpttktttbttttttt
1-5 n: pnnngnnn
3-4 f: ffhf
3-7 p: tqpnncpczlp
4-13 b: ppbnsfztshmbbggn
1-4 r: rvlrrqrrrt
4-8 s: snfwsssrsrrssssszp
1-7 w: fwwwwwww
1-4 d: fdjb
7-8 l: llglthmjvlllt
7-8 w: wwwwwwzjw
7-9 v: zrgvvvvvvv
2-7 d: pdddzvh
2-9 w: nwwwbjswwxwxczlmh
5-10 w: wwcwwwwfwwghwbw
6-8 n: dqgnqjnnnnn
4-14 r: rdrfrrrrrrrrrvrrr
10-11 d: ddddddghtdfdhd
2-6 n: gngqzn
6-7 f: ffffdff
5-9 b: bbbbwbbbzb
7-9 n: knnnngnfnnn
8-14 b: gbnbsdbwcwdbvb
6-9 w: nttwjwbmw
3-13 c: gswwmvqdchfcgfrqcn
11-12 k: kzkvhkfrjxxjv
3-9 d: xdzkdgfdrx
6-13 q: qqqqcqqqqqqqqqq
7-9 b: bmbbbbbbb
8-16 p: hppgwpbmppcppppd
9-12 m: mwmmscmmdmpkmmm
3-6 n: nnnnnnn
3-16 f: lfqfhfffdfffszfkh
12-13 f: ffffffffffffmftffxf
1-5 k: kkkqk
3-6 f: ffsgft
2-9 z: ktzvzztzzrzzfnk
4-7 p: pppppgp
5-9 j: jgtjkvjhtjmvtc
4-5 g: ngngw
5-6 f: ffffcgf
3-11 k: xkkkcvwkkck
7-11 c: qcccpchcccc
3-17 h: hhnhhhhhhhhhhhhhhh
4-5 x: bxjxj
18-19 v: vbvcvvvcwvvvvvvvvtn
12-14 d: dddddddddddwdxddd
6-10 b: bbbbbbbbbbbb
1-4 f: pfjf
1-8 b: bbbbbbltbbbbbb
14-15 d: dzddkfqcdxwfdnd
8-10 t: tvxwlxltjt
7-9 l: lxklrwlhl
3-6 c: cclccdc
15-17 w: wdwwwwwwwwxwwwqwfw
1-4 h: ngkhh
3-4 j: jjjj
4-9 h: nphhzhhmhgb
5-10 v: tsxzvvdvmvvsvp
1-11 r: frjgrqrrrrkrrmrl
10-12 p: zlkppppppmxppphsgd
5-8 p: stmggpsmx
3-5 r: rrrrrrrrrrrrrr
2-3 t: ttgt
6-11 m: mmjmsmhmmsmdmfmvm
6-8 s: pnkbhsfsfgsr
7-13 t: gchcvtttwgkmlbw
8-11 l: lllllllrllrlh
5-7 d: djvddzdd
3-4 z: zzzzkk
5-11 s: wsbdskxssjtqcs
2-3 w: wwwszj
1-4 m: mmvm
3-9 x: bkzkrvkjfbtxn
5-6 z: zzzzzwz
1-4 v: vvvrvv
1-4 d: zdxd
6-8 k: klfnzkrswq
1-6 p: pkjpcpntjzvp
14-16 p: pdpppqmpmppqppppgp
9-10 w: wwvglrwkrbwwwkwzww
3-6 v: vfdvvcsvv
9-13 z: zzzzzzbzzgfzzzzzczz
4-5 n: nnnqnn
4-13 m: jmbmmmmmmmnmmmvmm
2-10 r: rlrcrrdnkrkrsqr
9-14 r: rzrgrrrrhrrbrsrr
9-11 f: ffpffzfvffzf
10-11 j: jzjjjjzfpjjjrsgjjt
3-4 b: bbbnbb
4-6 z: zgzwzqhq
10-11 j: jjxjxhjjjwj
4-5 b: bbbbb
4-5 d: dbzhw
2-8 r: rrrlrrrrgrgfrwdf
1-5 q: qmtrq
9-13 j: jkjjjjjjjzjjt
3-7 j: rjjjjjjjm
5-9 z: zzzzdzzznzz
2-13 t: tjtttttttfttsttt
12-13 d: kbddmmkmcwdkddw
3-4 q: qqql
5-6 j: jjjjsqjj
1-2 b: bbgwqt
3-11 t: tftjtttttttttt
9-12 h: hjxhhhhhqhhzz
1-2 m: ncmmmml
1-3 x: qxxs
1-7 t: dtstrnxttt
11-13 q: qqdqqpjjqktqbqnqqq
2-5 p: pppppp
2-4 n: njdjzpnghzbgvnngqn
11-12 g: lpfwcvsqgmggfrjmdvs
1-7 n: hrwhnvrmm
12-13 s: hssdssscsgsksjssss
3-8 x: csxgdxkxxptmlw
9-11 q: qqqqqqnqkqmqqqqq
3-4 g: wzkf
7-8 t: cktttttt
4-12 c: fgdjrccpmhcccwcgfm
6-8 p: jppppppt
1-4 p: pppppr
1-7 n: nnrrrtndwn
1-6 l: rldlkq
2-4 x: rglr
2-7 p: vpvmkgp
4-5 n: nnnnz
5-18 w: txgfflhvtdpdvwlwmmq
9-10 l: tlllllllddl
1-3 b: xpzbbbrbbr
3-5 n: npnpnn
10-14 q: nqqqqqqqqqqqqqqdqx
7-10 w: bdwwwwgwljxgv
7-11 k: kwknkkdlzkk
1-10 w: wsjbvzwslmwttq
15-18 b: bbbbbbbcbbbrbbbbbbb
6-8 j: jdjjnlfj
10-11 r: xrgrrrrrnvwrrfrr
11-15 x: xxxxxxxxxxxxxxjx
5-10 w: wfwwnwvngwlwwlw
2-4 k: kkkk
3-5 h: hjhhh
7-8 s: lqsssscjrss
10-12 t: tttsttttttttg
3-8 p: szpsqzqp
3-8 x: xxxxxxxxx
6-7 r: rrxrrdrr
1-2 b: zbbbbbbbbbbbbb
3-6 v: vxvkvv
4-5 w: wwwwwwdw
3-5 n: nnfnn
11-12 g: gggggggvggxgg
10-12 s: sssqssssssssns
3-7 h: hlmhhhhhhh
7-8 v: vsdcvkvvszzm
6-9 g: ggwnldgws
14-15 q: qqqqkqqqqqqqkwkq
8-9 l: bttjllqhnqjdvhsnk
10-11 s: sqsscsqsscts
10-14 h: hjhxhhhnhhxglkhvzl
3-6 r: krrnvr
12-17 z: zzsfzzzjzzzrzhzzgh
1-5 b: bdnmb
18-19 c: cccccccccccccccccckc
13-16 t: tttttttrtttcdttpt
5-6 c: ccczlxc
2-7 b: phbqtkkkdglk
4-6 x: tgrmqlxwgrgwxmkfr
2-7 p: xspljfg
4-9 b: bbbwbbbbmbbb
3-9 b: brbvbbxqb
13-14 c: cccpckqscbcchc
1-3 m: mmmm
1-2 v: bvvvvc
2-3 b: bbsbbbnbbb
1-2 f: gkfms
5-6 n: nnnnnq
4-5 c: kffccnrmn
1-6 b: slgwbm
2-3 x: mxcj
3-4 p: gpbqpfsp
5-8 s: szwszsss
5-6 g: zkgjggg
3-10 v: twmqbvvnvv
3-5 z: shlzs
1-6 r: wrrljrfntswb
2-7 j: jjjjjjjjjj
4-5 f: jfffqw
1-3 r: kwrrrrfwp
2-9 c: ccmcrthdqtk
13-15 w: wwwwwwwwwwwwrwwww
14-15 s: ssssssssssssssss
2-5 r: rhmrfmr
6-7 x: dwxgfpsbtvx
7-8 b: bbbbcbbb
1-5 l: slllcqlll
3-4 h: hhbr
3-6 k: kkkpkkk
2-5 s: nsssmsssbs
7-8 s: xtxtwtzspxsszmgjlpzx
2-4 r: jzqc
9-10 h: hhhhhhhbwh
8-13 g: xgzjgjgggggmgggzc
1-10 j: lrhzsjmfrzz
4-10 z: dkqdhhrszpcplmfqgg
7-9 x: xxxxxxwxxx
12-13 f: fffpfqcfbkdvsbtzwwf
5-8 g: ghsvggggzgggg
10-14 z: ctzzkszzzlzmzzzz
2-4 d: xfwdd
9-15 j: xjjdjcjhnjjjfjjj
1-2 h: hhhhhgwjhznh
9-13 d: kddddbdddxddjsdsdd
7-9 x: rxxxxdwxxxxnxkxcx
6-16 r: rlrtlkdftfgqpkrsljr
1-3 z: pzzz
5-6 h: krhbsh
8-9 x: mxqhpmqglxxwxqwxxxp
2-4 z: vmfj
12-15 s: sssfsssssksssst
3-5 f: fwhfb
10-12 j: jjjjjzwjjjjw
4-6 j: jjjjjjjjjjj
11-12 k: kkkkvfktkkkkkkwwzknk
5-8 m: mhhmbvmvms
10-14 r: rlwrdfzkhgrcrlz
5-6 h: hhhhfh
2-4 w: wwqhwww
1-5 x: nxxxwxx
11-16 h: xpshnhxbwclbhrhwsh
7-9 t: ttttflgtkh
10-20 n: bnknnnnnnlnnnnmnvncn
2-5 w: pwwhwkq
1-5 j: jhjjj
5-6 f: fzffzfwfr
3-6 s: sssssgs
9-10 w: wwwwwnwxbrww
5-6 z: xzzhzjzzzzhzhz
17-18 v: vvvvvvvvvvvvvvvtvbv
13-20 l: llllldllllllllllllll
8-14 k: kkkkkkkgkkkkkkkk
7-9 j: jjnjjjjjjj
7-14 j: tjbjljjrjjjjzjjjj
1-4 m: jcmmm
6-9 g: ggnggsghggg
2-16 v: pvvqdcrpzpsmppfvdftf
8-11 j: jjjjjjjjjvj
4-6 m: qbmmxmjpm
2-12 l: pllqdxmwfmmlmznqr
3-4 b: bsbhbbbbb
1-4 w: wwww
1-11 r: rrrrjrrrgmrr
3-8 t: tnrztcht
3-14 p: pjppkpplsphlpn
7-8 j: tdfcjdjbjjjvjj
10-11 n: nnnnnnmhnnnnrddrnn
1-7 p: tppgqppptqscprnp
3-4 c: cqcmcc
2-8 l: llllllrlll
9-12 j: dmcwsjjrvmzjp
4-8 h: hhhrhhhb
1-5 n: nnnnnn
5-6 s: srssss
2-8 n: nrbngnntnnn
1-13 f: bffmjfdfffffp
7-8 t: tqtttttt
3-4 x: xxhh
15-18 j: jjjjjjjjjjjjjjpjjk
7-9 v: vkvvmzvvv
5-7 j: xjjgkjknjjp
2-4 l: llslkh
10-11 m: mmmmmmmmmjwmmmwmm
5-6 j: pjjzjqbqv
5-11 n: nnnncnnnnnfnnnnnn
2-13 g: gdfrmlcszxcwj
9-16 b: bbbbbbwhpztbhdbzb
1-4 f: fffffc
1-3 f: fffkf
16-17 p: pppppppppppppppkt
6-10 h: wzcnzhvhml
1-9 f: ffffffffff
3-8 f: kffgggng
8-13 m: mmmmmmmmmmmmmm
12-19 k: zkzzlkkvpnllksklljr
1-4 j: jjmjjjjxjwj
4-5 h: phhhhzhhhmhhprh
11-12 p: ppppppppppvppp
13-16 j: hpgjjjwfhjgmdttl
2-4 w: wwjwhthzhvpmpfkw
9-10 k: kkxkkkkskkv
17-20 j: jjjjjjbjjjzjjjjjjjjj
1-3 v: cvvvb
5-8 s: zbnmbfgdp
10-11 x: xxxxgmdtxxtxxxbx
12-17 n: nmnnjcndnndcnncnnrnn
3-6 p: lmblxwpjvfgjps
9-12 s: ssssssssfsssw
9-10 g: ggggggwgkzgggg
5-12 m: pzmmmfxgvmtmlmq
2-7 p: ptppprn
9-10 c: bgqtkccxcqb
8-11 r: rdrrrrrhrrmr
7-9 w: wwqwwwfwwjwhgrw
5-7 r: rrrrrrh
2-10 s: rsflsvlwfs
3-7 b: bbqbbbb
11-12 m: mmjmmqmnmmmm
7-13 h: hhhhhhphhhnhghh
12-13 b: bbbbbbblbbbtk
5-13 h: ppgzjhhhlhhqx
14-19 q: qlbqmqqqjqqqqrqkjnq
3-19 f: pxmznsfdhzjqrdfjqrd
16-17 q: qqmdqrqqxcqfxfgjg
12-13 j: njjjzjghjjjjc
9-11 l: vmbsllkcshmrhklrl
1-2 c: tccccc
3-6 p: jspprpjxhn
5-8 x: xrxzxfwxxx
9-10 z: zdznzzzzzzzgzz
4-5 j: jjpjq
4-6 r: rcxscm
2-6 k: pkqjskrlfknnrqt
3-11 k: bqbskncdkfrphshvv
11-13 g: ggqgggggggggggg
6-14 f: fffdxmfffjfffmffff
19-20 z: zzzznzzzzzzzzzzzzzzz
5-8 j: jjjjjjjjjgjjjjjjjjj
2-4 k: pkbkqpsrgkcwc
8-12 b: dbbwtbwbqxvbwrbl
1-8 v: rvrvfcnlcwflcvlsv
4-5 f: hffhfkq
3-12 g: zggpngtnvzgd
4-8 t: ttttwrwt
12-13 x: xxxxxxxvxxxdnx
9-12 j: jrvjjjjjbjjp
1-13 b: zbhbbbbbbbbbvbb
1-2 w: wwwwwww
15-16 k: tfkxskmvqlkkmfkj
12-18 b: bdpxktjwpxhsbgmrfb
8-10 v: vvvvvvtzvzvv
18-19 g: ggglgggggggggggggggg
4-8 s: pnzsjvwsmxwgrjmsm
14-17 p: pppppxppppppppprpkp
9-17 n: nvlnqnwnnnztfcgnpdn
3-5 l: mlqflfl
7-11 z: dzzzzdmnzznzvzzz
14-16 r: xrrsvrhhrlnjjrvrr
12-14 z: vnwzqsvvtdnpvvdrhgz
1-4 h: mhhhh
1-5 m: pmmmmmm
6-11 j: jmkljhjjvjmfmjpj
2-4 f: xhtkdf
5-14 x: frqqxljjwsxndx
"""
| 20.596542 | 67 | 0.752157 |
c117a49a617eb6a2f668db118acef871854d3e87 | 6,761 | //
// CollectionViewController.swift
// CustomTransition
//
// Created by naru on 2016/07/27.
// Copyright © 2016年 naru. All rights reserved.
//
import UIKit
class PresentingViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationItem.titleView = self.titleLabel
self.navigationItem.leftBarButtonItem = self.closeItem
self.view.addSubview(self.collectionView)
}
// MARK: Elements
let transitionController: TransitionController = TransitionController()
var selectedIndexPath: IndexPath = IndexPath(item: 0, section: 0)
lazy var collectionView: UICollectionView = {
let lendth: CGFloat = (UIScreen.main.bounds.size.width - 4.0)/3.0
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: lendth, height: lendth)
layout.minimumLineSpacing = 1.0
layout.minimumInteritemSpacing = 1.0
layout.scrollDirection = .vertical
let collectionView: UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(PresentingCollectionViewCell.self, forCellWithReuseIdentifier: "presenting_cell")
collectionView.backgroundColor = UIColor.white
collectionView.contentInset = UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0)
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
lazy var titleLabel: UILabel = {
let font: UIFont = UIFont(name: "Futura-Medium", size: 16.0)!
let label: UILabel = UILabel()
label.font = font
label.text = "All"
label.sizeToFit()
return label
}()
lazy var closeItem: UIBarButtonItem = {
let item: UIBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(onCloseButtonClicked(sender:)))
return item
}()
// MARK: CollectionView Delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedIndexPath = indexPath
let presentedViewController: PresentedViewController = PresentedViewController()
presentedViewController.transitionController = self.transitionController
transitionController.userInfo = ["destinationIndexPath": indexPath as NSIndexPath, "initialIndexPath": indexPath as NSIndexPath]
// This example will push view controller if presenting view controller has navigation controller.
// Otherwise, present another view controller
if let navigationController = self.navigationController {
// Set transitionController as a navigation controller delegate and push.
navigationController.delegate = transitionController
transitionController.push(viewController: presentedViewController, on: self, attached: presentedViewController)
} else {
// Set transitionController as a transition delegate and present.
presentedViewController.transitioningDelegate = transitionController
transitionController.present(viewController: presentedViewController, on: self, attached: presentedViewController, completion: nil)
}
collectionView.deselectItem(at: indexPath, animated: true)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let _ = self.navigationController { return }
if scrollView.contentOffset.y <= -100.0 {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: CollectionView Data Source
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 50
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: PresentingCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "presenting_cell", for: indexPath) as! PresentingCollectionViewCell
cell.contentView.backgroundColor = UIColor.lightGray
cell.content.image = UIImage(named: "image\(indexPath.item%4 + 1)")
return cell
}
// MARK: Actions
@objc func onCloseButtonClicked(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
}
extension PresentingViewController: View2ViewTransitionPresenting {
func initialFrame(_ userInfo: [String: Any]?, isPresenting: Bool) -> CGRect {
guard let indexPath: IndexPath = userInfo?["initialIndexPath"] as? IndexPath, let attributes: UICollectionViewLayoutAttributes = self.collectionView.layoutAttributesForItem(at: indexPath) else {
return CGRect.zero
}
return self.collectionView.convert(attributes.frame, to: self.collectionView.superview)
}
func initialView(_ userInfo: [String: Any]?, isPresenting: Bool) -> UIView {
let indexPath: IndexPath = userInfo!["initialIndexPath"] as! IndexPath
let cell: UICollectionViewCell = self.collectionView.cellForItem(at: indexPath)!
return cell.contentView
}
func prepareInitialView(_ userInfo: [String : Any]?, isPresenting: Bool) {
let indexPath: IndexPath = userInfo!["initialIndexPath"] as! IndexPath
if !isPresenting && !self.collectionView.indexPathsForVisibleItems.contains(indexPath) {
self.collectionView.reloadData()
self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
self.collectionView.layoutIfNeeded()
}
}
}
public class PresentingCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(self.content)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public lazy var content: UIImageView = {
let view: UIImageView = UIImageView(frame: self.contentView.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.backgroundColor = UIColor.gray
view.clipsToBounds = true
view.contentMode = .scaleAspectFill
return view
}()
}
| 39.30814 | 202 | 0.680964 |
fb50409bba7ad556d3972402fa24669c0b327ca1 | 823 | //
// DealCell.swift
// Yelp
//
// Created by Utkarsh Sengar on 4/8/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol DealCellDelegate {
@objc optional func dealCell(dealCell: DealCell, didChangeValue value: Bool)
}
class DealCell: UITableViewCell {
@IBOutlet weak var dealSwitch: UISwitch!
weak var delegate: DealCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
dealSwitch.addTarget(self, action: #selector(DealCell.switchValueChanged), for: UIControlEvents.valueChanged)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func switchValueChanged() {
delegate?.dealCell!(dealCell: self, didChangeValue: dealSwitch.isOn)
}
}
| 24.939394 | 117 | 0.703524 |
16e5f96e8cce21a66fb12c7ff1ae532fde50f982 | 676 | //
// CollectionGameCell.swift
// DYZB
//
// Created by 刘金萌 on 2019/7/25.
// Copyright © 2019 刘金萌. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionGameCell: UICollectionViewCell {
// MARK:- 控件属性
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
// MARK:- 定义模型属性
var baseGame: BaseGameModel?{
didSet{
titleLabel.text = baseGame?.game_name
guard let iconURL = URL(string: baseGame?.game_icon ?? "home_header_normal") else { return }
iconImageView.kf.setImage(with: iconURL,placeholder: UIImage(named: "home_more_btn"))
}
}
}
| 24.142857 | 104 | 0.650888 |
9cd045934e1ff3ea38490dbd6060be856b7ae6ed | 1,053 | //
// ManagedCache.swift
// FeedStoreChallenge
//
// Created by Juan Landy on 27/4/21.
// Copyright © 2021 Essential Developer. All rights reserved.
//
import Foundation
import CoreData
@objc(ManagedCache)
final class ManagedCache: NSManagedObject {
@NSManaged var timestamp: Date
@NSManaged var feed: NSOrderedSet
static func newUniqueInstance(in context: NSManagedObjectContext) throws -> ManagedCache {
try find(in: context).map(context.delete)
return ManagedCache(context: context)
}
static func find(in context: NSManagedObjectContext) throws -> ManagedCache? {
let request = NSFetchRequest<ManagedCache>(entityName: entity().name!)
request.returnsObjectsAsFaults = false
return try context.fetch(request).first
}
static func delete(context: NSManagedObjectContext) throws {
try find(in: context).map(context.delete)
}
var localFeed: [LocalFeedImage] {
return feed.compactMap { ($0 as? ManagedFeedImage) }.map { LocalFeedImage(id: $0.id, description: $0.imageDescription, location: $0.location, url: $0.url) }
}
}
| 29.25 | 158 | 0.752137 |
ff9a9cd8a2056a3de58c8b2abb6d939ff23d670c | 1,588 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol ___VARIABLE_sceneName___DisplayLogic: class {
}
class ___VARIABLE_sceneName___ViewController: UICollectionViewController, ___VARIABLE_sceneName___DisplayLogic {
var interactor: ___VARIABLE_sceneName___BusinessLogic?
var router: (NSObjectProtocol & ___VARIABLE_sceneName___RoutingLogic & ___VARIABLE_sceneName___DataPassing)?
// MARK: Object lifecycle
init(configurator: ___VARIABLE_sceneName___Configurator = ___VARIABLE_sceneName___Configurator()) {
super.init(nibName: nil, bundle: nil)
configurator.configure(viewController: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
___VARIABLE_sceneName___Configurator().configure(viewController: self)
}
// MARK: Setup
// MARK: Routing
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let scene = segue.identifier {
let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
if let router = router, router.responds(to: selector) {
router.perform(selector, with: segue)
}
}
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Do something
//@IBOutlet weak var nameTextField: UITextField!
}
| 27.859649 | 112 | 0.745592 |
fccd47d855cf03d7688e1d58314f4e8ff4a10349 | 673 | import XCTest
@testable import Notes
class NotesTests47: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func NotesUnitTest() {
XCTAssertEqual("/v2/top-picks/rate", "/v2/top-picks/rate")
XCTAssertEqual("super", "super")
XCTAssertEqual("123", "123")
XCTAssertEqual("1", "1")
if false {
XCTAssertEqual("-420", "-420")
} else {
XCTAssertEqual("-480", "-480")
}
XCTAssertEqual("xxx", "xxx")
XCTAssertEqual("xxx", "xxx")
XCTAssertNotNil("xxx")
}
}
| 24.925926 | 67 | 0.514116 |
1c92b9266cf60c6c567a789ba5f89d87091233f7 | 5,720 | //
// MenuOptionsViewController.swift
// edX
//
// Created by Tang, Jeff on 5/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol MenuOptionsViewControllerDelegate : class {
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int)
func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index: Int) -> Bool
}
//TODO: Remove this (duplicate) when swift compiler recognizes this extension from DiscussionTopicCell.swift
extension UITableViewCell {
fileprivate func indentationOffsetForDepth(itemDepth depth : UInt) -> CGFloat {
return CGFloat(depth + 1) * StandardHorizontalMargin
}
}
public class MenuOptionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
class MenuOptionTableViewCell : UITableViewCell {
static let identifier = "MenuOptionTableViewCellIdentifier"
fileprivate let optionLabel = UILabel()
var depth : UInt = 0 {
didSet {
optionLabel.snp_updateConstraints { (make) -> Void in
make.leading.equalTo(contentView).offset(self.indentationOffsetForDepth(itemDepth: depth))
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(optionLabel)
optionLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(contentView)
make.leading.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public struct MenuOption {
let depth : UInt
let label : String
}
static let menuItemHeight: CGFloat = 30.0
private var tableView: UITableView?
var options: [MenuOption] = []
var selectedOptionIndex: Int?
weak var delegate : MenuOptionsViewControllerDelegate?
private var titleTextStyle : OEXTextStyle {
let style = OEXTextStyle(weight: .normal, size: .small, color: OEXStyles.shared().neutralDark())
return style
}
public override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView?.register(MenuOptionTableViewCell.classForCoder(), forCellReuseIdentifier: MenuOptionTableViewCell.identifier)
tableView?.dataSource = self
tableView?.delegate = self
tableView?.layer.borderColor = OEXStyles.shared().neutralLight().cgColor
tableView?.layer.borderWidth = 1.0
tableView?.applyStandardSeparatorInsets()
if #available(iOS 9.0, *) {
tableView?.cellLayoutMarginsFollowReadableWidth = false
}
view.addSubview(tableView!)
setConstraints()
}
private func setConstraints() {
tableView?.snp_updateConstraints { (make) -> Void in
make.edges.equalTo(view)
make.height.equalTo(view.snp_height).offset(-2)
}
}
// MARK: - Table view data source
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.applyStandardSeparatorInsets()
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MenuOptionTableViewCell.identifier, for: indexPath as IndexPath) as! MenuOptionTableViewCell
// Configure the cell...
let style : OEXTextStyle
let option = options[indexPath.row]
cell.selectionStyle = option.depth == 0 ? .none : .default
if let optionIndex = selectedOptionIndex, indexPath.row == optionIndex {
cell.backgroundColor = OEXStyles.shared().neutralLight()
style = titleTextStyle.withColor(OEXStyles.shared().neutralBlack())
}
else {
cell.backgroundColor = OEXStyles.shared().neutralWhite()
style = titleTextStyle
}
cell.depth = option.depth
cell.optionLabel.attributedText = style.attributedString(withText: option.label)
cell.applyStandardSeparatorInsets()
if delegate?.menuOptionsController(controller: self, canSelectOptionAtIndex:indexPath.row) ?? false {
cell.accessibilityHint = Strings.accessibilitySelectValueHint
}
else {
cell.accessibilityHint = nil
}
return cell
}
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if delegate?.menuOptionsController(controller: self, canSelectOptionAtIndex:indexPath.row) ?? false {
return indexPath
}
else {
return nil
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.menuOptionsController(controller: self, selectedOptionAtIndex: indexPath.row)
}
// MARK: - Table view delegate
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 30
}
}
| 35.092025 | 157 | 0.652622 |
14ae7b6b1a0465a18ccdadfa7cfd70880f966f81 | 453 | //
// SuccessResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct SuccessResponse: Codable {
public var message: String?
public var result: Bool?
public var payload: AnyCodable?
public init(message: String?, result: Bool?, payload: AnyCodable?) {
self.message = message
self.result = result
self.payload = payload
}
}
| 16.777778 | 72 | 0.666667 |
62f1d6cfc3def4ee9f12c87e13002410de2b0df2 | 971 | //
// GoodBooksTests.swift
// GoodBooksTests
//
// Created by J1aDong on 2017/1/24.
// Copyright © 2017年 J1aDong. All rights reserved.
//
import XCTest
@testable import GoodBooks
class GoodBooksTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.243243 | 111 | 0.634398 |
1c63ee2109e874e54f976c69cf2632834706229b | 899 | //
// PokemonTests.swift
// PokemonTests
//
// Created by Abraao Nascimento on 18/10/21.
//
import XCTest
@testable import Pokemon
class PokemonTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.441176 | 111 | 0.664071 |
62da790eeb4c972b8a60169fbe871cdc5db647c2 | 1,311 | open class Cities {
var x: Int
public init(x: Int) { self.x = x }
public init!(y: Int) { self.x = y }
open func mooloolaba(x: Cities, y: Cities?) {}
open func toowoomba(x: [Cities], y: [Cities]?) {}
open func mareeba(x: [String : Cities?], y: [String : Cities]?) {}
open func yandina(x: [[String : Cities]]!) {}
open func buderim() -> Cities? { return Cities(x: 1) }
open func noosa() -> [[String : Cities]?] { return [] }
open func maroochy(x: Int?, y: Int?) {}
public struct CityKind {
static public let Town = 1
}
}
public protocol ExtraCities {
func coolum(x: [String : [Int : [(((String))?)]]])
func blibli(x: (String?, String) -> String!)
func currimundi(x: (Int, (Int, Int))!)
}
public protocol MoreCities {
func setZooLocation(x: Int, y: Int, z: Int)
}
public func setCityProperty1(_ c : Cities, _ p : Int) {}
public func globalCityFunc() {}
public func setCityProperty2(_ c : Cities, _ p : Int, _ q: Int) {}
public func globalCityFunc2(_ c : Cities) {}
public func globalCityFunc3(_ c : Cities, _ p : Int) -> Int { return 0 }
public func globalCityFunc4(_ c : Cities, _ p : Int, _ q: Int) -> Int { return 0 }
public func globalCityFunc5() -> Int { return 0 }
public func globalCityPointerTaker(_ c : UnsafePointer<Cities>, _ p : Int, _ q: Int) -> Int { return 0 } | 38.558824 | 104 | 0.633867 |
4bd1e5fe19b3b06eb4a515bc3c945039fff18aff | 2,158 | //
// AppDelegate.swift
// VirtualTourist
//
// Created by Ibrahim.Moustafa on 5/23/16.
// Copyright © 2016 Ibrahim.Moustafa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.914894 | 285 | 0.755329 |
e5d16fd86f8e31adb3b01c549a25fce4d31c0004 | 19,213 | //
// MZDownloadManager.swift
// MZDownloadManager
//
// Created by Muhammad Zeeshan on 19/04/2016.
// Copyright © 2016 ideamakerz. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc public protocol MZDownloadManagerDelegate {
/**A delegate method called each time whenever any download task's progress is updated
*/
func downloadRequestDidUpdateProgress(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called when interrupted tasks are repopulated
*/
func downloadRequestDidPopulatedInterruptedTasks(_ downloadModel: [MZDownloadModel])
/**A delegate method called each time whenever new download task is start downloading
*/
@objc optional func downloadRequestStarted(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever running download task is paused. If task is already paused the action will be ignored
*/
@objc optional func downloadRequestDidPaused(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever any download task is resumed. If task is already downloading the action will be ignored
*/
@objc optional func downloadRequestDidResumed(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever any download task is resumed. If task is already downloading the action will be ignored
*/
@objc optional func downloadRequestDidRetry(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever any download task is cancelled by the user
*/
@objc optional func downloadRequestCanceled(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever any download task is finished successfully
*/
@objc optional func downloadRequestFinished(_ downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever any download task is failed due to any reason
*/
@objc optional func downloadRequestDidFailedWithError(_ error: NSError, downloadModel: MZDownloadModel, index: Int)
/**A delegate method called each time whenever specified destination does not exists. It will be called on the session queue. It provides the opportunity to handle error appropriately
*/
@objc optional func downloadRequestDestinationDoestNotExists(_ downloadModel: MZDownloadModel, index: Int, location: URL)
}
open class MZDownloadManager: NSObject {
fileprivate var sessionManager: Foundation.URLSession!
open var downloadingArray: [MZDownloadModel] = []
fileprivate var delegate: MZDownloadManagerDelegate?
fileprivate var backgroundSessionCompletionHandler: (() -> Void)?
fileprivate let TaskDescFileNameIndex = 0
fileprivate let TaskDescFileURLIndex = 1
fileprivate let TaskDescFileDestinationIndex = 2
public convenience init(session sessionIdentifer: String, delegate: MZDownloadManagerDelegate) {
self.init()
self.delegate = delegate
self.sessionManager = self.backgroundSession(sessionIdentifer)
self.populateOtherDownloadTasks()
}
public convenience init(session sessionIdentifer: String, delegate: MZDownloadManagerDelegate, completion: (() -> Void)?) {
self.init(session: sessionIdentifer, delegate: delegate)
self.backgroundSessionCompletionHandler = completion
}
fileprivate func backgroundSession(_ sessionIdentifer: String) -> Foundation.URLSession {
struct sessionStruct {
static var onceToken : Int = 0;
static var session : Foundation.URLSession? = nil
}
let sessionConfiguration : URLSessionConfiguration
sessionConfiguration = URLSessionConfiguration.background(withIdentifier: sessionIdentifer)
sessionStruct.session = Foundation.URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
return sessionStruct.session!
}
}
// MARK: Private Helper functions
extension MZDownloadManager {
fileprivate func downloadTasks() -> NSArray {
return self.tasksForKeyPath("downloadTasks")
}
fileprivate func tasksForKeyPath(_ keyPath: NSString) -> NSArray {
var tasks: NSArray = NSArray()
let semaphore : DispatchSemaphore = DispatchSemaphore(value: 0)
sessionManager.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) -> Void in
if keyPath == "downloadTasks" {
if let pendingTasks: NSArray = downloadTasks as NSArray? {
tasks = pendingTasks
debugPrint("pending tasks \(tasks)")
}
}
semaphore.signal()
}
let _ = semaphore.wait(timeout: DispatchTime.distantFuture)
return tasks
}
fileprivate func populateOtherDownloadTasks() {
let downloadTasks = self.downloadTasks()
for object in downloadTasks {
let downloadTask = object as! URLSessionDownloadTask
let taskDescComponents: [String] = downloadTask.taskDescription!.components(separatedBy: ",")
let fileName = taskDescComponents[TaskDescFileNameIndex]
let fileURL = taskDescComponents[TaskDescFileURLIndex]
let destinationPath = taskDescComponents[TaskDescFileDestinationIndex]
let downloadModel = MZDownloadModel.init(fileName: fileName, fileURL: fileURL, destinationPath: destinationPath)
downloadModel.task = downloadTask
downloadModel.startTime = Date()
if downloadTask.state == .running {
downloadModel.status = TaskStatus.downloading.description()
downloadingArray.append(downloadModel)
} else if(downloadTask.state == .suspended) {
downloadModel.status = TaskStatus.paused.description()
downloadingArray.append(downloadModel)
} else {
downloadModel.status = TaskStatus.failed.description()
}
}
}
fileprivate func isValidResumeData(_ resumeData: Data?) -> Bool {
guard resumeData != nil || resumeData?.count > 0 else {
return false
}
do {
var resumeDictionary : AnyObject!
resumeDictionary = try PropertyListSerialization.propertyList(from: resumeData!, options: PropertyListSerialization.MutabilityOptions(), format: nil) as AnyObject!
var localFilePath = (resumeDictionary?["NSURLSessionResumeInfoLocalPath"] as? String)
if localFilePath == nil || localFilePath?.characters.count < 1 {
localFilePath = (NSTemporaryDirectory() as String) + (resumeDictionary["NSURLSessionResumeInfoTempFileName"] as! String)
}
let fileManager : FileManager! = FileManager.default
debugPrint("resume data file exists: \(fileManager.fileExists(atPath: localFilePath! as String))")
return fileManager.fileExists(atPath: localFilePath! as String)
} catch let error as NSError {
debugPrint("resume data is nil: \(error)")
return false
}
}
}
extension MZDownloadManager: URLSessionDelegate {
func URLSession(_ session: Foundation.URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
for (index, downloadModel) in self.downloadingArray.enumerated() {
if downloadTask.isEqual(downloadModel.task) {
DispatchQueue.main.async(execute: { () -> Void in
let receivedBytesCount = Double(downloadTask.countOfBytesReceived)
let totalBytesCount = Double(downloadTask.countOfBytesExpectedToReceive)
let progress = Float(receivedBytesCount / totalBytesCount)
let taskStartedDate = downloadModel.startTime!
let timeInterval = taskStartedDate.timeIntervalSinceNow
let downloadTime = TimeInterval(-1 * timeInterval)
let speed = Float(totalBytesWritten) / Float(downloadTime)
let remainingContentLength = totalBytesExpectedToWrite - totalBytesWritten
let remainingTime = remainingContentLength / Int64(speed)
let hours = Int(remainingTime) / 3600
let minutes = (Int(remainingTime) - hours * 3600) / 60
let seconds = Int(remainingTime) - hours * 3600 - minutes * 60
let totalFileSize = MZUtility.calculateFileSizeInUnit(totalBytesExpectedToWrite)
let totalFileSizeUnit = MZUtility.calculateUnit(totalBytesExpectedToWrite)
let downloadedFileSize = MZUtility.calculateFileSizeInUnit(totalBytesWritten)
let downloadedSizeUnit = MZUtility.calculateUnit(totalBytesWritten)
let speedSize = MZUtility.calculateFileSizeInUnit(Int64(speed))
let speedUnit = MZUtility.calculateUnit(Int64(speed))
downloadModel.remainingTime = (hours, minutes, seconds)
downloadModel.file = (totalFileSize, totalFileSizeUnit as String)
downloadModel.downloadedFile = (downloadedFileSize, downloadedSizeUnit as String)
downloadModel.speed = (speedSize, speedUnit as String)
downloadModel.progress = progress
self.downloadingArray[index] = downloadModel
self.delegate?.downloadRequestDidUpdateProgress(downloadModel, index: index)
})
break
}
}
}
func URLSession(_ session: Foundation.URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingToURL location: URL) {
for (index, downloadModel) in downloadingArray.enumerated() {
if downloadTask.isEqual(downloadModel.task) {
let fileName = downloadModel.fileName as NSString
let basePath = downloadModel.destinationPath == "" ? MZUtility.baseFilePath : downloadModel.destinationPath
let destinationPath = (basePath as NSString).appendingPathComponent(fileName as String)
let fileManager : FileManager = FileManager.default
//If all set just move downloaded file to the destination
if fileManager.fileExists(atPath: basePath) {
let fileURL = URL(fileURLWithPath: destinationPath as String)
debugPrint("directory path = \(destinationPath)")
do {
try fileManager.moveItem(at: location, to: fileURL)
} catch let error as NSError {
debugPrint("Error while moving downloaded file to destination path:\(error)")
DispatchQueue.main.async(execute: { () -> Void in
self.delegate?.downloadRequestDidFailedWithError?(error, downloadModel: downloadModel, index: index)
})
}
} else {
//Opportunity to handle the folder doesnot exists error appropriately.
//Move downloaded file to destination
//Delegate will be called on the session queue
//Otherwise blindly give error Destination folder does not exists
if let _ = self.delegate?.downloadRequestDestinationDoestNotExists {
self.delegate?.downloadRequestDestinationDoestNotExists?(downloadModel, index: index, location: location)
} else {
let error = NSError(domain: "FolderDoesNotExist", code: 404, userInfo: [NSLocalizedDescriptionKey : "Destination folder does not exists"])
self.delegate?.downloadRequestDidFailedWithError?(error, downloadModel: downloadModel, index: index)
}
}
break
}
}
}
func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
debugPrint("task id: \(task.taskIdentifier)")
/***** Any interrupted tasks due to any reason will be populated in failed state after init *****/
if (error?.userInfo[NSURLErrorBackgroundTaskCancelledReasonKey] as? NSNumber)?.intValue == NSURLErrorCancelledReasonUserForceQuitApplication || (error?.userInfo[NSURLErrorBackgroundTaskCancelledReasonKey] as? NSNumber)?.intValue == NSURLErrorCancelledReasonBackgroundUpdatesDisabled {
let downloadTask = task as! URLSessionDownloadTask
let taskDescComponents: [String] = downloadTask.taskDescription!.components(separatedBy: ",")
let fileName = taskDescComponents[TaskDescFileNameIndex]
let fileURL = taskDescComponents[TaskDescFileURLIndex]
let destinationPath = taskDescComponents[TaskDescFileDestinationIndex]
let downloadModel = MZDownloadModel.init(fileName: fileName, fileURL: fileURL, destinationPath: destinationPath)
downloadModel.status = TaskStatus.failed.description()
downloadModel.task = downloadTask
let resumeData = error?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
DispatchQueue.main.async(execute: { () -> Void in
var newTask = downloadTask
if self.isValidResumeData(resumeData) == true {
newTask = self.sessionManager.downloadTask(withResumeData: resumeData!)
} else {
newTask = self.sessionManager.downloadTask(with: URL(string: fileURL as String)!)
}
newTask.taskDescription = downloadTask.taskDescription
downloadModel.task = newTask
self.downloadingArray.append(downloadModel)
self.delegate?.downloadRequestDidPopulatedInterruptedTasks(self.downloadingArray)
})
} else {
for(index, object) in self.downloadingArray.enumerated() {
let downloadModel = object
if task.isEqual(downloadModel.task) {
if error?.code == NSURLErrorCancelled || error == nil {
DispatchQueue.main.async(execute: { () -> Void in
self.downloadingArray.remove(at: index)
if error == nil {
self.delegate?.downloadRequestFinished?(downloadModel, index: index)
} else {
self.delegate?.downloadRequestCanceled?(downloadModel, index: index)
}
})
} else {
let resumeData = error?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
DispatchQueue.main.async(execute: { () -> Void in
var newTask = task
if self.isValidResumeData(resumeData) == true {
newTask = self.sessionManager.downloadTask(withResumeData: resumeData!)
} else {
newTask = self.sessionManager.downloadTask(with: URL(string: downloadModel.fileURL)!)
}
newTask.taskDescription = task.taskDescription
downloadModel.status = TaskStatus.failed.description()
downloadModel.task = newTask as? URLSessionDownloadTask
self.downloadingArray[index] = downloadModel
if let error = error {
self.delegate?.downloadRequestDidFailedWithError?(error, downloadModel: downloadModel, index: index)
} else {
let error: NSError = NSError(domain: "MZDownloadManagerDomain", code: 1000, userInfo: [NSLocalizedDescriptionKey : "Unknown error occurred"])
self.delegate?.downloadRequestDidFailedWithError?(error, downloadModel: downloadModel, index: index)
}
})
}
break;
}
}
}
}
public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let backgroundCompletion = self.backgroundSessionCompletionHandler {
DispatchQueue.main.async(execute: {
backgroundCompletion()
})
}
debugPrint("All tasks are finished")
}
}
//MARK: Public Helper Functions
extension MZDownloadManager {
public func addDownloadTask(_ fileName: String, fileURL: String, destinationPath: String) {
let url = URL(string: fileURL as String)!
let request = URLRequest(url: url)
let downloadTask = sessionManager.downloadTask(with: request)
downloadTask.taskDescription = [fileName, fileURL, destinationPath].joined(separator: ",")
downloadTask.resume()
debugPrint("session manager:\(sessionManager) url:\(url) request:\(request)")
let downloadModel = MZDownloadModel.init(fileName: fileName, fileURL: fileURL, destinationPath: destinationPath)
downloadModel.startTime = Date()
downloadModel.status = TaskStatus.downloading.description()
downloadModel.task = downloadTask
downloadingArray.append(downloadModel)
delegate?.downloadRequestStarted?(downloadModel, index: downloadingArray.count - 1)
}
public func addDownloadTask(_ fileName: String, fileURL: String) {
addDownloadTask(fileName, fileURL: fileURL, destinationPath: "")
}
public func pauseDownloadTaskAtIndex(_ index: Int) {
let downloadModel = downloadingArray[index]
guard downloadModel.status != TaskStatus.paused.description() else {
return
}
let downloadTask = downloadModel.task
downloadTask!.suspend()
downloadModel.status = TaskStatus.paused.description()
downloadModel.startTime = Date()
downloadingArray[index] = downloadModel
delegate?.downloadRequestDidPaused?(downloadModel, index: index)
}
public func resumeDownloadTaskAtIndex(_ index: Int) {
let downloadModel = downloadingArray[index]
guard downloadModel.status != TaskStatus.downloading.description() else {
return
}
let downloadTask = downloadModel.task
downloadTask!.resume()
downloadModel.status = TaskStatus.downloading.description()
downloadingArray[index] = downloadModel
delegate?.downloadRequestDidResumed?(downloadModel, index: index)
}
public func retryDownloadTaskAtIndex(_ index: Int) {
let downloadModel = downloadingArray[index]
guard downloadModel.status != TaskStatus.downloading.description() else {
return
}
let downloadTask = downloadModel.task
downloadTask!.resume()
downloadModel.status = TaskStatus.downloading.description()
downloadModel.startTime = Date()
downloadModel.task = downloadTask
downloadingArray[index] = downloadModel
}
public func cancelTaskAtIndex(_ index: Int) {
let downloadInfo = downloadingArray[index]
let downloadTask = downloadInfo.task
downloadTask!.cancel()
}
public func presentNotificationForDownload(_ notifAction: String, notifBody: String) {
let application = UIApplication.shared
let applicationState = application.applicationState
if applicationState == UIApplicationState.background {
let localNotification = UILocalNotification()
localNotification.alertBody = notifBody
localNotification.alertAction = notifAction
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber += 1
application.presentLocalNotificationNow(localNotification)
}
}
}
| 41.053419 | 288 | 0.696039 |
287ca04f951bcc11d849dce7a365b74f702874b7 | 4,615 | // RUN: %target-typecheck-verify-swift -swift-version 4
// SR-1661: Dollar was accidentally allowed as an identifier in Swift 3.
// SE-0144: Reject this behavior in the future.
func dollarVar() {
var $ : Int = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
$ += 1 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarLet() {
let $ = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarClass() {
class $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarEnum() {
enum $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
}
func dollarStruct() {
struct $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
}
func dollarFunc() {
func $($ dollarParam: Int) {}
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
$($: 24)
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{5-6=`$`}}
}
func escapedDollarVar() {
var `$` : Int = 42 // no error
`$` += 1
print(`$`)
}
func escapedDollarLet() {
let `$` = 42 // no error
print(`$`)
}
func escapedDollarClass() {
class `$` {} // no error
}
func escapedDollarEnum() {
enum `$` {} // no error
}
func escapedDollarStruct() {
struct `$` {} // no error
}
func escapedDollarFunc() {
func `$`(`$`: Int) {} // no error
`$`(`$`: 25) // no error
}
func escapedDollarAnd() {
// FIXME: Bad diagnostics.
`$0` = 1 // expected-error {{expected expression}}
`$$` = 2
`$abc` = 3
}
// Test that we disallow user-defined $-prefixed identifiers. However, the error
// should not be emitted on $-prefixed identifiers that are not considered
// declarations.
func $declareWithDollar() { // expected-error{{cannot declare entity named '$declareWithDollar'}}
var $foo: Int { // expected-error{{cannot declare entity named '$foo'}}
get { 0 }
set($value) {} // expected-error{{cannot declare entity named '$value'}}
}
func $bar() { } // expected-error{{cannot declare entity named '$bar'}}
func wibble(
$a: Int, // expected-error{{cannot declare entity named '$a'}}
$b c: Int) { } // expected-error{{cannot declare entity named '$b'}}
let _: (Int) -> Int = {
[$capture = 0] // expected-error{{cannot declare entity named '$capture'}}
$a in // expected-error{{cannot declare entity named '$a'}}
$capture
}
let ($a: _, _) = (0, 0) // expected-error{{cannot declare entity named '$a'}}
$label: if true { // expected-error{{cannot declare entity named '$label'}}
break $label
}
switch 0 {
@$dollar case _: // expected-error {{unknown attribute '$dollar'}}
break
}
if #available($Dummy 9999, *) {} // expected-warning {{unrecognized platform name '$Dummy'}}
@_swift_native_objc_runtime_base($Dollar)
class $Class {} // expected-error{{cannot declare entity named '$Class'; the '$' prefix is reserved}}
enum $Enum {} // expected-error{{cannot declare entity named '$Enum'; the '$' prefix is reserved}}
struct $Struct { // expected-error{{cannot declare entity named '$Struct'; the '$' prefix is reserved}}
@_projectedValueProperty($dummy)
let property: Never
}
}
protocol $Protocol {} // expected-error {{cannot declare entity named '$Protocol'; the '$' prefix is reserved}}
precedencegroup $Precedence { // expected-error {{cannot declare entity named '$Precedence'; the '$' prefix is reserved}}
higherThan: $Precedence // expected-error {{cycle in 'higherThan' relation}}
}
infix operator **: $Precedence
#$UnknownDirective() // expected-error {{use of unknown directive '#$UnknownDirective'}}
// SR-13232
@propertyWrapper
struct Wrapper {
var wrappedValue: Int
var projectedValue: String { String(wrappedValue) }
}
struct S {
@Wrapper var café = 42
}
let _ = S().$café // Okay
infix operator $ // expected-error{{'$' is considered an identifier and must not appear within an operator name}} // SR-13092
infix operator `$` // expected-error{{'$' is considered an identifier and must not appear within an operator name}} // SR-13092
| 37.520325 | 127 | 0.641387 |
4b2f0a9237d8c771055ae7796d6e491f1df488fa | 561 | //
// ViewController.swift
// MakeItHybrid
//
// Created by yusufm on 07/06/2015.
// Copyright (c) 2015 yusufm. All rights reserved.
//
import UIKit
import MakeItHybrid
class ViewController: UIViewController {
var openUrl = MakeItHybrid()
override func viewDidLoad() {
super.viewDidLoad()
openUrl.superView = self.view
openUrl.makeHybridWithUrlString("http://miletli.com")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.344828 | 58 | 0.691622 |
e90f4da299d6380873f731b01d62d141806e77d3 | 9,993 | //
// NDFillButton.swift
// NDFillButton
//
// Created by Neil Dwyer on 7/28/15.
// Copyright (c) 2015 Neil Dwyer. All rights reserved.
//
import UIKit
@IBDesignable public class NDFillButton: UIControl {
let backgroundLayer = CALayer()
let foregroundLayer = CALayer()
let fillAnimationLayer = CALayer()
@objc @IBInspectable public var fillColor: UIColor {
didSet {
fillAnimationLayer.backgroundColor = fillColor.CGColor
}
}
@objc @IBInspectable public var emptyColor: UIColor = UIColor.clearColor()
@objc @IBInspectable public var normalBorderColor: UIColor = UIColor.redColor() {
didSet {
updateLayers()
}
}
@objc @IBInspectable public var activeBorderColor: UIColor = UIColor.blueColor() {
didSet {
updateLayers()
}
}
@objc @IBInspectable public var cornerRadius: CGFloat = 5.0 {
didSet {
updateLayers()
}
}
@objc @IBInspectable public var pressedCornerRadius: CGFloat = 5.0
@objc @IBInspectable public var borderWidth: CGFloat = 2 {
didSet {
updateLayers()
}
}
@objc @IBInspectable public var activeFontName: String = "Helvetica" {
didSet {
updateLabel(false)
}
}
@objc @IBInspectable public var activeFontColor: UIColor = UIColor.blackColor() {
didSet {
updateLabel(false)
}
}
@objc @IBInspectable public var activeFontSize: CGFloat = 14.0 {
didSet {
updateLabel(false)
}
}
@objc @IBInspectable public var normalFontName: String = "Helvetica" {
didSet {
updateLabel(false)
}
}
@objc @IBInspectable public var normalFontColor: UIColor = UIColor.blackColor()
@objc @IBInspectable public var normalFontSize: CGFloat = 14.0
@IBInspectable var textLabel: UILabel = UILabel()
@objc @IBInspectable public var activeText: String = "Active" {
didSet {
updateLabel(false)
}
}
@objc @IBInspectable public var normalText: String = "Inactive" {
didSet {
updateLabel(false)
}
}
@IBInspectable var animateTextChange: Bool = true
var animateEnabled: Bool = true
@objc public var active: Bool = false {
didSet {
self.animateFill(active, animated: animateEnabled)
updateLabel(animateTextChange && animateEnabled)
}
}
var pressed: Bool = false {
didSet {
let duration = 0.1
if pressed {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
self.backgroundLayer.cornerRadius = pressedCornerRadius
CATransaction.commit()
} else {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
self.backgroundLayer.cornerRadius = cornerRadius
CATransaction.commit()
}
}
}
required public init?(coder aDecoder: NSCoder) {
fillColor = UIColor.redColor()
super.init(coder: aDecoder)
backgroundColor = UIColor.clearColor()
setupLayers()
setupLabel()
self.setActive(false, animated: false)
}
override init(frame: CGRect) {
fillColor = UIColor.redColor()
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
setupLayers()
setupLabel()
self.setActive(false, animated: false)
}
convenience init() {
self.init(frame:CGRectZero)
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateLayers()
updateLabel(false)
}
@objc public func toggle() {
active = !active
}
@objc public func setActive(active: Bool, animated: Bool) {
animateEnabled = animated
self.active = active
animateEnabled = true
}
}
// MARK: - Touch Overrides
extension NDFillButton {
override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
pressed = true
return true
}
override public func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
return true
}
override public func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
pressed = false
}
override public func cancelTrackingWithEvent(event: UIEvent?) {
pressed = false
}
}
// MARK: - layer
extension NDFillButton {
private func animateFill(active: Bool, animated: Bool) {
let R = sqrt(backgroundLayer.bounds.size.height * backgroundLayer.bounds.size.height + backgroundLayer.bounds.size.width * backgroundLayer.bounds.size.width) / 2 + 3
let duration = 0.15 * Double(animated)
let midPoint = CGPoint(x: backgroundLayer.bounds.size.width / 2, y: backgroundLayer.bounds.size.height / 2)
if active {
backgroundLayer.borderColor = activeBorderColor.CGColor
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
self.fillAnimationLayer.bounds = CGRect(origin: CGPointZero, size: CGSize(width: R * 2, height: R * 2))
self.fillAnimationLayer.cornerRadius = R
self.fillAnimationLayer.position = midPoint
CATransaction.commit()
} else {
backgroundLayer.borderColor = normalBorderColor.CGColor
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
self.fillAnimationLayer.bounds = CGRect(origin: midPoint, size: CGSizeZero)
self.fillAnimationLayer.position = midPoint
self.fillAnimationLayer.cornerRadius = 0
CATransaction.commit()
}
}
private func setupLayers() {
self.layer.addSublayer(backgroundLayer)
self.backgroundLayer.addSublayer(fillAnimationLayer)
self.layer.addSublayer(foregroundLayer)
let midPoint = CGPoint(x: backgroundLayer.bounds.size.width / 2, y: backgroundLayer.bounds.size.height / 2)
fillAnimationLayer.backgroundColor = fillColor.CGColor
fillAnimationLayer.frame = CGRect(origin: midPoint, size: CGSizeZero)
updateLayers()
}
private func updateLayers() {
backgroundLayer.frame = CGRect(origin: CGPointZero, size: frame.size)
backgroundLayer.cornerRadius = cornerRadius
backgroundLayer.borderWidth = borderWidth
if active {
backgroundLayer.borderColor = activeBorderColor.CGColor
} else {
backgroundLayer.borderColor = normalBorderColor.CGColor
}
backgroundLayer.masksToBounds = true
foregroundLayer.frame = frame
setActive(active, animated: false)
}
public override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
updateLayers()
}
}
// MARK: - Label
extension NDFillButton {
private func setupLabel() {
updateLabel(false)
self.addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0)
let centerY = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)
self.addConstraints([centerX, centerY])
}
private func updateLabel(animated: Bool) {
if(!animated) {
self.changeLabelText()
return
}
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.textLabel.transform = CGAffineTransformMakeScale(0.1, 0.1)
}) { (anim) -> Void in
self.changeLabelText()
UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { () -> Void in
self.textLabel.transform = CGAffineTransformMakeScale(1, 1)
}, completion:nil)
}
}
private func changeLabelText() {
var fontName: String
var fontSize: CGFloat
var fontText: String
var textColor: UIColor
if(self.active) {
fontName = self.activeFontName
fontSize = self.activeFontSize
fontText = self.activeText
textColor = self.activeFontColor
} else {
fontName = self.normalFontName
fontSize = self.normalFontSize
fontText = self.normalText
textColor = self.normalFontColor
}
self.textLabel.font = UIFont(name: fontName, size: fontSize)
self.textLabel.text = fontText
self.textLabel.textColor = textColor
self.textLabel.sizeToFit()
}
}
public extension NDFillButton {
@objc public override func sizeThatFits(size: CGSize) -> CGSize {
let labelSize = textLabel.sizeThatFits(size)
return CGSize(width: labelSize.width + 4, height: labelSize.height)
}
} | 35.562278 | 214 | 0.635645 |
7aa076a4332a053cbff747682f7417a5995dc487 | 112 | //
// Nothing.swift
// Spottie
//
// Created by Lee Jun Kit on 20/5/21.
//
struct Nothing: Codable {
}
| 10.181818 | 38 | 0.571429 |
2217fe6aaf6b03176459fd8ee114c5da0497f394 | 2,991 | //
// CustomStyleView.swift
// AxisSegmentedViewExample
//
// Created by jasu on 2022/03/26.
// Copyright (c) 2022 jasu All rights reserved.
//
import SwiftUI
import AxisSegmentedView
struct CustomStyleView: View {
@State private var selection: Int = 0
var body: some View {
HStack {
AxisSegmentedView(selection: $selection, constant: .init(axisMode: .vertical)) {
Image(systemName: "align.horizontal.left")
.itemTag(0, selectArea: 0) {
SelectionItemView("align.horizontal.left.fill")
}
Image(systemName: "align.horizontal.right")
.itemTag(1, selectArea: 260) {
SelectionItemView("align.horizontal.right.fill")
}
Image(systemName: "align.vertical.top")
.itemTag(2, selectArea: 0) {
SelectionItemView("align.vertical.top.fill")
}
Image(systemName: "align.vertical.bottom")
.itemTag(3, selectArea: 260) {
SelectionItemView("align.vertical.bottom.fill")
}
} style: {
CustomStyle(color: .blue)
} onTapReceive: { selectionTap in
/// Imperative syntax
print("---------------------")
print("Selection : ", selectionTap)
print("Already selected : ", self.selection == selectionTap)
}
.frame(width: 44)
AxisSegmentedView(selection: $selection, constant: .init()) {
Image(systemName: "align.horizontal.left")
.itemTag(0, selectArea: 0) {
SelectionItemView("align.horizontal.left.fill")
}
Image(systemName: "align.horizontal.right")
.itemTag(1, selectArea: 160) {
SelectionItemView("align.horizontal.right.fill")
}
Image(systemName: "align.vertical.top")
.itemTag(2, selectArea: 0) {
SelectionItemView("align.vertical.top.fill")
}
Image(systemName: "align.vertical.bottom")
.itemTag(3, selectArea: 160) {
SelectionItemView("align.vertical.bottom.fill")
}
} style: {
CustomStyle(color: .red)
} onTapReceive: { selectionTap in
/// Imperative syntax
print("---------------------")
print("Selection : ", selectionTap)
print("Already selected : ", self.selection == selectionTap)
}
.frame(height: 44)
}
}
}
struct CustomStyleView_Previews: PreviewProvider {
static var previews: some View {
CustomStyleView()
}
}
| 37.3875 | 92 | 0.488465 |
d548b3e0f51925b79e97faf43582adf0c2a15241 | 257 | //
// SearchTracks.swift
// SpotiFav
//
// Created by Cao Mai on 10/23/20.
// Copyright © 2020 Cao. All rights reserved.
//
import Foundation
struct SearchTracks: Model {
let tracks: Tracks
}
struct Tracks: Model {
let items: [ArtistTrack]
}
| 14.277778 | 46 | 0.66537 |
015bff15f91ab29a2ae45c8a08e775a9e9ce029a | 937 | //
// GetPledgeDetailRequest.swift
// Vite
//
// Created by Stone on 2018/10/25.
// Copyright © 2018年 vite labs. All rights reserved.
//
import Foundation
import JSONRPCKit
public struct GetPledgeDetailRequest: JSONRPCKit.Request {
public typealias Response = PledgeDetail
let address: ViteAddress
let index: Int
let count: Int
public var method: String {
return "contract_getStakeList"
}
public var parameters: Any? {
return [address, index, count]
}
public init(address: ViteAddress, index: Int, count: Int) {
self.address = address
self.index = index
self.count = count
}
public func response(from resultObject: Any) throws -> Response {
guard let response = resultObject as? [String: Any],
let ret = PledgeDetail(JSON: response)else {
throw ViteError.JSONTypeError
}
return ret
}
}
| 22.853659 | 69 | 0.638207 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.