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
|
---|---|---|---|---|---|
5bcdf41526e4d476e8f2a4325d5c153ec7f3df57 | 643 | /*
Binary Search
Recursively splits the array in half until the value is found.
If there is more than one occurrence of the search key in the array, then
there is no guarantee which one it finds.
Note: The array must be sorted!
*/
func binarySearch<T: Comparable>(a: [T], key: T) -> Int? {
var range = 0..<a.count
while range.startIndex < range.endIndex {
let midIndex = range.startIndex + (range.endIndex - range.startIndex) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
range.startIndex = midIndex + 1
} else {
range.endIndex = midIndex
}
}
return nil
}
| 25.72 | 77 | 0.654743 |
1697571fc5b91622ad23ec174cb9ac0355b24f1a | 1,752 | // ------------------------------------------------------------------------
// Copyright 2017 Dan Waltin
//
// 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.
// ------------------------------------------------------------------------
//
// ExecuteStepBindingFunctionTests.swift
// SwiftSpec
//
// Created by Dan Waltin on 2016-07-23.
//
// ------------------------------------------------------------------------
import XCTest
@testable import SwiftSpec
@testable import GherkinSwift
class ExecuteStepBindingFunctionTests : XCTestCase {
func test_functionIsExecuted() {
var hasBeenExecuted = false
let s = step {_ in
hasBeenExecuted = true
}
try! s.execute(BindingsParameters())
XCTAssertTrue(hasBeenExecuted)
}
func test_bindingsParametersAreSet() {
var parameters: BindingsParameters?
let s = step {
parameters = $0
}
try! s.execute(BindingsParameters(tableParameter: TableParameter(columns: ["c"])))
XCTAssertEqual(parameters, BindingsParameters(tableParameter: TableParameter(columns: ["c"])))
}
// MARK: - Factory methods
private func step(_ function: @escaping (BindingsParameters) -> ()) -> StepBindingImplementation {
return StepBindingImplementation(stepText: "text", function: function)
}
}
| 31.854545 | 99 | 0.646689 |
e855910eb7943f81c276387b42ee56d6e0c2d2a3 | 11,108 | //
// FeedCollectionViewController.swift
// Hackers
//
// Created by Weiran Zhang on 06/07/2020.
// Copyright © 2020 Weiran Zhang. All rights reserved.
//
import UIKit
import PromiseKit
import SafariServices
import Loaf
class FeedCollectionViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var authenticationUIService: AuthenticationUIService?
private lazy var dataSource = makeDataSource()
private lazy var viewModel = FeedViewModel()
private var refreshToken: NotificationToken?
private let cellIdentifier = "ItemCell"
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupCollectionViewListConfiguration()
setupTitle()
setupNotificationCenter()
showOnboarding()
fetchFeed()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
smoothlyDeselectItems(collectionView)
}
private func setupTitle() {
let button = TitleButton()
button.setTitleText(viewModel.postType.title)
button.setupMenu()
button.handler = { postType in
self.viewModel.postType = postType
self.setupTitle()
self.viewModel.reset()
self.update(with: self.viewModel, animate: false)
self.fetchFeed()
}
navigationItem.titleView = button
title = viewModel.postType.title
}
private func fetchFeed(fetchNextPage: Bool = false) {
firstly {
viewModel.fetchFeed(fetchNextPage: fetchNextPage)
}.done {
self.update(with: self.viewModel, animate: fetchNextPage == true)
}.catch { _ in
Loaf("Error connecting to Hacker News", state: .error, sender: self).show()
}.finally {
self.collectionView.refreshControl?.endRefreshing()
}
}
@objc private func fetchFeedWithReset() {
setupCollectionViewListConfiguration()
viewModel.reset()
fetchFeed()
}
@objc private func fetchFeedNextPage() {
fetchFeed(fetchNextPage: true)
}
private func setupNotificationCenter() {
refreshToken = NotificationCenter.default.observe(
name: Notification.Name.refreshRequired,
object: nil,
queue: .main
) { [weak self] _ in
self?.fetchFeedWithReset()
}
}
private func showOnboarding() {
if let onboardingVC = OnboardingService.onboardingViewController() {
present(onboardingVC, animated: true)
}
}
}
extension FeedCollectionViewController: UICollectionViewDelegate {
private func setupCollectionViewListConfiguration() {
var config = UICollectionLayoutListConfiguration(appearance: .plain)
if UserDefaults.standard.swipeActionsEnabled {
config.leadingSwipeActionsConfigurationProvider = voteSwipeActionConfiguration(indexPath:)
}
config.showsSeparators = false
let layout = UICollectionViewCompositionalLayout.list(using: config)
collectionView.setCollectionViewLayout(layout, animated: false)
}
private func setupCollectionView() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(
self,
action: #selector(fetchFeedWithReset),
for: .valueChanged
)
collectionView.refreshControl = refreshControl
collectionView.backgroundView = TableViewBackgroundView.loadingBackgroundView()
collectionView.register(
UINib(nibName: cellIdentifier, bundle: nil),
forCellWithReuseIdentifier: cellIdentifier
)
collectionView.dataSource = dataSource
}
private func makeDataSource() -> UICollectionViewDiffableDataSource<FeedViewModel.Section, Post> {
return UICollectionViewDiffableDataSource(
collectionView: collectionView
) { (collectionView, indexPath, post) in
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: self.cellIdentifier,
for: indexPath
) as? ItemCell else {
fatalError("Couldn't dequeue cell \(self.cellIdentifier)")
}
cell.apply(post: post)
cell.setupThumbnail(with: UserDefaults.standard.showThumbnails ? post.url : nil)
cell.linkPressedHandler = { post in
self.openURL(url: post.url) {
if let svc = SFSafariViewController.instance(for: post.url) {
self.navigationController?.present(svc, animated: true)
}
}
}
return cell
}
}
private func update(with viewModel: FeedViewModel, animate: Bool = true) {
var snapshot = NSDiffableDataSourceSnapshot<FeedViewModel.Section, Post>()
snapshot.appendSections(FeedViewModel.Section.allCases)
snapshot.appendItems(viewModel.posts, toSection: FeedViewModel.Section.main)
self.dataSource.apply(snapshot, animatingDifferences: animate)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if viewModel.postType == .jobs,
let post = dataSource.itemIdentifier(for: indexPath) {
self.openURL(url: post.url) {
if let svc = SFSafariViewController.instance(for: post.url) {
self.navigationController?.present(svc, animated: true)
}
}
} else {
performSegue(withIdentifier: "ShowCommentsSegue", sender: collectionView)
}
}
func collectionView(
_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath
) {
if indexPath.row == viewModel.posts.count - 5 && !viewModel.isFetching {
fetchFeedNextPage()
}
}
func collectionView(
_ collectionView: UICollectionView,
contextMenuConfigurationForItemAt indexPath: IndexPath,
point: CGPoint
) -> UIContextMenuConfiguration? {
let post = viewModel.posts[indexPath.row]
return UIContextMenuConfiguration(
identifier: nil,
previewProvider: nil
) { _ in
let upvote = UIAction(
title: "Upvote",
image: UIImage(systemName: "arrow.up"),
identifier: UIAction.Identifier(rawValue: "upvote")
) { _ in
self.vote(on: post)
}
let unvote = UIAction(
title: "Unvote",
image: UIImage(systemName: "arrow.uturn.down"),
identifier: UIAction.Identifier(rawValue: "unvote")
) { _ in
self.vote(on: post)
}
let openLink = UIAction(
title: "Open Link",
image: UIImage(systemName: "safari"),
identifier: UIAction.Identifier(rawValue: "open.link")
) { _ in
self.openURL(url: post.url) {
if let svc = SFSafariViewController.instance(for: post.url) {
self.navigationController?.present(svc, animated: true)
}
}
}
let shareLink = UIAction(
title: "Share Link",
image: UIImage(systemName: "square.and.arrow.up"),
identifier: UIAction.Identifier(rawValue: "share.link")
) { _ in
let url = post.url.host != nil ? post.url : post.hackerNewsURL
let activityViewController = UIActivityViewController(
activityItems: [url],
applicationActivities: nil
)
let cell = collectionView.cellForItem(at: indexPath)
activityViewController.popoverPresentationController?.sourceView = cell
self.present(activityViewController, animated: true, completion: nil)
}
let voteMenu = post.upvoted ? unvote : upvote
let linkMenu = UIMenu(title: "", options: .displayInline, children: [openLink, shareLink])
return UIMenu(title: "", image: nil, identifier: nil, children: [voteMenu, linkMenu])
}
}
}
extension FeedCollectionViewController {
private func voteSwipeActionConfiguration(indexPath: IndexPath) -> UISwipeActionsConfiguration {
let post = self.viewModel.posts[indexPath.row]
let voteAction = UIContextualAction(
style: .normal,
title: nil,
handler: { _, _, completion in
self.vote(on: post)
completion(true)
}
)
if post.upvoted {
// unvote
voteAction.image = UIImage(systemName: "arrow.uturn.down")
} else {
voteAction.image = UIImage(systemName: "arrow.up")
}
if !post.upvoted {
voteAction.backgroundColor = AppTheme.default.upvotedColor
}
return UISwipeActionsConfiguration(actions: [voteAction])
}
private func vote(on post: Post) {
let isUpvote = !post.upvoted
// optimistally update
updateVote(on: post, isUpvote: isUpvote)
firstly {
viewModel.vote(on: post, upvote: isUpvote)
}.catch { [weak self] error in
self?.updateVote(on: post, isUpvote: !isUpvote)
self?.handleVoteError(error: error)
}
}
private func updateVote(on post: Post, isUpvote: Bool) {
post.upvoted = isUpvote
post.score += isUpvote ? 1 : -1
if let index = viewModel.posts.firstIndex(of: post),
let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? ItemCell {
cell.apply(post: post)
}
}
private func handleVoteError(error: Error) {
guard
let error = error as? HackersKitError,
let authenticationUIService = self.authenticationUIService else {
return
}
switch error {
case .unauthenticated:
self.present(
authenticationUIService.unauthenticatedAlertController(),
animated: true
)
default:
Loaf("Error connecting to Hacker News", state: .error, sender: self).show()
}
}
}
extension FeedCollectionViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowCommentsSegue",
let navVC = segue.destination as? UINavigationController,
let commentsVC = navVC.children.first as? CommentsViewController,
let indexPath = collectionView.indexPathsForSelectedItems?.first,
let post = dataSource.itemIdentifier(for: indexPath) {
commentsVC.post = post
commentsVC.postId = post.id
}
}
}
| 33.558912 | 102 | 0.60587 |
64b9b78e85c069992fd2d1f94c8a23a25765d996 | 1,402 | //
// Extensions.swift
// ATTAlertController
//
// Created by Ammar AlTahhan on 12/12/2018.
// Copyright © 2018 Ammar AlTahhan. All rights reserved.
//
import Foundation
import UIKit
extension Array {
mutating func unsheft(contentsOf new: [Element]) {
let copy = self
self = []
self.append(contentsOf: new)
self.append(contentsOf: copy)
}
}
extension UIView {
func roundCorners(_ corners: CACornerMask, radius: CGFloat) {
if #available(iOS 11, *) {
self.layer.cornerRadius = radius
self.layer.maskedCorners = corners
} else {
var cornerMask = UIRectCorner()
if(corners.contains(.layerMinXMinYCorner)){
cornerMask.insert(.topLeft)
}
if(corners.contains(.layerMaxXMinYCorner)){
cornerMask.insert(.topRight)
}
if(corners.contains(.layerMinXMaxYCorner)){
cornerMask.insert(.bottomLeft)
}
if(corners.contains(.layerMaxXMaxYCorner)){
cornerMask.insert(.bottomRight)
}
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: cornerMask, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
| 29.208333 | 144 | 0.584879 |
2f4f9897c1243bea0b15a0c4c1eb340a4240781e | 1,049 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftMatrices",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftMatrices",
targets: ["SwiftMatrices"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftMatrices",
dependencies: []),
.testTarget(
name: "SwiftMatricesTests",
dependencies: ["SwiftMatrices"]),
]
)
| 36.172414 | 122 | 0.629171 |
f5f1d0d43cb38458b86a6fec1af7947cc5cb8836 | 1,291 | import BitcoinKit
import BitcoinCore
import HdWalletKit
import HsToolKit
import RxSwift
class BitcoinAdapter: BaseAdapter {
let bitcoinKit: BitcoinKit
init(words: [String], bip: Bip, testMode: Bool, syncMode: BitcoinCore.SyncMode, logger: Logger) {
let networkType: BitcoinKit.NetworkType = testMode ? .testNet : .mainNet
bitcoinKit = try! BitcoinKit(withWords: words, bip: bip, walletId: "walletId", syncMode: syncMode, networkType: networkType, confirmationsThreshold: 1, logger: logger.scoped(with: "BitcoinKit"))
super.init(name: "Bitcoin", coinCode: "BTC", abstractKit: bitcoinKit)
bitcoinKit.delegate = self
}
class func clear() {
try? BitcoinKit.clear()
}
}
extension BitcoinAdapter: BitcoinCoreDelegate {
func transactionsUpdated(inserted: [TransactionInfo], updated: [TransactionInfo]) {
transactionsSignal.notify()
}
func transactionsDeleted(hashes: [String]) {
transactionsSignal.notify()
}
func balanceUpdated(balance: BalanceInfo) {
balanceSignal.notify()
}
func lastBlockInfoUpdated(lastBlockInfo: BlockInfo) {
lastBlockSignal.notify()
}
public func kitStateUpdated(state: BitcoinCore.KitState) {
syncStateSignal.notify()
}
}
| 28.065217 | 202 | 0.699458 |
0977abf13e19c983ca7a4d5631e41d5edbdce313 | 105 | //
// PickerFor.swift
// Demo3Pods
//
// Created by Nguyen Van Tinh on 4/27/21.
//
import Foundation
| 11.666667 | 42 | 0.647619 |
8ae66b34a6a04a071dd09205ae5ced3c1ae72085 | 1,676 | /// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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
| 54.064516 | 83 | 0.758353 |
eddef70b02e9349a5af672c82e92bd7b58c7c8aa | 5,620 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _MatchingEngine
/*
Inspired by "Staged Parser Combinators for Efficient Data Processing" by Jonnalagedda et al.
*/
// Stages are represented as nested namespaces that bind generic
// types
public enum Combinators {
public enum BindElement<Element: Comparable & Hashable> {
public enum BindPosition<Position: Comparable & Hashable> {
// TODO: it's not clear if error is bound earlier or
// later than the collection...
public enum BindError<Err: Error & Hashable> {
}
public enum BindInput<Input: Collection>
where Input.Element == Element, Input.Index == Position {
}
}
}
}
extension Combinators.BindElement.BindPosition.BindError {
public struct ParseResult<T: Hashable>: Hashable {
var next: Position
var result: Result<T, Err>
}
public struct Parser<T: Hashable> {
let apply: (Position) throws -> ParseResult<T>
init(_ f: @escaping (Position) throws -> ParseResult<T>) {
self.apply = f
}
}
}
// Helpers
extension
Combinators.BindElement.BindPosition.BindError.ParseResult
{
public typealias ParseResult = Combinators.BindElement<Element>.BindPosition<Position>.BindError<Err>.ParseResult
public var value: T? {
switch result {
case .failure(_): return nil
case .success(let v): return v
}
}
public var isError: Bool { value == nil }
// Paper does this, not sure if we want to distinguish
// successful empty parses from error parses, and if
// we want error recovery to involve skipping...
public var isEmpty: Bool { isError }
public func mapValue<U: Hashable>(_ f: (T) -> U) -> ParseResult<U> {
ParseResult(next: next, result: result.map(f))
}
public func flatMap<U: Hashable>(
_ f: (Position, T) throws -> ParseResult<U>
) rethrows -> ParseResult<U> {
switch result {
case .success(let v):
return try f(next, v)
case .failure(let e):
return ParseResult(next: next, result: .failure(e))
}
}
public var successSelf: Self? {
guard !isError else { return nil }
return self
}
public var errorSelf: Self? {
guard isError else { return nil }
return self
}
}
// Combinators
extension Combinators.BindElement.BindPosition.BindError.Parser {
public typealias Parser = Combinators.BindElement<Element>.BindPosition<Position>.BindError<Err>.Parser
public typealias ParseResult = Combinators.BindElement<Element>.BindPosition<Position>.BindError<Err>.ParseResult
// Backtracking alternation
public func or(_ rhs: Self) -> Self {
Self { pos in
try self.apply(pos).successSelf ?? rhs.apply(pos)
}
}
public func map<U: Hashable>(
_ f: @escaping (T) -> U
) -> Parser<U> {
Parser { pos in
try self.apply(pos).mapValue(f)
}
}
public func flatMap<U: Hashable>(
_ f: @escaping (T) -> Parser<U>
) -> Parser<U> {
return Parser { pos in
try self.apply(pos).flatMap { (p, v) in
try f(v).apply(p)
}
}
}
public func chain<U: Hashable, V: Hashable>(
_ rhs: Parser<U>, combining f: @escaping (T, U) -> V
) -> Parser<V> {
Parser { pos in
try self.apply(pos).flatMap { p, t in
try rhs.apply(p).mapValue { u in f(t, u) }
}
}
}
public func chain<U: Hashable>(
_ rhs: Parser<U>
) -> Parser<Pair<T, U>> {
self.chain(rhs) { Pair($0, $1) }
}
public func chainLeft<U: Hashable>(
_ rhs: Parser<U>
) -> Parser<T> {
self.chain(rhs) { r, _ in r }
}
public func chainRight<U: Hashable>(
_ rhs: Parser<U>
) -> Parser<U> {
self.chain(rhs) { _, r in r }
}
public var `repeat`: Parser<[T]> {
// TODO: non-primitive construction
Parser { pos in
var pos = pos
var result = Array<T>()
while let intr = try self.apply(pos).successSelf {
pos = intr.next
result.append(intr.value!)
}
return ParseResult(next: pos, result: .success(result))
}
}
public func `repeat`(exactly n: Int) -> Parser<[T]> {
// TODO: non-primitive construction
Parser { pos in
var pos = pos
var result = Array<T>()
for _ in 0..<n {
let intr = try self.apply(pos)
guard !intr.isError else {
return intr.mapValue { _ in fatalError() }
}
pos = intr.next
result.append(intr.value!)
}
return ParseResult(next: pos, result: .success(result))
}
}
}
// Tuple isn't Hashable...
public struct Pair<T: Hashable, U: Hashable>: Hashable {
var first: T
var second: U
init(_ t: T, _ u: U) {
self.first = t
self.second = u
}
}
/*
Extract HTTP response body
def status = (
("HTTP/" ~ decimalNumber) ~> wholeNumber <~ (text ~ crlf)
) map (_.toInt)
def headers = rep(header)
def header = (headerName <~ ":") flatMap { key =>
(valueParser(key) <~ crlf) map { value => (key, value) }
}
def valueParser(key: String) =
if (key == "Content-Length") wholeNumber else text
def body(i: Int) = repN(anyChar, i) <~ crlf
def response = (status ~ headers <~ crlf) map {
case st ~ hs => Response(st, hs)
}
def respWithPayload = response flatMap { r =>
body(r.contentLength)
}
*/
| 24.541485 | 115 | 0.609253 |
697efe007a795bcc3b89a31782c920c12d2d13a0 | 35,566 | // RUN: %target-parse-verify-swift
//===----------------------------------------------------------------------===//
// Tests and samples.
//===----------------------------------------------------------------------===//
// Comment. With unicode characters: ¡ç®åz¥!
func markUsed<T>(_: T) {}
// Various function types.
var func1 : () -> () // No input, no output.
var func2 : (Int) -> Int
var func3 : () -> () -> () // Takes nothing, returns a fn.
var func3a : () -> (() -> ()) // same as func3
var func6 : (_ fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing.
var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple.
// Top-Level expressions. These are 'main' content.
func1()
_ = 4+7
var bind_test1 : () -> () = func1
var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused l-value}}
(func1, func2) // expected-error {{expression resolves to an unused l-value}}
func basictest() {
// Simple integer variables.
var x : Int
var x2 = 4 // Simple Type inference.
var x3 = 4+x*(4+x2)/97 // Basic Expressions.
// Declaring a variable Void, aka (), is fine too.
var v : Void
var x4 : Bool = true
var x5 : Bool =
4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
//var x6 : Float = 4+5
var x7 = 4; 5 // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
// Test implicit conversion of integer literal to non-Int64 type.
var x8 : Int8 = 4
x8 = x8 + 1
_ = x8 + 1
_ = 0 + x8
1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var x9 : Int16 = x8 + 1 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int8' and 'Int'}} expected-note {{expected an argument list of type '(Int16, Int16)'}}
// Various tuple types.
var tuple1 : ()
var tuple2 : (Int)
var tuple3 : (Int, Int, ())
var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}}
var tuple3a : (a : Int, b : Int, c : ())
var tuple4 = (1, 2) // Tuple literal.
var tuple5 = (1, 2, 3, 4) // Tuple literal.
var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}}
// Brace expressions.
var brace3 = {
var brace2 = 42 // variable shadowing.
_ = brace2+7
}
// Function calls.
var call1 : () = func1()
var call2 = func2(1)
var call3 : () = func3()()
// Cannot call an integer.
bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}{{13-15=}}
}
// Infix operators and attribute lists.
infix operator %% : MinPrecedence
precedencegroup MinPrecedence {
associativity: left
lowerThan: AssignmentPrecedence
}
func %%(a: Int, b: Int) -> () {}
var infixtest : () = 4 % 2 + 27 %% 123
// The 'func' keyword gives a nice simplification for function definitions.
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl2() {
return funcdecl1(4, 2)
}
func funcdecl3() -> Int {
return 12
}
func funcdecl4(_ a: ((Int) -> Int), b: Int) {}
func signal(_ sig: Int, f: (Int) -> Void) -> (Int) -> Void {}
// Doing fun things with named arguments. Basic stuff first.
func funcdecl6(_ a: Int, b: Int) -> Int { return a+b }
// Can dive into tuples, 'b' is a reference to a whole tuple, c and d are
// fields in one. Cannot dive into functions or through aliases.
func funcdecl7(_ a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int {
_ = a + b.0 + b.c + third.0 + third.1
b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}}
}
// Error recovery.
func testfunc2 (_: (((), Int)) -> Int) -> Int {}
func errorRecovery() {
testfunc2({ $0 + 1 }) // expected-error {{binary operator '+' cannot be applied to operands of type '((), Int)' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}}
enum union1 {
case bar
case baz
}
var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}}
var b: union1 = .bar // ok
var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}}
var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}}
var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}}
var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}}
// <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698
var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}}
}
func acceptsInt(_ x: Int) {}
acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}}
var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}}
var test1b = { 42 }
var test1c = { { 42 } }
var test1d = { { { 42 } } }
func test2(_ a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{34-37=}} expected-note {{did you mean 'a'?}} expected-note {{did you mean 'b'?}}
_ = a+b
a+b+c // expected-error{{use of unresolved identifier 'c'}}
return a+b
}
func test3(_ arg1: Int, arg2: Int) -> Int {
return 4
}
func test4() -> ((_ arg1: Int, _ arg2: Int) -> Int) {
return test3
}
func test5() {
let a: (Int, Int) = (1,2)
var
_: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)'}}
let c: (a: Int, b: Int) = (1,2)
let _: (b: Int, a: Int) = c // Ok, reshuffle tuple.
}
// Functions can obviously take and return values.
func w3(_ a: Int) -> Int { return a }
func w4(_: Int) -> Int { return 4 }
func b1() {}
func foo1(_ a: Int, b: Int) -> Int {}
func foo2(_ a: Int) -> (_ b: Int) -> Int {}
func foo3(_ a: Int = 2, b: Int = 3) {}
prefix operator ^^
prefix func ^^(a: Int) -> Int {
return a + 1
}
func test_unary1() {
var x: Int
x = ^^(^^x)
x = *x // expected-error {{'*' is not a prefix unary operator}}
x = x* // expected-error {{'*' is not a postfix unary operator}}
x = +(-x)
x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}}
}
func test_unary2() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_unary3() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_as_1() {
var _: Int
}
func test_as_2() {
let x: Int = 1
x as [] // expected-error {{expected element type}}
}
func test_lambda() {
// A simple closure.
var a = { (value: Int) -> () in markUsed(value+1) }
// A recursive lambda.
// FIXME: This should definitely be accepted.
var fib = { (n: Int) -> Int in
if (n < 2) {
return n
}
return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}}
}
}
func test_lambda2() {
{ () -> protocol<Int> in
// expected-warning @-1 {{'protocol<...>' composition syntax is deprecated and not needed here}} {{11-24=Int}}
// expected-error @-2 {{non-protocol type 'Int' cannot be used within a protocol composition}}
// expected-warning @-3 {{result of call is unused}}
return 1
}()
}
func test_floating_point() {
_ = 0.0
_ = 100.1
var _: Float = 0.0
var _: Double = 0.0
}
func test_nonassoc(_ x: Int, y: Int) -> Bool {
// FIXME: the second error and note here should arguably disappear
return x == y == x // expected-error {{adjacent operators are in non-associative precedence group 'ComparisonPrecedence'}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}}
}
// More realistic examples.
func fib(_ n: Int) -> Int {
if (n < 2) {
return n
}
return fib(n-2) + fib(n-1)
}
//===----------------------------------------------------------------------===//
// Integer Literals
//===----------------------------------------------------------------------===//
// FIXME: Should warn about integer constants being too large <rdar://problem/14070127>
var
il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
var il_b: Int8
= 123123
var il_c: Int8 = 4 // ok
struct int_test4 : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral value: Int) {} // user type.
}
var il_g: int_test4 = 4
// This just barely fits in Int64.
var il_i: Int64 = 18446744073709551615
// This constant is too large to fit in an Int64, but it is fine for Int128.
// FIXME: Should warn about the first. <rdar://problem/14070127>
var il_j: Int64 = 18446744073709551616
// var il_k: Int128 = 18446744073709551616
var bin_literal: Int64 = 0b100101
var hex_literal: Int64 = 0x100101
var oct_literal: Int64 = 0o100101
// verify that we're not using C rules
var oct_literal_test: Int64 = 0123
assert(oct_literal_test == 123)
// ensure that we swallow random invalid chars after the first invalid char
var invalid_num_literal: Int64 = 0QWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{expected a digit in floating point exponent}}
// rdar://11088443
var negative_int32: Int32 = -1
// <rdar://problem/11287167>
var tupleelemvar = 1
markUsed((tupleelemvar, tupleelemvar).1)
func int_literals() {
// Fits exactly in 64-bits - rdar://11297273
_ = 1239123123123123
// Overly large integer.
// FIXME: Should warn about it. <rdar://problem/14070127>
_ = 123912312312312312312
}
// <rdar://problem/12830375>
func tuple_of_rvalues(_ a:Int, b:Int) -> Int {
return (a, b).1
}
extension Int {
func testLexingMethodAfterIntLiteral() {}
func _0() {}
// Hex letters
func ffa() {}
// Hex letters + non hex.
func describe() {}
// Hex letters + 'p'.
func eap() {}
// Hex letters + 'p' + non hex.
func fpValue() {}
}
123.testLexingMethodAfterIntLiteral()
0b101.testLexingMethodAfterIntLiteral()
0o123.testLexingMethodAfterIntLiteral()
0x1FFF.testLexingMethodAfterIntLiteral()
123._0()
0b101._0()
0o123._0()
0x1FFF._0()
0x1fff.ffa()
0x1FFF.describe()
0x1FFF.eap()
0x1FFF.fpValue()
var separator1: Int = 1_
var separator2: Int = 1_000
var separator4: Int = 0b1111_0000_
var separator5: Int = 0b1111_0000
var separator6: Int = 0o127_777_
var separator7: Int = 0o127_777
var separator8: Int = 0x12FF_FFFF
var separator9: Int = 0x12FF_FFFF_
//===----------------------------------------------------------------------===//
// Float Literals
//===----------------------------------------------------------------------===//
var fl_a = 0.0
var fl_b: Double = 1.0
var fl_c: Float = 2.0
// FIXME: crummy diagnostic
var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}}
var fl_e: Float = 1.0e42
var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}}
var fl_g: Float = 1.0E+42
var fl_h: Float = 2e-42
var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}}
var fl_j: Float = 0x1p0
var fl_k: Float = 0x1.0p0
var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}}
var fl_m: Float = 0x1.FFFFFEP-2
var fl_n: Float = 0x1.fffffep+2
var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}}
var fl_p: Float = 0x1p // expected-error {{expected a digit in floating point exponent}}
var fl_q: Float = 0x1p+ // expected-error {{expected a digit in floating point exponent}}
var fl_r: Float = 0x1.0fp // expected-error {{expected a digit in floating point exponent}}
var fl_s: Float = 0x1.0fp+ // expected-error {{expected a digit in floating point exponent}}
var fl_t: Float = 0x1.p // expected-error {{value of type 'Int' has no member 'p'}}
var fl_u: Float = 0x1.p2 // expected-error {{value of type 'Int' has no member 'p2'}}
var fl_v: Float = 0x1.p+ // expected-error {{'+' is not a postfix unary operator}}
var fl_w: Float = 0x1.p+2 // expected-error {{value of type 'Int' has no member 'p'}}
var if1: Double = 1.0 + 4 // integer literal ok as double.
var if2: Float = 1.0 + 4 // integer literal ok as float.
var fl_separator1: Double = 1_.2_
var fl_separator2: Double = 1_000.2_
var fl_separator3: Double = 1_000.200_001
var fl_separator4: Double = 1_000.200_001e1_
var fl_separator5: Double = 1_000.200_001e1_000
var fl_separator6: Double = 1_000.200_001e1_000
var fl_separator7: Double = 0x1_.0FFF_p1_
var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001
var fl_bad_separator1: Double = 1e_ // expected-error {{expected a digit in floating point exponent}}
var fl_bad_separator2: Double = 0x1p_ // expected-error {{expected a digit in floating point exponent}} expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} expected-error {{consecutive statements on a line must be separated by ';'}} {{37-37=;}}
//===----------------------------------------------------------------------===//
// String Literals
//===----------------------------------------------------------------------===//
var st_a = ""
var st_b: String = ""
var st_c = "asdfasd // expected-error {{unterminated string literal}}
var st_d = " \t\n\r\"\'\\ " // Valid simple escapes
var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes
var st_u1 = " \u{1} "
var st_u2 = " \u{123} "
var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}}
var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}}
var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}}
var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs.
var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}}
var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}}
var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane
var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}}
func stringliterals(_ d: [String: Int]) {
// rdar://11385385
let x = 4
"Hello \(x+1) world" // expected-warning {{expression of type 'String' is unused}}
"Error: \(x+1"; // expected-error {{unterminated string literal}}
"Error: \(x+1 // expected-error {{unterminated string literal}}
; // expected-error {{';' statements are not allowed}}
// rdar://14050788 [DF] String Interpolations can't contain quotes
"test \("nested")"
"test \("\("doubly nested")")"
"test \(d["hi"])"
"test \("quoted-paren )")"
"test \("quoted-paren (")"
"test \("\\")"
"test \("\n")"
"test \("\")" // expected-error {{unterminated string literal}}
"test \
// expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}}
"test \("\
// expected-error @-1 {{unterminated string literal}}
"test newline \("something" +
"something else")"
// expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}}
// FIXME: bad diagnostics.
// expected-warning @+1 {{initialization of variable 'x2' was never used; consider replacing with assignment to '_' or removing it}}
/* expected-error {{unterminated string literal}} expected-error {{expected ',' separator}} expected-error {{expected ',' separator}} expected-note {{to match this opening '('}} */ var x2 : () = ("hello" + "
; // expected-error {{expected expression in list of expressions}}
} // expected-error {{expected ')' in expression list}}
func testSingleQuoteStringLiterals() {
_ = 'abc' // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}}
_ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}}
_ = 'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\nc"}}
_ = "abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{13-18="def"}}
_ = "abc' // expected-error{{unterminated string literal}}
_ = 'abc" // expected-error{{unterminated string literal}}
_ = "a'c"
_ = 'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab'c"}}
_ = 'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-13="ab\\"c"}}
_ = 'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\"c"}}
_ = 'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-15="ab\\\\\\"c"}}
}
// <rdar://problem/17128913>
var s = ""
s.append(contentsOf: ["x"])
//===----------------------------------------------------------------------===//
// InOut arguments
//===----------------------------------------------------------------------===//
func takesInt(_ x: Int) {}
func takesExplicitInt(_ x: inout Int) { }
func testInOut(_ arg: inout Int) {
var x: Int
takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
takesExplicitInt(&x)
takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}}
var y = &x // expected-error{{'&' can only appear immediately in a call argument list}} \
// expected-error {{type 'inout Int' of variable is not materializable}}
var z = &arg // expected-error{{'&' can only appear immediately in a call argument list}} \
// expected-error {{type 'inout Int' of variable is not materializable}}
takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}}
}
//===----------------------------------------------------------------------===//
// Conversions
//===----------------------------------------------------------------------===//
var pi_f: Float
var pi_d: Double
struct SpecialPi {} // Type with no implicit construction.
var pi_s: SpecialPi
func getPi() -> Float {} // expected-note 3 {{found this candidate}}
func getPi() -> Double {} // expected-note 3 {{found this candidate}}
func getPi() -> SpecialPi {}
enum Empty { }
extension Empty {
init(_ f: Float) { }
}
func conversionTest(_ a: inout Double, b: inout Int) {
var f: Float
var d: Double
a = Double(b)
a = Double(f)
a = Double(d) // no-warning
b = Int(a)
f = Float(b)
var pi_f1 = Float(pi_f)
var pi_d1 = Double(pi_d)
var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}}
var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_s2: SpecialPi = getPi() // no-warning
var float = Float.self
var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_f4 = float.init(pi_f)
var e = Empty(f)
var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}}
var e3 = Empty(Float(d))
}
struct Rule { // expected-note {{'init(target:dependencies:)' declared here}}
var target: String
var dependencies: String
}
var ruleVar: Rule
ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}}
class C {
var x: C?
init(other: C?) { x = other }
func method() {}
}
_ = C(3) // expected-error {{missing argument label 'other:' in call}}
_ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}}
//===----------------------------------------------------------------------===//
// Unary Operators
//===----------------------------------------------------------------------===//
func unaryOps(_ i8: inout Int8, i64: inout Int64) {
i8 = ~i8
i64 += 1
i8 -= 1
Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}}
// <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float
let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}}
var b : Int { get { }}
b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}}
}
//===----------------------------------------------------------------------===//
// Iteration
//===----------------------------------------------------------------------===//
func..<(x: Double, y: Double) -> Double {
return x + y
}
func iterators() {
_ = 0..<42
_ = 0.0..<42.0
}
//===----------------------------------------------------------------------===//
// Magic literal expressions
//===----------------------------------------------------------------------===//
func magic_literals() {
_ = __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}}
_ = __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}}
_ = __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}}
_ = __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}}
_ = #file
_ = #line + #column
var _: UInt8 = #line + #column
}
//===----------------------------------------------------------------------===//
// lvalue processing
//===----------------------------------------------------------------------===//
infix operator +-+=
@discardableResult
func +-+= (x: inout Int, y: Int) -> Int { return 0}
func lvalue_processing() {
var i = 0
i += 1 // obviously ok
var fn = (+-+=)
var n = 42
fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}}
fn(&n, 12) // expected-warning {{result of call is unused, but produces 'Int'}}
n +-+= 12
(+-+=)(&n, 12) // ok.
(+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
}
struct Foo {
func method() {}
}
func test() {
var x = Foo()
// rdar://15708430
(&x).method() // expected-error {{'inout Foo' is not convertible to 'Foo'}}
}
// Unused results.
func unusedExpressionResults() {
// Unused l-value
_ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
// <rdar://problem/20749592> Conditional Optional binding hides compiler error
let optionalc:C? = nil
optionalc?.method() // ok
optionalc?.method // expected-error {{expression resolves to an unused function}}
}
//===----------------------------------------------------------------------===//
// Collection Literals
//===----------------------------------------------------------------------===//
func arrayLiterals() {
let _ = [1,2,3]
let _ : [Int] = []
let _ = [] // expected-error {{empty collection literal requires an explicit type}}
}
func dictionaryLiterals() {
let _ = [1 : "foo",2 : "bar",3 : "baz"]
let _: Dictionary<Int, String> = [:]
let _ = [:] // expected-error {{empty collection literal requires an explicit type}}
}
func invalidDictionaryLiteral() {
// FIXME: lots of unnecessary diagnostics.
var a = [1: ; // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{14-14=,}} {{14-14=,}} expected-error {{expected key expression in dictionary literal}} expected-error {{expected ']' in container literal expression}} expected-note {{to match this opening '['}}
var b = [1: ;] // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{14-14=,}} {{14-14=,}} expected-error {{expected key expression in dictionary literal}}
var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error 2{{expected ',' separator}} {{20-20=,}} {{20-20=,}}
var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{21-21=,}}
var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}}
var f = [1: "one", 2 ;] // expected-error 2{{expected ',' separator}} {{23-23=,}} {{23-23=,}} expected-error 1{{expected key expression in dictionary literal}} expected-error {{expected ':' in dictionary literal}}
var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{24-24=,}} {{24-24=,}} expected-error {{expected key expression in dictionary literal}}
}
// FIXME: The issue here is a type compatibility problem, there is no ambiguity.
[4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}}
[4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}}
//===----------------------------------------------------------------------===//
// nil/metatype comparisons
//===----------------------------------------------------------------------===//
_ = Int.self == nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}}
_ = nil == Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}}
_ = Int.self != nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}}
_ = nil != Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}}
// <rdar://problem/19032294> Disallow postfix ? when not chaining
func testOptionalChaining(_ a : Int?, b : Int!, c : Int??) {
_ = a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{8-9=}}
_ = a?.customMirror
_ = b? // expected-error {{'?' must be followed by a call, member lookup, or subscript}}
_ = b?.customMirror
var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}}
}
// <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence
func testNilCoalescePrecedence(cond: Bool, a: Int?, r: CountableClosedRange<Int>?) {
// ?? should have higher precedence than logical operators like || and comparisons.
if cond || (a ?? 42 > 0) {} // Ok.
if (cond || a) ?? 42 > 0 {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}}
if (cond || a) ?? (42 > 0) {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}}
if cond || a ?? 42 > 0 {} // Parses as the first one, not the others.
// ?? should have lower precedence than range and arithmetic operators.
let r1 = r ?? (0...42) // ok
let r2 = (r ?? 0)...42 // not ok: expected-error {{binary operator '??' cannot be applied to operands of type 'CountableClosedRange<Int>?' and 'Int'}}
// expected-note @-1 {{overloads for '??' exist with these partially matching parameter lists:}}
let r3 = r ?? 0...42 // parses as the first one, not the second.
// <rdar://problem/27457457> [Type checker] Diagnose unsavory optional injections
// Accidental optional injection for ??.
let i = 42
_ = i ?? 17 // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is never used}} {{9-15=}}
}
// <rdar://problem/19772570> Parsing of as and ?? regressed
func testOptionalTypeParsing(_ a : AnyObject) -> String {
return a as? String ?? "default name string here"
}
func testParenExprInTheWay() {
let x = 42
if x & 4.0 {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}}
if (x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}}
if !(x & 4.0) {} // expected-error {{no '&' candidates produce the expected contextual result type 'Bool'}}
//expected-note @-1 {{overloads for '&' exist with these result types: UInt8, Int8, UInt16, Int16, UInt32, Int32, UInt64, Int64, UInt, Int, T, Self}}
if x & x {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization
public struct TestPropMethodOverloadGroup {
public typealias Hello = String
public let apply:(Hello) -> Int
public func apply(_ input:Hello) -> Int {
return apply(input)
}
}
// <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler
func inoutTests(_ arr: inout Int) {
var x = 1, y = 2
(true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}}
// expected-warning @-1 {{expression of type 'inout Int' is unused}}
let a = (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}}
// expected-error @-1 {{type 'inout Int' of variable is not materializable}}
inoutTests(true ? &x : &y); // expected-error 2 {{'&' can only appear immediately in a call argument list}}
&_ // expected-error {{expression type 'inout _' is ambiguous without more context}}
inoutTests((&x)) // expected-error {{'&' can only appear immediately in a call argument list}}
inoutTests(&x)
// <rdar://problem/17489894> inout not rejected as operand to assignment operator
&x += y // expected-error {{'&' can only appear immediately in a call argument list}}
// <rdar://problem/23249098>
func takeAny(_ x: Any) {}
takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeManyAny(_ x: Any...) {}
takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeIntAndAny(_ x: Int, _ y: Any) {}
takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
}
// <rdar://problem/20802757> Compiler crash in default argument & inout expr
var g20802757 = 2
func r20802757(_ z: inout Int = &g20802757) { // expected-error {{'&' can only appear immediately in a call argument list}}
print(z)
}
_ = _.foo // expected-error {{type of expression is ambiguous without more context}}
// <rdar://problem/22211854> wrong arg list crashing sourcekit
func r22211854() {
func f(_ x: Int, _ y: Int, _ z: String = "") {} // expected-note 2 {{'f' declared here}}
func g<T>(_ x: T, _ y: T, _ z: String = "") {} // expected-note 2 {{'g' declared here}}
f(1) // expected-error{{missing argument for parameter #2 in call}}
g(1) // expected-error{{missing argument for parameter #2 in call}}
func h() -> Int { return 1 }
f(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
g(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
}
// <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument
func r22348394() {
func f(x: Int = 0) { }
f(Int(3)) // expected-error{{missing argument label 'x:' in call}}
}
// <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit
protocol P { var y: String? { get } }
func r23185177(_ x: P?) -> [String] {
return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}}
}
// <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0
func r22913570() {
func f(_ from: Int = 0, to: Int) {} // expected-note {{'f(_:to:)' declared here}}
f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}}
}
// <rdar://problem/23708702> Emit deprecation warnings for ++/-- in Swift 2.2
func swift22_deprecation_increment_decrement() {
var i = 0
var f = 1.0
i++ // expected-error {{'++' is unavailable}} {{4-6= += 1}}
--i // expected-error {{'--' is unavailable}} {{3-5=}} {{6-6= -= 1}}
_ = i++ // expected-error {{'++' is unavailable}}
++f // expected-error {{'++' is unavailable}} {{3-5=}} {{6-6= += 1}}
f-- // expected-error {{'--' is unavailable}} {{4-6= -= 1}}
_ = f-- // expected-error {{'--' is unavailable}} {{none}}
// <rdar://problem/24530312> Swift ++fix-it produces bad code in nested expressions
// This should not get a fixit hint.
var j = 2
i = ++j // expected-error {{'++' is unavailable}} {{none}}
}
// SR-628 mixing lvalues and rvalues in tuple expression
var x = 0
var y = 1
let _ = (x, x + 1).0
let _ = (x, 3).1
(x,y) = (2,3)
(x,4) = (1,2) // expected-error {{cannot assign to value: literals are not mutable}}
(x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}}
x = (x,(3,y)).1.1
// SE-0101 sizeof family functions are reconfigured into MemoryLayout
protocol Pse0101 {
associatedtype Value
func getIt() -> Value
}
class Cse0101<U> {
typealias T = U
var val: U { fatalError() }
}
func se0101<P: Pse0101>(x: Cse0101<P>) {
// Note: The first case is actually not allowed, but it is very common and can be compiled currently.
_ = sizeof(P) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-16=>.size}} {{none}}
// expected-warning@-1 {{missing '.self' for reference to metatype of type 'P'}}
_ = sizeof(P.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}}
_ = sizeof(P.Value.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{21-27=>.size}} {{none}}
_ = sizeof(Cse0101<P>.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{24-30=>.size}} {{none}}
_ = alignof(Cse0101<P>.T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{27-33=>.alignment}} {{none}}
_ = strideof(P.Type.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{22-28=>.stride}} {{none}}
_ = sizeof(type(of: x)) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-26=MemoryLayout<Cse0101<P>>.size}} {{none}}
}
| 39.694196 | 314 | 0.618231 |
3352c9d7562da16f012c3d99af32875260a416ba | 803 | //
// ItemView.swift
// SwiftUICarousel
//
// Created by Chau Chin Yiu on 19.01.21.
//
import SwiftUI
public struct ItemView<Content: View>: View {
@EnvironmentObject var uiState: UIStateModel
let cardWidth: CGFloat
let cardHeight: CGFloat
var _id: Int
var content: Content
public init(
_id: Int,
spacing: CGFloat,
displayWidthOfSideCards: CGFloat,
cardHeight: CGFloat,
@ViewBuilder _ content: () -> Content
) {
self.content = content()
self.cardWidth = UIScreen.main.bounds.width - (displayWidthOfSideCards*2) - (spacing*2) //279
self.cardHeight = cardHeight
self._id = _id
}
public var body: some View {
content
.frame(width: cardWidth, alignment: .center)
}
}
| 22.305556 | 101 | 0.617684 |
75078059e8e414c3fb16c10439dd468dbd2bfaea | 6,346 | //
// GeneralRenderModel.swift
// CavernSeer
//
// Created by Samuel Grush on 6/13/21.
// Copyright © 2021 Samuel K. Grush. All rights reserved.
//
import Foundation
import SceneKit
import SwiftUI
import Combine
class GeneralRenderModel : ObservableObject {
static let cameraNodeName = "the-camera"
static let ambientLightNodeName = "ambient-light"
static private let nodesToSkipOnUpdate: [String?] = [cameraNodeName, ambientLightNodeName]
/// triggers changes in observers and indicates that changes have occurred
@Published
public private(set) var shouldUpdateView = false
/// indicates that the sceneNodes have changed
public private(set) var shouldUpdateNodes = false
public private(set) var initialUpdate = true
public private(set) weak var scan: ScanFile? = nil
public private(set) var offset: SCNVector3? = nil
public private(set) var sceneNodes: [SCNNode] = []
public private(set) var doubleSided = false
// settings
public private(set) var color: UIColor?
public private(set) var ambientColor: UIColor?
public private(set) var quiltMesh: Bool = false
public private(set) var interactionMode3d: SCNInteractionMode = .orbitAngleMapping
public private(set) var lengthPref: LengthPreference = .CustomaryFoot
private weak var settings: SettingsStore? = nil
private var settingsCancelBag = Set<AnyCancellable>()
init() {
}
func dismantle() {
sceneNodes.removeAll()
settingsCancelBag.removeAll()
}
func viewUpdateHandler(scnView: SCNView) {
if self.shouldUpdateView {
if let ambientColor = self.ambientColor {
scnView.scene?.rootNode
.childNode(
withName: Self.ambientLightNodeName, recursively: false
)?.light?.color = ambientColor
}
if self.shouldUpdateNodes {
if let scene = scnView.scene {
scnView.scene?.rootNode
.childNodes { (node, _) in
!Self.nodesToSkipOnUpdate.contains(node.name)
}
.forEach { $0.removeFromParentNode() }
if quiltMesh {
sceneNodes.forEach {
$0.geometry?.firstMaterial?.diffuse.contents =
UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)
}
} else if let color = color {
sceneNodes.forEach {
$0.geometry?.firstMaterial?.diffuse.contents = color
}
}
sceneNodes.forEach { scene.rootNode.addChildNode($0) }
doneUpdating()
}
} else {
self.doneUpdating()
}
}
}
func doneUpdating() {
self.shouldUpdateNodes = false
self.shouldUpdateView = false
}
func doubleSidedButton() -> some View {
Button(action: {
[weak self] in
self!.doubleSided.toggle()
self!.sceneNodes.forEach {
[unowned self] in
$0.geometry?.firstMaterial?.isDoubleSided = self!.doubleSided
}
self!.shouldUpdateNodes = true
self!.shouldUpdateView = true
}) {
[unowned self] in
Image(
systemName: self.doubleSided
? "square.on.square"
: "square.on.square.dashed"
)
}
}
func setSettings(_ settings: SettingsStore) {
self.settings = settings
self.settingsCancelBag.removeAll()
settings.$ColorMesh
.sink {
[unowned self] color in
let cgColor = color?.cgColor
self.color = (cgColor != nil && cgColor!.alpha > 0.05)
? UIColor(cgColor: cgColor!)
: nil
self.updateColor()
}
.store(in: &settingsCancelBag)
settings.$ColorLightAmbient
.sink {
[unowned self] color in
self.ambientColor = color.map { UIColor($0) }
self.updateColor()
}
.store(in: &settingsCancelBag)
settings.$ColorMeshQuilt
.sink {
[unowned self] doQuiltMesh in
self.quiltMesh = doQuiltMesh ?? self.quiltMesh
self.updateColor()
}
.store(in: &settingsCancelBag)
settings.$InteractionMode3d
.sink {
[unowned self] mode in
self.interactionMode3d = mode ?? self.interactionMode3d
self.shouldUpdateView = true
}
.store(in: &settingsCancelBag)
settings.$UnitsLength
.sink {
[unowned self] pref in
self.lengthPref = pref ?? self.lengthPref
self.updateNodes()
}
.store(in: &settingsCancelBag)
}
func updateScanAndSettings(scan: ScanFile, settings: SettingsStore) {
self.scan = scan
self.offset = SCNVector3Make(-scan.center.x, -scan.center.y, -scan.center.z)
self.setSettings(settings)
self.updateNodes()
}
private func updateNodes() {
if scan != nil {
sceneNodes = scan!.toSCNNodes(
color: color,
quilt: quiltMesh,
lengthPref: lengthPref,
doubleSided: doubleSided
)
self.shouldUpdateNodes = true
self.shouldUpdateView = true
}
}
private func updateColor() {
// if quiltMesh {
// sceneNodes.forEach {
// $0.geometry?.firstMaterial?.diffuse.contents = UIColor(
// hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1
// )
// }
// } else if color != nil {
// sceneNodes.forEach {
// $0.geometry?.firstMaterial?.diffuse.contents = color
// }
// }
shouldUpdateNodes = true
shouldUpdateView = true
}
}
| 32.050505 | 104 | 0.53388 |
01439df35afd0dc61a7698bf3d99be62d4136343 | 398 | //
// CreditsViewController.swift
// GIFt-ed
//
// Created by Manish Singh on 12/8/20.
//
import Cocoa
class CreditsViewController: NSViewController {
static var viewController: CreditsViewController {
let vc = CreditsViewController(nibName: "CreditsViewController", bundle: nil)
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 18.090909 | 85 | 0.668342 |
032fd8e17a1b6db38e2cc15ec629b87510c60614 | 979 | //
// SwiftTestTests.swift
// SwiftTestTests
//
// Created by Jiabin wang on 2018/4/18.
// Copyright © 2018年 Jiabin wang. All rights reserved.
//
import XCTest
@testable import SwiftTest
class SwiftTestTests: 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.459459 | 111 | 0.635342 |
d9f463cce6eae9783e696f22428c62053d4877c6 | 903 | //___FILEHEADER___
import napkin
protocol ___VARIABLE_productName___Interactable: Interactable {
var router: ___VARIABLE_productName___Routing? { get set }
var listener: ___VARIABLE_productName___Listener? { get set }
}
protocol ___VARIABLE_productName___ViewControllable: ViewControllable {
// TODO: Declare methods the router invokes to manipulate the view hierarchy.
}
final class ___VARIABLE_productName___Router: ViewableRouter<___VARIABLE_productName___Interactable, ___VARIABLE_productName___ViewControllable>, ___VARIABLE_productName___Routing {
// TODO: Constructor inject child builder protocols to allow building children.
override init(interactor: ___VARIABLE_productName___Interactable, viewController: ___VARIABLE_productName___ViewControllable) {
super.init(interactor: interactor, viewController: viewController)
interactor.router = self
}
}
| 41.045455 | 181 | 0.819491 |
4614d13f43ff4bbf7e8ea8ffcc6248a641cefb1d | 2,177 | //
// Examen.swift
// Poliplanner
//
// Created by Mateo Fidabel on 2020-11-26.
//
import Foundation
import RealmSwift
/// Modelo que representa un examen de alguna sección
class Examen: Object, Identifiable, Calendarizable, CascadingDeletable {
// MARK: Propiedades
/// Identificador del examen
@objc dynamic var id = UUID().uuidString
/// Tipo de examen en String.
/// Tratar de no editar directamente y utlizar en su sustitución `Examen.tipoEnum`
@objc dynamic var tipo: String = TipoExamen.evaluacion.rawValue
/// Fecha del examen
@objc dynamic var fecha: Date = Date()
/// Aula del examen
@objc dynamic var aula: String = ""
/// Revisión del examen
@objc dynamic var revision: Revision?
/// Secciones al que este examen pertenece.
/// En teoría solo debe haber uno pero se deja la posibilidad de unir examenes que
/// coinciden de distintas secciones de la misma materia
let secciones = LinkingObjects(fromType: Seccion.self, property: "examenes")
/// Sección a la cual pertenece este examen
var seccion: Seccion? {
secciones.first
}
/// Puente entre enumerador de tipo de examen a atributo `Examen.tipo`.
var tipoEnum: TipoExamen {
get {
return TipoExamen(rawValue: tipo)!
}
set {
tipo = newValue.rawValue
}
}
// MARK: Protocolo Calendarizable
/// Evento que se mostrará en el calendario
var eventoCalendario: InfoEventoCalendario {
InfoEventoCalendario(fecha: fecha,
titulo: tipoEnum.nombreLindo(),
descripcion: seccion?.asignatura!.nombre ?? "",
aula: aula)
}
// MARK: Protocolo CascadingDeletable
/// Propiedades que se eliminarán si se elimina este objeto
static var propertiesToCascadeDelete: [String] = ["revision"]
// MARK: Métodos
/// Función auxiliar que permite a `Realm` identificar los examenes por su id en la base de datos.
override static func primaryKey() -> String? {
return "id"
}
}
| 29.821918 | 102 | 0.626091 |
0828f6f84dfb657e986a722f14a1fd99dfb607cf | 2,166 | //
// GlucoseRangeOverrideTableViewCell.swift
// LoopKit
//
// Created by Nate Racklyeft on 7/13/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
protocol GlucoseAlarmInputCellDelegate: class {
func glucoseAlarmInputCellDidUpdateValue(_ cell: GlucoseAlarmInputCell, value: Double)
}
class GlucoseAlarmInputCell: UITableViewCell, UITextFieldDelegate {
public enum GlucoseAlarmType: String {
case low = "Low"
case high = "High"
}
weak var delegate: GlucoseAlarmInputCellDelegate?
var minValue: Double = 0 {
didSet {
minValueTextField.text = valueNumberFormatter.string(from: NSNumber(value: minValue))
}
}
public var tag2: String?
lazy var valueNumberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 1
return formatter
}()
var alarmType: GlucoseAlarmType? {
didSet {
titleLabel.text = alarmType?.rawValue ?? "invalid"
}
}
var unitString: String? {
get {
return unitLabel.text
}
set {
unitLabel.text = newValue
}
}
// MARK: Outlets
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var unitLabel: UILabel!
@IBOutlet weak var minValueTextField: UITextField!
// MARK: - UITextFieldDelegate
func textFieldDidBeginEditing(_ textField: UITextField) {
print("textfield did begin editing")
DispatchQueue.main.async {
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
let value = valueNumberFormatter.number(from: textField.text ?? "")?.doubleValue ?? 0
switch textField {
case minValueTextField:
minValue = value
default:
break
}
delegate?.glucoseAlarmInputCellDidUpdateValue(self, value: value)
}
}
| 24.896552 | 127 | 0.649584 |
e87fb79d383283a03ec812dc85f78ea0a68ac932 | 2,833 | //
// FPSHelper.swift
// PerformanceMonitor
//
// Created by roy.cao on 2019/8/24.
// Copyright © 2019 roy. All rights reserved.
//
import Foundation
@objc public protocol FPSMonitorDelegate: class {
func fpsMonitor(with monitor: FPSMonitor, fps: Double)
}
public class FPSMonitor: NSObject {
class WeakProxy {
weak var target: FPSMonitor?
init(target: FPSMonitor) {
self.target = target
}
@objc func tick(link: CADisplayLink) {
target?.tick(link: link)
}
}
enum Constants {
static let timeInterval: TimeInterval = 1.0
}
public weak var delegate: FPSMonitorDelegate?
private var link: CADisplayLink?
private var count: Int = 0
private var lastTime: TimeInterval = 0.0
public override init() {
super.init()
link = CADisplayLink(target: WeakProxy.init(target: self), selector: #selector(WeakProxy.tick(link:)))
link?.isPaused = true
link?.add(to: RunLoop.main, forMode: .common)
setupObservers()
}
public func start() {
link?.isPaused = false
}
public func stop() {
link?.isPaused = true
}
func setupObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillResignActiveNotification),
name: UIApplication.willResignActiveNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActiveNotification),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
deinit {
link?.invalidate()
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
func tick(link: CADisplayLink) {
count += 1
let timePassed = link.timestamp - self.lastTime
guard timePassed >= Constants.timeInterval else {
return
}
self.lastTime = link.timestamp
let fps = Double(self.count) / timePassed
self.count = 0
self.delegate?.fpsMonitor(with: self, fps: fps)
}
}
private extension FPSMonitor {
@objc func applicationWillResignActiveNotification() {
stop()
}
@objc func applicationDidBecomeActiveNotification() {
start()
}
}
| 28.049505 | 118 | 0.567243 |
fc10d642b8b7ce587ed3dc00439cee49d3958edc | 3,412 | import UIKit
class VDrawProjectSizeDimension:UIView
{
private(set) weak var textField:UITextField!
private let kLabelHeight:CGFloat = 45
private let kLabelBottom:CGFloat = -5
private let kFieldMargin:CGFloat = 19
private let kFieldTop:CGFloat = 25
private let kCornerRadius:CGFloat = 4
private let kBackgroundMargin:CGFloat = 9
private let kBorderWidth:CGFloat = 1
init(title:String)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = UIFont.regular(size:16)
label.textColor = UIColor.black
label.text = title
let textField:UITextField = UITextField()
textField.borderStyle = UITextBorderStyle.none
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clipsToBounds = true
textField.backgroundColor = UIColor.clear
textField.placeholder = NSLocalizedString("VDrawProjectSizeDimension_placeholder", comment:"")
textField.keyboardType = UIKeyboardType.numbersAndPunctuation
textField.keyboardAppearance = UIKeyboardAppearance.light
textField.spellCheckingType = UITextSpellCheckingType.no
textField.autocorrectionType = UITextAutocorrectionType.no
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.clearButtonMode = UITextFieldViewMode.never
textField.returnKeyType = UIReturnKeyType.next
textField.tintColor = UIColor.black
textField.textColor = UIColor.black
textField.font = UIFont.numeric(size:20)
self.textField = textField
let background:UIView = UIView()
background.backgroundColor = UIColor.white
background.translatesAutoresizingMaskIntoConstraints = false
background.clipsToBounds = true
background.isUserInteractionEnabled = false
background.layer.cornerRadius = kCornerRadius
background.layer.borderColor = UIColor(white:0, alpha:0.1).cgColor
background.layer.borderWidth = kBorderWidth
addSubview(label)
addSubview(background)
addSubview(textField)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self,
constant:kLabelBottom)
NSLayoutConstraint.height(
view:label,
constant:kLabelHeight)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self)
NSLayoutConstraint.topToTop(
view:textField,
toView:self,
constant:kFieldTop)
NSLayoutConstraint.bottomToTop(
view:textField,
toView:label)
NSLayoutConstraint.equalsHorizontal(
view:textField,
toView:self,
margin:kFieldMargin)
NSLayoutConstraint.equals(
view:textField,
toView:background,
margin:kBackgroundMargin)
}
required init?(coder:NSCoder)
{
return nil
}
}
| 35.915789 | 102 | 0.666764 |
160c372fcb33c233822b9bf011aec6f7eb358f9e | 1,191 | /// Represents an address
public struct Address {
/// Address in data format
public let data: Data
/// Address in string format, EIP55 encoded
public let string: String
public init(data: Data, string: String) {
self.data = data
self.string = string
}
}
extension Address {
public init(data: Data) {
self.data = data
self.string = "0x" + EIP55.encode(data)
}
public init(string: String) {
self.data = Data(hex: string.stripHexPrefix())
self.string = string
}
}
extension Address: Codable {
private enum CodingKeys: String, CodingKey {
case data
case string
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
data = try container.decode(Data.self, forKey: .data)
string = try container.decode(String.self, forKey: .string)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(data, forKey: .data)
try container.encode(string, forKey: .string)
}
}
| 25.891304 | 71 | 0.617968 |
79f053c817323a07b3a9ff6fa391463b0b77bf68 | 499 | //
// AppDelegate.swift
// 5623_07_code
//
// Created by Stuart Grimshaw on 25/10/16.
// Copyright © 2016 Stuart Grimshaw. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 18.481481 | 69 | 0.739479 |
1a4d4c2b58075c89a2ec1e370d6d741ef9c1f4b7 | 1,677 | //
// UICollectionViewExtensions.swift
// Swan
//
// Created by Antti Laitala on 03/06/15.
//
//
import Foundation
import UIKit
public extension UICollectionView {
final func registerCell<T: UICollectionViewCell>(_ cell: T.Type) {
self.register(cell, forCellWithReuseIdentifier: NSStringFromClass(cell))
}
final func registerSectionHeader<T: UICollectionReusableView>(_ header: T.Type) {
self.register(header, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: NSStringFromClass(header))
}
final func registerSectionFooter<T: UICollectionReusableView>(_ footer: T.Type) {
self.register(footer, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: NSStringFromClass(footer))
}
final func dequeueCell<T: UICollectionViewCell>(_ cell: T.Type, forIndexPath indexPath: IndexPath!) -> T {
return self.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(cell), for: indexPath) as! T
}
final func dequeueSectionHeader<T: UICollectionReusableView>(_ header: T.Type, forIndexPath indexPath: IndexPath!) -> T {
return self.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier:NSStringFromClass(header), for: indexPath) as! T
}
final func dequeueSectionFooter<T: UICollectionReusableView>(_ footer: T.Type, forIndexPath indexPath: IndexPath!) -> T {
return self.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier:NSStringFromClass(footer), for: indexPath) as! T
}
}
| 43 | 172 | 0.759094 |
901e931d0d3c865e976023f805fb82ab2653c0cc | 5,082 | //
// ArchieveTasks.swift
// StreakTasks
//
// Created by Stefan Stevanovic on 3/30/19.
// Copyright © 2019 Joey Tawadrous. All rights reserved.
//
import UIKit
import CoreData
class ArchieveTasks:UIViewController, UITableViewDelegate, UITableViewDataSource {
var tasks = [AnyObject]()
var selectedGoal = String()
@IBOutlet weak var tableView: UITableView!
/* MARK: Init
/////////////////////////////////////////// */
override func viewWillAppear(_ animated: Bool) {
refresh();
// Styling
Utils.insertGradientIntoView(viewController: self)
self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
// Observer for every notification received
NotificationCenter.default.addObserver(self, selector: #selector(Tasks.backgoundNofification(_:)), name: UIApplication.willEnterForegroundNotification, object: nil);
}
@objc func backgoundNofification(_ noftification:Notification){
refresh()
}
func refresh() {
selectedGoal = Utils.string(key: Constants.LocalData.SELECTED_GOAL)
//self.title = selectedGoal
tasks = CoreData.fetchCoreDataObject(Constants.CoreData.ARCHIEVE_TASK, predicate: selectedGoal)
tasks = tasks.reversed() // newest first
self.tableView.reloadData()
}
override var prefersStatusBarHidden: Bool {
return true
}
/* MARK: Table Functionality
/////////////////////////////////////////// */
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: TasksTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell") as? TasksTableViewCell
if cell == nil {
cell = TasksTableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "cell")
}
let tasks = self.tasks[indexPath.row]
let type = tasks.value(forKey: Constants.CoreData.TYPE) as! String?
// Style
cell!.selectionStyle = .none
cell.reasonLabel!.text = tasks.value(forKey: Constants.CoreData.REASON) as! String?
cell.thumbnailImageView!.image = UIImage(named: type!)
cell.thumbnailImageView!.image = cell.thumbnailImageView!.image!.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
cell.thumbnailImageView!.tintColor = UIColor.white
cell.updateConstraints()
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Set task in defaults (so we can get task details it later)
Utils.set(key: Constants.LocalData.SELECTED_TASK_INDEX, value: NSInteger(indexPath.row))
// Show task view
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let taskView = storyBoard.instantiateViewController(withIdentifier: Constants.Views.TASK) as! Task
self.show(taskView as UIViewController, sender: taskView)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 74.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let emptyView = UIView(frame: CGRect(x:0, y:0, width:self.view.bounds.size.width, height:self.view.bounds.size.height))
if tasks.count == 0 {
let emptyImageView = UIImageView(frame: CGRect(x:0, y:0, width:150, height:150))
emptyImageView.center = CGPoint(x:self.view.frame.width / 2, y: self.view.bounds.size.height * 0.30)
let emptyImage = Utils.imageResize(UIImage(named: "Fitness")!, sizeChange: CGSize(width: 150, height: 150)).withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
emptyImageView.image = emptyImage
emptyImageView.tintColor = UIColor.white
emptyView.addSubview(emptyImageView)
let emptyLabel = UILabel(frame: CGRect(x:0, y:0, width:self.view.bounds.size.width - 100, height:self.view.bounds.size.height))
emptyLabel.center = CGPoint(x:self.view.frame.width / 2, y: self.view.bounds.size.height * 0.53)
emptyLabel.text = "Now that you have created a goal, what will it take to achieve it? Create a task now!"
emptyLabel.font = UIFont.GothamProRegular(size: 15.0)
emptyLabel.textAlignment = NSTextAlignment.center
emptyLabel.textColor = UIColor.white
emptyLabel.numberOfLines = 5
emptyView.addSubview(emptyLabel)
self.tableView.backgroundView = emptyView
return 0
}
else {
self.tableView.backgroundView = emptyView
return tasks.count
}
}
}
| 41.317073 | 175 | 0.644038 |
1a3dd12fecf6de8d7b2e4301a3fe27da289650ad | 1,321 | //
// StringFile.swift
// StringsTT
//
// Created by EvenLin on 2022/3/29.
//
import Cocoa
struct StringFile {
var path: String? {
didSet {
parseFile()
}
}
var dic : [String: String] = [:]
private(set) var keys: [String] = []
private mutating func parseFile() {
guard let path = path else {
return
}
guard FileManager.default.fileExists(atPath: path) else {
print("文件不存在\(path)")
return
}
let file = File(path: path)
do {
let mapString = try file.read()
dic = Parser.convertToDic(string: mapString)
keys = (dic as NSDictionary).allKeys as! [String]
} catch let error {
print(error.localizedDescription)
}
}
func save() {
guard let outputString = Parser.convertToString(dic: dic) else {
return
}
var outputPath = self.path
if outputPath == nil {
outputPath = Parser.outputPath(prefix: Date().timeString("yyyyMMddHHmm"))
}
do {
try File(path: outputPath!).write(contents: outputString)
} catch let error {
print(error.localizedDescription)
}
}
}
| 22.775862 | 85 | 0.510977 |
9c3d11e6bac16db49a2205dc97d27bd8da89a81f | 690 | //
// ViewController.swift
// YHFPSStatus
//
// Created by apple on 23/3/17.
// Copyright © 2017年 于欢. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLb: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.titleLb.layer.cornerRadius = 3
self.titleLb.layer.masksToBounds = true
}
@IBAction func pushBtn(_ sender: Any) {
self.navigationController?.pushViewController(UIViewController.init(), animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 22.258065 | 94 | 0.673913 |
6ae0433ed403757c76c663236bfe8955d11e34a5 | 6,428 | //
// TribeLinkPreviewView.swift
// sphinx
//
// Created by Tomas Timinskas on 03/12/2020.
// Copyright © 2020 Sphinx. All rights reserved.
//
import UIKit
protocol LinkPreviewDelegate: class {
func didTapOnTribeButton()
func didTapOnContactButton()
}
class TribeLinkPreviewView: LinkPreviewBubbleView {
weak var delegate: LinkPreviewDelegate?
@IBOutlet private var contentView: UIView!
@IBOutlet weak var tribeImageView: UIImageView!
@IBOutlet weak var tribeNameLabel: UILabel!
@IBOutlet weak var tribeDescriptionTextView: UITextView!
@IBOutlet weak var containerButton: UIButton!
@IBOutlet weak var tribeButtonContainer: UIView!
var messageId: Int = -1
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
Bundle.main.loadNibNamed("TribeLinkPreviewView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
tribeDescriptionTextView.textContainer.lineFragmentPadding = 0
tribeDescriptionTextView.textContainerInset = .zero
tribeDescriptionTextView.contentInset = .zero
tribeDescriptionTextView.clipsToBounds = true
tribeButtonContainer.layer.cornerRadius = 3
tribeImageView.layer.cornerRadius = 3
tribeImageView.clipsToBounds = true
tribeImageView.layer.borderWidth = 1
tribeImageView.layer.borderColor = UIColor.Sphinx.SecondaryText.withAlphaComponent(0.5).resolvedCGColor(with: self)
}
func configurePreview(messageRow: TransactionMessageRow, delegate: LinkPreviewDelegate, doneCompletion: @escaping (Int) -> ()) {
messageId = messageRow.transactionMessage.id
let link = messageRow.getMessageContent().stringFirstTribeLink
loadTribeDetails(link: link, completion: { tribeInfo in
if let tribeInfo = tribeInfo {
messageRow.transactionMessage.tribeInfo = tribeInfo
doneCompletion(self.messageId)
}
})
}
func configureView(messageRow: TransactionMessageRow, tribeInfo: GroupsManager.TribeInfo?, delegate: LinkPreviewDelegate) {
guard let tribeInfo = tribeInfo else {
return
}
self.delegate = delegate
configureColors(messageRow: messageRow)
addBubble(messageRow: messageRow)
tribeButtonContainer?.isHidden = messageRow.isJoinedTribeLink(uuid: tribeInfo.uuid)
tribeNameLabel.text = tribeInfo.name ?? "title.not.available".localized
tribeDescriptionTextView.text = tribeInfo.description ?? "description.not.available".localized
loadImage(tribeInfo: tribeInfo)
}
func configureColors(messageRow: TransactionMessageRow) {
let incoming = messageRow.isIncoming()
let color = incoming ? UIColor.Sphinx.SecondaryText : UIColor.Sphinx.SecondaryTextSent
tribeDescriptionTextView.textColor = color
tribeImageView.tintColor = color
tribeImageView.layer.borderColor = color.resolvedCGColor(with: self)
let buttonColor = incoming ? UIColor.Sphinx.LinkReceivedButtonColor : UIColor.Sphinx.LinkSentButtonColor
tribeButtonContainer.backgroundColor = buttonColor
}
func loadImage(tribeInfo: GroupsManager.TribeInfo?) {
guard let tribeInfo = tribeInfo, let imageUrlString = tribeInfo.img, let imageUrl = URL(string: imageUrlString) else {
tribeImageView.contentMode = .center
tribeImageView.image = UIImage(named: "tribePlaceholder")
tribeImageView.layer.borderWidth = 1
return
}
MediaLoader.asyncLoadImage(imageView: tribeImageView, nsUrl: imageUrl, placeHolderImage: UIImage(named: "tribePlaceholder"), completion: { image in
MediaLoader.storeImageInCache(img: image, url: imageUrlString)
self.tribeImageView.image = image
self.tribeImageView.layer.borderWidth = 0
self.tribeImageView.contentMode = .scaleAspectFill
}, errorCompletion: { _ in
self.tribeImageView.image = UIImage(named: "tribePlaceholder")
self.tribeImageView.contentMode = .center
})
}
func loadTribeDetails(link: String, completion: @escaping (GroupsManager.TribeInfo?) -> ()) {
if var tribeInfo = GroupsManager.sharedInstance.getGroupInfo(query: link) {
API.sharedInstance.getTribeInfo(host: tribeInfo.host, uuid: tribeInfo.uuid, callback: { groupInfo in
GroupsManager.sharedInstance.update(tribeInfo: &tribeInfo, from: groupInfo)
completion(tribeInfo)
}, errorCallback: {
completion(nil)
})
return
}
completion(nil)
}
func addBubble(messageRow: TransactionMessageRow) {
let width = getViewWidth(messageRow: messageRow)
let height = CommonChatTableViewCell.getLinkPreviewHeight(messageRow: messageRow) - Constants.kBubbleBottomMargin
let bubbleSize = CGSize(width: width, height: height)
let consecutiveBubble = MessageBubbleView.ConsecutiveBubbles(previousBubble: true, nextBubble: false)
let existingObject = messageRow.isJoinedTribeLink()
if messageRow.isIncoming() {
self.showIncomingLinkBubble(contentView: contentView, messageRow: messageRow, size: bubbleSize, consecutiveBubble: consecutiveBubble, bubbleMargin: 0, existingObject: existingObject)
} else {
self.showOutgoingLinkBubble(contentView: contentView, messageRow: messageRow, size: bubbleSize, consecutiveBubble: consecutiveBubble, bubbleMargin: 0, existingObject: existingObject)
}
self.contentView.bringSubviewToFront(tribeImageView)
self.contentView.bringSubviewToFront(tribeNameLabel)
self.contentView.bringSubviewToFront(tribeDescriptionTextView)
self.contentView.bringSubviewToFront(tribeButtonContainer)
self.contentView.bringSubviewToFront(containerButton)
}
@IBAction func seeTribeButtonTouched() {
delegate?.didTapOnTribeButton()
}
}
| 41.74026 | 194 | 0.689328 |
dbfdb4e209a39334e5707d2d2cf07c1d16a06082 | 1,896 | /*
**********************************************************************************
| |
| Copyright 2021. Huawei Technologies Co., Ltd. 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 SwiftUI
struct ConversationCell: View {
let conservation: Conversation
var body: some View {
VStack(alignment: .leading) {
HStack(spacing: 12) {
ProfileImageView(imageUrl: conservation.user.profileImageUrl, width: 56, height: 56)
VStack(alignment: .leading, spacing: 4) {
Text(conservation.user.username )
.font(.system(size: 14, weight: .semibold))
Text(conservation.message.message.text )
.font(.system(size: 14))
.lineLimit(2)
.frame(height: 35)
.fixedSize(horizontal: false, vertical: true)
}
.foregroundColor(Color(.label))
}
.padding(.horizontal)
Divider()
}
}
}
//struct ConversationCell_Previews: PreviewProvider {
// static var previews: some View {
// ConversationCell(message: "1")
// }
//}
| 33.263158 | 100 | 0.526371 |
28bb9ec376141676472d39c60519bc4f5a09d1a9 | 3,391 | //
// ViewController.swift
// Calculator
//
// Created by Dylan Walker Brown on 12/11/15.
// Copyright © 2015 Dylan Walker Brown. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var brain = CalculatorBrain()
var userIsInTheMiddleOfTypingANumber: Bool = false
var operandStack: Array<Double> = []
@IBOutlet weak var display: UILabel!
@IBOutlet weak var history: UILabel!
@IBAction func appendDigit(sender: UIButton) {
var digit = sender.currentTitle!
// Prevent leading zeros.
if !userIsInTheMiddleOfTypingANumber && "0" == digit {
display.text = digit
return
}
// Handle entries of "." in the display.
if "." == digit {
if userIsInTheMiddleOfTypingANumber {
// Return if user enters more than one "." in the display.
if display.text!.containsString(".") {
return
}
} else {
// If this is the first entry, append a leading zero.
digit = "0."
}
}
// Handle existing entries of π in the display.
if "π" == display.text! {
enter()
}
// Handle new entries of π.
if "π" == digit {
if userIsInTheMiddleOfTypingANumber {
enter()
}
display.text = digit
}
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
}
userIsInTheMiddleOfTypingANumber = true
}
@IBAction func operate(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
enter()
}
if let operation = sender.currentTitle {
if let result = brain.performOperation(operation) {
displayValue = result
setHistoryDisplay()
} else {
displayValue = nil
history.text = "ERROR"
}
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
var result: Double? = nil
if (displayValue != nil) {
result = brain.pushOperand(displayValue!)
} else {
result = brain.pushOperand(display.text!)
}
if nil != result {
setHistoryDisplay()
} else {
displayValue = nil
history.text = "ERROR"
}
}
@IBAction func clear(sender: UIButton) {
brain.clearStack()
brain.clearVariables()
userIsInTheMiddleOfTypingANumber = false
displayValue = nil
history.text = " "
}
func setHistoryDisplay() {
history.text = brain.description
}
var displayValue: Double? {
get {
if let interpretedNumber = NSNumberFormatter().numberFromString(display.text!) {
return interpretedNumber.doubleValue
}
return nil
}
set {
if (nil != newValue) {
display.text = "\(newValue!)"
} else {
display.text = " "
}
userIsInTheMiddleOfTypingANumber = false
}
}
}
| 26.912698 | 92 | 0.509584 |
090e3bf2faf54b48d472f4df31d1a17d70534bb8 | 2,881 | //
// MovieDetailResponse.swift
// TestMerqueo
//
// Created by Juan Esteban Monsalve Echeverry on 6/01/21.
//
import Foundation
// MARK: - Welcome
struct MovieDetailResponse: Codable, Equatable {
let adult: Bool?
let backdropPath: String?
let belongsToCollection: BelongsToCollection?
let budget: Int?
let genres: [Genre]?
let homepage: String?
let id: Int?
let imdbID, originalLanguage, originalTitle, overview: String?
let popularity: Double?
let posterPath: String?
let productionCompanies: [ProductionCompany]?
let productionCountries: [ProductionCountry]?
let releaseDate: String?
let revenue, runtime: Int?
let spokenLanguages: [SpokenLanguage]?
let status, tagline, title: String?
let video: Bool?
let voteAverage: Double?
let voteCount: Int?
enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case belongsToCollection = "belongs_to_collection"
case budget, genres, homepage, id
case imdbID = "imdb_id"
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview, popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case revenue, runtime
case spokenLanguages = "spoken_languages"
case status, tagline, title, video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
static func == (lhs: MovieDetailResponse, rhs: MovieDetailResponse) -> Bool {
lhs.id == rhs.id
}
}
// MARK: - BelongsToCollection
struct BelongsToCollection: Codable {
let id: Int?
let name, posterPath, backdropPath: String?
enum CodingKeys: String, CodingKey {
case id, name
case posterPath = "poster_path"
case backdropPath = "backdrop_path"
}
}
// MARK: - Genre
struct Genre: Codable {
let id: Int?
let name: String?
}
// MARK: - ProductionCompany
struct ProductionCompany: Codable {
let id: Int?
let logoPath: String?
let name, originCountry: String?
enum CodingKeys: String, CodingKey {
case id
case logoPath = "logo_path"
case name
case originCountry = "origin_country"
}
}
// MARK: - ProductionCountry
struct ProductionCountry: Codable {
let iso3166_1, name: String?
enum CodingKeys: String, CodingKey {
case iso3166_1 = "iso_3166_1"
case name
}
}
// MARK: - SpokenLanguage
struct SpokenLanguage: Codable {
let englishName, iso639_1, name: String?
enum CodingKeys: String, CodingKey {
case englishName = "english_name"
case iso639_1 = "iso_639_1"
case name
}
}
| 25.954955 | 81 | 0.658452 |
69889e7414e4f0268278b3b74b7bef5024c36016 | 132 | import XCTest
import LocalStoreRealmTests
var tests = [XCTestCaseEntry]()
tests += LocalStoreRealmTests.allTests()
XCTMain(tests)
| 16.5 | 40 | 0.80303 |
0a443fec5336f49fe21e95817d59a5bbf600c17b | 690 | //
// Copyright (c) 2021 gematik GmbH
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Card item
public protocol CardItemType: Equatable {}
| 32.857143 | 76 | 0.724638 |
f799f08c394ce50cb61d67b5602a70683ab8453a | 1,464 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftRulesEngine",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftRulesEngine",
targets: ["SwiftRulesEngine"]
)
//
// .library(
// name: "RulesDSL",
// targets: ["RulesDSL"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
// .package(url: "https://github.com/Realm/SwiftLint", from: "0.28.1")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftRulesEngine",
dependencies: []
),
.testTarget(
name: "SwiftRulesEngineTests",
dependencies: ["SwiftRulesEngine"]
),
// .target(
// name: "RulesDSL",
// dependencies: []),
// .testTarget(
// name: "RulesDSLTests",
// dependencies: ["RulesEngine", "RulesDSL"])
]
)
| 34.046512 | 122 | 0.577869 |
f5a8e0e37f016174f1effbf9124b7d8ea2fa665f | 1,729 | //
// FromNibCell.swift
//
// Copyright © 2019 Borja Igartua.
//
// 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 EDataSource
import Reusable
class FromNibCell: RegisteredCell, Reusable, NibLoadable {
@IBOutlet weak var bulletLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var bottomLabel: UILabel!
func fill(withItem item: CellItemProtocol) {
guard let item = item as? String else {
return
}
print("filling FromNibCell")
bulletLabel.text = "🐽: "
titleLabel.text = item
bottomLabel.text = "👯♂️ 👯♀️ 👯♂️ 👯♀️ 👯♂️ 👯♀️ 👯♂️ 👯♀️ 👯♂️ 👯♀️"
}
}
| 37.586957 | 81 | 0.685946 |
f5c2e4032e3ed7a6e1af4c7ba7c72571741f62a0 | 2,847 | //
// BaseSupplementaryViewDidDisplayTester.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 10/23/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import Foundation
@testable import GenericDataSource
import XCTest
class BaseSupplementaryViewDidDisplayTester<CellType>: DataSourceTester where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
let dataSource: ReportBasicDataSource<CellType> = ReportBasicDataSource<CellType>()
let creator = MockSupplementaryViewCreator()
var kind: String { fatalError("Abstract") }
required init(id: Int, numberOfReports: Int, collectionView: GeneralCollectionView) {
dataSource.items = Report.generate(numberOfReports: numberOfReports)
dataSource.registerReusableViewsInCollectionView(collectionView)
dataSource.set(headerCreator: creator, footerCreator: creator)
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) {
fatalError("Abstract")
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, collectionView: UICollectionView) {
dataSource.collectionView(collectionView, didEndDisplayingSupplementaryView: UICollectionReusableView(), forElementOfKind: kind, at: indexPath)
}
func assert(result: Void, indexPath: IndexPath, collectionView: GeneralCollectionView) {
XCTAssertTrue(creator.didDisplayCalled)
XCTAssertFalse(creator.willDisplayCalled)
XCTAssertEqual(kind, kind)
if collectionView is UITableView {
XCTAssertEqual(indexPath.section, creator.indexPath?.section)
} else {
XCTAssertEqual(indexPath, creator.indexPath)
}
}
func assertNotCalled(collectionView: GeneralCollectionView) {
XCTAssertFalse(creator.willDisplayCalled)
XCTAssertFalse(creator.didDisplayCalled)
}
}
class HeaderSupplementaryViewDidDisplayTester<CellType>: BaseSupplementaryViewDidDisplayTester<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
override var kind: String { return headerKind }
override func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) {
dataSource.tableView(tableView, didEndDisplayingHeaderView: UITableViewHeaderFooterView(), forSection: indexPath.section)
}
}
class FooterSupplementaryViewDidDisplayTester<CellType>: BaseSupplementaryViewDidDisplayTester<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
override var kind: String { return footerKind }
override func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) {
dataSource.tableView(tableView, didEndDisplayingFooterView: UITableViewHeaderFooterView(), forSection: indexPath.section)
}
}
| 42.492537 | 178 | 0.767826 |
d52a59f5484c87a4e5a04109a7f4fb8b8c9c49cb | 110 | @testable import TemplateExampleTests
import XCTest
XCTMain([
testCase(TemplateExampleTests.allTests)
])
| 15.714286 | 43 | 0.809091 |
90fd60fe104e69f24f45865a4ceb5ba1201b7d1e | 5,204 | //
// SearchViewModel.swift
// TheRestaurants
//
// Created by ADMIN on 9/7/2563 BE.
// Copyright © 2563 BE Thinh Nguyen P[6]. All rights reserved.
//
import Foundation
import RealmSwift
protocol SearchViewModelDelegate: class {
func syncFavorite(viewModel: SearchViewModel, needPerforms action: SearchViewModel.Action)
}
enum Search {
case result
case history
}
final class SearchViewModel {
enum Action {
case reloadData
case fail(Error)
}
var results: [Restaurant] = []
var histories: [SearchHistory] = []
var notificationToken: NotificationToken?
weak var delegate: SearchViewModelDelegate?
deinit {
notificationToken?.invalidate()
}
func numberOfRowInSectionResult() -> Int {
return results.count
}
func numberOfRowInSectionHistoried() -> Int {
return histories.count
}
func getResult(keywork: String, completion: @escaping APICompletion) {
let param = Api.Search.SearchRestaurant(entityType: "city", q: keywork)
Api.Search.searchRestaurants(param: param) { [weak self ](result) in
guard let this = self else { return }
switch result {
case .success(let results):
this.results = results
this.fetchRealmData(completion: completion)
case .failure(let error):
completion(.failure(error))
}
}
}
func viewModelForHistoryCell(at indexPath: IndexPath) -> HistorySearchCellModel {
let item = histories[indexPath.row]
let viewModel = HistorySearchCellModel(searchHistory: item)
return viewModel
}
func viewModelForResultCell(indexPath: IndexPath) -> HomeCellModel {
let item = results[indexPath.row]
let viewModel = HomeCellModel(restaurant: item)
return viewModel
}
func fetchSearchHistoryData(completion: @escaping APICompletion) {
do {
let realm = try Realm()
let results = realm.objects(SearchHistory.self)
histories = Array((results).reversed())
completion(.success)
} catch {
completion(.failure(error))
}
}
func saveKeyToRealm(searchKey: String, completion: @escaping APICompletion) {
do {
let realm = try Realm()
let result = SearchHistory()
result.searchKey = searchKey
try realm.write {
realm.add(result)
}
completion(.success)
} catch {
completion(.failure(error))
}
}
func didSelectRowAt(indexPath: IndexPath) -> DetailViewModel {
let item = results[indexPath.row]
let viewModel = DetailViewModel(restaurant: item)
return viewModel
}
func fetchRealmData(completion: @escaping APICompletion) {
do {
let realm = try Realm()
let resultsRealm = Array(realm.objects(Restaurant.self))
for item in results {
if resultsRealm.contains(where: { $0.id == item.id }) {
item.favorite = true
}
}
completion(.success)
} catch {
completion(.failure(error))
}
}
func addFavorite(index: Int, completion: @escaping APICompletion) {
do {
let realm = try Realm()
let restaurant = results[index]
try realm.write {
restaurant.favorite = true
realm.create(Restaurant.self, value: restaurant, update: .all)
}
completion(.success)
} catch {
completion(.failure(error))
}
}
func unFavorite(index: Int, completion: @escaping APICompletion) {
do {
let realm = try Realm()
let restaurant = results[index]
let result = realm.objects(Restaurant.self).filter("id = '\(restaurant.id ?? "")'")
try realm.write {
realm.delete(result)
}
completion(.success)
} catch {
completion(.failure(error))
}
}
func setupObserver() {
do {
let realm = try Realm()
notificationToken = realm.objects(Restaurant.self).observe({ [weak self] changes in
guard let this = self else { return }
switch changes {
case .update(let restaurants, _, _, _):
for item in this.results {
if restaurants.contains(where: { $0.id == item.id }) {
item.favorite = true
} else {
item.favorite = false
}
}
this.delegate?.syncFavorite(viewModel: this, needPerforms: .reloadData)
case .error(let error):
this.delegate?.syncFavorite(viewModel: this, needPerforms: .fail(error))
default: break
}
})
} catch {
delegate?.syncFavorite(viewModel: self, needPerforms: .fail(error))
}
}
}
| 30.611765 | 95 | 0.553805 |
034b43969dc17c947e96136edf8f964f29fcb83f | 8,623 | //
// Created by Tom Baranes on 05/05/16.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import UIKit
public class FlipAnimator: NSObject, AnimatedTransitioning {
// MARK: - AnimatorProtocol
public var transitionAnimationType: TransitionAnimationType
public var transitionDuration: Duration = defaultTransitionDuration
public var reverseAnimationType: TransitionAnimationType?
public var interactiveGestureType: InteractiveGestureType?
// MARK: - Private params
private var fromDirection: TransitionDirection
// MARK: - Private fold transition
private var transform: CATransform3D = CATransform3DIdentity
private var reverse: Bool = false
private var horizontal: Bool = false
// MARK: - Life cycle
public init(fromDirection: TransitionDirection, transitionDuration: Duration) {
self.fromDirection = fromDirection
self.transitionDuration = transitionDuration
horizontal = fromDirection.isHorizontal
switch fromDirection {
case .Right:
self.transitionAnimationType = .Flip(fromDirection: .Right)
self.reverseAnimationType = .Flip(fromDirection: .Left)
self.interactiveGestureType = .Pan(fromDirection: .Left)
reverse = true
default:
self.transitionAnimationType = .Flip(fromDirection: .Left)
self.reverseAnimationType = .Flip(fromDirection: .Right)
self.interactiveGestureType = .Pan(fromDirection: .Right)
reverse = false
}
super.init()
}
}
extension FlipAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return retrieveTransitionDuration(transitionContext)
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext)
guard let fromView = tempfromView, toView = tempToView, containerView = tempContainerView else {
transitionContext.completeTransition(true)
return
}
containerView.insertSubview(toView, atIndex: 0)
transform.m34 = -0.002
containerView.layer.sublayerTransform = transform
toView.frame = fromView.frame
let flipViews = createSnapshots(toView: toView, fromView: fromView, containerView: containerView)
animateFlipTransition(flipViews.0, flippedSectionOfToView: flipViews.1) {
if transitionContext.transitionWasCancelled() {
self.removeOtherViews(fromView)
} else {
self.removeOtherViews(toView)
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
// MARK: - Setup flip transition
private extension FlipAnimator {
func createSnapshots(toView toView: UIView, fromView: UIView, containerView: UIView) -> ((UIView, UIView), (UIView, UIView)) {
let toViewSnapshots = createSnapshot(fromView: toView, afterUpdates: true)
var flippedSectionOfToView = toViewSnapshots[reverse ? 0 : 1]
let fromViewSnapshots = createSnapshot(fromView: fromView, afterUpdates: false)
var flippedSectionOfFromView = fromViewSnapshots[reverse ? 1 : 0]
flippedSectionOfFromView = addShadow(toView: flippedSectionOfFromView, reverse: !reverse)
let flippedSectionOfFromViewShadow = flippedSectionOfFromView.subviews[1]
flippedSectionOfFromViewShadow.alpha = 0.0
flippedSectionOfToView = addShadow(toView: flippedSectionOfToView, reverse:reverse)
let flippedSectionOfToViewShadow = flippedSectionOfToView.subviews[1]
flippedSectionOfToViewShadow.alpha = 1.0
var axesValues = valuesForAxe(reverse ? 0.0 : 1.0, reverseValue: 0.5)
updateAnchorPointAndOffset(CGPoint(x: axesValues.0, y: axesValues.1), view: flippedSectionOfFromView)
axesValues = valuesForAxe(reverse ? 1.0 : 0.0, reverseValue: 0.5)
updateAnchorPointAndOffset(CGPoint(x: axesValues.0, y: axesValues.1), view: flippedSectionOfToView)
flippedSectionOfToView.layer.transform = rotate(reverse ? M_PI_2 : -M_PI_2)
return ((flippedSectionOfFromView, flippedSectionOfFromViewShadow), (flippedSectionOfToView, flippedSectionOfToViewShadow))
}
func createSnapshot(fromView view: UIView, afterUpdates: Bool) -> [UIView] {
let containerView = view.superview
let width = valuesForAxe(view.frame.size.width / 2, reverseValue: view.frame.size.width)
let height = valuesForAxe(view.frame.size.height, reverseValue: view.frame.size.height / 2)
var snapshotRegion = CGRect(x: 0, y: 0, width: width.0, height: height.0)
let leftHandView = view.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: UIEdgeInsetsZero)
leftHandView.frame = snapshotRegion
containerView?.addSubview(leftHandView)
let x = valuesForAxe(view.frame.size.width / 2, reverseValue: 0)
let y = valuesForAxe(0, reverseValue: view.frame.size.height / 2)
snapshotRegion = CGRect(x: x.0, y: y.0, width: width.0, height: height.0)
let rightHandView = view.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: UIEdgeInsetsZero)
rightHandView.frame = snapshotRegion
containerView?.addSubview(rightHandView)
containerView?.sendSubviewToBack(view)
return [leftHandView, rightHandView]
}
func addShadow(toView view: UIView, reverse: Bool) -> UIView {
let containerView = view.superview
let viewWithShadow = UIView(frame: view.frame)
containerView?.insertSubview(viewWithShadow, aboveSubview: view)
view.removeFromSuperview()
let shadowView = UIView(frame: viewWithShadow.bounds)
let gradient = CAGradientLayer()
gradient.frame = shadowView.bounds
gradient.colors = [UIColor(white: 0.0, alpha: 0.0), UIColor(white: 0.0, alpha: 0.5)]
if horizontal {
var axesValues = valuesForAxe(reverse ? 0.0 : 1.0, reverseValue: reverse ? 0.2 : 0.0)
gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1)
axesValues = valuesForAxe(reverse ? 1.0 : 0.0, reverseValue: reverse ? 0.0 : 1.0)
gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1)
} else {
var axesValues = valuesForAxe(reverse ? 0.2 : 0.0, reverseValue: reverse ? 0.0 : 1.0)
gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1)
axesValues = valuesForAxe(reverse ? 0.0 : 1.0, reverseValue: reverse ? 1.0 : 0.0)
gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1)
}
shadowView.layer.insertSublayer(gradient, atIndex: 1)
view.frame = view.bounds
viewWithShadow.addSubview(view)
viewWithShadow.addSubview(shadowView)
return viewWithShadow
}
func updateAnchorPointAndOffset(anchorPoint: CGPoint, view: UIView) {
view.layer.anchorPoint = anchorPoint
if horizontal {
let xOffset = anchorPoint.x - 0.5
view.frame = view.frame.offsetBy(dx: xOffset * view.frame.size.width, dy: 0)
} else {
let yOffset = anchorPoint.y - 0.5
view.frame = view.frame.offsetBy(dx: 0, dy: yOffset * view.frame.size.height)
}
}
func rotate(angle: Double) -> CATransform3D {
let axesValues = valuesForAxe(0.0, reverseValue: 1.0)
return CATransform3DMakeRotation(CGFloat(angle), axesValues.0, axesValues.1, 0.0)
}
}
// MARK: - Animates
private extension FlipAnimator {
func animateFlipTransition(flippedSectionOfFromView: (UIView, UIView), flippedSectionOfToView: (UIView, UIView), completion: AnimatableCompletion) {
UIView.animateKeyframesWithDuration(transitionDuration, delay: 0, options: .LayoutSubviews, animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: {
flippedSectionOfFromView.0.layer.transform = self.rotate(self.reverse ? -M_PI_2 : M_PI_2)
flippedSectionOfFromView.1.alpha = 1.0
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
flippedSectionOfToView.0.layer.transform = self.rotate(self.reverse ? 0.001 : -0.001)
flippedSectionOfToView.1.alpha = 0.0
})
}) { _ in
completion()
}
}
}
// MARK: - Helpers
private extension FlipAnimator {
func removeOtherViews(viewToKeep: UIView) {
let containerView = viewToKeep.superview
containerView?.subviews.forEach {
if $0 != viewToKeep {
$0.removeFromSuperview()
}
}
}
func valuesForAxe(initialValue: CGFloat, reverseValue: CGFloat) -> (CGFloat, CGFloat) {
return horizontal ? (initialValue, reverseValue) : (reverseValue, initialValue)
}
}
| 40.483568 | 150 | 0.728865 |
fc460e45794dba224a83b8ea874cdaae95b1907c | 1,362 | //___FILEHEADER___
import XCTest
class ___FILEBASENAMEASIDENTIFIER___: XCTestCase {
override func setUpWithError() throws {
// 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
// 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 tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 35.842105 | 182 | 0.665198 |
0e703f248a2789f1c33683dcc6b52839ee47e948 | 2,205 | //
// ButtonsContainedVC.swift
// Habanero
//
// Created by Jarrod Parkes on 05/06/2020.
//
import Habanero
import UIKit
// MARK: - ButtonsContainedVC: ButtonsVC
class ButtonsContainedVC: ButtonsVC {
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Contained Button"
}
// MARK: ButtonsVC
override func getExampleButtons() -> [UIButton] {
let containedButtonPrimary = Button(frame: CGRect(x: 20, y: 120, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.primary))
containedButtonPrimary.styleWith(theme: theme)
let containedButtonSecondary1 = Button(frame: CGRect(x: 200, y: 120, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.secondary1))
containedButtonSecondary1.styleWith(theme: theme)
let containedButtonSecondary2 = Button(frame: CGRect(x: 20, y: 170, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.secondary2))
containedButtonSecondary2.styleWith(theme: theme)
let containedButtonSecondary3 = Button(frame: CGRect(x: 200, y: 170, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.secondary3))
containedButtonSecondary3.styleWith(theme: theme)
let containedButtonSecondary4 = Button(frame: CGRect(x: 20, y: 220, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.secondary4))
containedButtonSecondary4.styleWith(theme: theme)
let containedButtonSecondary5 = Button(frame: CGRect(x: 200, y: 220, width: BUTTON_WIDTH, height: BUTTON_HEIGHT), style: .contained(.secondary5))
containedButtonSecondary5.styleWith(theme: theme)
let defaultButton = UIButton(type: .system)
defaultButton.frame = CGRect(x: 20, y: 270, width: BUTTON_WIDTH, height: BUTTON_HEIGHT)
return [
containedButtonPrimary,
containedButtonSecondary1,
containedButtonSecondary2,
containedButtonSecondary3,
containedButtonSecondary4,
containedButtonSecondary5,
defaultButton
]
}
}
| 38.684211 | 154 | 0.666213 |
29c84ef3f182240b43d66338a761085248911fca | 846 | //
// TweetCell.swift
// iOSSocialMediaApp
//
// Created by Henry Paulino on 10/22/18.
// Copyright © 2018 Henry Paulino. All rights reserved.
//
import UIKit
import Firebase
class TweetCell: UITableViewCell {
@IBOutlet weak var tweetText: UILabel!
@IBOutlet weak var displayName: UILabel!
@IBOutlet weak var username: UILabel!
let user = Auth.auth().currentUser!
var UsersDB: Users!
func setTweet(tweet: Tweet) {
tweetText.text = tweet.text
displayName.text = user.displayName
username.text = ""
let FS = Global.FS
let UsersDB = FS?.collection("users")
UsersDB!.document(user.uid).getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.get("username")
let username = dataDescription as? String
self.username.text = username!
}
}
}
}
| 22.864865 | 64 | 0.70331 |
ab551b59991328883a483a6d8ac51ddab67b98b2 | 7,895 | /*
SalesforceSDKManagerExtensions
Created by Raj Rao on 11/27/17.
Copyright (c) 2017-present, salesforce.com, inc. All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written
permission of salesforce.com, inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import SalesforceSDKCore
import SmartSync
import PromiseKit
extension SalesforceSwiftSDKManager {
public static var Builder:SalesforceSDKManagerBuilder.Type {
get {
_ = SalesforceSwiftSDKManager.initSDK()
return SalesforceSDKManagerBuilder.self
}
}
public class SalesforceSDKManagerBuilder {
/**
Provides a Builder based mechanism to setup the app config for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}
```
- Parameter config: The block which will be invoked with a config object.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func configure(config : @escaping (SFSDKAppConfig) -> Void ) -> SalesforceSDKManagerBuilder.Type {
config(SalesforceSwiftSDKManager.shared().appConfig!)
return self
}
/**
Provides a Builder based mechanism to setup the post inititialization settings for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}.postInit {
}
```
- Parameter action: The block which will be invoked.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func postInit(action: () -> Void) -> SalesforceSDKManagerBuilder.Type {
action()
return self
}
/**
Provides a way to set the post launch action for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}
.postLaunch { [unowned self] (launchActionList: SFSDKLaunchAction) in
let launchActionString = SalesforceSDKManager.launchActionsStringRepresentation(launchActionList)
SalesforceSwiftLogger.log(type(of:self), level:.info, message:"Post-launch: launch actions taken: \(launchActionString)")
}.done()
```
- Parameter action: The block which will be invoked after a succesfull SDK Launch.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func postLaunch(action : @escaping SFSDKPostLaunchCallbackBlock) -> SalesforceSDKManagerBuilder.Type {
SalesforceSwiftSDKManager.shared().postLaunchAction = action
return self
}
/**
Provides a way to set the post logout action for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}
.postLaunch { (launchActionList: SFSDKLaunchAction) in
...
}
.postLogout {
}.done()
```
- Parameter action: The block which will be invoked after a succesfull SDK Launch.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func postLogout(action : @escaping SFSDKLogoutCallbackBlock) -> SalesforceSDKManagerBuilder.Type {
SalesforceSwiftSDKManager.shared().postLogoutAction = action
return self
}
/**
Provides a way to set the switch user action for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}
.postLaunch { (launchActionList: SFSDKLaunchAction) in
...
}
.postLogout {
}
.switchUser { from,to in
}.done()
```
- Parameter action: The block which will be invoked after a succesfull SDK Launch.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func switchUser(action : @escaping SFSDKSwitchUserCallbackBlock) -> SalesforceSDKManagerBuilder.Type {
SalesforceSwiftSDKManager.shared().switchUserAction = action
return self
}
/**
Provides a way to set the error handling during sdk launch for the Salesforce Application.
```
SalesforceSwiftSDKManager.Builder.configure { (appconfig) in
appconfig.remoteAccessConsumerKey = RemoteAccessConsumerKey
appconfig.oauthRedirectURI = OAuthRedirectURI
appconfig.oauthScopes = ["web", "api"]
}
.postLaunch { (launchActionList: SFSDKLaunchAction) in
...
}
.postLogout {
}
.switchUser { from,to in
}
.launchError { error,launchAction in
}.done()
```
- Parameter action: The block which will be invoked after a succesfull SDK Launch.
- Returns: The instance of SalesforceSDKManagerBuilder.
*/
public class func launchError(action : @escaping SFSDKLaunchErrorCallbackBlock) -> SalesforceSDKManagerBuilder.Type {
SalesforceSwiftSDKManager.shared().launchErrorAction = action
SalesforceSwiftLogger.d(SalesforceSDKManager.self, message: "error")
return self
}
/**
Last call for the builder returns Void to suppress warnings.
*/
public class func done () -> Void {
}
}
}
| 42.219251 | 134 | 0.657251 |
e953e8002b917a68ca6361ac1a69bfac55e87cee | 778 | //
// FXBannerCollectionViewCell.swift
// AnimationDemo
//
// Created by lieon on 2019/11/12.
// Copyright © 2019 lieon. All rights reserved.
//
import UIKit
class FXBannerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var coverView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var btn: UIButton!
@IBOutlet weak var shadowView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
containerView.layer.cornerRadius = 8
shadowView.layer.shadowColor = UIColor.gray.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
shadowView.layer.shadowRadius = 20
shadowView.layer.shadowOpacity = 0.4
}
}
| 27.785714 | 67 | 0.699229 |
d9e3dec34dcd51606bf7a05ec758d7c775ba7904 | 98 | //
// AppStore.swift
// Serengeti
//
// Created by Sammie on 12/11/2021.
//
import Foundation
| 10.888889 | 36 | 0.642857 |
0e04a381e47885fb678ea53b115c24056444d319 | 10,071 | // Configuration.swift
//
// Copyright © 2018-2021 Vasilis Panagiotopoulos. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIESS 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
/// Type for mock delay randomizer.
/// - parameters:
/// - min: The lower bound of interval.
/// - max: The upper bound of interval.
public typealias MockDelayType = (min: TimeInterval, max: TimeInterval)
/// A configuration class that can be used with Environment, Router, Route and Request.
/// A configuration object follows the following rules:
/// 1. When a Configuration object is passed to an Environment,
/// each Router with its routes and requests will inherit this configuration.
/// 2. When a Configuration object is passed to Router, all its routes and requests will inherit this configuration.
public final class Configuration {
// MARK: Public properties
/// The cache policy of the request.
public var cachePolicy: URLRequest.CachePolicy?
/// The timeout interval of the request.
public var timeoutInterval: TimeInterval?
/// The request body type of the request. Can be either .xWWWFormURLEncoded or .JSON.
public var requestBodyType: RequestBodyType?
/// The certificate file paths used for certificate pining.
public var certificatePaths: [String]? {
didSet {
if let certPaths = certificatePaths {
setCertificateData(with: certPaths)
}
}
}
/// Enables or disables debug mode.
public var verbose: Bool?
/// Additional headers of the request. They will be merged with the headers specified in RouteConfiguration.
public var headers: [String: String]?
/// The Bundle object of mock data used when useMockData is true.
public var mockDataBundle: Bundle?
/// Enables or disables request mocking.
public var mockDataEnabled: Bool?
/// Specifies a delay when mock data is used.
public var mockDelay: MockDelayType?
/// Specifies a key decoding strategy. Take a look
/// at: https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy
public var keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy?
/// Error handlers that will be used as a fallback after request failure.
public var interceptors: [InterceptorProtocol.Type]?
/// Request middleware
public var requestMiddleware: [RequestMiddlewareProtocol.Type]?
// MARK: Internal properties
/// The certificate data when certificate pinning is enabled.
internal var certificateData: [NSData]?
/// Skip Interceptors for being executed
internal var skipInterceptors = false
// MARK: Initializers
/// Default initializer of Configuration
/// - parameters:
/// - cachePolicy: The cache policy of the request.
/// - timeoutInterval: The timeout interval of the request.
/// - requestBodyType: The request body type of the request. Can be either .xWWWFormURLEncoded or .JSON.
/// - certificatePaths: The certificate file paths used for certificate pining.
/// - verbose: Enables or disables debug mode.
/// - headers: Additional headers of the request. Will be merged with the headers specified
/// in RouteConfiguration.
/// - mockDataBundle: The Bundle object of mock data used when useMockData is true.
/// - mockDataEnabled: Enables or disables request mocking.
/// - mockDelay: Specifies a delay when mock data is used.
/// - keyDecodingStrategy: // Specifies a key decoding strategy. Take a look,
/// at: https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy
/// - errorHandlers: Error handlers that will be used as a fallback after request failure.
/// - requestMiddleware: Request middleware. For example see
/// Examples/Communication/Middleware/CryptoMiddleware.swift
public init(cachePolicy: URLRequest.CachePolicy? = nil,
timeoutInterval: TimeInterval? = nil,
requestBodyType: RequestBodyType? = nil,
certificatePaths: [String]? = nil,
verbose: Bool? = nil,
headers: [String: String]? = nil,
mockDataBundle: Bundle? = nil,
mockDataEnabled: Bool? = nil,
mockDelay: MockDelayType? = nil,
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy? = nil,
interceptors: [InterceptorProtocol.Type]? = nil,
requestMiddleware: [RequestMiddlewareProtocol.Type]? = nil) {
self.cachePolicy = cachePolicy
self.timeoutInterval = timeoutInterval
self.requestBodyType = requestBodyType
self.verbose = verbose
self.headers = headers
self.mockDataBundle = mockDataBundle
self.mockDataEnabled = mockDataEnabled
self.mockDelay = mockDelay
self.keyDecodingStrategy = keyDecodingStrategy
self.interceptors = interceptors
self.requestMiddleware = requestMiddleware
if let certPaths = certificatePaths {
setCertificateData(with: certPaths)
}
}
// MARK: Internal methods
internal func setCertificateData(with paths: [String]) {
self.certificateData = paths.count > 0 ? [] : nil
paths.forEach { path in
if let certData = NSData(contentsOfFile: path) {
self.certificateData?.append(certData)
} else {
Log.printSimpleErrorIfNeeded(TNError.invalidCertificatePath(path))
}
}
}
}
extension Configuration: NSCopying {
/// NSCopying implementation, used for cloning Configuration objects.
public func copy(with zone: NSZone? = nil) -> Any {
let configuration = Configuration()
configuration.cachePolicy = cachePolicy
configuration.timeoutInterval = timeoutInterval
configuration.requestBodyType = requestBodyType
configuration.certificatePaths = certificatePaths
configuration.certificateData = certificateData
configuration.verbose = verbose
configuration.headers = headers
configuration.mockDataBundle = mockDataBundle
configuration.mockDelay = mockDelay
configuration.mockDataEnabled = mockDataEnabled
configuration.keyDecodingStrategy = keyDecodingStrategy
configuration.interceptors = interceptors
configuration.requestMiddleware = requestMiddleware
return configuration
}
}
extension Configuration {
/// Generates a default configuration
static func makeDefaultConfiguration() -> Configuration {
return Configuration(cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 60,
requestBodyType: .xWWWFormURLEncoded,
verbose: false,
headers: [:],
mockDataBundle: nil,
mockDataEnabled: false,
mockDelay: MockDelayType(min: 0.01, max: 0.07))
}
// swiftlint:disable cyclomatic_complexity
static func override(left: Configuration,
right: Configuration)
-> Configuration {
let leftClone = left.copy() as? Configuration ?? Configuration()
if let cachePolicy = right.cachePolicy {
leftClone.cachePolicy = cachePolicy
}
if let timeoutInterval = right.timeoutInterval {
leftClone.timeoutInterval = timeoutInterval
}
if let requestBodyType = right.requestBodyType {
leftClone.requestBodyType = requestBodyType
}
if let certificatePaths = right.certificatePaths {
leftClone.certificatePaths = certificatePaths
}
if let certificateData = right.certificateData {
leftClone.certificateData = certificateData
}
if let verbose = right.verbose {
leftClone.verbose = verbose
}
// Merge headers
var cloneHeaders = leftClone.headers ?? [:]
let headers = right.headers ?? [:]
cloneHeaders.merge(headers, uniquingKeysWith: { (_, new) in new })
leftClone.headers = cloneHeaders
if let mockDataBundle = right.mockDataBundle {
leftClone.mockDataBundle = mockDataBundle
}
if let mockDataEnabled = right.mockDataEnabled {
leftClone.mockDataEnabled = mockDataEnabled
}
if let mockDelay = right.mockDelay {
leftClone.mockDelay = mockDelay
}
if let requestMiddleware = right.requestMiddleware {
leftClone.requestMiddleware = requestMiddleware
}
if let keyDecodingStrategy = right.keyDecodingStrategy {
leftClone.keyDecodingStrategy = keyDecodingStrategy
}
if let interceptors = right.interceptors {
leftClone.interceptors = interceptors
}
return leftClone
}
}
| 44.76 | 116 | 0.668156 |
9135b1027647a0ba54a5c8948bb7f19fca4640ec | 2,258 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
public final class FeedViewController: UITableViewController, UITableViewDataSourcePrefetching {
@IBOutlet private(set) public var errorView: ErrorView?
var viewModel: FeedViewModel? {
didSet { bind() }
}
var tableModel = [FeedImageCellController]() {
didSet { tableView.reloadData() }
}
public override func viewDidLoad() {
super.viewDidLoad()
refresh()
}
@IBAction private func refresh() {
viewModel?.loadFeed()
}
func bind() {
viewModel?.onLoadingStateChange = { [weak self] isLoading in
if isLoading {
self?.refreshControl?.beginRefreshing()
} else {
self?.refreshControl?.endRefreshing()
}
}
viewModel?.onErrorLoadingFeed = { [weak self] errorMessage in
guard let errorMessage = errorMessage else {
self?.errorView?.hideMessage()
return
}
self?.errorView?.show(message: errorMessage)
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.sizeTableHeaderToFit()
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableModel.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cellController(forRowAt: indexPath).view(in: tableView)
}
public override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cancelCellControllerLoad(forRowAt: indexPath)
}
public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
indexPaths.forEach { indexPath in
cellController(forRowAt: indexPath).preload()
}
}
public func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
indexPaths.forEach(cancelCellControllerLoad)
}
private func cellController(forRowAt indexPath: IndexPath) -> FeedImageCellController {
return tableModel[indexPath.row]
}
private func cancelCellControllerLoad(forRowAt indexPath: IndexPath) {
cellController(forRowAt: indexPath).cancelLoad()
}
}
| 27.204819 | 130 | 0.721435 |
f9154493ba50f0e2e7252399539fdda3229edb8d | 6,101 |
import UIKit
class UartModeViewController: UartBaseViewController {
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Title
let localizationManager = LocalizationManager.sharedInstance
let name = blePeripheral?.name ?? localizationManager.localizedString("peripherallist_unnamed")
self.title = traitCollection.horizontalSizeClass == .regular ? String(format: localizationManager.localizedString("uart_navigation_title_format"), arguments: [name]) : localizationManager.localizedString("uart_tab_title")
// Init Uart
uartData = UartPacketManager(delegate: self, isPacketCacheEnabled: true, isMqttEnabled: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UART
override func isInMultiUartMode() -> Bool {
return blePeripheral == nil
}
override func setupUart() {
updateUartReadyUI(isReady: false)
// Reset colors assigned to peripherals
let colors = UartStyle.defaultColors()
colorForPeripheral.removeAll()
// Enable uart
if isInMultiUartMode() { // Multiple peripheral mode
let blePeripherals = BleManager.sharedInstance.connectedPeripherals()
for (i, blePeripheral) in blePeripherals.enumerated() {
colorForPeripheral[blePeripheral.identifier] = colors[i % colors.count]
blePeripheral.uartEnable(uartRxHandler: uartData.rxPacketReceived) { [weak self] error in
guard let context = self else { return }
let peripheralName = blePeripheral.name ?? blePeripheral.identifier.uuidString
DispatchQueue.main.async { [unowned context] in
guard error == nil else {
DLog("Error initializing uart")
context.dismiss(animated: true, completion: { [weak self] () -> Void in
if let context = self {
showErrorAlert(from: context, title: "Error", message: "Uart protocol can not be initialized for peripheral: \(peripheralName)")
BleManager.sharedInstance.disconnect(from: blePeripheral)
}
})
return
}
// Done
DLog("Uart enabled for \(peripheralName)")
if blePeripheral == blePeripherals.last {
context.updateUartReadyUI(isReady: true)
}
}
}
}
} else if let blePeripheral = blePeripheral { // Single peripheral mode
colorForPeripheral[blePeripheral.identifier] = colors.first
blePeripheral.uartEnable(uartRxHandler: uartData.rxPacketReceived) { [weak self] error in
guard let context = self else { return }
DispatchQueue.main.async { [unowned context] in
guard error == nil else {
DLog("Error initializing uart")
context.dismiss(animated: true, completion: { [weak self] in
if let context = self {
showErrorAlert(from: context, title: "Error", message: "Uart protocol can not be initialized")
if let blePeripheral = context.blePeripheral {
BleManager.sharedInstance.disconnect(from: blePeripheral)
}
}
})
return
}
// Done
DLog("Uart enabled")
context.updateUartReadyUI(isReady: true)
}
}
}
}
override func send(message: String) {
guard let uartData = self.uartData as? UartPacketManager else { DLog("Error send with invalid uartData class"); return }
if let blePeripheral = blePeripheral { // Single peripheral mode
uartData.send(blePeripheral: blePeripheral, text: message)
} else { // Multiple peripheral mode
let peripherals = BleManager.sharedInstance.connectedPeripherals()
if let multiUartSendToPeripheralId = multiUartSendToPeripheralId {
// Send to single peripheral
if let peripheral = peripherals.first(where: {$0.identifier == multiUartSendToPeripheralId}) {
uartData.send(blePeripheral: peripheral, text: message)
}
} else {
// Send to all peripherals
for peripheral in peripherals {
uartData.send(blePeripheral: peripheral, text: message)
}
}
}
}
// MARK: - Style
override func colorForPacket(packet: UartPacket) -> UIColor {
var color: UIColor?
if let peripheralId = packet.peripheralId {
color = colorForPeripheral[peripheralId]
}
return color ?? UIColor.black
}
// MARK: - MqttManagerDelegate
override func onMqttMessageReceived(message: String, topic: String) {
guard let blePeripheral = blePeripheral else { return }
DispatchQueue.main.async { [unowned self] in
guard let uartData = self.uartData as? UartPacketManager else { DLog("Error send with invalid uartData class"); return }
uartData.send(blePeripheral: blePeripheral, text: message, wasReceivedFromMqtt: true)
}
}
}
| 43.892086 | 230 | 0.539911 |
766f04cb034973b472549c5cd1a4f46af99e1f3b | 3,568 | //
// MergeCollectionDifference.swift
//
//
// Created by Natchanon Luangsomboon on 1/1/2563 BE.
//
public extension CollectionDifference {
/// Returns a new `CollectionDifference` whose application is equivalent to applying `self`, *then* `other`.
func combining(with other: Self) -> Self {
func offsets(of change: Self.Change) -> (offset: Int, associatedOffset: Int?) {
switch change {
case let .insert(offset, _, associatedOffset),
let .remove(offset, _, associatedOffset):
return (offset, associatedOffset)
}
}
func compute(near: [Change], far: [Change], queries: [Change]) -> [Int: (offset: Int, duplicated: Bool)] {
var nearIterator = near.makeIterator(), farIterator = far.makeIterator(), nearCount = 0, farCount = 0
var nearOffsets = nearIterator.next().map(offsets(of:)), farOffset = farIterator.next().map(offsets(of:))?.offset
return Dictionary(uniqueKeysWithValues: queries.compactMap { query in
let query = offsets(of: query).offset
while let (offset, associatedOffset) = nearOffsets, offset <= query {
if offset == query {
return associatedOffset.map { (query, ($0, true)) }
}
nearCount += 1
nearOffsets = nearIterator.next().map(offsets(of:))
}
let partialResult = query - nearCount
while let offset = farOffset, offset <= partialResult {
farCount += 1
farOffset = farIterator.next().map {
offsets(of: $0).offset - farCount
}
}
return (query, (partialResult + farCount, false))
})
}
let secondRemovalMapping = compute(near: self.insertions, far: self.removals, queries: other.removals)
let firstInsertionMapping = compute(near: other.removals, far: other.insertions, queries: self.insertions)
var tmp: [Change] = []
tmp.reserveCapacity(self.count + other.count)
tmp.append(contentsOf: self.lazy.compactMap { change -> Change? in
switch change {
case let .remove(offset, element, associatedOffset):
return .remove(offset: offset, element: element, associatedWith: associatedOffset.map { firstInsertionMapping[$0]?.offset } ?? nil)
case let .insert(offset, element, associatedOffset):
guard let (offset, duplicated) = firstInsertionMapping[offset],
!duplicated else {
return nil
}
return .insert(offset: offset, element: element, associatedWith: associatedOffset)
}
})
tmp.append(contentsOf: other.lazy.compactMap { change -> Change? in
switch change {
case let .insert(offset, element, associatedOffset):
return .insert(offset: offset, element: element, associatedWith: associatedOffset.map { secondRemovalMapping[$0]?.offset } ?? nil)
case let .remove(offset, element, associatedOffset):
guard let (offset, duplicated) = secondRemovalMapping[offset],
!duplicated else {
return nil
}
return .remove(offset: offset, element: element, associatedWith: associatedOffset)
}
})
return Self(tmp)!
}
}
| 44.049383 | 147 | 0.568946 |
766bbaad66b559c82493da5b3033e3bd9cd9d225 | 35,325 | // XLActionController.swift
// XLActionController ( https://github.com/xmartlabs/XLActionController )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: - Section class
open class Section<ActionDataType, SectionHeaderDataType> {
open var data: SectionHeaderDataType? {
get { return _data?.data }
set { _data = RawData(data: newValue) }
}
open var actions = [Action<ActionDataType>]()
fileprivate var _data: RawData<SectionHeaderDataType>?
public init() {}
}
// MARK: - Enum definitions
public enum CellSpec<CellType: UICollectionViewCell, CellDataType> {
case nibFile(nibName: String, bundle: Bundle?, height:((CellDataType)-> CGFloat))
case cellClass(height:((CellDataType)-> CGFloat))
public var height: ((CellDataType) -> CGFloat) {
switch self {
case .cellClass(let heightCallback):
return heightCallback
case .nibFile(_, _, let heightCallback):
return heightCallback
}
}
}
public enum HeaderSpec<HeaderType: UICollectionReusableView, HeaderDataType> {
case nibFile(nibName: String, bundle: Bundle?, height:((HeaderDataType) -> CGFloat))
case cellClass(height:((HeaderDataType) -> CGFloat))
public var height: ((HeaderDataType) -> CGFloat) {
switch self {
case .cellClass(let heightCallback):
return heightCallback
case .nibFile(_, _, let heightCallback):
return heightCallback
}
}
}
private enum ReusableViewIds: String {
case Cell = "Cell"
case Header = "Header"
case SectionHeader = "SectionHeader"
}
// MARK: - Row class
final class RawData<T> {
var data: T!
init?(data: T?) {
guard let data = data else { return nil }
self.data = data
}
}
// MARK: - ActionController class
open class ActionController<ActionViewType: UICollectionViewCell, ActionDataType, HeaderViewType: UICollectionReusableView, HeaderDataType, SectionHeaderViewType: UICollectionReusableView, SectionHeaderDataType>: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
// MARK - Public properties
open var headerData: HeaderDataType? {
set { _headerData = RawData(data: newValue) }
get { return _headerData?.data }
}
open var settings: ActionControllerSettings = ActionControllerSettings.defaultSettings()
open var cellSpec: CellSpec<ActionViewType, ActionDataType>
open var sectionHeaderSpec: HeaderSpec<SectionHeaderViewType, SectionHeaderDataType>?
open var headerSpec: HeaderSpec<HeaderViewType, HeaderDataType>?
open var onConfigureHeader: ((HeaderViewType, HeaderDataType) -> ())?
open var onConfigureSectionHeader: ((SectionHeaderViewType, SectionHeaderDataType) -> ())?
open var onConfigureCellForAction: ((ActionViewType, Action<ActionDataType>, IndexPath) -> ())?
open var contentHeight: CGFloat = 0.0
open var safeAreaInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return view.safeAreaInsets
}
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
open var cancelView: UIView?
lazy open var backgroundView: UIView = {
let backgroundView = UIView()
backgroundView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return backgroundView
}()
lazy open var collectionView: UICollectionView = { [unowned self] in
let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: self.collectionViewLayout)
collectionView.alwaysBounceVertical = self.settings.behavior.bounces
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = .clear
collectionView.bounces = self.settings.behavior.bounces
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isScrollEnabled = self.settings.behavior.scrollEnabled
collectionView.showsVerticalScrollIndicator = false
if self.settings.behavior.hideOnTap {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ActionController.tapGestureDidRecognize(_:)))
collectionView.backgroundView = UIView(frame: collectionView.bounds)
collectionView.backgroundView?.isUserInteractionEnabled = true
collectionView.backgroundView?.addGestureRecognizer(tapRecognizer)
}
if self.settings.behavior.hideOnScrollDown && !self.settings.behavior.scrollEnabled {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(ActionController.swipeGestureDidRecognize(_:)))
swipeGesture.direction = .down
collectionView.addGestureRecognizer(swipeGesture)
}
return collectionView
}()
lazy open var collectionViewLayout: DynamicCollectionViewFlowLayout = { [unowned self] in
let collectionViewLayout = DynamicCollectionViewFlowLayout()
collectionViewLayout.useDynamicAnimator = self.settings.behavior.useDynamics
collectionViewLayout.minimumInteritemSpacing = 0.0
collectionViewLayout.minimumLineSpacing = 0
return collectionViewLayout
}()
open var presentingNavigationController: UINavigationController? {
return (presentingViewController as? UINavigationController) ?? presentingViewController?.navigationController
}
// MARK: - ActionController initializers
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
cellSpec = .cellClass(height: { _ -> CGFloat in 60 })
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
transitioningDelegate = self
modalPresentationStyle = .custom
}
public required init?(coder aDecoder: NSCoder) {
cellSpec = .cellClass(height: { _ -> CGFloat in 60 })
super.init(coder: aDecoder)
transitioningDelegate = self
modalPresentationStyle = .custom
}
// MARK - Public API
open func addAction(_ action: Action<ActionDataType>) {
if let section = _sections.last {
section.actions.append(action)
} else {
let section = Section<ActionDataType, SectionHeaderDataType>()
addSection(section)
section.actions.append(action)
}
}
@discardableResult
open func addSection(_ section: Section<ActionDataType, SectionHeaderDataType>) -> Section<ActionDataType, SectionHeaderDataType> {
_sections.append(section)
return section
}
// MARK: - Helpers
open func sectionForIndex(_ index: Int) -> Section<ActionDataType, SectionHeaderDataType>? {
return _sections[index]
}
open func actionForIndexPath(_ indexPath: IndexPath) -> Action<ActionDataType>? {
return _sections[(indexPath as NSIndexPath).section].actions[(indexPath as NSIndexPath).item]
}
open func actionIndexPathFor(_ indexPath: IndexPath) -> IndexPath {
if hasHeader() {
return IndexPath(item: (indexPath as NSIndexPath).item, section: (indexPath as NSIndexPath).section - 1)
}
return indexPath
}
open func dismiss() {
dismiss(nil)
}
open func dismiss(_ completion: (() -> ())?) {
disableActions = true
presentingViewController?.dismiss(animated: true) { [weak self] in
self?.disableActions = false
completion?()
}
}
// MARK: - View controller behavior
open override func viewDidLoad() {
super.viewDidLoad()
modalPresentationCapturesStatusBarAppearance = settings.statusBar.modalPresentationCapturesStatusBarAppearance
// background view
view.addSubview(backgroundView)
// register main cell
switch cellSpec {
case .nibFile(let nibName, let bundle, _):
collectionView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:ReusableViewIds.Cell.rawValue)
case .cellClass:
collectionView.register(ActionViewType.self, forCellWithReuseIdentifier:ReusableViewIds.Cell.rawValue)
}
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
// register main header
if let headerSpec = headerSpec, let _ = headerData {
switch headerSpec {
case .cellClass:
collectionView.register(HeaderViewType.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: ReusableViewIds.Header.rawValue)
case .nibFile(let nibName, let bundle, _):
collectionView.register(UINib(nibName: nibName, bundle: bundle), forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: ReusableViewIds.Header.rawValue)
}
}
// register section header
if let headerSpec = sectionHeaderSpec {
switch headerSpec {
case .cellClass:
collectionView.register(SectionHeaderViewType.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: ReusableViewIds.SectionHeader.rawValue)
case .nibFile(let nibName, let bundle, _):
collectionView.register(UINib(nibName: nibName, bundle: bundle), forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: ReusableViewIds.SectionHeader.rawValue)
}
}
view.addSubview(collectionView)
// calculate content Inset
collectionView.layoutSubviews()
if let section = _sections.last, !settings.behavior.useDynamics {
let lastSectionIndex = _sections.count - 1
let layoutAtts = collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: section.actions.count - 1, section: hasHeader() ? lastSectionIndex + 1 : lastSectionIndex))
contentHeight = layoutAtts!.frame.origin.y + layoutAtts!.frame.size.height
if settings.cancelView.showCancel && !settings.cancelView.hideCollectionViewBehindCancelView {
contentHeight += settings.cancelView.height
}
}
setUpContentInsetForHeight(view.frame.height)
// set up collection view initial position taking into account top content inset
collectionView.frame = view.bounds
collectionView.frame.origin.y += contentHeight + (settings.cancelView.showCancel ? settings.cancelView.height : 0)
collectionViewLayout.footerReferenceSize = CGSize(width: 320, height: 0)
// -
if settings.cancelView.showCancel {
cancelView = cancelView ?? createCancelView()
view.addSubview(cancelView!)
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
backgroundView.frame = view.bounds
if let navController = presentingNavigationController, settings.behavior.hideNavigationBarOnShow {
navigationBarWasHiddenAtStart = navController.isNavigationBarHidden
navController.setNavigationBarHidden(true, animated: animated)
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let navController = presentingNavigationController, settings.behavior.hideNavigationBarOnShow {
navController.setNavigationBarHidden(navigationBarWasHiddenAtStart, animated: animated)
}
}
@available(iOS 11.0, *)
open override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
setUpContentInsetForHeight(view.frame.height)
updateCancelViewLayout()
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
collectionView.setNeedsLayout()
if let _ = settings.animation.scale {
presentingViewController?.view.transform = CGAffineTransform.identity
}
collectionView.collectionViewLayout.invalidateLayout()
coordinator.animate(alongsideTransition: { [weak self] _ in
self?.setUpContentInsetForHeight(size.height)
self?.collectionView.reloadData()
if let scale = self?.settings.animation.scale {
self?.presentingViewController?.view.transform = CGAffineTransform(scaleX: scale.width, y: scale.height)
}
}, completion: nil)
collectionView.layoutIfNeeded()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.collectionViewLayout.invalidateLayout()
}
open override var prefersStatusBarHidden: Bool {
return !settings.statusBar.showStatusBar
}
open override var preferredStatusBarStyle : UIStatusBarStyle {
return settings.statusBar.style
}
open func createCancelView() -> UIView {
let cancelView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: settings.cancelView.height + safeAreaInsets.bottom))
cancelView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
cancelView.backgroundColor = settings.cancelView.backgroundColor
let cancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: settings.cancelView.height))
cancelButton.addTarget(self, action: #selector(ActionController.cancelButtonDidTouch(_:)), for: .touchUpInside)
cancelButton.setTitle(settings.cancelView.title, for: UIControl.State())
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelView.addSubview(cancelButton)
let metrics = ["height": settings.cancelView.height]
cancelView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[button]|", options: [], metrics: metrics, views: ["button": cancelButton]))
cancelView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[button(height)]", options: [], metrics: metrics, views: ["button": cancelButton]))
return cancelView
}
open func updateCancelViewLayout() {
guard settings.cancelView.showCancel, let cancelView = self.cancelView else {
return
}
cancelView.frame.size.height = settings.cancelView.height + safeAreaInsets.bottom
}
// MARK: - UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfSections()
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if hasHeader() && section == 0 { return 0 }
let rows = _sections[actionSectionIndexFor(section)].actions.count
guard let dynamicSectionIndex = _dynamicSectionIndex else {
return settings.behavior.useDynamics ? 0 : rows
}
if settings.behavior.useDynamics && section > dynamicSectionIndex {
return 0
}
return rows
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader {
if (indexPath as NSIndexPath).section == 0 && hasHeader() {
let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ReusableViewIds.Header.rawValue, for: indexPath) as? HeaderViewType
onConfigureHeader?(reusableview!, headerData!)
return reusableview!
} else {
let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ReusableViewIds.SectionHeader.rawValue, for: indexPath) as? SectionHeaderViewType
onConfigureSectionHeader?(reusableview!, sectionForIndex(actionSectionIndexFor((indexPath as NSIndexPath).section))!.data!)
return reusableview!
}
}
fatalError()
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let action = actionForIndexPath(actionIndexPathFor(indexPath))
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ReusableViewIds.Cell.rawValue, for: indexPath) as? ActionViewType
self.onConfigureCellForAction?(cell!, action!, indexPath)
return cell!
}
// MARK: - UICollectionViewDelegate & UICollectionViewDelegateFlowLayout
open func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
let cell = collectionView.cellForItem(at: indexPath) as? ActionViewType
(cell as? SeparatorCellType)?.hideSeparator()
if let prevCell = prevCell(indexPath) {
(prevCell as? SeparatorCellType)?.hideSeparator()
}
return true
}
open func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? ActionViewType
(cell as? SeparatorCellType)?.showSeparator()
if let prevCell = prevCell(indexPath) {
(prevCell as? SeparatorCellType)?.showSeparator()
}
}
open func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return !disableActions && actionForIndexPath(actionIndexPathFor(indexPath))?.enabled == true
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let action = self.actionForIndexPath(actionIndexPathFor(indexPath))
if let action = action, action.executeImmediatelyOnTouch {
action.handler?(action)
}
self.dismiss() {
if let action = action, !action.executeImmediatelyOnTouch {
action.handler?(action)
}
}
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let action = self.actionForIndexPath(actionIndexPathFor(indexPath)), let actionData = action.data else {
return CGSize.zero
}
let referenceWidth = collectionView.bounds.size.width
let margins = 2 * settings.collectionView.lateralMargin + collectionView.contentInset.left + collectionView.contentInset.right
return CGSize(width: referenceWidth - margins, height: cellSpec.height(actionData))
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
if let headerData = headerData, let headerSpec = headerSpec {
return CGSize(width: collectionView.bounds.size.width, height: headerSpec.height(headerData))
} else if let sectionHeaderSpec = sectionHeaderSpec, let section = sectionForIndex(actionSectionIndexFor(section)), let sectionData = section.data {
return CGSize(width: collectionView.bounds.size.width, height: sectionHeaderSpec.height(sectionData))
}
} else if let sectionHeaderSpec = sectionHeaderSpec, let section = sectionForIndex(actionSectionIndexFor(section)), let sectionData = section.data {
return CGSize(width: collectionView.bounds.size.width, height: sectionHeaderSpec.height(sectionData))
}
return CGSize.zero
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize.zero
}
// MARK: - UIViewControllerTransitioningDelegate
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
// MARK: - UIViewControllerAnimatedTransitioning
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return isPresenting ? 0 : settings.animation.dismiss.duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let fromView = fromViewController.view
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let toView = toViewController.view
if isPresenting {
toView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
containerView.addSubview(toView!)
transitionContext.completeTransition(true)
presentView(toView!, presentingView: fromView!, animationDuration: settings.animation.present.duration, completion: nil)
} else {
dismissView(fromView!, presentingView: toView!, animationDuration: settings.animation.dismiss.duration) { completed in
if completed {
fromView?.removeFromSuperview()
}
transitionContext.completeTransition(completed)
}
}
}
open func presentView(_ presentedView: UIView, presentingView: UIView, animationDuration: Double, completion: ((_ completed: Bool) -> Void)?) {
onWillPresentView()
let animationSettings = settings.animation.present
UIView.animate(withDuration: animationDuration,
delay: animationSettings.delay,
usingSpringWithDamping: animationSettings.damping,
initialSpringVelocity: animationSettings.springVelocity,
options: animationSettings.options.union(.allowUserInteraction),
animations: { [weak self] in
if let transformScale = self?.settings.animation.scale {
presentingView.transform = CGAffineTransform(scaleX: transformScale.width, y: transformScale.height)
}
self?.performCustomPresentationAnimation(presentedView, presentingView: presentingView)
},
completion: { [weak self] finished in
self?.onDidPresentView()
completion?(finished)
})
}
open func dismissView(_ presentedView: UIView, presentingView: UIView, animationDuration: Double, completion: ((_ completed: Bool) -> Void)?) {
onWillDismissView()
let animationSettings = settings.animation.dismiss
UIView.animate(withDuration: animationDuration,
delay: animationSettings.delay,
usingSpringWithDamping: animationSettings.damping,
initialSpringVelocity: animationSettings.springVelocity,
options: animationSettings.options.union(.allowUserInteraction),
animations: { [weak self] in
if let _ = self?.settings.animation.scale {
presentingView.transform = CGAffineTransform.identity
}
self?.performCustomDismissingAnimation(presentedView, presentingView: presentingView)
},
completion: { [weak self] _ in
self?.onDidDismissView()
completion?(true)
})
}
open func onWillPresentView() {
backgroundView.alpha = 0.0
cancelView?.frame.origin.y = view.bounds.size.height
collectionView.collectionViewLayout.invalidateLayout()
collectionView.layoutSubviews()
// Override this to add custom behavior previous to start presenting view animated.
// Tip: you could start a new animation from this method
}
open func performCustomPresentationAnimation(_ presentedView: UIView, presentingView: UIView) {
backgroundView.alpha = 1.0
cancelView?.frame.origin.y = view.bounds.size.height - settings.cancelView.height - safeAreaInsets.bottom
collectionView.frame = view.bounds
// Override this to add custom animations. This method is performed within the presentation animation block
}
open func onDidPresentView() {
// Override this to add custom behavior when the presentation animation block finished
}
open func onWillDismissView() {
// Override this to add custom behavior previous to start dismissing view animated
// Tip: you could start a new animation from this method
}
open func performCustomDismissingAnimation(_ presentedView: UIView, presentingView: UIView) {
backgroundView.alpha = 0.0
cancelView?.frame.origin.y = view.bounds.size.height
collectionView.frame.origin.y = contentHeight + (settings.cancelView.showCancel ? settings.cancelView.height : 0) + settings.animation.dismiss.offset
// Override this to add custom animations. This method is performed within the presentation animation block
}
open func onDidDismissView() {
// Override this to add custom behavior when the presentation animation block finished
}
// MARK: - Event handlers
@objc func cancelButtonDidTouch(_ sender: UIButton) {
self.dismiss()
}
@objc func tapGestureDidRecognize(_ gesture: UITapGestureRecognizer) {
self.dismiss()
}
@objc func swipeGestureDidRecognize(_ gesture: UISwipeGestureRecognizer) {
self.dismiss()
}
// MARK: - Internal helpers
func prevCell(_ indexPath: IndexPath) -> ActionViewType? {
let prevPath: IndexPath?
switch (indexPath as NSIndexPath).item {
case 0 where (indexPath as NSIndexPath).section > 0:
prevPath = IndexPath(item: collectionView(collectionView, numberOfItemsInSection: (indexPath as NSIndexPath).section - 1) - 1, section: (indexPath as NSIndexPath).section - 1)
case let x where x > 0:
prevPath = IndexPath(item: x - 1, section: (indexPath as NSIndexPath).section)
default:
prevPath = nil
}
guard let unwrappedPrevPath = prevPath else { return nil }
return collectionView.cellForItem(at: unwrappedPrevPath) as? ActionViewType
}
func hasHeader() -> Bool {
return headerData != nil && headerSpec != nil
}
fileprivate func numberOfActions() -> Int {
return _sections.flatMap({ $0.actions }).count
}
fileprivate func numberOfSections() -> Int {
return hasHeader() ? _sections.count + 1 : _sections.count
}
fileprivate func actionSectionIndexFor(_ section: Int) -> Int {
return hasHeader() ? section - 1 : section
}
fileprivate func setUpContentInsetForHeight(_ height: CGFloat) {
if initialContentInset == nil {
initialContentInset = collectionView.contentInset
}
var leftInset = initialContentInset.left
var rightInset = initialContentInset.right
var bottomInset = settings.cancelView.showCancel ? settings.cancelView.height : initialContentInset.bottom
var topInset = height - contentHeight - safeAreaInsets.bottom
if settings.cancelView.showCancel {
topInset -= settings.cancelView.height
}
topInset = max(topInset, 30)
bottomInset += safeAreaInsets.bottom
leftInset += safeAreaInsets.left
rightInset += safeAreaInsets.right
topInset += safeAreaInsets.top
collectionView.contentInset = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
if !settings.behavior.useDynamics {
collectionView.contentOffset.y = -height + contentHeight + safeAreaInsets.bottom
}
}
// MARK: - Private properties
fileprivate var navigationBarWasHiddenAtStart = false
fileprivate var initialContentInset: UIEdgeInsets!
fileprivate var disableActions = false
fileprivate var isPresenting = false
fileprivate var _dynamicSectionIndex: Int?
fileprivate var _headerData: RawData<HeaderDataType>?
fileprivate var _sections = [Section<ActionDataType, SectionHeaderDataType>]()
}
// MARK: - DynamicsActionController class
open class DynamicsActionController<ActionViewType: UICollectionViewCell, ActionDataType, HeaderViewType: UICollectionReusableView, HeaderDataType, SectionHeaderViewType: UICollectionReusableView, SectionHeaderDataType> : ActionController<ActionViewType, ActionDataType, HeaderViewType, HeaderDataType, SectionHeaderViewType, SectionHeaderDataType> {
open lazy var animator: UIDynamicAnimator = {
return UIDynamicAnimator()
}()
open lazy var gravityBehavior: UIGravityBehavior = {
let gravity = UIGravityBehavior(items: [self.collectionView])
gravity.magnitude = 10
return gravity
}()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
settings.behavior.useDynamics = true
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
settings.behavior.useDynamics = true
}
open override func viewDidLoad() {
super.viewDidLoad()
collectionView.frame = view.bounds
contentHeight = CGFloat(numberOfActions()) * settings.collectionView.cellHeightWhenDynamicsIsUsed + (CGFloat(_sections.count) * (collectionViewLayout.sectionInset.top + collectionViewLayout.sectionInset.bottom))
contentHeight += collectionView.contentInset.bottom
setUpContentInsetForHeight(view.frame.height)
view.setNeedsLayout()
view.layoutIfNeeded()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
for (index, section) in _sections.enumerated() {
var rowIndex = -1
let indexPaths = section.actions.map({ _ -> IndexPath in
rowIndex += 1
return IndexPath(row: rowIndex, section: index)
})
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.3 * Double(index) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
self._dynamicSectionIndex = index
self.collectionView.performBatchUpdates({
if indexPaths.count > 0 {
self.collectionView.insertItems(at: indexPaths)
}
}, completion: nil)
})
}
}
// MARK: - UICollectionViewDelegate & UICollectionViewDelegateFlowLayout
open override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let alignment = (collectionViewLayout as? DynamicCollectionViewFlowLayout)?.itemsAligment , alignment != .fill else {
return super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
}
if let action = self.actionForIndexPath(actionIndexPathFor(indexPath)), let actionData = action.data {
let referenceWidth = min(collectionView.bounds.size.width, collectionView.bounds.size.height)
let width = referenceWidth - (2 * settings.collectionView.lateralMargin) - collectionView.contentInset.left - collectionView.contentInset.right
return CGSize(width: width, height: cellSpec.height(actionData))
}
return CGSize.zero
}
// MARK: - Overrides
open override func dismiss() {
dismiss(nil)
}
open override func dismiss(_ completion: (() -> ())?) {
animator.addBehavior(gravityBehavior)
UIView.animate(withDuration: settings.animation.dismiss.duration, animations: { [weak self] in
self?.backgroundView.alpha = 0.0
})
presentingViewController?.dismiss(animated: true, completion: completion)
}
open override func dismissView(_ presentedView: UIView, presentingView: UIView, animationDuration: Double, completion: ((_ completed: Bool) -> Void)?) {
onWillDismissView()
UIView.animate(withDuration: animationDuration,
animations: { [weak self] in
presentingView.transform = CGAffineTransform.identity
self?.performCustomDismissingAnimation(presentedView, presentingView: presentingView)
},
completion: { [weak self] finished in
self?.onDidDismissView()
completion?(finished)
})
}
open override func onWillPresentView() {
backgroundView.frame = view.bounds
backgroundView.alpha = 0.0
self.backgroundView.alpha = 1.0
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
open override func performCustomDismissingAnimation(_ presentedView: UIView, presentingView: UIView) {
// Nothing to do in this case
}
}
| 43.237454 | 373 | 0.68535 |
e6ed2e408eab13f94da1c10b889c05fda436a1ad | 979 | //
// IOS8SwiftFileManagementTutorialTests.swift
// IOS8SwiftFileManagementTutorialTests
//
// Created by Arthur Knopper on 03/03/15.
// Copyright (c) 2015 Arthur Knopper. All rights reserved.
//
import UIKit
import XCTest
class IOS8SwiftFileManagementTutorialTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 26.459459 | 111 | 0.644535 |
e8752732f1e1283af8e4c348f0ca9ed775ae06a1 | 1,871 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: MSCenteredLabelCell
open class MSCenteredLabelCell: UITableViewCell {
public static let identifier: String = "MSCenteredLabelCell"
public static let defaultHeight: CGFloat = 45
private struct Constants {
static let labelFont: UIFont = MSFonts.body
static let paddingVerticalSmall: CGFloat = 5
}
// Public to be able to change style without wrapping every property
public let label: UILabel = {
let label = UILabel()
label.backgroundColor = .clear
label.font = Constants.labelFont
label.textColor = MSColors.Table.CenteredLabelCell.text
return label
}()
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(label)
backgroundColor = MSColors.Table.Cell.background
}
@objc public required init(coder aDecoder: NSCoder) {
preconditionFailure("init(coder:) has not been implemented")
}
/// Set up the cell with text to be displayed in the centered label
///
/// - Parameter text: The text to be displayed
open func setup(text: String) {
label.text = text
setNeedsLayout()
}
open override func layoutSubviews() {
super.layoutSubviews()
let labelFittingSize = label.sizeThatFits(CGSize(width: contentView.frame.width - layoutMargins.left - layoutMargins.right, height: CGFloat.greatestFiniteMagnitude))
label.frame.size = labelFittingSize
label.centerInSuperview()
}
open override func setHighlighted(_ highlighted: Bool, animated: Bool) { }
open override func setSelected(_ selected: Bool, animated: Bool) { }
}
| 32.824561 | 173 | 0.691074 |
56b572570f6cfea0008f5baa82d5ba5d34567126 | 7,073 | //
// AccountViewController.swift
// ravenwallet
//
// Created by Adrian Corscadden on 2016-11-16.
// Copyright © 2018 Ravenwallet Team. All rights reserved.
//
import UIKit
import Core
import MachO
let manageAssetHeaderHeight: CGFloat = E.isIPhoneXOrLater ? 90 : 67.0
class ManageAssetDisplayVC : UIViewController, Subscriber {
//MARK: - Private
private let headerView: ManageAssetHeaderView
private let transitionDelegate = ModalTransitionDelegate(type: .transactionDetail)
private var assetFilterListVC: AssetFilterTableVC!
private var isLoginRequired = false
private let headerContainer = UIView()
private let filters: [AssetManager.AssetFilter] = [
.blacklist,
.whitelist
]
private let filterSelectorView = UIView()
private let filterSelectorControl: UISegmentedControl
private let whitelistAdapter: WhitelistAdapter
private let blacklistAdapter: BlacklistAdapter
private var shouldShowStatusBar: Bool = true {
didSet {
if oldValue != shouldShowStatusBar {
UIView.animate(withDuration: C.animationDuration) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
}
}
init() {
self.headerView = ManageAssetHeaderView(title: S.Asset.settingTitle)
self.assetFilterListVC = AssetFilterTableVC()
self.whitelistAdapter = WhitelistAdapter(assetManager: AssetManager.shared)
self.blacklistAdapter = BlacklistAdapter(assetManager: AssetManager.shared)
// Filter setup
self.filterSelectorControl = UISegmentedControl(items: filters.map({$0.displayString}))
super.init(nibName: nil, bundle: nil)
self.whitelistAdapter.delegate = self
self.blacklistAdapter.delegate = self
let assetFilter = AssetManager.shared.assetFilter
filterSelectorControl.selectedSegmentIndex = filters.firstIndex(of: assetFilter)!
filterSelectorControl.valueChanged = filterSelectorDidChange
showFilterList(assetFilter)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - UIViewController
extension ManageAssetDisplayVC {
override func viewDidLoad() {
super.viewDidLoad()
addSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
shouldShowStatusBar = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkForEmptyWhitelist()
}
}
//MARK: - View Setup
extension ManageAssetDisplayVC {
private func addSubviews() {
// Style
view.backgroundColor = .whiteTint
// Header container
view.addSubview(headerContainer)
headerContainer.constrainTopCorners(height: manageAssetHeaderHeight)
// Header
headerContainer.addSubview(headerView)
headerView.constrain(toSuperviewEdges: nil)
// Selector container
view.addSubview(filterSelectorView)
filterSelectorView.constrain([
filterSelectorView.topAnchor.constraint(equalTo: headerContainer.bottomAnchor),
filterSelectorView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
filterSelectorView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
filterSelectorView.heightAnchor.constraint(equalToConstant: 40.0)
])
// Selector
filterSelectorView.addSubview(filterSelectorControl)
filterSelectorControl.constrain([
filterSelectorControl.rightAnchor.constraint(equalTo: filterSelectorView.rightAnchor, constant: -C.padding[1]),
filterSelectorControl.centerYAnchor.constraint(equalTo: filterSelectorView.centerYAnchor),
filterSelectorControl.leftAnchor.constraint(equalTo: filterSelectorView.leftAnchor, constant: C.padding[1]),
filterSelectorControl.topAnchor.constraint(equalTo: filterSelectorView.topAnchor, constant: C.padding[1]),
filterSelectorControl.bottomAnchor.constraint(equalTo: filterSelectorView.bottomAnchor, constant: -C.padding[1])
])
// Filter list view controller
addChild(assetFilterListVC, layout: {
if #available(iOS 11.0, *) {
assetFilterListVC.view.constrain([
assetFilterListVC.view.topAnchor.constraint(equalTo: filterSelectorView.bottomAnchor),
assetFilterListVC.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
assetFilterListVC.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
assetFilterListVC.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
])
} else {
assetFilterListVC.view.constrain(toSuperviewEdges: nil)
}
})
}
override var prefersStatusBarHidden: Bool {
return !shouldShowStatusBar
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
private func showFilterList(_ filter: AssetManager.AssetFilter) {
switch filter {
case .whitelist:
self.assetFilterListVC.adapter = self.whitelistAdapter
checkForEmptyWhitelist()
case .blacklist:
self.assetFilterListVC.adapter = self.blacklistAdapter
}
}
private func checkForEmptyWhitelist() {
// Check that the adapter is the whitelist adapter, we don't care about whether or not the blacklist is empty
guard let adapter = assetFilterListVC.adapter as? WhitelistAdapter else { return }
if adapter.includedList.count == 0 {
showEmptyWhitelistAlert()
}
}
func showEmptyWhitelistAlert() {
let alertVc = UIAlertController(
title: S.Alert.warning,
message: S.Asset.whitelistEmptyWarningMessage,
preferredStyle: .alert)
let dismissAction = UIAlertAction(title: S.Button.dismiss, style: .default, handler: nil)
alertVc.addAction(dismissAction)
present(alertVc, animated: false)
}
}
//MARK: - Handlers
extension ManageAssetDisplayVC {
func filterSelectorDidChange() {
let index = filterSelectorControl.selectedSegmentIndex
let filter = filters[index]
AssetManager.shared.setAssetFilter(filter)
showFilterList(filter)
}
}
extension ManageAssetDisplayVC: AssetFilterAdapterDelegate {
func didRemoveFromList(_ adapter: AssetFilterAdapterProtocol) {
checkForEmptyWhitelist()
}
}
| 34.671569 | 124 | 0.669164 |
feb510724170298d4a85db6df331246fee831807 | 3,811 | //
// MediaInfo.swift
// OpenVideoCall
//
// Created by GongYuhua on 4/11/16.
// Copyright © 2016 Agora. All rights reserved.
//
import Foundation
import AgoraRtcKit
struct RTCStatistics {
struct Local {
var stats = AgoraChannelStats()
}
struct Remote {
var videoStats = AgoraRtcRemoteVideoStats()
var audioStats = AgoraRtcRemoteAudioStats()
}
enum StatisticsType {
case local(Local), remote(Remote)
var isLocal: Bool {
switch self {
case .local: return true
case .remote: return false
}
}
}
var dimension = CGSize.zero
var fps = 0
var txQuality: AgoraNetworkQuality = .unknown
var rxQuality: AgoraNetworkQuality = .unknown
var type: StatisticsType
init(type: StatisticsType) {
self.type = type
}
mutating func updateChannelStats(_ stats: AgoraChannelStats) {
guard self.type.isLocal else {
return
}
let info = Local(stats: stats)
self.type = .local(info)
}
mutating func updateVideoStats(_ stats: AgoraRtcRemoteVideoStats) {
switch type {
case .remote(let info):
var new = info
new.videoStats = stats
self.type = .remote(new)
default:
break
}
}
mutating func updateAudioStats(_ stats: AgoraRtcRemoteAudioStats) {
switch type {
case .remote(let info):
var new = info
new.audioStats = stats
self.type = .remote(new)
default:
break
}
}
func description() -> String {
var full: String
switch type {
case .local(let info): full = localDescription(info: info)
case .remote(let info): full = remoteDescription(info: info)
}
return full
}
func localDescription(info: Local) -> String {
let join = "\n"
let dimensionFps = "\(Int(dimension.width))×\(Int(dimension.height)), \(fps)fps"
let quality = "Send/Recv Quality: \(txQuality.description())/\(rxQuality.description())"
let lastmile = "Lastmile Delay: \(info.stats.lastmileDelay)ms"
let videoSendRecv = "Video Send/Recv: \(info.stats.txVideoKBitrate)kbps/\(info.stats.rxVideoKBitrate)kbps"
let audioSendRecv = "Audio Send/Recv: \(info.stats.txAudioKBitrate)kbps/\(info.stats.rxAudioKBitrate)kbps"
let cpu = "CPU: App/Total \(info.stats.cpuAppUsage)%/\(info.stats.cpuTotalUsage)%"
let sendRecvLoss = "Send/Recv Loss: \(info.stats.txPacketLossRate)%/\(info.stats.rxPacketLossRate)%"
return dimensionFps + join + lastmile + join + videoSendRecv + join + audioSendRecv + join + cpu + join + quality + join + sendRecvLoss
}
func remoteDescription(info: Remote) -> String {
let join = "\n"
let dimensionFpsBit = "\(Int(dimension.width))×\(Int(dimension.height)), \(fps)fps, \(info.videoStats.receivedBitrate)kbps"
let quality = "Send/Recv Quality: \(txQuality.description())/\(rxQuality.description())"
var audioQuality: AgoraNetworkQuality
if let quality = AgoraNetworkQuality(rawValue: info.audioStats.quality) {
audioQuality = quality
} else {
audioQuality = AgoraNetworkQuality.unknown
}
let audioNet = "Audio Net Delay/Jitter: \(info.audioStats.networkTransportDelay)ms/\(info.audioStats.jitterBufferDelay)ms)"
let audioLoss = "Audio Loss/Quality: \(info.audioStats.audioLossRate)% \(audioQuality.description())"
return dimensionFpsBit + join + quality + join + audioNet + join + audioLoss
}
}
| 32.29661 | 144 | 0.600105 |
dd98aaf7c30a73c43b6580c62c50dd14a04759de | 226 | //
// HolidayCollectionViewCell.swift
// HolidayList
//
// Created by Sue Cho on 2020/11/15.
//
import UIKit
class HolidayCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
}
| 15.066667 | 55 | 0.70354 |
2202189f468618205ffe6781070b88f3bebe695e | 225 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum B : b { func a
{
if true {
C((f: a
{
class
case c,
| 18.75 | 87 | 0.715556 |
e92954ce02f8d39ab50f5272d11f3755860840e6 | 5,056 | import Foundation
struct EnvParseError: Error {
let message: String
}
let NULL_KEYWORD = "null"
/// Parser that allows to read simple key:value Dictionary<String, Any?> to nested structure using dicts, arrays and simple types
/// Separator is used to split keys into parts.
/// Each part corresponds to one level in output data.
///
/// If currentPart is last part, the value from input dict is assigned to it
/// If currentPart isn't last part and may be casted to int, it means that it is array index (If there are indexes missing in result it will be filled with nil)
/// If currentPart isn't last part and isn't castable to int, it means that this is nested dictionary key
class FlatDictConfigParser {
let data: [String: Any?]
let separator: Character
init(data: [String: Any?], separator: Character) {
self.data = data
self.separator = separator
}
/// Splits key to array of strings using predefined separator
private func keyToPathArray(_ key: String) -> [String] {
return key.split(separator: separator).compactMap { $0.lowercased() }
}
/// Joins array of string to KeyPathReferenceable format
private func pathArrayToKeyPath(_ pathArray: [String]) -> String {
return pathArray.joined(separator: ".")
}
public func decode() throws -> Storage {
var result: Storage = [:]
let sortedKeys = Array(data.keys).sorted()
for key in sortedKeys {
let value = data[key]
let splittedPath = keyToPathArray(key)
var path: [String] = []
for (i, pathPart) in keyToPathArray(key).enumerated() {
path.append("\(pathPart)")
let keyPath = pathArrayToKeyPath(path)
let isLastPart = i == splittedPath.count - 1
let isCurrentKeyInt: Bool = Int("\(pathPart)") != nil
let isNextKeyInt: Bool = isLastPart ? false : Int("\(splittedPath[i + 1])") != nil
let currentValue: Any? = result[keyPath: keyPath]
// Check if value exists
if let currentValue = currentValue {
// Value already exists, need to check if type matches value
if isLastPart {
// Means that there is duplicate key in environment
throw EnvParseError(message: "Attempt to override existing value: '\(currentValue)' for path: '\(keyPath)', with '\(key)=\(String(describing: value))'. Please check env configuration")
} else {
if currentValue as? Storage != nil, !isNextKeyInt {
// Current value is dict and next key is string type
continue
} else if currentValue as? StorageArray != nil, isNextKeyInt {
// Current value is array and next key is int type
continue
} else {
// Value is not wrapper type
throw EnvParseError(message: "Misconfiguration error: Expected array or dict, got '\(currentValue)' for path: '\(keyPath)', with '\(key)=\(String(describing: value))'. Please check env configuration")
}
}
} else {
// If it's last part value should be assigned directly
// If not, need to create array or dict wrapper
if isCurrentKeyInt {
fillMissingArrayIndexes(path: path, pathPart: pathPart, result: &result)
}
if isLastPart {
if let value = (value as? String), value == NULL_KEYWORD {
result[keyPath: keyPath] = nil
} else {
result[keyPath: keyPath] = value as Any?
}
} else {
// Check whether next key might be casted to INT, if so we suppose that wrapper should be array
// If not dict is used as wrapper
if isNextKeyInt {
result[keyPath: keyPath] = []
} else {
result[keyPath: keyPath] = [:]
}
}
}
}
}
return result
}
private func fillMissingArrayIndexes(path: [String], pathPart: String, result: inout Storage) {
let parentPath = pathArrayToKeyPath(Array(path[0 ..< path.count - 1]))
var parentValue = result[keyPath: parentPath] as! [Any?]
let currentIntKey = Int("\(pathPart)")!
if parentValue.count <= currentIntKey {
// Fill missing values with nil
for _ in parentValue.count ... currentIntKey {
parentValue.append(nil)
}
result[keyPath: parentPath] = parentValue
}
}
}
| 43.965217 | 228 | 0.541733 |
cc2ecd46ba598bebc77809e55eb54c7c9d1cf947 | 1,639 | //
// ChildSettingsTabViewController.swift
// Story Squad
//
// Created by macbook on 3/23/20.
// Copyright © 2020 Lambda School. All rights reserved.
//
import UIKit
class ChildSettingsTabViewController: UIViewController {
// MARK: - Properties
var networkingController: NetworkingController?
var parentUser: Parent?
var childUser: Child?
override func viewDidLoad() {
super.viewDidLoad()
receiveDataFromTabBar()
updateViews()
// Hide the Keyboard with tap gesture
self.hideKeyboardWhenTappedAround()
}
@IBAction func logoutButtonTapped(_ sender: UIButton) {
handleSignOut()
}
// Sign out
private func handleSignOut() {
networkingController?.logOut()
dismiss(animated: true, completion: nil)
}
// To receive the Child, Parent and NetworkingController from the Tab Bar
private func receiveDataFromTabBar() {
guard let tabBar = tabBarController as? ChildTabBarController else { return }
self.parentUser = tabBar.parentUser
self.childUser = tabBar.childUser
self.networkingController = tabBar.networkingController
}
private func updateViews() {
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 26.435484 | 106 | 0.649786 |
d93080b617db8d233e8b50e45fa48e2790d6a365 | 868 | //
// ELNTag+CoreDataProperties.swift
// ios-logger
//
// Created by Evgeniy Akhmerov on 27/11/2017.
// Copyright © 2017 e-Legion. All rights reserved.
//
//
import Foundation
import CoreData
extension ELNTag {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ELNTag> {
return NSFetchRequest<ELNTag>(entityName: "ELNTag")
}
@NSManaged public var value: String
@NSManaged public var message: NSSet
}
// MARK: Generated accessors for message
extension ELNTag {
@objc(addMessageObject:)
@NSManaged public func addToMessage(_ value: ELNMessage)
@objc(removeMessageObject:)
@NSManaged public func removeFromMessage(_ value: ELNMessage)
@objc(addMessage:)
@NSManaged public func addToMessage(_ values: NSSet)
@objc(removeMessage:)
@NSManaged public func removeFromMessage(_ values: NSSet)
}
| 21.170732 | 73 | 0.714286 |
166c7812b4dab713b200de354d964f30cfd2c1c1 | 604 | //
// AppDelegate.swift
// SlackNewWorkspace
//
// Created by giftbot on 16/05/2019.
// Copyright © 2019 giftbot. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
}
| 23.230769 | 143 | 0.730132 |
5b75dd4e348ee76ce6cabd3d484a75c101720116 | 2,588 | //
// StarRoutineWidget.swift
// StarRoutineWidget
//
// Created by David Barsamian on 2/8/21.
//
import SwiftUI
import WidgetKit
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date())
}
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> Void) {
let entry = SimpleEntry(date: Date())
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
}
struct StarRoutineWidgetEntryView: View {
var entry: Provider.Entry
var body: some View {
VStack {
Text("Goal")
.font(.headline)
Text("Date")
.font(.subheadline)
.italic()
Image(systemName: "star.fill")
.font(.largeTitle)
.foregroundColor(.yellow)
.padding()
}
}
}
@main
struct StarRoutineWidget: Widget {
let kind: String = "com.davidbarsam.starboard-goals"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
StarRoutineWidgetEntryView(entry: entry)
}
.configurationDisplayName("StarRoutine")
.description("Keep track of a goal and easily mark today off.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
struct StarRoutineWidget_Previews: PreviewProvider {
static var previews: some View {
Group {
StarRoutineWidgetEntryView(entry: SimpleEntry(date: Date()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
StarRoutineWidgetEntryView(entry: SimpleEntry(date: Date()))
.previewContext(WidgetPreviewContext(family: .systemMedium))
StarRoutineWidgetEntryView(entry: SimpleEntry(date: Date()))
.previewContext(WidgetPreviewContext(family: .systemLarge))
}
}
}
| 30.447059 | 104 | 0.623261 |
1430ac60cc722bf06c3c25307f0ed001551c059c | 1,411 | //
// Logger.swift
// DigiMeSDKExample
//
// Created on 21/07/2021.
// Copyright © 2021 digi.me Limited. All rights reserved.
//
import UIKit
class Logger {
weak var textView: UITextView?
enum Defaults {
static let font = UIFont(name: "Courier-Bold", size: 12)
}
init(textView: UITextView) {
self.textView = textView
textView.backgroundColor = .black
textView.textColor = .white
textView.isEditable = false
textView.font = Defaults.font
textView.text = ""
}
func log(message: String) {
DispatchQueue.main.async {
guard !message.isEmpty, let textView = self.textView else {
return
}
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let dateString = formatter.string(from: now)
textView.text += "\n" + dateString + " " + message + "\n"
self.scrollToBottom()
}
}
func reset() {
DispatchQueue.main.async {
self.textView?.text = ""
}
}
private func scrollToBottom() {
guard let textLength = textView?.text.count, textLength > 0 else {
return
}
textView?.scrollRangeToVisible(NSRange(location: textLength - 1, length: 1))
}
}
| 24.754386 | 84 | 0.549256 |
0a5d773f289af1f50446ca16eff84f4b240046ca | 1,391 | //
// InterButton.swift
// InterButton
//
// Created by Junya on 2020/10/10.
//
import UIKit
@IBDesignable
public final class InterButton: UIButton {
@IBInspectable public var minimumScale: CGFloat = 0.98
@IBInspectable public var duration: TimeInterval = 0.2
private let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
feedbackGenerator.prepare()
addTarget(self, action: #selector(touchDown(_:)), for: .touchDown)
addTarget(self, action: #selector(touchUp(_:)), for: .touchUpInside)
addTarget(self, action: #selector(touchUp(_:)), for: .touchUpOutside)
}
@objc private func touchDown(_ sender:UIButton) {
feedbackGenerator.impactOccurred()
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.transform = CGAffineTransform(scaleX: self.minimumScale, y: self.minimumScale)
})
}
@objc private func touchUp(_ sender:UIButton) {
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseIn) {
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
}
}
| 28.979167 | 95 | 0.63839 |
1af16a81dae42ddae36f190bead0f558ed94bf63 | 2,647 | //
// CEFLoadHandler.g.swift
// CEF.swift
//
// Created by Tamas Lustyik on 2015. 08. 05..
// Copyright © 2015. Tamas Lustyik. All rights reserved.
//
import Foundation
func CEFLoadHandler_on_loading_state_change(ptr: UnsafeMutablePointer<cef_load_handler_t>,
browser: UnsafeMutablePointer<cef_browser_t>,
isLoading: Int32,
canGoBack: Int32,
canGoForward: Int32) {
guard let obj = CEFLoadHandlerMarshaller.get(ptr) else {
return
}
obj.onLoadingStateChange(CEFBrowser.fromCEF(browser)!,
isLoading: isLoading != 0,
canGoBack: canGoBack != 0,
canGoForward: canGoForward != 0)
}
func CEFLoadHandler_on_load_start(ptr: UnsafeMutablePointer<cef_load_handler_t>,
browser: UnsafeMutablePointer<cef_browser_t>,
frame: UnsafeMutablePointer<cef_frame_t>) {
guard let obj = CEFLoadHandlerMarshaller.get(ptr) else {
return
}
obj.onLoadStart(CEFBrowser.fromCEF(browser)!, frame: CEFFrame.fromCEF(frame)!)
}
func CEFLoadHandler_on_load_end(ptr: UnsafeMutablePointer<cef_load_handler_t>,
browser: UnsafeMutablePointer<cef_browser_t>,
frame: UnsafeMutablePointer<cef_frame_t>,
statusCode: Int32) {
guard let obj = CEFLoadHandlerMarshaller.get(ptr) else {
return
}
obj.onLoadEnd(CEFBrowser.fromCEF(browser)!,
frame: CEFFrame.fromCEF(frame)!,
statusCode: Int(statusCode))
}
func CEFLoadHandler_on_load_error(ptr: UnsafeMutablePointer<cef_load_handler_t>,
browser: UnsafeMutablePointer<cef_browser_t>,
frame: UnsafeMutablePointer<cef_frame_t>,
errorCode: cef_errorcode_t,
errorMsg: UnsafePointer<cef_string_t>,
url: UnsafePointer<cef_string_t>) {
guard let obj = CEFLoadHandlerMarshaller.get(ptr) else {
return
}
obj.onLoadError(CEFBrowser.fromCEF(browser)!,
frame: CEFFrame.fromCEF(frame)!,
errorCode: CEFErrorCode.fromCEF(errorCode.rawValue),
errorMessage: CEFStringToSwiftString(errorMsg.memory),
url: NSURL(string: CEFStringToSwiftString(url.memory))!)
}
| 40.106061 | 90 | 0.563657 |
8790aa2cf31929d0588c9cd0730ceb0937d270f7 | 4,424 | //
// SectionViewController.swift
// Kouri-Vini
//
// Created by Aaron Walton on 8/23/16.
// Copyright © 2016 Apple. All rights reserved.
//
import UIKit
extension UILabel {
func setHTMLFromString(_ text: String) {
let modifiedFont = NSString(format:"<span style=\"font-family:Helvetica Neue; font-size: \(self.font!.pointSize)\">%@</span>" as NSString, text) as String
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
}
}
class SectionViewController: UIViewController {
//MARK: Properties
var labels = [String]()
@IBOutlet weak var textScroll: UIScrollView!
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if self.textScroll != nil {
navigationItem.title = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
// The following creates a ScrollView, takes the text for the section from an file, divides it, and puts it in labels. Currently, this code is working and working relatively well.
let sv = UIScrollView(frame: self.view.bounds)
sv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(sv)
sv.backgroundColor = UIColor.white
var y: CGFloat = 10
let file = detailItem as! String
navigationItem.title = file
/* let sectionsFile:String = Bundle.main.path(forResource: "OrthographySections", ofType: "txt")!
let sections = try? String(contentsOfFile: sectionsFile, encoding: String.Encoding.utf8)
let lines = sections?.components(separatedBy: "\n")
for (_, line) in (lines?.enumerated())! {
objects.append(line)
*/
if let sectionsFile:String = Bundle.main.path(forResource: file, ofType: "txt") {
if let sectionText = try? NSString(contentsOfFile: sectionsFile, encoding: String.Encoding.utf8.rawValue) {
let lineMaker = sectionText.replacingOccurrences(of: "*", with: "\n")
let lines = lineMaker.components(separatedBy: "\n")
for (index, line) in lines.enumerated() {
labels.append(line)
let label = UILabel()
label.setHTMLFromString(labels[index])
label.sizeToFit()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.frame.origin = CGPoint(x: 10,y: y)
sv.addSubview(label)
label.backgroundColor = UIColor.white
let desiredLabelWidth = self.view.bounds.size.width - 20
let size = label.sizeThatFits(CGSize(width: desiredLabelWidth, height: CGFloat.greatestFiniteMagnitude))
label.frame = CGRect(x: 10, y: y, width: desiredLabelWidth, height: size.height)
y += label.bounds.size.height + 10
label.autoresizingMask = .flexibleWidth
}
var sz = sv.bounds.size
sz.height = y
sv.contentSize = sz
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 36.262295 | 187 | 0.595615 |
edf0301123e30dc77c80c1b1a4bb9479f7829e57 | 1,425 | //
// AppDelegate.swift
// MultipliQuiz
//
// Created by Oscar da Silva on 06.05.20.
// Copyright © 2020 Oscar da Silva. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.5 | 179 | 0.747368 |
691b52e3f593ea9af7c79af309685c3918e50b21 | 1,446 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import Reusable
final class ReactionHistoryViewCell: UITableViewCell, NibReusable, Themable {
// MARK: - Properties
@IBOutlet private weak var reactionLabel: UILabel!
@IBOutlet private weak var userDisplayNameLabel: UILabel!
@IBOutlet private weak var timestampLabel: UILabel!
// MARK: - Public
func fill(with viewData: ReactionHistoryViewData) {
self.reactionLabel.text = viewData.reaction
self.userDisplayNameLabel.text = viewData.userDisplayName
self.timestampLabel.text = viewData.dateString
}
func update(theme: Theme) {
self.backgroundColor = theme.backgroundColor
self.reactionLabel.textColor = theme.textPrimaryColor
self.userDisplayNameLabel.textColor = theme.textPrimaryColor
self.timestampLabel.textColor = theme.textSecondaryColor
}
}
| 33.627907 | 77 | 0.741355 |
c1508b575a1eb89623feec88f1d57879b8a706fa | 1,820 | /*
Copyright (c) 2015 Kyohei Yamaguchi. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.white
title = "MainViewController"
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Open",
style: UIBarButtonItem.Style.plain,
target: self,
action: #selector(didTapOpenButton)
)
}
@objc func didTapOpenButton(_ sender: UIBarButtonItem) {
if let drawerController = navigationController?.parent as? KYDrawerController {
drawerController.setDrawerState(.opened, animated: true)
}
}
}
| 37.916667 | 87 | 0.736264 |
2f30e508873c6ce7a194988328b445e965056e44 | 5,833 | //
// ChannelGraphQLModel.swift
// AwesomeCore-iOS10.0
//
// Created by Evandro Harrison Hoffmann on 7/22/18.
//
import Foundation
public struct QuestChannelGraphQLModel {
// MARK: - Model Sections
// Channel
static let channelModel = "id description publishedAt slug title attendingMedia { \(mediaModel) } coverAsset { \(QuestGraphQLModel.assetImageModel) }"
static let channelContentModel = "\(channelModel) series { \(serieModel) } authors { \(authorModel) }"
static let channelSeriesContentModel = "\(channelModel) series { \(serieContentModel) }"
// Series
static let serieModel = "id publishedAt slug subtitle title coverAsset { \(QuestGraphQLModel.assetImageModel) }"
static let serieContentModel = "\(serieModel) media { \(mediaModel) } authors { \(authorModel) }"
// Media
static let mediaModel = "totalDuration averageRating currentRating featured favourite id publishedAt slug title type attendanceCount attending info endedAt startedAt tags { \(tagModel) } coverAsset { \(QuestGraphQLModel.assetImageModel) } author { \(authorModel) } settings { \(mediaSettingsModel) } description mediaAsset { \(QuestGraphQLModel.assetModel) } previewAsset { \(QuestGraphQLModel.assetModel) } "
static let tagModel = "name"
static let favouriteMediaModel = "favouriteMedia(authorId: %@) { \(mediaModel) }"
static let latestMediaModel = "latestMedia(authorId: %@, limit: %d) { \(mediaModel) }"
static let featuredMediaModel = "featuredMedia(authorId: %@, limit: %d) { \(mediaModel) }"
static let channelMediaModel = "media(authorId: %@, sort: %@, type: %@){ \(mediaModel) }"
static let authorModel = "avatarAsset { \(QuestGraphQLModel.assetImageModel) } description id name slug"
static let mediaSettingsModel = "zoomWebinarId"
// MARK: - Channel Query
private static let channelsModel = "query { channels { \(channelModel) %@ } }"
public static func queryChannels(withAuthorId authorId: String?, featuredMediaLimit: Int, latestMediaLimit: Int) -> [String: AnyObject] {
var extra = ""
if let authorId = authorId {
extra.append(" \(String(format: favouriteMediaModel, arguments: [authorId]))")
if featuredMediaLimit > 0 {
extra.append(" \(String(format: featuredMediaModel, arguments: [authorId, featuredMediaLimit]))")
}
if latestMediaLimit > 0 {
extra.append(" \(String(format: latestMediaModel, arguments: [authorId, latestMediaLimit]))")
}
}
return ["query": String(format: channelModel, arguments: [extra]) as AnyObject]
}
// MARK: - Single Channel Query
private static let singleChannelModel = "query { channel(id:%@) { \(channelContentModel) %@ } }"
private static let singleChannelSeriesModel = "query { channel(id:%@) { \(channelSeriesContentModel) %@ } }"
public static func querySingleChannelModel(withId id: String, authorId: String?, featuredMediaLimit: Int, latestMediaLimit: Int, seriesContent: Bool = false) -> [String: AnyObject] {
var extra = ""
if let authorId = authorId {
extra.append(" \(String(format: favouriteMediaModel, arguments: [authorId]))")
if featuredMediaLimit > 0 {
extra.append(" \(String(format: featuredMediaModel, arguments: [authorId, featuredMediaLimit]))")
}
if latestMediaLimit > 0 {
extra.append(" \(String(format: latestMediaModel, arguments: [authorId, latestMediaLimit]))")
}
}
return ["query": String(format: seriesContent ? singleChannelSeriesModel : singleChannelModel, arguments: [id, extra]) as AnyObject]
}
// MARK: - Single Series Query
private static let singleSeriesModel = "query { series(id:%@) { \(serieContentModel) } }"
public static func querySingleSeriesModel(withId id: String) -> [String: AnyObject] {
return ["query": String(format: singleSeriesModel, arguments: [id]) as AnyObject]
}
// MARK: - Single Media Query
private static let singleMediaModel = "query { media(id:%@) { \(mediaModel) } }"
public static func querySingleMediaModel(withId id: String) -> [String: AnyObject] {
return ["query": String(format: singleMediaModel, arguments: [id]) as AnyObject]
}
// MARK: - Media Rating Mutation
private static let mediaRatingModel = "mutation { rateMedia(mediaId:%@, rating:%.2f) { id } }"
public static func mutationMediaRatingModel(withId id: String, rating: Double) -> [String: AnyObject] {
return ["query": String(format: mediaRatingModel, arguments: [id, rating]) as AnyObject]
}
// MARK: - RSVP/Attend Media Mutation
private static let attendMediaModel = "mutation { attendMedia(mediaId:%@) { id } }"
private static let unattendMediaModel = "mutation { unattendMedia(mediaId:%@) { id } }"
public static func mutationAttendMediaModel(withId id: String, attend: Bool) -> [String: AnyObject] {
return ["query": String(format: attend ? attendMediaModel : unattendMediaModel, arguments: [id]) as AnyObject]
}
// MARK: - Favourite Media Mutation
private static let setFavouriteMediaModel = "mutation { setMediaAsFavourite(mediaId:%@) { id } }"
private static let unsetFavouriteMediaModel = "mutation { unsetMediaAsFavourite(mediaId:%@) { id } }"
public static func mutationFavouriteMediaModel(withId id: String, favourite: Bool) -> [String: AnyObject] {
return ["query": String(format: favourite ? setFavouriteMediaModel : unsetFavouriteMediaModel, arguments: [id]) as AnyObject]
}
}
| 47.422764 | 413 | 0.658838 |
232bca93652485be4a0d947ebb78ca9508326afb | 1,802 | //
// GATTSerialNumberString.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/27/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Serial Number String
[Serial Number String](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.serial_number_string.xml)
The value of this characteristic is a variable-length UTF-8 string representing the serial number for a particular instance of the device.
*/
public struct GATTSerialNumberString: RawRepresentable, GATTCharacteristic {
public static var uuid: BluetoothUUID { return .serialNumberString }
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard let rawValue = String(data: data, encoding: .utf8)
else { return nil }
self.init(rawValue: rawValue)
}
public var data: Data {
return Data(rawValue.utf8)
}
}
extension GATTSerialNumberString: Equatable {
public static func == (lhs: GATTSerialNumberString, rhs: GATTSerialNumberString) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTSerialNumberString: CustomStringConvertible {
public var description: String {
return rawValue
}
}
extension GATTSerialNumberString: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(rawValue: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(rawValue: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(rawValue: value)
}
}
| 23.710526 | 148 | 0.657048 |
727f2a38953f5d0cf29e962596737689438237d7 | 28,923 | // Copyright 2019 Google LLC
//
// 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
//
// https://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
public class Fuzzer {
/// Id of this fuzzer.
public let id: UUID
/// Has this fuzzer been initialized?
public private(set) var isInitialized = false
/// Has this fuzzer been stopped?
public private(set) var isStopped = false
/// The configuration used by this fuzzer.
public let config: Configuration
/// The list of events that can be dispatched on this fuzzer instance.
public let events: Events
/// Timer API for this fuzzer.
public let timers: Timers
/// The script runner used to execute generated scripts.
public let runner: ScriptRunner
/// The fuzzer engine producing new programs from existing ones and executing them.
public let engine: FuzzEngine
/// The active code generators. It is possible to change these (temporarily) at runtime. This is e.g. done by some ProgramTemplates.
public var codeGenerators: WeightedList<CodeGenerator>
/// The active program templates. These are only used if the HybridEngine is enabled.
public let programTemplates: WeightedList<ProgramTemplate>
/// The mutators used by the engine.
public let mutators: WeightedList<Mutator>
/// The evaluator to score generated programs.
public let evaluator: ProgramEvaluator
/// The model of the target environment.
public let environment: Environment
/// The lifter to translate FuzzIL programs to the target language.
public let lifter: Lifter
/// The corpus of "interesting" programs found so far.
public let corpus: Corpus
// The minimizer to shrink programs that cause crashes or trigger new interesting behaviour.
public let minimizer: Minimizer
/// The modules active on this fuzzer.
var modules = [String: Module]()
/// The DispatchQueue this fuzzer operates on.
/// This could in theory be publicly exposed, but then the stopping logic wouldn't work correctly anymore and would probably need to be implemented differently.
private let queue: DispatchQueue
/// DispatchGroup to group all tasks related to a fuzzing iterations together and thus be able to determine when they have all finished.
/// The next fuzzing iteration will only be performed once all tasks in this group have finished. As such, this group can generally be used
/// for all (long running) tasks during which it doesn't make sense to perform fuzzing.
private let fuzzGroup = DispatchGroup()
/// The logger instance for the main fuzzer.
private var logger: Logger
/// State management.
private var maxIterations = -1
private var iterations = 0
/// Fuzzer instances can be looked up from a dispatch queue through this key. See below.
private static let dispatchQueueKey = DispatchSpecificKey<Fuzzer>()
/// Constructs a new fuzzer instance with the provided components.
public init(
configuration: Configuration, scriptRunner: ScriptRunner, engine: FuzzEngine, mutators: WeightedList<Mutator>,
codeGenerators: WeightedList<CodeGenerator>, programTemplates: WeightedList<ProgramTemplate>, evaluator: ProgramEvaluator, environment: Environment,
lifter: Lifter, corpus: Corpus, minimizer: Minimizer, queue: DispatchQueue? = nil
) {
// Ensure collect runtime types mode is not enabled without abstract interpreter.
assert(!configuration.collectRuntimeTypes || configuration.useAbstractInterpretation)
let uniqueId = UUID()
self.id = uniqueId
self.queue = queue ?? DispatchQueue(label: "Fuzzer \(uniqueId)", target: DispatchQueue.global())
self.config = configuration
self.events = Events()
self.timers = Timers(queue: self.queue)
self.engine = engine
self.mutators = mutators
self.codeGenerators = codeGenerators
self.programTemplates = programTemplates
self.evaluator = evaluator
self.environment = environment
self.lifter = lifter
self.corpus = corpus
self.runner = scriptRunner
self.minimizer = minimizer
self.logger = Logger(withLabel: "Fuzzer")
// Register this fuzzer instance with its queue so that it is possible to
// obtain a reference to the Fuzzer instance when running on its queue.
// This creates a reference cycle, but Fuzzer instances aren't expected
// to be deallocated, so this is ok.
self.queue.setSpecific(key: Fuzzer.dispatchQueueKey, value: self)
}
/// Returns the fuzzer for the active DispatchQueue.
public static var current: Fuzzer? {
return DispatchQueue.getSpecific(key: Fuzzer.dispatchQueueKey)
}
/// Schedule work on this fuzzer's dispatch queue.
public func async(block: @escaping () -> ()) {
queue.async {
guard !self.isStopped else { return }
block()
}
}
/// Schedule work on this fuzzer's dispatch queue and wait for its completion.
public func sync(block: () -> ()) {
queue.sync {
guard !self.isStopped else { return }
block()
}
}
/// Adds a module to this fuzzer. Can only be called before the fuzzer is initialized.
public func addModule(_ module: Module) {
assert(!isInitialized)
assert(modules[module.name] == nil)
modules[module.name] = module
}
/// Initializes this fuzzer.
///
/// This will initialize all components and modules, causing event listeners to be registerd,
/// timers to be scheduled, communication channels to be established, etc. After initialization,
/// task may already be scheduled on this fuzzer's dispatch queue.
public func initialize() {
dispatchPrecondition(condition: .onQueue(queue))
assert(!isInitialized)
// Initialize the script runner first so we are able to execute programs.
runner.initialize(with: self)
// Then initialize all components.
engine.initialize(with: self)
evaluator.initialize(with: self)
environment.initialize(with: self)
corpus.initialize(with: self)
minimizer.initialize(with: self)
// Finally initialize all modules.
for module in modules.values {
module.initialize(with: self)
}
// Install a watchdog to monitor utilization of master instances.
if config.isMaster {
var lastCheck = Date()
timers.scheduleTask(every: 1 * Minutes) {
// Monitor responsiveness
let now = Date()
let interval = now.timeIntervalSince(lastCheck)
lastCheck = now
// Currently, minimization can take a very long time (up to a few minutes on slow CPUs for
// big samples). As such, the fuzzer would quickly be regarded as unresponsive by this metric.
// Ideally, it would be possible to split minimization into multiple smaller tasks or otherwise
// reduce its impact on the responsiveness of the fuzzer. But for now we just use a very large
// tolerance interval here...
if interval > 180 {
self.logger.warning("Fuzzing master appears unresponsive (watchdog only triggered after \(Int(interval))s instead of 60s). This is usually fine but will slow down synchronization a bit")
}
}
}
// Schedule a timer to print mutator statistics
if config.logLevel.isAtLeast(.info) {
timers.scheduleTask(every: 15 * Minutes) {
let stats = self.mutators.map({ "\($0.name): \(String(format: "%.2f%%", $0.stats.correctnessRate * 100))" }).joined(separator: ", ")
self.logger.info("Mutator correctness rates: \(stats)")
}
}
dispatchEvent(events.Initialized)
logger.info("Initialized")
isInitialized = true
}
/// Starts the fuzzer and runs for the specified number of iterations.
///
/// This must be called after initializing the fuzzer.
/// Use -1 for maxIterations to run indefinitely.
public func start(runFor maxIterations: Int) {
dispatchPrecondition(condition: .onQueue(queue))
assert(isInitialized)
assert(!corpus.isEmpty)
self.maxIterations = maxIterations
logger.info("Let's go!")
if config.isFuzzing {
// Start fuzzing
queue.async {
self.fuzzOne()
}
}
}
/// Shuts down this fuzzer.
public func shutdown(reason: ShutdownReason) {
dispatchPrecondition(condition: .onQueue(queue))
guard !isStopped else { return }
// No more scheduled tasks will execute after this point.
isStopped = true
timers.stop()
logger.info("Shutting down due to \(reason)")
dispatchEvent(events.Shutdown, data: reason)
dispatchEvent(events.ShutdownComplete, data: reason)
}
/// Registers a new listener for the given event.
public func registerEventListener<T>(for event: Event<T>, listener: @escaping Event<T>.EventListener) {
dispatchPrecondition(condition: .onQueue(queue))
event.addListener(listener)
}
/// Dispatches an event.
public func dispatchEvent<T>(_ event: Event<T>, data: T) {
dispatchPrecondition(condition: .onQueue(queue))
for listener in event.listeners {
listener(data)
}
}
/// Dispatches an event.
public func dispatchEvent(_ event: Event<Void>) {
dispatchEvent(event, data: ())
}
/// Imports a potentially interesting program into this fuzzer.
///
/// When importing, the program will be treated like one that was generated by this fuzzer. As such it will
/// be executed and evaluated to determine whether it results in previously unseen, interesting behaviour.
/// When dropout is enabled, a configurable percentage of programs will be ignored during importing. This
/// mechanism can help reduce the similarity of different fuzzer instances.
public func importProgram(_ program: Program, enableDropout: Bool = false, origin: ProgramOrigin) {
dispatchPrecondition(condition: .onQueue(queue))
if enableDropout && probability(config.dropoutRate) {
return
}
let execution = execute(program)
switch execution.outcome {
case .crashed(let termsig):
// Here we explicitly deal with the possibility that an interesting sample
// from another instance triggers a crash in this instance.
processCrash(program, withSignal: termsig, withStderr: execution.stderr, origin: origin)
case .succeeded:
if let aspects = evaluator.evaluate(execution) {
processInteresting(program, havingAspects: aspects, origin: origin)
}
default:
break
}
}
/// Imports a crashing program into this fuzzer.
///
/// Similar to importProgram, but will make sure to generate a CrashFound event even if the crash does not reproduce.
public func importCrash(_ program: Program, origin: ProgramOrigin) {
dispatchPrecondition(condition: .onQueue(queue))
let execution = execute(program)
if case .crashed(let termsig) = execution.outcome {
processCrash(program, withSignal: termsig, withStderr: execution.stderr, origin: origin)
} else {
// Non-deterministic crash
dispatchEvent(events.CrashFound, data: (program, behaviour: .flaky, signal: 0, isUnique: true, origin: origin))
}
}
/// When importing a corpus, this determines how valid samples are added to the corpus
public enum CorpusImportMode {
/// All valid programs are added to the corpus. This is intended to aid in finding
/// variants of existing bugs. Programs are not minimized before inclusion.
case all
/// Only programs that increase coverage are included in the fuzzing corpus.
/// These samples are intended as a solid starting point for the fuzzer.
case interestingOnly(shouldMinimize: Bool)
}
/// Imports multiple programs into this fuzzer.
///
/// This will import each program in the given array into this fuzzer while potentially discarding
/// some percentage of the programs if dropout is enabled.
public func importCorpus(_ corpus: [Program], importMode: CorpusImportMode, enableDropout: Bool = false) {
dispatchPrecondition(condition: .onQueue(queue))
for (count, program) in corpus.enumerated() {
if count % 500 == 0 {
logger.info("Imported \(count) of \(corpus.count)")
}
// Regardless of the import mode, we need to execute and evaluate the program first to update the evaluator state
let execution = execute(program)
guard execution.outcome == .succeeded else { continue }
let maybeAspects = evaluator.evaluate(execution)
switch importMode {
case .all:
processInteresting(program, havingAspects: ProgramAspects(outcome: .succeeded), origin: .corpusImport(shouldMinimize: false))
case .interestingOnly(let shouldMinimize):
if let aspects = maybeAspects {
processInteresting(program, havingAspects: aspects, origin: .corpusImport(shouldMinimize: shouldMinimize))
}
}
}
if case .interestingOnly(let shouldMinimize) = importMode, shouldMinimize {
fuzzGroup.notify(queue: queue) {
self.logger.info("Corpus import completed. Corpus now contains \(self.corpus.size) programs")
}
}
}
/// Exports the internal state of this fuzzer.
///
/// The state returned by this function can be passed to the importState method to restore
/// the state. This can be used to synchronize different fuzzer instances and makes it
/// possible to resume a previous fuzzing run at a later time.
public func exportState() throws -> Data {
dispatchPrecondition(condition: .onQueue(queue))
let state = try Fuzzilli_Protobuf_FuzzerState.with {
$0.corpus = try corpus.exportState()
$0.evaluatorState = evaluator.exportState()
}
return try state.serializedData()
}
/// Import a previously exported fuzzing state.
public func importState(from data: Data) throws {
dispatchPrecondition(condition: .onQueue(queue))
let state = try Fuzzilli_Protobuf_FuzzerState(serializedData: data)
try evaluator.importState(state.evaluatorState)
try corpus.importState(state.corpus)
}
/// Executes a program.
///
/// This will first lift the given FuzzIL program to the target language, then use the configured script runner to execute it.
///
/// - Parameters:
/// - program: The FuzzIL program to execute.
/// - timeout: The timeout after which to abort execution. If nil, the default timeout of this fuzzer will be used.
/// - Returns: An Execution structure representing the execution outcome.
public func execute(_ program: Program, withTimeout timeout: UInt32? = nil) -> Execution {
dispatchPrecondition(condition: .onQueue(queue))
assert(runner.isInitialized)
let script = lifter.lift(program, withOptions: .minify)
dispatchEvent(events.PreExecute, data: program)
let execution = runner.run(script, withTimeout: timeout ?? config.timeout)
dispatchEvent(events.PostExecute, data: execution)
return execution
}
private func inferMissingTypes(in program: Program) {
var ai = AbstractInterpreter(for: self.environment)
let runtimeTypes = program.types.onlyRuntimeTypes().indexedByInstruction(for: program)
var types = ProgramTypes()
for instr in program.code {
let typeChanges = ai.execute(instr)
for (variable, type) in typeChanges {
types.setType(of: variable, to: type, after: instr.index, quality: .inferred)
}
// Overwrite interpreter types with recently collected runtime types
for (variable, type) in runtimeTypes[instr.index] {
ai.setType(of: variable, to: type)
types.setType(of: variable, to: type, after: instr.index, quality: .runtime)
}
}
program.types = types
}
/// Collect and save runtime types of variables in program
private func collectRuntimeTypes(for program: Program) {
assert(program.typeCollectionStatus == .notAttempted)
let script = lifter.lift(program, withOptions: .collectTypes)
let execution = runner.run(script, withTimeout: 30 * config.timeout)
// JS prints lines alternating between variable name and its type
let fuzzout = execution.fuzzout
let lines = fuzzout.split(whereSeparator: \.isNewline)
if execution.outcome == .succeeded {
do {
var lineNumber = 0
while lineNumber < lines.count {
let variable = Variable(number: Int(lines[lineNumber])!), instrCount = Int(lines[lineNumber + 1])!
lineNumber += 2
// Parse (instruction, type) pairs for given variable
for i in stride(from: lineNumber, to: lineNumber + 2 * instrCount, by: 2) {
let proto = try Fuzzilli_Protobuf_Type(jsonUTF8Data: lines[i+1].data(using: .utf8)!)
let runtimeType = try Type(from: proto)
// Runtime types collection is not able to determine all types
// e.g. it cannot determine function signatures
if runtimeType != .unknown {
program.types.setType(of: variable, to: runtimeType, after: Int(lines[i])!, quality: .runtime)
}
}
lineNumber = lineNumber + 2 * instrCount
}
} catch {
logger.warning("Could not deserialize runtime types: \(error)")
if config.enableDiagnostics {
logger.warning("Fuzzout:\n\(fuzzout)")
}
}
} else {
logger.warning("Execution for type collection did not succeeded, outcome: \(execution.outcome)")
if config.enableDiagnostics, case .failed = execution.outcome {
logger.warning("Stdout:\n\(execution.stdout)")
}
}
// Save result of runtime types collection to Program
program.typeCollectionStatus = TypeCollectionStatus(from: execution.outcome)
}
@discardableResult
func updateTypeInformation(for program: Program) -> (didCollectRuntimeTypes: Bool, didInferTypesStatically: Bool) {
var didCollectRuntimeTypes = false, didInferTypesStatically = false
if config.collectRuntimeTypes && program.typeCollectionStatus == .notAttempted {
collectRuntimeTypes(for: program)
didCollectRuntimeTypes = true
}
// Interpretation is needed either if the program does not have any type info (e.g. was minimized)
// or if we collected runtime types which can now be improved statically by the interpreter
let newTypesNeeded = config.collectRuntimeTypes || !program.hasTypeInformation
if config.useAbstractInterpretation && newTypesNeeded {
inferMissingTypes(in: program)
didInferTypesStatically = true
}
return (didCollectRuntimeTypes, didInferTypesStatically)
}
/// Process a program that has interesting aspects.
func processInteresting(_ program: Program, havingAspects aspects: ProgramAspects, origin: ProgramOrigin) {
func processCommon(_ program: Program) {
let (newTypeCollectionRun, _) = updateTypeInformation(for: program)
dispatchEvent(events.InterestingProgramFound, data: (program, origin, newTypeCollectionRun))
// All interesting programs are added to the corpus for future mutations and splicing
corpus.add(program)
}
if !origin.requiresMinimization() {
return processCommon(program)
}
fuzzGroup.enter()
minimizer.withMinimizedCopy(program, withAspects: aspects, usingMode: .normal) { minimizedProgram in
self.fuzzGroup.leave()
// Minimization invalidates any existing runtime type information
assert(minimizedProgram.typeCollectionStatus == .notAttempted && !minimizedProgram.hasTypeInformation)
processCommon(minimizedProgram)
}
}
/// Process a program that causes a crash.
func processCrash(_ program: Program, withSignal termsig: Int, withStderr stderr: String, origin: ProgramOrigin) {
func processCommon(_ program: Program) {
let hasStderrComment = program.comments.at(.footer)?.contains("STDERR") ?? false
if !hasStderrComment {
// Append a comment containing the content of stderr the first time a crash occurred
program.comments.add("STDERR:\n" + stderr, at: .footer)
}
// Check for uniqueness only after minimization
let execution = execute(program, withTimeout: self.config.timeout * 2)
if case .crashed = execution.outcome {
let isUnique = evaluator.evaluateCrash(execution) != nil
dispatchEvent(events.CrashFound, data: (program, .deterministic, termsig, isUnique, origin))
} else {
dispatchEvent(events.CrashFound, data: (program, .flaky, termsig, true, origin))
}
}
if !origin.requiresMinimization() {
return processCommon(program)
}
fuzzGroup.enter()
minimizer.withMinimizedCopy(program, withAspects: ProgramAspects(outcome: .crashed(termsig)), usingMode: .aggressive) { minimizedProgram in
self.fuzzGroup.leave()
processCommon(minimizedProgram)
}
}
/// Constructs a new ProgramBuilder using this fuzzing context.
public func makeBuilder(forMutating parent: Program? = nil, mode: ProgramBuilder.Mode = .aggressive) -> ProgramBuilder {
dispatchPrecondition(condition: .onQueue(queue))
let interpreter = config.useAbstractInterpretation ? AbstractInterpreter(for: self.environment) : nil
// Program ancestor chains are only constructed if inspection mode is enabled
let parent = config.inspection.contains(.history) ? parent : nil
return ProgramBuilder(for: self, parent: parent, interpreter: interpreter, mode: mode)
}
/// Performs one round of fuzzing.
private func fuzzOne() {
dispatchPrecondition(condition: .onQueue(queue))
assert(config.isFuzzing)
guard maxIterations == -1 || iterations < maxIterations else {
return shutdown(reason: .finished)
}
iterations += 1
engine.fuzzOne(fuzzGroup)
// Do the next fuzzing iteration as soon as all tasks related to the current iteration are finished.
fuzzGroup.notify(queue: queue) {
guard !self.isStopped else { return }
self.fuzzOne()
}
}
/// Constructs a non-trivial program. Useful to measure program execution speed.
private func makeComplexProgram() -> Program {
let b = makeBuilder()
let f = b.definePlainFunction(withSignature: FunctionSignature(withParameterCount: 2)) { params in
let x = b.loadProperty("x", of: params[0])
let y = b.loadProperty("y", of: params[0])
let s = b.binary(x, y, with: .Add)
let p = b.binary(s, params[1], with: .Mul)
b.doReturn(value: p)
}
b.forLoop(b.loadInt(0), .lessThan, b.loadInt(1000), .Add, b.loadInt(1)) { i in
let x = b.loadInt(42)
let y = b.loadInt(43)
let arg1 = b.createObject(with: ["x": x, "y": y])
let arg2 = i
b.callFunction(f, withArgs: [arg1, arg2])
}
return b.finalize()
}
/// Runs a number of startup tests to check whether everything is configured correctly.
public func runStartupTests() {
assert(isInitialized)
#if os(Linux)
do {
let corePattern = try String(contentsOfFile: "/proc/sys/kernel/core_pattern", encoding: String.Encoding.ascii)
if !corePattern.hasPrefix("|/bin/false") {
logger.fatal("Please run: sudo sysctl -w 'kernel.core_pattern=|/bin/false'")
}
} catch {
logger.warning("Could not check core dump behaviour. Please ensure core_pattern is set to '|/bin/false'")
}
#endif
// Check if we can execute programs
var execution = execute(Program())
guard case .succeeded = execution.outcome else {
logger.fatal("Cannot execute programs (exit code must be zero when no exception was thrown). Are the command line flags valid?")
}
// Check if we can detect failed executions (i.e. an exception was thrown)
var b = self.makeBuilder()
let exception = b.loadInt(42)
b.throwException(exception)
execution = execute(b.finalize())
guard case .failed = execution.outcome else {
logger.fatal("Cannot detect failed executions (exit code must be nonzero when an uncaught exception was thrown)")
}
var maxExecutionTime: TimeInterval = 0
// Dispatch a non-trivial program and measure its execution time
let complexProgram = makeComplexProgram()
for _ in 0..<5 {
let execution = execute(complexProgram)
maxExecutionTime = max(maxExecutionTime, execution.execTime)
}
// Check if we can detect crashes and measure their execution time
for test in config.crashTests {
b = makeBuilder()
b.eval(test)
execution = execute(b.finalize())
guard case .crashed = execution.outcome else {
logger.fatal("Testcase \"\(test)\" did not crash")
}
maxExecutionTime = max(maxExecutionTime, execution.execTime)
}
if config.crashTests.isEmpty {
logger.warning("Cannot check if crashes are detected")
}
// Determine recommended timeout value (rounded up to nearest multiple of 10ms)
let maxExecutionTimeMs = (Int(maxExecutionTime * 1000 + 9) / 10) * 10
let recommendedTimeout = 10 * maxExecutionTimeMs
logger.info("Recommended timeout: at least \(recommendedTimeout)ms. Current timeout: \(config.timeout)ms")
// Check if we can receive program output
b = makeBuilder()
let str = b.loadString("Hello World!")
b.doPrint(str)
let output = execute(b.finalize()).fuzzout.trimmingCharacters(in: .whitespacesAndNewlines)
if output != "Hello World!" {
logger.warning("Cannot receive FuzzIL output (got \"\(output)\" instead of \"Hello World!\")")
}
// Check if we can collect runtime types if enabled
if config.collectRuntimeTypes {
b = self.makeBuilder()
b.binary(b.loadInt(42), b.loadNull(), with: .Add)
let program = b.finalize()
collectRuntimeTypes(for: program)
// First 2 variables are inlined and abstractInterpreter will take care ot these types
let expectedTypes = ProgramTypes(
from: VariableMap([0: (.integer, .inferred), 1: (.undefined, .inferred), 2: (.integer, .runtime)]),
in: program
)
guard program.types == expectedTypes, program.typeCollectionStatus == .success else {
logger.fatal("Cannot collect runtime types (got \"\(program.types)\" instead of \"\(expectedTypes)\")")
}
}
logger.info("Startup tests finished successfully")
}
}
| 43.362819 | 206 | 0.642949 |
e07c120f217b60ff61751d9a739898d5a2051523 | 2,224 | import Foundation
import ShellCommand
import Toolkit
public final class DWARFUUIDProviderImpl: DWARFUUIDProvider {
private let shellCommandExecutor: ShellCommandExecutor
public init(shellCommandExecutor: ShellCommandExecutor) {
self.shellCommandExecutor = shellCommandExecutor
}
public func obtainDwarfUUIDs(path: String) throws -> [DWARFUUID] {
let command = BaseShellCommand(
launchPath: "/usr/bin/dwarfdump",
arguments: [
"--uuid",
path
],
environment: [:]
)
let result = shellCommandExecutor.execute(command: command)
guard let output = result.output,
result.terminationStatus == 0
else
{
throw DSYMSymbolizerError.unableToObtainDWARFDumpUUID(
path: path,
code: result.terminationStatus,
output: result.output,
error: result.error
)
}
// UUID: A867BB40-4976-379A-8583-8E824C5CAC98 (x86_64) /Users/user/.calcifer/localCache/Unbox/9d4fe28fbbba90398d230f46ea0210f1/Unbox.framework/Unbox
// UUID: A867BB40-4976-379A-8583-8E824C5CAC98 (x86_64) /Users/user/.calcifer/localCache/Unbox/9d4fe28fbbba90398d230f46ea0210f1/Unbox.framework/Unbox
let lines = output.components(separatedBy: "\n")
let dwarfUUIDs: [DWARFUUID] = lines.compactMap { line in
let outputComponents = line.split(separator: " ")
if outputComponents.count >= 4 &&
outputComponents[0] == "UUID:",
let uuid = UUID(uuidString: String(outputComponents[1])) // check is valid UUID
{
let architecture = String(outputComponents[2]).chomp(1).chop()
return DWARFUUID(uuid: uuid, architecture: architecture)
}
return nil
}
if dwarfUUIDs.isEmpty {
throw DSYMSymbolizerError.unableToObtainDWARFDumpUUID(
path: path,
code: result.terminationStatus,
output: result.output,
error: result.error
)
}
return dwarfUUIDs
}
}
| 37.694915 | 156 | 0.597572 |
1d252f838a2dd7d5b53ea1f8ff67165f2f832e74 | 306 | //
// UIKitView.swift
// Pyto
//
// Created by Adrian Labbé on 04-09-20.
// Copyright © 2020 Adrian Labbé. All rights reserved.
//
import UIKit
@available(iOS 13.0, *) @objc public class PyUIKitView: PyView {
public override class var pythonName: String {
return "UIKitView"
}
}
| 18 | 64 | 0.647059 |
11818c83bc7b57db19731cec0fa64c4cee7960dc | 888 | //
// PXLAlbumViewModel.swift
// Example
//
// Created by Csaba Toth on 2020. 01. 17..
// Copyright © 2020. Pixlee. All rights reserved.
//
import Foundation
public struct PXLAlbumViewModel {
public var album: PXLAlbum
public var photos: [PXLPhoto] {
album.photos
}
public init(album: PXLAlbum) {
self.album = album
}
func loadMore() {
_ = album.triggerEventLoadMoreTapped(completionHandler: { error in
if let error = error {
print("🛑 Error during analytics call:\(error)")
}
print("Logged")
})
}
func openedWidget(_ widget: PXLWidgetType) {
_ = album.triggerEventOpenedWidget(widget: widget, completionHandler: { error in
if let error = error {
print("🛑 Error during analytics call:\(error)")
}
})
}
}
| 23.368421 | 88 | 0.574324 |
b9a6b640754af41a4d52aedb0815fb83149b167b | 6,145 | import UIKit
class GenerateAvatarView: RootView {
let camera: SFCamera = {
let camera = SFCamera()
camera.previewLayer.alpha = 0
camera.previewLayer.clipsToBounds = true
return camera
}()
let titleLabel: UILabel = {
let label = UILabel()
label.textColor = .sfTextPrimary
label.textAlignment = .center
label.font = Palette.fontBold.withSize(34.0)
label.text = "setupAvatarTitle".libraryLocalized
return label
}()
let subtitleLabel: UILabel = {
let label = UILabel()
label.textColor = .sfTextPrimary
label.textAlignment = .center
label.font = Palette.fontMedium.withSize(16)
label.text = "setupAvatarSubtitle".libraryLocalized
label.numberOfLines = 0
return label
}()
let onboardingAvatarVideoView = OnboardingAvatarVideoView()
let linesRoundRotateAnimationView: LinesRoundRotateAnimationView = {
let view = LinesRoundRotateAnimationView()
view.isUserInteractionEnabled = true
return view
}()
let avatarImageView: UIImageView = {
let view = UIImageView()
return view
}()
let backgroundImageView: UIImageView = {
let view = UIImageView()
view.image = UIImage(libraryNamed: "mvp_background")
view.layer.cornerRadius = 280.0/2
view.clipsToBounds = true
view.alpha = 0
return view
}()
let avatarPlaceholderView: UIImageView = {
let view = UIImageView()
view.image = UIImage(libraryNamed: "camera_72")?.withRenderingMode(.alwaysTemplate)
view.tintColor = .sfAccentBrand
return view
}()
let descriptionLabel: UILabel = {
let label = UILabel()
label.text = "setupAvatarDescription".libraryLocalized
label.textColor = .sfTextSecondary
label.textAlignment = .center
label.font = Palette.fontMedium.withSize(12)
label.numberOfLines = 0
return label
}()
let continueButton: UIButton = {
let button = UIButton(type: .system)
button.setTitleColor(.sfAccentBrand, for: .normal)
button.setTitle("setupAvatarContinueTitle".libraryLocalized, for: .normal)
button.titleLabel?.font = Palette.fontSemiBold.withSize(16.0)
button.backgroundColor = .clear
return button
}()
let allowButton: UIButton = {
let button = UIButton(type: .system)
button.setTitleColor(.sfDefaultWhite, for: .normal)
button.setTitle("setupAvatarAllowTitle".libraryLocalized, for: .normal)
button.titleLabel?.font = Palette.fontBold.withSize(16.0)
button.backgroundColor = .sfAccentBrand
button.layer.cornerRadius = 14.0
return button
}()
override func setup() {
backgroundColor = .white
addSubview(titleLabel)
addSubview(subtitleLabel)
addSubview(avatarPlaceholderView)
addSubview(camera.previewLayer)
addSubview(onboardingAvatarVideoView)
addSubview(linesRoundRotateAnimationView)
addSubview(continueButton)
addSubview(allowButton)
addSubview(descriptionLabel)
addSubview(backgroundImageView)
addSubview(avatarImageView)
setupConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
camera.previewLayer.frame = avatarImageView.frame
camera.previewLayer.layer.cornerRadius = avatarImageView.frame.width / 2
}
private func setupConstraints() {
titleLabel.snp.makeConstraints { make in
make.top.equalTo(safeAreaLayoutGuide.snp.top).offset(32.0)
make.left.equalToSuperview().offset(32.0)
make.right.equalToSuperview().offset(-32.0)
}
subtitleLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(16.0)
make.left.equalToSuperview().offset(48.0)
make.right.equalToSuperview().offset(-48.0)
}
avatarPlaceholderView.snp.makeConstraints { make in
make.center.equalTo(onboardingAvatarVideoView)
make.size.equalTo(72.0)
}
backgroundImageView.snp.makeConstraints { make in
make.edges.equalTo(avatarImageView.snp.edges)
}
avatarImageView.snp.makeConstraints { make in
make.center.equalTo(linesRoundRotateAnimationView.snp.center)
make.centerX.equalToSuperview()
make.size.equalTo(280.0)
}
onboardingAvatarVideoView.snp.makeConstraints { make in
make.center.equalTo(linesRoundRotateAnimationView.snp.center)
make.centerX.equalToSuperview()
make.size.equalTo(280.0)
}
linesRoundRotateAnimationView.snp.makeConstraints { make in
make.top.equalTo(subtitleLabel.snp.bottom).offset(90.0)
make.centerX.equalToSuperview()
make.size.equalTo(LinesRoundRotateAnimationView.Layout.side)
}
continueButton.snp.makeConstraints { make in
make.bottom.equalTo(allowButton.snp.top).offset(-8.0)
make.right.equalToSuperview().offset(-32.0)
make.left.equalToSuperview().offset(32)
make.height.equalTo(48.0)
}
allowButton.snp.makeConstraints { make in
make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).offset(-16.0)
make.right.equalToSuperview().offset(-32.0)
make.left.equalToSuperview().offset(32)
make.height.equalTo(48.0)
}
descriptionLabel.snp.makeConstraints { make in
make.left.equalToSuperview().offset(48.0)
make.right.equalToSuperview().offset(-48.0)
make.bottom.equalTo(continueButton.snp.top).offset(-16.0)
}
}
}
| 32.513228 | 91 | 0.615134 |
18221e72269878f167ebf68683014582c1c9aa48 | 12,453 | //
// connection.swift
// stream
//
// Created by xpwu on 2021/4/1.
//
import Foundation
/*
lencontent protocol:
1, handshake protocol:
client ------------------ server
| |
| |
ABCDEF (A^...^F = 0xff) ---> check(A^...^F == 0xff) --- N--> over
(A is version)
| |
| |Y
| |
version 1: set client heartbeat <----- HeartBeat_s (2 bytes, net order)
version 2: set config <----- HeartBeat_s | FrameTimeout_s | MaxConcurrent | MaxBytes | connect id
HeartBeat_s: 2 bytes, net order
FrameTimeout_s: 1 byte
MaxConcurrent: 1 byte
MaxBytes: 4 bytes, net order
connect id: 8 bytes, net order
| |
| |
| |
data <--------> data
2, data protocol:
1) length | content
length: 4 bytes, net order; length=sizeof(content)+4; length=0 => heartbeat
*/
class Connection:NSObject {
var connectTimeout = 30*Duration.Second
var frameTimeout = 15*Duration.Second
var hearBeatTime = 4*Duration.Minute
var maxBytes:UInt64 = 1024 * 1024
var maxConcurrent = 5
var connectId = ""
var onConnected = {()->Void in}
var onMessage = {(_:[Byte]) -> Void in}
var onClose = {(_:String) -> Void in}
var onError = {(_:Error) -> Void in}
var inputStream:InputStream?
var outputStream:OutputStream?
var inputTimer:Timer?
var outputTimer:Timer?
var sendBuffer:[Byte] = []
var read:()->Void = {}
var write:()->Void = {}
var concurrent:Int = 0
var waitForSending:[[Byte]] = []
init(connectTimeout: Duration, onConnected:@escaping ()->Void, onMessage:@escaping ([Byte]) -> Void
, onClose:@escaping (String) -> Void, onError:@escaping (Error) -> Void) {
super.init()
self.connectTimeout = connectTimeout
self.onConnected = {[unowned self]()->Void in
self.onConnected = {()->Void in}
onConnected()
}
self.onClose = {[unowned self](s:String)->Void in
self.onClose = {(_:String) -> Void in}
onClose(s)
}
self.onError = {[unowned self](e:Error) -> Void in
self.onError = {(_:Error) -> Void in}
// 处理错误时,也需要关闭连接操作
close()
onError(e)
}
self.onMessage = onMessage
self.write = writeHandshake()
self.read = readHandshake()
}
}
// MARK: - api
extension Connection {
func connect(host:String, port:Int, tls:Bool)->Error? {
inputTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(connectTimeout.second()), repeats: false, block: {
[unowned self] (_:Timer) in
self.onConnected = {()->Void in}
self.onError(StrError("connect time out"))
})
Stream.getStreamsToHost(withName: host, port: port
, inputStream: &inputStream, outputStream: &outputStream)
if (inputStream == nil || outputStream == nil) {
inputTimer?.invalidate()
// 不能使用以下异步的方式通过onError接口传递错误,因为可能调用方调用close()后提前释放了Connection 实例
// unowned 捕获就是异常,所以只能同步返回
// async {[unowned self] in self.onError(StrError("connect --- get stream error"))}
return StrError("connect --- get stream error")
}
inputStream?.delegate = self
outputStream?.delegate = self
inputStream?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
outputStream?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
if tls {
inputStream?.setProperty(StreamSocketSecurityLevel.negotiatedSSL
, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outputStream?.setProperty(StreamSocketSecurityLevel.negotiatedSSL
, forKey: Stream.PropertyKey.socketSecurityLevelKey)
}
inputStream?.open()
outputStream?.open()
return nil
}
// 不会引起 onClose的回调
func close() {
// 可能实例已经释放了,所有的回调原有的unowned self 都可能报错,所以全部变为空
onConnected = {()->Void in}
onMessage = {(_:[Byte]) -> Void in}
onClose = {(_:String) -> Void in}
onError = {(_:Error) -> Void in}
inputStream?.close()
inputStream?.remove(from: RunLoop.current, forMode: RunLoop.Mode.default)
outputStream?.close()
outputStream?.remove(from: RunLoop.current, forMode: RunLoop.Mode.default)
inputTimer?.invalidate()
outputTimer?.invalidate()
// 如果关闭的时候还没有连接成功,delegate的回调可能都还没来得及调用,所以这里需要调用一次 onclose
// 不能使用以下异步的方式通过onClose接口传递关闭的结果,因为可能调用方调用close()后提前释放了Connection 实例
// unowned 捕获就是异常,所以onClose的回调无法执行
// async {[unowned self] in self.onClose("closed by self")}
print("close connection, id = " + connectId)
}
}
extension Connection {
func send(_ data:[Byte])->Error? {
if data.count > maxBytes {
return StrError(String(format: "data is too large, must be less than %d Bytes", maxBytes))
}
waitForSending.append(data)
_send()
return nil
}
func sendForce(_ data:[Byte]) {
var len:[Byte] = [0, 0, 0, 0]
UInt32(data.count + 4).toNet(&len)
sendBuffer += len + data
trySend()
}
private func _send() {
if concurrent >= maxConcurrent {
return
}
if waitForSending.isEmpty {
return
}
concurrent += 1
let data = waitForSending.removeFirst()
// todo: test calling sendForce()
var len:[Byte] = [0, 0, 0, 0]
UInt32(data.count + 4).toNet(&len)
sendBuffer += len + data
trySend()
}
func receivedOneResponse() {
concurrent -= 1
// 防御性代码
if (concurrent < 0) {
concurrent = 0
}
_send();
}
}
// MARK: - handshake
extension Connection {
func handshake() -> [Byte] {
var handshake = [Byte](repeating: 0, count: 6)
// version: 2
handshake[0] = 2
handshake[1] = Byte(Int.random(in: 0..<256))
handshake[2] = Byte(Int.random(in: 0..<256))
handshake[3] = Byte(Int.random(in: 0..<256))
handshake[4] = Byte(Int.random(in: 0..<256))
handshake[5] = 0xff
for i in 0..<5 {
handshake[5] ^= handshake[i]
}
return handshake
}
func writeHandshake() ->()->Void {
var hs = self.handshake()
return {[unowned self] ()->Void in
if hs.count == 0 {
return
}
guard let n = outputStream?.write(hs, maxLength: hs.count) else {
return
}
if n <= 0 {
onError(outputStream?.streamError ?? StrError("write handshake error!"))
return
}
hs.removeFirst(n)
}
}
func readHandshake()-> ()->Void {
/**
HeartBeat_s: 2 bytes, net order
FrameTimeout_s: 1 byte
MaxConcurrent: 1 byte
MaxBytes: 4 bytes, net order
connect id: 8 bytes, net order
*/
var recBuffer:[Byte] = [Byte](repeating: 0, count: 2 + 1 + 1 + 4 + 8)
var pos = 0
return {[unowned self]()->Void in
guard let n = inputStream?.read(&recBuffer[pos], maxLength: recBuffer.count-pos) else {
return
}
if (n <= 0) {
onError(inputStream?.streamError ?? StrError("read handshake error!"))
return
}
pos += n
if (pos != recBuffer.count) {
return
}
// 握手成功,才算真正的连接成功
inputTimer?.invalidate()
hearBeatTime = recBuffer[0..<2].net2UInt64() * Duration.Second
frameTimeout = UInt64(recBuffer[2]) * Duration.Second
maxConcurrent = Int(recBuffer[3])
maxBytes = recBuffer[4..<8].net2UInt64()
connectId = String(format: "%016llx", recBuffer[8...].net2UInt64())
print("connect id = " + connectId)
read = readLength()
write = writeData()
onConnected()
}
}
}
// MARK: - output
extension Connection {
func initOutputHeartbeat() {
outputTimer?.invalidate()
outputTimer = Timer.scheduledTimer(
withTimeInterval: TimeInterval(hearBeatTime.second())
, repeats: true
, block: { [unowned self] (_:Timer) in
self.sendBuffer += [0, 0, 0, 0]
trySend()
print("send heartbeat to server")
})
}
func writeData()->()->Void {
initOutputHeartbeat()
return {[unowned self]()->Void in
trySend()
}
}
func trySend() {
guard let outputStream = self.outputStream else {
onError(StrError("not connected"))
return
}
if !outputStream.hasSpaceAvailable {
return
}
if (sendBuffer.isEmpty) {
// 没有数据了,就需要准备心跳发送了
initOutputHeartbeat()
return
}
// 取消可能的心跳定时
outputTimer?.invalidate()
// 不需要循环的写。要么sendBuffer全部写完,要么空间没有,都不需要再写
let n = outputStream.write(sendBuffer, maxLength: sendBuffer.count)
// 已经判断有空间了,再出现0,说明有错误
if (n <= 0) {
onError(outputStream.streamError ?? StrError("outputStream write error!"))
return
}
if (n == sendBuffer.count) {
sendBuffer = []
return
}
// O(n) 的效率,后期再考虑优化的问题
sendBuffer.removeFirst(n)
}
}
// MARK: - input
extension Connection {
func initInputHeartbeat() {
inputTimer?.invalidate()
inputTimer = Timer.scheduledTimer(
withTimeInterval: TimeInterval(2*hearBeatTime.second())
, repeats: false
, block: {[unowned self] (_:Timer) in
self.onError(StrError("heartbeat timeout"))
})
}
func initInputFrameTimeout() {
inputTimer?.invalidate()
inputTimer = Timer.scheduledTimer(
withTimeInterval: TimeInterval(frameTimeout.second())
, repeats: false
, block: {[unowned self] (_:Timer) in
self.onError(StrError("read frame timeout"))
})
}
private func readLength()->()->Void {
var pos = 0;
var length:[Byte] = [0, 0, 0, 0]
initInputHeartbeat()
return {[unowned self]()->Void in
guard let inputStream = self.inputStream else {
onError(StrError("not connected"))
return
}
inputTimer?.invalidate()
let n = inputStream.read(&length[pos], maxLength: 4-pos)
if n <= 0 {
onError(inputStream.streamError ?? StrError("stream read error!"))
return
}
pos += n
if pos < 4 {
initInputFrameTimeout()
return
}
var len:UInt32 = length.net2UInt32()
// heartbeat
if len == 0 {
print("recieve heartbeat from server")
read = readLength()
return
}
len -= 4
read = readContent(len: len)
}
}
private func readContent(len:UInt32)->()->Void {
var pos = 0
var content = [Byte](repeating: 0, count: Int(len))
initInputFrameTimeout()
return {[unowned self]()->Void in
guard let inputStream = inputStream else {
onError(StrError("not connected"))
return
}
inputTimer?.invalidate()
let n = inputStream.read(&content[pos], maxLength: content.count-pos)
if n <= 0 {
onError(inputStream.streamError ?? StrError("stream read error!"))
return
}
pos += n
if pos < content.count {
initInputFrameTimeout()
return
}
read = readLength()
onMessage(content)
}
}
}
// MARK: - delegate
extension Connection: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.endEncountered:
onClose("connection closed")
case Stream.Event.errorOccurred:
onError(aStream.streamError ?? StrError("stream error!"))
case Stream.Event.hasBytesAvailable:
guard let inputStream = inputStream else {
// 执行到这里时,inputStream一定存在,所以这里不需特别处理
return
}
// 读空
while inputStream.hasBytesAvailable {
read()
}
case Stream.Event.hasSpaceAvailable:
write()
// let v = handshake()
//
// outputStream?.write(v, maxLength: 6)
default:break
}
}
}
| 25.676289 | 119 | 0.56107 |
ff6fef54188430a67fe310a6a39ea73e2234f501 | 28,928 | //
// Created by Shin Yamamoto on 2018/09/18.
// Copyright © 2018 Shin Yamamoto. All rights reserved.
//
import UIKit
public protocol FloatingPanelControllerDelegate: class {
// if it returns nil, FloatingPanelController uses the default layout
func floatingPanel(_ vc: FloatingPanelController, layoutFor newCollection: UITraitCollection) -> FloatingPanelLayout?
// if it returns nil, FloatingPanelController uses the default behavior
func floatingPanel(_ vc: FloatingPanelController, behaviorFor newCollection: UITraitCollection) -> FloatingPanelBehavior?
/// Called when the floating panel has changed to a new position. Can be called inside an animation block, so any
/// view properties set inside this function will be automatically animated alongside the panel.
func floatingPanelDidChangePosition(_ vc: FloatingPanelController)
/// Asks the delegate if dragging should begin by the pan gesture recognizer.
func floatingPanelShouldBeginDragging(_ vc: FloatingPanelController) -> Bool
func floatingPanelDidMove(_ vc: FloatingPanelController) // any surface frame changes in dragging
// called on start of dragging (may require some time and or distance to move)
func floatingPanelWillBeginDragging(_ vc: FloatingPanelController)
// called on finger up if the user dragged. velocity is in points/second.
func floatingPanelDidEndDragging(_ vc: FloatingPanelController, withVelocity velocity: CGPoint, targetPosition: FloatingPanelPosition)
func floatingPanelWillBeginDecelerating(_ vc: FloatingPanelController) // called on finger up as we are moving
func floatingPanelDidEndDecelerating(_ vc: FloatingPanelController) // called when scroll view grinds to a halt
// called on start of dragging to remove its views from a parent view controller
func floatingPanelDidEndDraggingToRemove(_ vc: FloatingPanelController, withVelocity velocity: CGPoint)
// called when its views are removed from a parent view controller
func floatingPanelDidEndRemove(_ vc: FloatingPanelController)
/// Asks the delegate if the other gesture recognizer should be allowed to recognize the gesture in parallel.
///
/// By default, any tap and long gesture recognizers are allowed to recognize gestures simultaneously.
func floatingPanel(_ vc: FloatingPanelController, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
/// Asks the delegate for a content offset of the tracked scroll view to be pinned when a floating panel moves
///
/// If you do not implement this method, the controller uses a value of the content offset plus the content insets
/// of the tracked scroll view. Your implementation of this method can return a value for a navigation bar with a large
/// title, for example.
///
/// This method will not be called if the controller doesn't track any scroll view.
func floatingPanel(_ vc: FloatingPanelController, contentOffsetForPinning trackedScrollView: UIScrollView) -> CGPoint
}
public extension FloatingPanelControllerDelegate {
func floatingPanel(_ vc: FloatingPanelController, layoutFor newCollection: UITraitCollection) -> FloatingPanelLayout? {
return nil
}
func floatingPanel(_ vc: FloatingPanelController, behaviorFor newCollection: UITraitCollection) -> FloatingPanelBehavior? {
return nil
}
func floatingPanelDidChangePosition(_ vc: FloatingPanelController) {}
func floatingPanelShouldBeginDragging(_ vc: FloatingPanelController) -> Bool {
return true
}
func floatingPanelDidMove(_ vc: FloatingPanelController) {}
func floatingPanelWillBeginDragging(_ vc: FloatingPanelController) {}
func floatingPanelDidEndDragging(_ vc: FloatingPanelController, withVelocity velocity: CGPoint, targetPosition: FloatingPanelPosition) {}
func floatingPanelWillBeginDecelerating(_ vc: FloatingPanelController) {}
func floatingPanelDidEndDecelerating(_ vc: FloatingPanelController) {}
func floatingPanelDidEndDraggingToRemove(_ vc: FloatingPanelController, withVelocity velocity: CGPoint) {}
func floatingPanelDidEndRemove(_ vc: FloatingPanelController) {}
func floatingPanel(_ vc: FloatingPanelController, shouldRecognizeSimultaneouslyWith gestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
func floatingPanel(_ vc: FloatingPanelController, contentOffsetForPinning trackedScrollView: UIScrollView) -> CGPoint {
return CGPoint(x: 0.0, y: 0.0 - trackedScrollView.contentInset.top)
}
}
public enum FloatingPanelPosition: Int {
case full
case half
case tip
case hidden
static var allCases: [FloatingPanelPosition] {
return [.full, .half, .tip, .hidden]
}
func next(in positions: [FloatingPanelPosition]) -> FloatingPanelPosition {
#if swift(>=4.2)
guard
let index = positions.firstIndex(of: self),
positions.indices.contains(index + 1)
else { return self }
#else
guard
let index = positions.index(of: self),
positions.indices.contains(index + 1)
else { return self }
#endif
return positions[index + 1]
}
func pre(in positions: [FloatingPanelPosition]) -> FloatingPanelPosition {
#if swift(>=4.2)
guard
let index = positions.firstIndex(of: self),
positions.indices.contains(index - 1)
else { return self }
#else
guard
let index = positions.index(of: self),
positions.indices.contains(index - 1)
else { return self }
#endif
return positions[index - 1]
}
}
///
/// A container view controller to display a floating panel to present contents in parallel as a user wants.
///
open class FloatingPanelController: UIViewController {
/// Constants indicating how safe area insets are added to the adjusted content inset.
public enum ContentInsetAdjustmentBehavior: Int {
case always
case never
}
/// A flag used to determine how the controller object lays out the content view when the surface position changes.
public enum ContentMode: Int {
/// The option to fix the content to keep the height of the top most position.
case `static`
/// The option to scale the content to fit the bounds of the root view by changing the surface position.
case fitToBounds
}
/// The delegate of the floating panel controller object.
public weak var delegate: FloatingPanelControllerDelegate?{
didSet{
didUpdateDelegate()
}
}
/// Returns the surface view managed by the controller object. It's the same as `self.view`.
public var surfaceView: FloatingPanelSurfaceView! {
return floatingPanel.surfaceView
}
/// Returns the backdrop view managed by the controller object.
public var backdropView: FloatingPanelBackdropView! {
return floatingPanel.backdropView
}
/// Returns the scroll view that the controller tracks.
public weak var scrollView: UIScrollView? {
return floatingPanel.scrollView
}
// The underlying gesture recognizer for pan gestures
public var panGestureRecognizer: UIPanGestureRecognizer {
return floatingPanel.panGestureRecognizer
}
/// The current position of the floating panel controller's contents.
public var position: FloatingPanelPosition {
return floatingPanel.state
}
/// The layout object managed by the controller
public var layout: FloatingPanelLayout {
return floatingPanel.layoutAdapter.layout
}
/// The behavior object managed by the controller
public var behavior: FloatingPanelBehavior {
return floatingPanel.behavior
}
/// The content insets of the tracking scroll view derived from this safe area
public var adjustedContentInsets: UIEdgeInsets {
return floatingPanel.layoutAdapter.adjustedContentInsets
}
/// The behavior for determining the adjusted content offsets.
///
/// This property specifies how the content area of the tracking scroll view is modified using `adjustedContentInsets`. The default value of this property is FloatingPanelController.ContentInsetAdjustmentBehavior.always.
public var contentInsetAdjustmentBehavior: ContentInsetAdjustmentBehavior = .always
/// A Boolean value that determines whether the removal interaction is enabled.
public var isRemovalInteractionEnabled: Bool {
set { floatingPanel.isRemovalInteractionEnabled = newValue }
get { return floatingPanel.isRemovalInteractionEnabled }
}
/// The view controller responsible for the content portion of the floating panel.
public var contentViewController: UIViewController? {
set { set(contentViewController: newValue) }
get { return _contentViewController }
}
/// The NearbyPosition determines that finger's nearby position.
public var nearbyPosition: FloatingPanelPosition {
let currentY = surfaceView.frame.minY
return floatingPanel.targetPosition(from: currentY, with: .zero)
}
public var contentMode: ContentMode = .static {
didSet {
guard position != .hidden else { return }
activateLayout()
}
}
private var _contentViewController: UIViewController?
private(set) var floatingPanel: FloatingPanelCore!
private var preSafeAreaInsets: UIEdgeInsets = .zero // Capture the latest one
private var safeAreaInsetsObservation: NSKeyValueObservation?
private let modalTransition = FloatingPanelModalTransition()
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
/// Initialize a newly created floating panel controller.
public init(delegate: FloatingPanelControllerDelegate? = nil) {
super.init(nibName: nil, bundle: nil)
self.delegate = delegate
setUp()
}
private func setUp() {
_ = FloatingPanelController.dismissSwizzling
modalPresentationStyle = .custom
transitioningDelegate = modalTransition
floatingPanel = FloatingPanelCore(self,
layout: fetchLayout(for: self.traitCollection),
behavior: fetchBehavior(for: self.traitCollection))
}
private func didUpdateDelegate(){
floatingPanel.layoutAdapter.layout = fetchLayout(for: traitCollection)
floatingPanel.behavior = fetchBehavior(for: self.traitCollection)
}
// MARK:- Overrides
/// Creates the view that the controller manages.
open override func loadView() {
assert(self.storyboard == nil, "Storyboard isn't supported")
let view = FloatingPanelPassThroughView()
view.backgroundColor = .clear
backdropView.frame = view.bounds
view.addSubview(backdropView)
surfaceView.frame = view.bounds
view.addSubview(surfaceView)
self.view = view as UIView
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 11.0, *) {}
else {
// Because {top,bottom}LayoutGuide is managed as a view
if preSafeAreaInsets != layoutInsets,
floatingPanel.isDecelerating == false {
self.update(safeAreaInsets: layoutInsets)
}
}
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if view.translatesAutoresizingMaskIntoConstraints {
view.frame.size = size
view.layoutIfNeeded()
}
}
open override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
self.prepare(for: newCollection)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
safeAreaInsetsObservation = nil
}
// MARK:- Child view controller to consult
#if swift(>=4.2)
open override var childForStatusBarStyle: UIViewController? {
return contentViewController
}
open override var childForStatusBarHidden: UIViewController? {
return contentViewController
}
open override var childForScreenEdgesDeferringSystemGestures: UIViewController? {
return contentViewController
}
open override var childForHomeIndicatorAutoHidden: UIViewController? {
return contentViewController
}
#else
open override var childViewControllerForStatusBarStyle: UIViewController? {
return contentViewController
}
open override var childViewControllerForStatusBarHidden: UIViewController? {
return contentViewController
}
open override func childViewControllerForScreenEdgesDeferringSystemGestures() -> UIViewController? {
return contentViewController
}
open override func childViewControllerForHomeIndicatorAutoHidden() -> UIViewController? {
return contentViewController
}
#endif
// MARK:- Internals
func prepare(for newCollection: UITraitCollection) {
guard newCollection.shouldUpdateLayout(from: traitCollection) else { return }
// Change a layout & behavior for a new trait collection
reloadLayout(for: newCollection)
activateLayout()
floatingPanel.behavior = fetchBehavior(for: newCollection)
}
// MARK:- Privates
private func fetchLayout(for traitCollection: UITraitCollection) -> FloatingPanelLayout {
switch traitCollection.verticalSizeClass {
case .compact:
return self.delegate?.floatingPanel(self, layoutFor: traitCollection) ?? FloatingPanelDefaultLandscapeLayout()
default:
return self.delegate?.floatingPanel(self, layoutFor: traitCollection) ?? FloatingPanelDefaultLayout()
}
}
private func fetchBehavior(for traitCollection: UITraitCollection) -> FloatingPanelBehavior {
return self.delegate?.floatingPanel(self, behaviorFor: traitCollection) ?? FloatingPanelDefaultBehavior()
}
private func update(safeAreaInsets: UIEdgeInsets) {
guard
preSafeAreaInsets != safeAreaInsets
else { return }
log.debug("Update safeAreaInsets", safeAreaInsets)
// Prevent an infinite loop on iOS 10: setUpLayout() -> viewDidLayoutSubviews() -> setUpLayout()
preSafeAreaInsets = safeAreaInsets
activateLayout()
switch contentInsetAdjustmentBehavior {
case .always:
scrollView?.contentInset = adjustedContentInsets
default:
break
}
}
private func reloadLayout(for traitCollection: UITraitCollection) {
floatingPanel.layoutAdapter.layout = fetchLayout(for: traitCollection)
if let parent = self.parent {
if let layout = layout as? UIViewController, layout == parent {
log.warning("A memory leak will occur by a retain cycle because \(self) owns the parent view controller(\(parent)) as the layout object. Don't let the parent adopt FloatingPanelLayout.")
}
if let behavior = behavior as? UIViewController, behavior == parent {
log.warning("A memory leak will occur by a retain cycle because \(self) owns the parent view controller(\(parent)) as the behavior object. Don't let the parent adopt FloatingPanelBehavior.")
}
}
}
private func activateLayout() {
floatingPanel.layoutAdapter.prepareLayout(in: self)
// preserve the current content offset if contentInsetAdjustmentBehavior is `.always`
var contentOffset: CGPoint?
if contentInsetAdjustmentBehavior == .always {
contentOffset = scrollView?.contentOffset
}
floatingPanel.layoutAdapter.updateHeight()
floatingPanel.layoutAdapter.activateLayout(of: floatingPanel.state)
if let contentOffset = contentOffset {
scrollView?.contentOffset = contentOffset
}
}
// MARK: - Container view controller interface
/// Shows the surface view at the initial position defined by the current layout
public func show(animated: Bool = false, completion: (() -> Void)? = nil) {
// Must apply the current layout here
reloadLayout(for: traitCollection)
activateLayout()
if #available(iOS 11.0, *) {
// Must track the safeAreaInsets of `self.view` to update the layout.
// There are 2 reasons.
// 1. This or the parent VC doesn't call viewSafeAreaInsetsDidChange() on the bottom
// inset's update expectedly.
// 2. The safe area top inset can be variable on the large title navigation bar(iOS11+).
// That's why it needs the observation to keep `adjustedContentInsets` correct.
safeAreaInsetsObservation = self.view.observe(\.safeAreaInsets, options: [.initial, .new, .old]) { [weak self] (_, change) in
// Use `self.view.safeAreaInsets` becauese `change.newValue` can be nil in particular case when
// is reported in https://github.com/SCENEE/FloatingPanel/issues/330
guard let `self` = self, change.oldValue != self.view.safeAreaInsets else { return }
self.update(safeAreaInsets: self.view.safeAreaInsets)
}
} else {
// KVOs for topLayoutGuide & bottomLayoutGuide are not effective.
// Instead, update(safeAreaInsets:) is called at `viewDidLayoutSubviews()`
}
move(to: floatingPanel.layoutAdapter.layout.initialPosition,
animated: animated,
completion: completion)
}
/// Hides the surface view to the hidden position
public func hide(animated: Bool = false, completion: (() -> Void)? = nil) {
move(to: .hidden,
animated: animated,
completion: completion)
}
/// Adds the view managed by the controller as a child of the specified view controller.
/// - Parameters:
/// - parent: A parent view controller object that displays FloatingPanelController's view. A container view controller object isn't applicable.
/// - belowView: Insert the surface view managed by the controller below the specified view. By default, the surface view will be added to the end of the parent list of subviews.
/// - animated: Pass true to animate the presentation; otherwise, pass false.
public func addPanel(toParent parent: UIViewController, belowView: UIView? = nil, animated: Bool = false) {
guard self.parent == nil else {
log.warning("Already added to a parent(\(parent))")
return
}
precondition((parent is UINavigationController) == false, "UINavigationController displays only one child view controller at a time.")
precondition((parent is UITabBarController) == false, "UITabBarController displays child view controllers with a radio-style selection interface")
precondition((parent is UISplitViewController) == false, "UISplitViewController manages two child view controllers in a master-detail interface")
precondition((parent is UITableViewController) == false, "UITableViewController should not be the parent because the view is a table view so that a floating panel doens't work well")
precondition((parent is UICollectionViewController) == false, "UICollectionViewController should not be the parent because the view is a collection view so that a floating panel doens't work well")
if let belowView = belowView {
parent.view.insertSubview(self.view, belowSubview: belowView)
} else {
parent.view.addSubview(self.view)
}
#if swift(>=4.2)
parent.addChild(self)
#else
parent.addChildViewController(self)
#endif
view.frame = parent.view.bounds // Needed for a correct safe area configuration
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.view.topAnchor.constraint(equalTo: parent.view.topAnchor, constant: 0.0),
self.view.leftAnchor.constraint(equalTo: parent.view.leftAnchor, constant: 0.0),
self.view.rightAnchor.constraint(equalTo: parent.view.rightAnchor, constant: 0.0),
self.view.bottomAnchor.constraint(equalTo: parent.view.bottomAnchor, constant: 0.0),
])
show(animated: animated) { [weak self] in
guard let `self` = self else { return }
#if swift(>=4.2)
self.didMove(toParent: parent)
#else
self.didMove(toParentViewController: parent)
#endif
}
}
/// Removes the controller and the managed view from its parent view controller
/// - Parameters:
/// - animated: Pass true to animate the presentation; otherwise, pass false.
/// - completion: The block to execute after the view controller is dismissed. This block has no return value and takes no parameters. You may specify nil for this parameter.
public func removePanelFromParent(animated: Bool, completion: (() -> Void)? = nil) {
guard self.parent != nil else {
completion?()
return
}
hide(animated: animated) { [weak self] in
guard let `self` = self else { return }
#if swift(>=4.2)
self.willMove(toParent: nil)
#else
self.willMove(toParentViewController: nil)
#endif
self.view.removeFromSuperview()
#if swift(>=4.2)
self.removeFromParent()
#else
self.removeFromParentViewController()
#endif
completion?()
}
}
/// Moves the position to the specified position.
/// - Parameters:
/// - to: Pass a FloatingPanelPosition value to move the surface view to the position.
/// - animated: Pass true to animate the presentation; otherwise, pass false.
/// - completion: The block to execute after the view controller has finished moving. This block has no return value and takes no parameters. You may specify nil for this parameter.
public func move(to: FloatingPanelPosition, animated: Bool, completion: (() -> Void)? = nil) {
precondition(floatingPanel.layoutAdapter.vc != nil, "Use show(animated:completion)")
floatingPanel.move(to: to, animated: animated, completion: completion)
}
/// Sets the view controller responsible for the content portion of the floating panel.
public func set(contentViewController: UIViewController?) {
if let vc = _contentViewController {
#if swift(>=4.2)
vc.willMove(toParent: nil)
#else
vc.willMove(toParentViewController: nil)
#endif
vc.view.removeFromSuperview()
#if swift(>=4.2)
vc.removeFromParent()
#else
vc.removeFromParentViewController()
#endif
}
if let vc = contentViewController {
#if swift(>=4.2)
addChild(vc)
#else
addChildViewController(vc)
#endif
let surfaceView = floatingPanel.surfaceView
surfaceView.add(contentView: vc.view)
#if swift(>=4.2)
vc.didMove(toParent: self)
#else
vc.didMove(toParentViewController: self)
#endif
}
_contentViewController = contentViewController
}
@available(*, unavailable, renamed: "set(contentViewController:)")
open override func show(_ vc: UIViewController, sender: Any?) {
if let target = self.parent?.targetViewController(forAction: #selector(UIViewController.show(_:sender:)), sender: sender) {
target.show(vc, sender: sender)
}
}
@available(*, unavailable, renamed: "set(contentViewController:)")
open override func showDetailViewController(_ vc: UIViewController, sender: Any?) {
if let target = self.parent?.targetViewController(forAction: #selector(UIViewController.showDetailViewController(_:sender:)), sender: sender) {
target.showDetailViewController(vc, sender: sender)
}
}
// MARK: - Scroll view tracking
/// Tracks the specified scroll view to correspond with the scroll.
///
/// - Parameters:
/// - scrollView: Specify a scroll view to continuously and seamlessly work in concert with interactions of the surface view or nil to cancel it.
public func track(scrollView: UIScrollView?) {
guard let scrollView = scrollView else {
floatingPanel.scrollView = nil
return
}
floatingPanel.scrollView = scrollView
switch contentInsetAdjustmentBehavior {
case .always:
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
} else {
#if swift(>=4.2)
children.forEach { (vc) in
vc.automaticallyAdjustsScrollViewInsets = false
}
#else
childViewControllers.forEach { (vc) in
vc.automaticallyAdjustsScrollViewInsets = false
}
#endif
}
default:
break
}
}
// MARK: - Utilities
/// Updates the layout object from the delegate and lays out the views managed
/// by the controller immediately.
///
/// This method updates the `FloatingPanelLayout` object from the delegate and
/// then it calls `layoutIfNeeded()` of the root view to force the view
/// to update the floating panel's layout immediately. It can be called in an
/// animation block.
public func updateLayout() {
reloadLayout(for: traitCollection)
activateLayout()
}
/// Returns the y-coordinate of the point at the origin of the surface view.
public func originYOfSurface(for pos: FloatingPanelPosition) -> CGFloat {
return floatingPanel.layoutAdapter.positionY(for: pos)
}
}
extension FloatingPanelController {
private static let dismissSwizzling: Any? = {
let aClass: AnyClass! = UIViewController.self //object_getClass(vc)
if let imp = class_getMethodImplementation(aClass, #selector(dismiss(animated:completion:))),
let originalAltMethod = class_getInstanceMethod(aClass, #selector(fp_original_dismiss(animated:completion:))) {
method_setImplementation(originalAltMethod, imp)
}
let originalMethod = class_getInstanceMethod(aClass, #selector(dismiss(animated:completion:)))
let swizzledMethod = class_getInstanceMethod(aClass, #selector(fp_dismiss(animated:completion:)))
if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
// switch implementation..
method_exchangeImplementations(originalMethod, swizzledMethod)
}
return nil
}()
}
public extension UIViewController {
@objc func fp_original_dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
// Implementation will be replaced by IMP of self.dismiss(animated:completion:)
}
@objc func fp_dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
// Call dismiss(animated:completion:) to a content view controller
if let fpc = parent as? FloatingPanelController {
if fpc.presentingViewController != nil {
self.fp_original_dismiss(animated: flag, completion: completion)
} else {
fpc.removePanelFromParent(animated: flag, completion: completion)
}
return
}
// Call dismiss(animated:completion:) to FloatingPanelController directly
if let fpc = self as? FloatingPanelController {
// When a panel is presented modally and it's not a child view controller of the presented view controller.
if fpc.presentingViewController != nil, fpc.parent == nil {
self.fp_original_dismiss(animated: flag, completion: completion)
} else {
fpc.removePanelFromParent(animated: flag, completion: completion)
}
return
}
// For other view controllers
self.fp_original_dismiss(animated: flag, completion: completion)
}
}
| 42.169096 | 224 | 0.67585 |
50a652f9d8b96b88cc794668e628c77b79022e24 | 529 | import XCTest
@testable import LeetCode
@testable import Structure
final class BinaryTreeRightSideViewSpec: XCTestCase {
fileprivate let questions: [(([Int?]), [Int])] = [
(([1, 2, 3, nil, 5, nil, 4]), [1, 3, 4]),
(([1, nil, 3]), [1, 3]),
(([]), [])
]
func testBinaryTreeRightSideView() {
let solution = BinaryTreeRightSideView()
for ((elements), answer) in questions {
XCTAssertEqual(solution.rightSideView(BinaryTree(elements).root), answer)
}
}
}
| 26.45 | 85 | 0.586011 |
185407825ac29ccb0c7a217dc7e6460edd25a708 | 17,885 | //
// TrashViewController.swift
// Listtly
//
// Created by Ozan Mirza on 4/8/18.
// Copyright © 2018 Ozan Mirza. All rights reserved.
//
import UIKit
class TrashViewController: UIViewController {
@IBOutlet weak var nothing_here_label: UILabel!
@IBOutlet weak var listView: UIScrollView!
@IBOutlet weak var trashLbl: UILabel!
@IBOutlet weak var flag_button_background: UIButton!
@IBOutlet weak var flag_button_image: UIImageView!
@IBOutlet weak var trash_buttton_background: UIButton!
@IBOutlet weak var trash_button_image: UIImageView!
@IBOutlet weak var complete_button_background: UIButton!
@IBOutlet weak var complete_button_image: UIImageView!
var cells : [[UIView]] = [] // Cell, ColorCell, TitleCell
var listY : [Int] = [50]
var listViewHieght: CGFloat = 0
var list : [Item] = []
var openSideMenu: Bool = true
var openedMenu : [UIView] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
trashLbl.frame.origin.x = self.view.frame.size.width
for i in 0..<(toDoList?.count)! {
if toDoList?[i].section == .trash {
list.append(toDoList![i])
}
}
if list.count > 0 {
nothing_here_label.alpha = 0
} else {
nothing_here_label.transform = CGAffineTransform(scaleX: 0, y: 0)
}
flag_button_background.layer.cornerRadius = flag_button_background.frame.size.width / 2
trash_buttton_background.layer.cornerRadius = trash_buttton_background.frame.size.width / 2
complete_button_background.layer.cornerRadius = complete_button_background.frame.size.width / 2
flag_button_background.frame.origin.x = -75
trash_buttton_background.frame.origin.x = -75
complete_button_background.frame.origin.x = -75
flag_button_image.center = flag_button_background.center
trash_button_image.center = trash_buttton_background.center
complete_button_image.center = complete_button_background.center
flag_button_background.addTarget(self, action: #selector(move_Cell_To_Archive(_:)), for: UIControl.Event.touchUpInside)
trash_buttton_background.addTarget(self, action: #selector(move_Cell_To_Trash(_:)), for: UIControl.Event.touchUpInside)
complete_button_background.addTarget(self, action: #selector(move_Cell_To_Complete(_:)), for: UIControl.Event.touchUpInside)
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.nothing_here_label.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}) { (finished: Bool) in
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.nothing_here_label.transform = CGAffineTransform.identity
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.trashLbl.center.x = self.view.center.x - 25
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.trashLbl.center.x = self.view.frame.size.width / 2
}, completion: nil)
for i in 0..<self.list.count {
if CGFloat(self.listY[i]) > (self.listView.frame.size.height - 100) {
self.listViewHieght += 175
self.listView.contentSize.height = self.listViewHieght
}
let cell = UIView(frame: CGRect(x: 16, y: self.listY[i], width: Int(self.listView.frame.size.width - (16 * 2)), height: 100))
self.listY.append(Int(self.listY[i] + 100 + 20))
cell.layer.cornerRadius = cell.frame.size.height / 2
cell.backgroundColor = UIColor.init(red: (240 / 255), green: (240 / 255), blue: (240 / 255), alpha: 0.5)
cell.transform = CGAffineTransform(scaleX: 0, y: 0)
self.listView.addSubview(cell)
let colorCell = UIButton(frame: CGRect(x: self.view.frame.size.width, y: 0, width: 100, height: 100))
colorCell.alpha = 0
colorCell.layer.cornerRadius = colorCell.frame.size.height / 2
colorCell.backgroundColor = self.list[i].color.color
colorCell.addTarget(self, action: #selector(self.switcher(_:)), for: UIControl.Event.touchUpInside)
cell.addSubview(colorCell)
let titleCell = UILabel(frame: CGRect(x: 100, y: 0, width: Int(self.listView.frame.size.width - 100), height: 100))
titleCell.layer.cornerRadius = titleCell.frame.size.height / 2
titleCell.transform = CGAffineTransform(scaleX: 0, y: 0)
titleCell.backgroundColor = UIColor.clear
titleCell.textAlignment = NSTextAlignment.center
titleCell.text = self.list[i].title
titleCell.font = UIFont(name: "VarelaRound-Regular", size: 20)
titleCell.textColor = UIColor.black
cell.addSubview(titleCell)
UIView.animate(withDuration: 0.5, delay: 0.2, options: UIView.AnimationOptions.curveEaseInOut, animations: {
cell.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
cell.transform = CGAffineTransform.identity
}, completion: { (finished: Bool) in
colorCell.alpha = 1
UIView.animate(withDuration: 0.7, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
colorCell.frame.origin.x = -15
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.15, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
colorCell.frame.origin.x = 0
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.7, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
titleCell.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.15, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
titleCell.transform = CGAffineTransform.identity
}, completion: { (finished: Bool) in
self.cells.append([cell, colorCell, titleCell])
})
})
})
})
})
})
}
})
})
}
}
@IBAction func hide(_ sender: Any!) {
let HomeController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
HomeController.modalPresentationStyle = .fullScreen
self.present(HomeController, animated: false, completion: nil)
}
@objc func switcher(_ sender: UIButton!) {
if openSideMenu == true {
for i in 0..<self.cells.count {
if self.cells[i][0] == sender.superview {
self.openedMenu = self.cells[i]
}
}
let exit_button : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
exit_button.backgroundColor = UIColor.clear
exit_button.setBackgroundImage(UIImage(named: "icon_close"), for: UIControl.State.normal)
exit_button.alpha = 0.25
exit_button.transform = CGAffineTransform(scaleX: 0, y: 0)
exit_button.addTarget(self, action: #selector(close_switcher(_:)), for: UIControl.Event.touchUpInside)
sender.addSubview(exit_button)
trash_buttton_background.center.y = (sender.superview?.center.y)!
flag_button_background.center.y = (sender.superview?.center.y)!
complete_button_background.center.y = (sender.superview?.center.y)!
flag_button_image.center = flag_button_background.center
trash_button_image.center = trash_buttton_background.center
complete_button_image.center = complete_button_background.center
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowUserInteraction, animations: {
sender.superview?.frame.origin.x = self.view.frame.size.width - 105
exit_button.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.flag_button_background.frame.origin.x = 35
self.trash_buttton_background.frame.origin.x = 115
self.complete_button_background.frame.origin.x = 195
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.allowUserInteraction, animations: {
exit_button.transform = CGAffineTransform.identity
self.flag_button_background.frame.origin.x = 20
self.trash_buttton_background.frame.origin.x = 100
self.complete_button_background.frame.origin.x = 180
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.allowUserInteraction, animations: {
self.flag_button_background.frame.origin.x = 25
self.trash_buttton_background.frame.origin.x = 105
self.complete_button_background.frame.origin.x = 185
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
self.openSideMenu = false
return
})
})
})
} else if openSideMenu == false {
return
}
}
@objc func close_switcher(_ sender: UIButton!) {
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.flag_button_background.frame.origin.x = 20
self.trash_buttton_background.frame.origin.x = 100
self.complete_button_background.frame.origin.x = 180
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.flag_button_background.frame.origin.x = 35
self.trash_buttton_background.frame.origin.x = 115
self.complete_button_background.frame.origin.x = 195
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.flag_button_background.frame.origin.x = 20
self.trash_buttton_background.frame.origin.x = 100
self.complete_button_background.frame.origin.x = 180
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.flag_button_background.frame.origin.x = -75
self.trash_buttton_background.frame.origin.x = -75
self.complete_button_background.frame.origin.x = -75
self.flag_button_image.center = self.flag_button_background.center
self.trash_button_image.center = self.trash_buttton_background.center
self.complete_button_image.center = self.complete_button_background.center
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.15, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
sender.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
sender.transform = CGAffineTransform(scaleX: 0, y: 0)
sender.superview?.superview?.frame.origin.x = -16
}, completion: { (finished: Bool) in
UIView.animate(withDuration: 0.15, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
sender.superview?.superview?.frame.origin.x = 16
}, completion: { (finished: Bool) in
sender.removeFromSuperview()
self.openedMenu = []
self.openSideMenu = true
})
})
})
})
})
})
})
}
@objc func move_Cell_To_Trash(_ sender: UIButton!) {
if !openedMenu.isEmpty {
for i in 0..<(toDoList?.count)! {
if toDoList![i].title == (self.openedMenu[2] as! UILabel).text && toDoList![i].color.color == self.openedMenu[1].backgroundColor {
toDoList![i].section = .main
}
}
let TrashController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
TrashController.modalPresentationStyle = .fullScreen
self.present(TrashController, animated: false, completion: nil)
}
}
@objc func move_Cell_To_Complete(_ sender: UIButton!) {
if !openedMenu.isEmpty {
for i in 0..<(toDoList?.count)! {
if toDoList![i].title == (self.openedMenu[2] as! UILabel).text && toDoList![i].color.color == self.openedMenu[1].backgroundColor {
toDoList![i].section = .completed
}
}
let CompleteController = self.storyboard?.instantiateViewController(withIdentifier: "CompleteViewController") as! CompleteViewController
CompleteController.modalPresentationStyle = .fullScreen
self.present(CompleteController, animated: false, completion: nil)
}
}
@objc func move_Cell_To_Archive(_ sender: UIButton!) {
if !openedMenu.isEmpty {
for i in 0..<(toDoList?.count)! {
if toDoList![i].title == (self.openedMenu[2] as! UILabel).text && toDoList![i].color.color == self.openedMenu[1].backgroundColor {
toDoList![i].section = .flagged
}
}
let ArchiveController = self.storyboard?.instantiateViewController(withIdentifier: "ArchivedViewController") as! ArchivedViewController
ArchiveController.modalPresentationStyle = .fullScreen
self.present(ArchiveController, animated: false, completion: nil)
}
}
}
| 61.040956 | 153 | 0.58619 |
7a1c03f0c122e9a14ab3830e1b6182dfb6bde93e | 3,805 | //
// ENXChartView.swift
// GAEN Analytics
//
// Created by Bill Pugh on 2/14/22.
//
import SwiftUI
import TabularData
struct ENXChartsView: View {
let charts: [ChartOptions]
var body: some View {
ForEach(charts) { c in
ENXChartView(title: c.title, lineChart: LineChart(data: c.data, columns: c.columns, maxBound: c.maxBound))
}
}
}
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
struct ENXChartView: View {
@EnvironmentObject var analysisState: AnalysisState
let title: String
let lineChart: LineChart
@MainActor init(title: String, lineChart: LineChart) {
self.title = title
self.lineChart = lineChart
let exportTitle = title + ".csv"
if let csv = AnalysisState.exportToFileDocument(name: exportTitle, dataframe: lineChart.data) {
csvDocument = csv
} else {
csvDocument = CSVFile(name: "none", Data())
print("set empty csvDocument")
}
if let url = AnalysisState.exportToURL(name: exportTitle, dataframe: lineChart.data) {
csvItem = CSVItem(url: url,
title: title)
} else {
csvItem = CSVItem(url: nil, title: "tmp.csv")
}
}
@State var showingShare: Bool = false
let csvDocument: CSVFile
let csvItem: CSVItem
@State private var showingPopover = false
@State private var showingExport = false
//
var body: some View {
Section(header:
HStack {
Text(title)
Spacer()
Button(action: {
withAnimation(.easeInOut) {
showingPopover.toggle()
}
}) { Image(systemName: "info.circle") }
.padding(.horizontal)
Button(action: {
#if targetEnvironment(macCatalyst)
analysisState.export(csvFile: csvDocument)
#else
print("csv document \(csvDocument.name) has \(csvDocument.data.count) bytes")
shareURL = AnalysisState.exportToURL(csvFile: csvDocument)
shareTitle = csvDocument.name
showingShare = true
#endif
}) {
Image(systemName: "square.and.arrow.up")
}.animation(.easeInOut, value: showingShare)
}.padding(.top).font(.headline) // HStack
) {
if showingPopover {
Text(markdown(file: title)).transition(.scale).fixedSize(horizontal: false, vertical: true)
}
// TestView()
lineChart.frame(height: 300)
}.textCase(nil)
.sheet(isPresented: self.$showingShare, onDismiss: { print("share sheet dismissed") },
content: {
ActivityView(activityItems: [
CSVItem(url: shareURL,
title: shareTitle),
] as [Any], applicationActivities: nil, isPresented: self.$showingShare)
})
}
}
//
// struct ENXChartView_Previews: PreviewProvider {
// static var previews: some View {
// ENXChartView(title: "Title")
// }
// }
| 30.934959 | 118 | 0.547438 |
ac5aa3e3550003db2e7bebb6d4aae7aa488c2532 | 2,627 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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.
struct Library {
var sortedBooks: [Book] { booksCache }
/// An in-memory cache of the manually-sorted books that are persistently stored.
private var booksCache: [Book] = [
.init(title: "Ein Neues Land", author: "Shaun Tan"),
.init(title: "Bosch", author: "Laurinda Dixon"),
.init(title: "Dare to Lead", author: "Brené Brown"),
.init(title: "Blasting for Optimum Health Recipe Book", author: "NutriBullet"),
.init(title: "Drinking with the Saints", author: "Michael P. Foley"),
.init(title: "A Guide to Tea", author: "Adagio Teas"),
.init(title: "The Life and Complete Work of Francisco Goya", author: "P. Gassier & J Wilson"),
.init(title: "Lady Cottington's Pressed Fairy Book", author: "Lady Cottington"),
.init(title: "How to Draw Cats", author: "Janet Rancan"),
.init(title: "Drawing People", author: "Barbara Bradley"),
.init(title: "What to Say When You Talk to Yourself", author: "Shad Helmstetter")
]
}
| 55.893617 | 98 | 0.725162 |
cc96005915de231912f9f9d98da004d4366dddcf | 2,653 | //
// Calculator.swift
// Calculator
//
// Created by Adrian Romero on 4/8/15.
// Copyright (c) 2015 AR. All rights reserved.
//
import Foundation
class Calculator {
private enum Op: Printable {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double, Double) -> Double)
var description: String {
get {
switch self {
case .Operand(let value): return value.description
case .UnaryOperation(let symbol, _): return symbol
case .BinaryOperation(let symbol, _): return symbol
}
}
}
}
private var opStack = [Op]()
private var knownOps = [String:Op]()
init() {
knownOps["+"] = Op.BinaryOperation("+", +)
knownOps["x"] = Op.BinaryOperation("x", *)
knownOps["-"] = Op.BinaryOperation("-", {$1 - $0})
knownOps["/"] = Op.BinaryOperation("/", {$1 / $0})
knownOps["S"] = Op.UnaryOperation("S", sqrt)
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
print("\(opStack) = \(result) with \(remainder) left over")
return result
}
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvalution = evaluate(remainingOps)
if let operand = operandEvalution.result {
return (operation(operand), operandEvalution.remainingOps)
}
case .BinaryOperation(_, let operation):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
}
}
return (nil, ops)
}
} | 31.963855 | 90 | 0.534866 |
612248994ef3112686dfecd806be02c53a79af6e | 35,819 | //
// ServerUniverse.swift
// NetrekServer
//
// Created by Darrell Root on 5/31/20.
// Copyright © 2020 Darrell Root. All rights reserved.
//
import Foundation
//import Network
import NIO
class Universe {
let updatesPerSecond = 20.0
var timer: Timer?
//var weakTimer: Timer? = nil
var timerCount = 0
static let planetFilename = "netrek.planets"
let fileManager = FileManager()
static let startPlanets = [
Planet(planetID: 0, positionX: 20000, positionY: 80000, name: "Earth", team: .federation, homeworld: true),
Planet(planetID: 1, positionX: 10000, positionY: 60000, name: "Rigel", team: .federation, homeworld: false),
Planet(planetID: 2, positionX: 25000, positionY: 60000, name: "Canopus", team: .federation, homeworld: false),
Planet(planetID: 3, positionX: 44000, positionY: 81000, name: "Beta Crucis", team: .federation, homeworld: false),
Planet(planetID: 4, positionX: 39000, positionY: 55000, name: "Organia", team: .federation, homeworld: false),
Planet(planetID: 5, positionX: 30000, positionY: 90000, name: "Deneb", team: .federation, homeworld: false),
Planet(planetID: 6, positionX: 45000, positionY: 66000, name: "Ceti Alpha V", team: .federation, homeworld: false),
Planet(planetID: 7, positionX: 11000, positionY: 75000, name: "Altair", team: .federation, homeworld: false),
Planet(planetID: 8, positionX: 8000, positionY: 93000, name: "Vega", team: .federation, homeworld: false),
Planet(planetID: 9, positionX: 32000, positionY: 74000, name: "Alpha Centauri", team: .federation, homeworld: false),
Planet(planetID: 10, positionX: 20000, positionY: 20000, name: "Rome", team: .roman, homeworld: true),
Planet(planetID: 11, positionX: 45000, positionY: 7000, name: "Eridani", team: .roman, homeworld: false),
Planet(planetID: 12, positionX: 4000, positionY: 12000, name: "Aldeberan", team: .roman, homeworld: false),
Planet(planetID: 13, positionX: 42000, positionY: 44000, name: "Regulus", team: .roman, homeworld: false),
Planet(planetID: 14, positionX: 13000, positionY: 45000, name: "Capella", team: .roman, homeworld: false),
Planet(planetID: 15, positionX: 28000, positionY: 8000, name: "Tauri", team: .roman, homeworld: false),
Planet(planetID: 16, positionX: 28000, positionY: 23000, name: "Draconis", team: .roman, homeworld: false),
Planet(planetID: 17, positionX: 40000, positionY: 25000, name: "Sirius", team: .roman, homeworld: false),
Planet(planetID: 18, positionX: 25000, positionY: 44000, name: "Indi", team: .roman, homeworld: false),
Planet(planetID: 19, positionX: 8000, positionY: 29000, name: "Hydrae", team: .roman, homeworld: false),
Planet(planetID: 20, positionX: 80000, positionY: 20000, name: "Kazari", team: .kazari, homeworld: true),
Planet(planetID: 21, positionX: 70000, positionY: 40000, name: "Pliedes V", team: .kazari, homeworld: false),
Planet(planetID: 22, positionX: 60000, positionY: 10000, name: "Andromeda", team: .kazari, homeworld: false),
Planet(planetID: 23, positionX: 56400, positionY: 38200, name: "Lalande", team: .kazari, homeworld: false),
Planet(planetID: 24, positionX: 91120, positionY: 9320, name: "Praxis", team: .kazari, homeworld: false),
Planet(planetID: 25, positionX: 89960, positionY: 31760, name: "Lyrae", team: .kazari, homeworld: false),
Planet(planetID: 26, positionX: 70720, positionY: 26320, name: "Scorpii", team: .kazari, homeworld: false),
Planet(planetID: 27, positionX: 83600, positionY: 45400, name: "Mira", team: .kazari, homeworld: false),
Planet(planetID: 28, positionX: 54600, positionY: 22600, name: "Cygni", team: .kazari, homeworld: false),
Planet(planetID: 29, positionX: 73080, positionY: 6640, name: "Achernar", team: .kazari, homeworld: false),
Planet(planetID: 30, positionX: 80000, positionY: 80000, name: "Orion", team: .orion, homeworld: true),
Planet(planetID: 31, positionX: 91200, positionY: 56600, name: "Cassiopeia", team: .orion, homeworld: false),
Planet(planetID: 32, positionX: 70800, positionY: 54200, name: "El Nath", team: .orion, homeworld: false),
Planet(planetID: 33, positionX: 57400, positionY: 62600, name: "Spica", team: .orion, homeworld: false),
Planet(planetID: 34, positionX: 72720, positionY: 70880, name: "Procyon", team: .orion, homeworld: false),
Planet(planetID: 35, positionX: 61400, positionY: 77000, name: "Polaris", team: .orion, homeworld: false),
Planet(planetID: 36, positionX: 55600, positionY: 89000, name: "Arcturus", team: .orion, homeworld: false),
Planet(planetID: 37, positionX: 91000, positionY: 94000, name: "Ursae Majoris", team: .orion, homeworld: false),
Planet(planetID: 38, positionX: 70000, positionY: 93000, name: "Herculis", team: .orion, homeworld: false),
Planet(planetID: 39, positionX: 86920, positionY: 68920, name: "Antares", team: .orion, homeworld: false),
]
var players: [Player] = []
var activePlayers: [Player] {
return self.players.filter({$0.status != .free})
}
var alivePlayers: [Player] {
return self.players.filter({$0.status == .alive})
}
var humanPlayers: [Player] {
return self.players.filter({$0.human})
}
var planets: [Planet] = [
Planet(planetID: 0, positionX: 20000, positionY: 80000, name: "Earth", team: .federation, homeworld: true),
Planet(planetID: 1, positionX: 10000, positionY: 60000, name: "Rigel", team: .federation, homeworld: false),
Planet(planetID: 2, positionX: 25000, positionY: 60000, name: "Canopus", team: .federation, homeworld: false),
Planet(planetID: 3, positionX: 44000, positionY: 81000, name: "Beta Crucis", team: .federation, homeworld: false),
Planet(planetID: 4, positionX: 39000, positionY: 55000, name: "Organia", team: .federation, homeworld: false),
Planet(planetID: 5, positionX: 30000, positionY: 90000, name: "Deneb", team: .federation, homeworld: false),
Planet(planetID: 6, positionX: 45000, positionY: 66000, name: "Ceti Alpha V", team: .federation, homeworld: false),
Planet(planetID: 7, positionX: 11000, positionY: 75000, name: "Altair", team: .federation, homeworld: false),
Planet(planetID: 8, positionX: 8000, positionY: 93000, name: "Vega", team: .federation, homeworld: false),
Planet(planetID: 9, positionX: 32000, positionY: 74000, name: "Alpha Centauri", team: .federation, homeworld: false),
Planet(planetID: 10, positionX: 20000, positionY: 20000, name: "Rome", team: .roman, homeworld: true),
Planet(planetID: 11, positionX: 45000, positionY: 7000, name: "Eridani", team: .roman, homeworld: false),
Planet(planetID: 12, positionX: 4000, positionY: 12000, name: "Aldeberan", team: .roman, homeworld: false),
Planet(planetID: 13, positionX: 42000, positionY: 44000, name: "Regulus", team: .roman, homeworld: false),
Planet(planetID: 14, positionX: 13000, positionY: 45000, name: "Capella", team: .roman, homeworld: false),
Planet(planetID: 15, positionX: 28000, positionY: 8000, name: "Tauri", team: .roman, homeworld: false),
Planet(planetID: 16, positionX: 28000, positionY: 23000, name: "Draconis", team: .roman, homeworld: false),
Planet(planetID: 17, positionX: 40000, positionY: 25000, name: "Sirius", team: .roman, homeworld: false),
Planet(planetID: 18, positionX: 25000, positionY: 44000, name: "Indi", team: .roman, homeworld: false),
Planet(planetID: 19, positionX: 8000, positionY: 29000, name: "Hydrae", team: .roman, homeworld: false),
Planet(planetID: 20, positionX: 80000, positionY: 20000, name: "Kazari", team: .kazari, homeworld: true),
Planet(planetID: 21, positionX: 70000, positionY: 40000, name: "Pliedes V", team: .kazari, homeworld: false),
Planet(planetID: 22, positionX: 60000, positionY: 10000, name: "Andromeda", team: .kazari, homeworld: false),
Planet(planetID: 23, positionX: 56400, positionY: 38200, name: "Lalande", team: .kazari, homeworld: false),
Planet(planetID: 24, positionX: 91120, positionY: 9320, name: "Praxis", team: .kazari, homeworld: false),
Planet(planetID: 25, positionX: 89960, positionY: 31760, name: "Lyrae", team: .kazari, homeworld: false),
Planet(planetID: 26, positionX: 70720, positionY: 26320, name: "Scorpii", team: .kazari, homeworld: false),
Planet(planetID: 27, positionX: 83600, positionY: 45400, name: "Mira", team: .kazari, homeworld: false),
Planet(planetID: 28, positionX: 54600, positionY: 22600, name: "Cygni", team: .kazari, homeworld: false),
Planet(planetID: 29, positionX: 73080, positionY: 6640, name: "Achernar", team: .kazari, homeworld: false),
Planet(planetID: 30, positionX: 80000, positionY: 80000, name: "Orion", team: .orion, homeworld: true),
Planet(planetID: 31, positionX: 91200, positionY: 56600, name: "Cassiopeia", team: .orion, homeworld: false),
Planet(planetID: 32, positionX: 70800, positionY: 54200, name: "El Nath", team: .orion, homeworld: false),
Planet(planetID: 33, positionX: 57400, positionY: 62600, name: "Spica", team: .orion, homeworld: false),
Planet(planetID: 34, positionX: 72720, positionY: 70880, name: "Procyon", team: .orion, homeworld: false),
Planet(planetID: 35, positionX: 61400, positionY: 77000, name: "Polaris", team: .orion, homeworld: false),
Planet(planetID: 36, positionX: 55600, positionY: 89000, name: "Arcturus", team: .orion, homeworld: false),
Planet(planetID: 37, positionX: 91000, positionY: 94000, name: "Ursae Majoris", team: .orion, homeworld: false),
Planet(planetID: 38, positionX: 70000, positionY: 93000, name: "Herculis", team: .orion, homeworld: false),
Planet(planetID: 39, positionX: 86920, positionY: 68920, name: "Antares", team: .orion, homeworld: false),
]
//var queue: [Player] = []
static let MAXPLAYERS = 32
var homeworld: [Team:Planet] = [:]
//var team1 = Team.federation
//var team2 = Team.roman
//var users: [User] = []
var userDatabase = UserDatabase()
var robotController = RobotController()
var gameState: GameState = .intramural
let tModeThreshold = 6
var metaserver: MetaserverUDP? = nil
//https://stackoverflow.com/questions/8304702/how-do-i-create-a-nstimer-on-a-background-thread
/*func scheduleTimerInBackgroundThread(){
DispatchQueue.global().async(execute: {
//This method schedules timer to current runloop.
self.weakTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats: true)
self.weakTimer?.tolerance = 0.03
//start runloop manually, otherwise timer won't fire
//add timer before run, otherwise runloop find there's nothing to do and exit directly.
RunLoop.current.run()
})
}*/
init() {
//logger.info("Universe.init")
// attempt to load planet database
var url = URL(fileURLWithPath: netrekOptions.directory)
url.appendPathComponent(Universe.planetFilename)
let decoder = JSONDecoder()
do {
let data = try Data(contentsOf: url)
let planets = try decoder.decode([Planet].self, from: data)
self.planets = planets
} catch {
logger.critical("Unable to read planet database from \(url) error \(error)")
logger.critical("Using default planet list")
}
//planets = Universe.startPlanets
for slotnum in 0 ..< Universe.MAXPLAYERS {
let homeworld: Planet?
let planetShuffle = planets.shuffled()
let player: Player
switch netrekOptions.gameStyle {
case .bronco:
player = Player(slot: slotnum, universe: self)
case .empire:
homeworld = planetShuffle[slotnum]
player = Player(slot: slotnum, universe: self, homeworld: homeworld)
}
self.players.append(player)
}
homeworld[.federation] = planets.first(where: {$0.name == "Earth"})!
homeworld[.roman] = planets.first(where: {$0.name == "Rome"})!
homeworld[.kazari] = planets.first(where: {$0.name == "Kazari"})!
homeworld[.orion] = planets.first(where: {$0.name == "Orion"})!
//timer = Timer.scheduledTimer(timeInterval: 1.0 / updatesPerSecond, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
//timer = Timer(timeInterval: 1.0 / updatesPerSecond, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
timer = Timer.scheduledTimer(withTimeInterval: 1.0 / updatesPerSecond, repeats: true) {_ in
self.timerFired()
}
timer?.tolerance = 0.3 / updatesPerSecond
logger.info("Timer initialized")
if let timer = timer {
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
}
if netrekOptions.domainName != nil {
self.metaserver = MetaserverUDP(universe: self)
//we send to metaserver later in timer
/*if let metaserver = self.metaserver {
metaserver.sendReport(ip: "161.35.226.186", port: 3521)
} else {
//cannot log here
print("Error: unable to send to metaserver")
}*/
} else {
//cannot log here
print("No metaserver specified on CLI: skipping metaserver reports")
}
logger.info("scheduling timer")
}
deinit {
logger.critical("universe.deinit")
}
/*
SP_PLANET_LOC pnum= 1 x= 10000 y= 60000 name= Rigel
SP_PLANET_LOC pnum= 2 x= 25000 y= 60000 name= Canopus
SP_PLANET_LOC pnum= 3 x= 44000 y= 81000 name= Beta Crucis
SP_PLANET_LOC pnum= 4 x= 39000 y= 55000 name= Organia
SP_PLANET_LOC pnum= 5 x= 30000 y= 90000 name= Deneb
SP_PLANET_LOC pnum= 6 x= 45000 y= 66000 name= Ceti Alpha V
SP_PLANET_LOC pnum= 7 x= 11000 y= 75000 name= Altair
SP_PLANET_LOC pnum= 8 x= 8000 y= 93000 name= Vega
SP_PLANET_LOC pnum= 9 x= 32000 y= 74000 name= Alpha Centauri
SP_PLANET_LOC pnum= 10 x= 20000 y= 20000 name= Romulus
SP_PLANET_LOC pnum= 11 x= 45000 y= 7000 name= Eridani
SP_PLANET_LOC pnum= 12 x= 4000 y= 12000 name= Aldeberan
SP_PLANET_LOC pnum= 13 x= 42000 y= 44000 name= Regulus
SP_PLANET_LOC pnum= 14 x= 13000 y= 45000 name= Capella
SP_PLANET_LOC pnum= 15 x= 28000 y= 8000 name= Tauri
SP_PLANET_LOC pnum= 16 x= 28000 y= 23000 name= Draconis
SP_PLANET_LOC pnum= 17 x= 40000 y= 25000 name= Sirius
SP_PLANET_LOC pnum= 18 x= 25000 y= 44000 name= Indi
SP_PLANET_LOC pnum= 19 x= 8000 y= 29000 name= Hydrae
SP_PLANET_LOC pnum= 20 x= 80000 y= 80000 name= Klingus
SP_PLANET_LOC pnum= 21 x= 70000 y= 40000 name= Pliedes V
SP_PLANET_LOC pnum= 22 x= 60000 y= 10000 name= Andromeda
SP_PLANET_LOC pnum= 23 x= 56400 y= 38200 name= Lalande
SP_PLANET_LOC pnum= 24 x= 91120 y= 9320 name= Praxis
SP_PLANET_LOC pnum= 25 x= 89960 y= 31760 name= Lyrae
SP_PLANET_LOC pnum= 26 x= 70720 y= 26320 name= Scorpii
SP_PLANET_LOC pnum= 27 x= 83600 y= 45400 name= Mira
SP_PLANET_LOC pnum= 28 x= 54600 y= 22600 name= Cygni
SP_PLANET_LOC pnum= 29 x= 73080 y= 6640 name= Achernar
SP_PLANET_LOC pnum= 30 x= 80000 y= 80000 name= Orion
SP_PLANET_LOC pnum= 31 x= 91200 y= 56600 name= Cassiopeia
SP_PLANET_LOC pnum= 32 x= 70800 y= 54200 name= El Nath
SP_PLANET_LOC pnum= 33 x= 57400 y= 62600 name= Spica
SP_PLANET_LOC pnum= 34 x= 72720 y= 70880 name= Procyon
SP_PLANET_LOC pnum= 35 x= 61400 y= 77000 name= Polaris
SP_PLANET_LOC pnum= 36 x= 55600 y= 89000 name= Arcturus
SP_PLANET_LOC pnum= 37 x= 91000 y= 94000 name= Ursae Majoris
SP_PLANET_LOC pnum= 38 x= 70000 y= 93000 name= Herculis
SP_PLANET_LOC pnum= 39 x= 86920 y= 68920 name= Antares
*/
func savePlanets() {
logger.info("saving planet database")
let encoder = JSONEncoder()
let directory = netrekOptions.directory
if !fileManager.directoryExists(directory) {
do {
try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: false)
} catch {
logger.critical("\(#file) \(#function) Unable to create directory \(directory) error \(error)")
return
//fatalError("\(#file) \(#function) Unable to create directory \(directory) error \(error)")
}
}
var url = URL(fileURLWithPath: netrekOptions.directory)
url.appendPathComponent(Universe.planetFilename)
if let encoded = try? encoder.encode(planets) {
do {
try encoded.write(to: url, options: .atomic)
} catch {
logger.critical("Unable to write planet database to \(url)")
return
}
}
logger.info("Saved planet database to url \(url)")
}
public func shutdownWarning() {
print("sending shutdown warnings")
logger.info("Sending shutdown warnings")
for player in self.activePlayers {
player.sendMessage(message: "Alert: Netrek Server shutting down. Try again in a few minutes.")
}
}
public func shutdownComplete() {
print("shutdown complete")
exit(0)
}
func randomFreeSlot() -> Int? {
let freeSlots = self.players.filter({$0.status == .free})
guard let randomFreeSlot = freeSlots.randomElement() else {
return nil
}
return randomFreeSlot.slot
/*for (slotnum,player) in self.players.enumerated() {
if player.status == .free {
return slotnum
}
}
return nil*/
}
func sendPlanetUpdates(_ forceUpdate: Bool = false) {
// this is called every 0.1 seconds
// it only sends updates for planets with needsUpdate set
// but always sends updates if force = true
for planet in planets.filter({($0.needsUpdate == true) || forceUpdate}) {
logger.debug("Sending SP_PLANETs for \(planet.name)")
let data = MakePacket.spPlanet(planet: planet)
for player in activePlayers {
player.sendData(data)
/*if let context = player.context {
context.eventLoop.execute {
let buffer = context.channel.allocator.buffer(bytes: data)
_ = context.channel.write(buffer)
}
}*/
}
planet.needsUpdate = false
}
}
@objc func timerFired() {
self.timerCount += 1
//logger.trace("\(#file) \(#function) count \(self.timerCount)")
self.sendPlanetUpdates()
for player in self.players {
if player.status != .free {
player.shortTimerFired()
}
}
//pop a planet every half second if we have at least one player
if timerCount % (Int(updatesPerSecond) / 2) == 0 && players.filter({ $0.status != .free}).count > 0 {
if let planet = planets.randomElement() {
planet.pop()
}
}
//once per second actions
if timerCount % Int(self.updatesPerSecond) == 0 {
for player in self.players {
if player.status != .free {
player.secondTimerFired()
}
}
robotController.secondTimerFired()
}
//once per minute actions
if timerCount % 60 * Int(self.updatesPerSecond) == 0 {
for player in self.players {
if player.status != .free {
player.minuteTimerFired()
}
}
}
//send a packet every tick
for player in self.humanPlayers {
player.flush()
}
//metaserver update every 3 minutes
if timerCount % (180 * Int(self.updatesPerSecond)) == 0 {
if let metaserver = self.metaserver {
metaserver.sendReport(ip: "69.164.215.96", port: 3521)
metaserver.sendReport(ip: "63.170.91.110", port: 3521)
} else {
logger.error("Error: unable to send to metaserver")
}
}
//save planets once per minute
if timerCount % (60 * Int(self.updatesPerSecond)) == 0 {
logger.info("Attempting to save planets")
self.savePlanets()
}
// stats report once per 30 minutes
//TODO change to 30 minutes
if timerCount % (60 * Int(self.updatesPerSecond)) == 0 {
userDatabase.updateStats()
for player in humanPlayers {
player.statsReport()
}
// save user database after stats report
try? userDatabase.save()
}
}
public func checkForWin() {
switch netrekOptions.gameStyle {
case .bronco:
checkForWinBronco()
case .empire:
checkForWinEmpire()
}
}
func checkForWinEmpire() {
var planetCount: [Team:Int] = [:]
for team in Team.allCases {
planetCount[team] = 0
}
for planet in self.planets {
planetCount[planet.team]! += 1
}
let goal = self.planets.count * 3 / 4
for team in Team.empireTeams {
if planetCount[team]! >= goal {
empireWin(winner: team)
}
}
}
func checkForWinBronco() {
var planetCount: [Team:Int] = [:]
for team in Team.allCases {
planetCount[team] = 0
}
for planet in self.planets {
planetCount[planet.team]! += 1
}
for team in Team.broncoTeams {
if planetCount[team]! < 1 {
broncoLoss(loser: team)
}
}
}
func broncoLoss(loser: Team) {
let winner = Team.broncoTeams.filter({$0 != loser}).first!
for player in humanPlayers {
player.sendMessage(message: "\(winner) dominates the galaxy!")
}
for player in activePlayers.filter({$0.team == loser}) {
player.impact(damage: 9999, whyDead: .genocide)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.broncoReset()
}
}
func empireWin(winner: Team) {
for player in humanPlayers {
player.sendMessage(message: "\(winner) dominates the galaxy!")
}
for player in activePlayers.filter({$0.team != winner}) {
player.impact(damage: 9999, whyDead: .genocide)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.empireReset()
}
}
func empireReset() {
self.planets = [
Planet(planetID: 0, positionX: 20000, positionY: 80000, name: "Earth", team: .federation, homeworld: true),
Planet(planetID: 1, positionX: 10000, positionY: 60000, name: "Rigel", team: .federation, homeworld: false),
Planet(planetID: 2, positionX: 25000, positionY: 60000, name: "Canopus", team: .federation, homeworld: false),
Planet(planetID: 3, positionX: 44000, positionY: 81000, name: "Beta Crucis", team: .federation, homeworld: false),
Planet(planetID: 4, positionX: 39000, positionY: 55000, name: "Organia", team: .federation, homeworld: false),
Planet(planetID: 5, positionX: 30000, positionY: 90000, name: "Deneb", team: .federation, homeworld: false),
Planet(planetID: 6, positionX: 45000, positionY: 66000, name: "Ceti Alpha V", team: .federation, homeworld: false),
Planet(planetID: 7, positionX: 11000, positionY: 75000, name: "Altair", team: .federation, homeworld: false),
Planet(planetID: 8, positionX: 8000, positionY: 93000, name: "Vega", team: .federation, homeworld: false),
Planet(planetID: 9, positionX: 32000, positionY: 74000, name: "Alpha Centauri", team: .federation, homeworld: false),
Planet(planetID: 10, positionX: 20000, positionY: 20000, name: "Rome", team: .roman, homeworld: true),
Planet(planetID: 11, positionX: 45000, positionY: 7000, name: "Eridani", team: .roman, homeworld: false),
Planet(planetID: 12, positionX: 4000, positionY: 12000, name: "Aldeberan", team: .roman, homeworld: false),
Planet(planetID: 13, positionX: 42000, positionY: 44000, name: "Regulus", team: .roman, homeworld: false),
Planet(planetID: 14, positionX: 13000, positionY: 45000, name: "Capella", team: .roman, homeworld: false),
Planet(planetID: 15, positionX: 28000, positionY: 8000, name: "Tauri", team: .roman, homeworld: false),
Planet(planetID: 16, positionX: 28000, positionY: 23000, name: "Draconis", team: .roman, homeworld: false),
Planet(planetID: 17, positionX: 40000, positionY: 25000, name: "Sirius", team: .roman, homeworld: false),
Planet(planetID: 18, positionX: 25000, positionY: 44000, name: "Indi", team: .roman, homeworld: false),
Planet(planetID: 19, positionX: 8000, positionY: 29000, name: "Hydrae", team: .roman, homeworld: false),
Planet(planetID: 20, positionX: 80000, positionY: 20000, name: "Kazari", team: .kazari, homeworld: true),
Planet(planetID: 21, positionX: 70000, positionY: 40000, name: "Pliedes V", team: .kazari, homeworld: false),
Planet(planetID: 22, positionX: 60000, positionY: 10000, name: "Andromeda", team: .kazari, homeworld: false),
Planet(planetID: 23, positionX: 56400, positionY: 38200, name: "Lalande", team: .kazari, homeworld: false),
Planet(planetID: 24, positionX: 91120, positionY: 9320, name: "Praxis", team: .kazari, homeworld: false),
Planet(planetID: 25, positionX: 89960, positionY: 31760, name: "Lyrae", team: .kazari, homeworld: false),
Planet(planetID: 26, positionX: 70720, positionY: 26320, name: "Scorpii", team: .kazari, homeworld: false),
Planet(planetID: 27, positionX: 83600, positionY: 45400, name: "Mira", team: .kazari, homeworld: false),
Planet(planetID: 28, positionX: 54600, positionY: 22600, name: "Cygni", team: .kazari, homeworld: false),
Planet(planetID: 29, positionX: 73080, positionY: 6640, name: "Achernar", team: .kazari, homeworld: false),
Planet(planetID: 30, positionX: 80000, positionY: 80000, name: "Orion", team: .orion, homeworld: true),
Planet(planetID: 31, positionX: 91200, positionY: 56600, name: "Cassiopeia", team: .orion, homeworld: false),
Planet(planetID: 32, positionX: 70800, positionY: 54200, name: "El Nath", team: .orion, homeworld: false),
Planet(planetID: 33, positionX: 57400, positionY: 62600, name: "Spica", team: .orion, homeworld: false),
Planet(planetID: 34, positionX: 72720, positionY: 70880, name: "Procyon", team: .orion, homeworld: false),
Planet(planetID: 35, positionX: 61400, positionY: 77000, name: "Polaris", team: .orion, homeworld: false),
Planet(planetID: 36, positionX: 55600, positionY: 89000, name: "Arcturus", team: .orion, homeworld: false),
Planet(planetID: 37, positionX: 91000, positionY: 94000, name: "Ursae Majoris", team: .orion, homeworld: false),
Planet(planetID: 38, positionX: 70000, positionY: 93000, name: "Herculis", team: .orion, homeworld: false),
Planet(planetID: 39, positionX: 86920, positionY: 68920, name: "Antares", team: .orion, homeworld: false),
]
for player in players {
player.homeworld = player.getRandomHomeworld()
}
for player in activePlayers {
player.impact(damage: 9999, whyDead: .genocide)
}
for player in humanPlayers {
player.sendMessage(message: "A new war spreads across the new galaxy!")
player.sendInitialTransfer()
}
}
func broncoReset() {
self.planets = [
Planet(planetID: 0, positionX: 20000, positionY: 80000, name: "Earth", team: .federation, homeworld: true),
Planet(planetID: 1, positionX: 10000, positionY: 60000, name: "Rigel", team: .federation, homeworld: false),
Planet(planetID: 2, positionX: 25000, positionY: 60000, name: "Canopus", team: .federation, homeworld: false),
Planet(planetID: 3, positionX: 44000, positionY: 81000, name: "Beta Crucis", team: .federation, homeworld: false),
Planet(planetID: 4, positionX: 39000, positionY: 55000, name: "Organia", team: .federation, homeworld: false),
Planet(planetID: 5, positionX: 30000, positionY: 90000, name: "Deneb", team: .federation, homeworld: false),
Planet(planetID: 6, positionX: 45000, positionY: 66000, name: "Ceti Alpha V", team: .federation, homeworld: false),
Planet(planetID: 7, positionX: 11000, positionY: 75000, name: "Altair", team: .federation, homeworld: false),
Planet(planetID: 8, positionX: 8000, positionY: 93000, name: "Vega", team: .federation, homeworld: false),
Planet(planetID: 9, positionX: 32000, positionY: 74000, name: "Alpha Centauri", team: .federation, homeworld: false),
Planet(planetID: 10, positionX: 20000, positionY: 20000, name: "Rome", team: .roman, homeworld: true),
Planet(planetID: 11, positionX: 45000, positionY: 7000, name: "Eridani", team: .roman, homeworld: false),
Planet(planetID: 12, positionX: 4000, positionY: 12000, name: "Aldeberan", team: .roman, homeworld: false),
Planet(planetID: 13, positionX: 42000, positionY: 44000, name: "Regulus", team: .roman, homeworld: false),
Planet(planetID: 14, positionX: 13000, positionY: 45000, name: "Capella", team: .roman, homeworld: false),
Planet(planetID: 15, positionX: 28000, positionY: 8000, name: "Tauri", team: .roman, homeworld: false),
Planet(planetID: 16, positionX: 28000, positionY: 23000, name: "Draconis", team: .roman, homeworld: false),
Planet(planetID: 17, positionX: 40000, positionY: 25000, name: "Sirius", team: .roman, homeworld: false),
Planet(planetID: 18, positionX: 25000, positionY: 44000, name: "Indi", team: .roman, homeworld: false),
Planet(planetID: 19, positionX: 8000, positionY: 29000, name: "Hydrae", team: .roman, homeworld: false),
Planet(planetID: 20, positionX: 80000, positionY: 20000, name: "Kazari", team: .kazari, homeworld: true),
Planet(planetID: 21, positionX: 70000, positionY: 40000, name: "Pliedes V", team: .kazari, homeworld: false),
Planet(planetID: 22, positionX: 60000, positionY: 10000, name: "Andromeda", team: .kazari, homeworld: false),
Planet(planetID: 23, positionX: 56400, positionY: 38200, name: "Lalande", team: .kazari, homeworld: false),
Planet(planetID: 24, positionX: 91120, positionY: 9320, name: "Praxis", team: .kazari, homeworld: false),
Planet(planetID: 25, positionX: 89960, positionY: 31760, name: "Lyrae", team: .kazari, homeworld: false),
Planet(planetID: 26, positionX: 70720, positionY: 26320, name: "Scorpii", team: .kazari, homeworld: false),
Planet(planetID: 27, positionX: 83600, positionY: 45400, name: "Mira", team: .kazari, homeworld: false),
Planet(planetID: 28, positionX: 54600, positionY: 22600, name: "Cygni", team: .kazari, homeworld: false),
Planet(planetID: 29, positionX: 73080, positionY: 6640, name: "Achernar", team: .kazari, homeworld: false),
Planet(planetID: 30, positionX: 80000, positionY: 80000, name: "Orion", team: .orion, homeworld: true),
Planet(planetID: 31, positionX: 91200, positionY: 56600, name: "Cassiopeia", team: .orion, homeworld: false),
Planet(planetID: 32, positionX: 70800, positionY: 54200, name: "El Nath", team: .orion, homeworld: false),
Planet(planetID: 33, positionX: 57400, positionY: 62600, name: "Spica", team: .orion, homeworld: false),
Planet(planetID: 34, positionX: 72720, positionY: 70880, name: "Procyon", team: .orion, homeworld: false),
Planet(planetID: 35, positionX: 61400, positionY: 77000, name: "Polaris", team: .orion, homeworld: false),
Planet(planetID: 36, positionX: 55600, positionY: 89000, name: "Arcturus", team: .orion, homeworld: false),
Planet(planetID: 37, positionX: 91000, positionY: 94000, name: "Ursae Majoris", team: .orion, homeworld: false),
Planet(planetID: 38, positionX: 70000, positionY: 93000, name: "Herculis", team: .orion, homeworld: false),
Planet(planetID: 39, positionX: 86920, positionY: 68920, name: "Antares", team: .orion, homeworld: false),
]
for player in activePlayers {
player.impact(damage: 9999, whyDead: .genocide)
}
for player in humanPlayers {
player.sendMessage(message: "A new war spreads across the new galaxy!")
}
}
func player(context: ChannelHandlerContext) -> Player? {
for player in self.players {
if context === player.context {
return player
}
}
logger.error("Error: \(#file) \(#function) unable to find player for context \(context)")
return nil
}
func player(remoteAddress: SocketAddress) -> Player? {
return self.players.first(where: {$0.remoteAddress == remoteAddress })
}
/*func player(connection: NWConnection) -> Player? {
for (slot, player) in self.players.enumerated() {
if connection === player.connection?.connection {
return player
}
}
logger.error("Error: \(#file) \(#function) unable to find player for connection \(connection)")
return nil
}*/
/*func connectionEnded(connection: ServerConnection) {
for (slot,player) in self.players.enumerated() {
if player.connection === connection {
player.disconnected()
}
}
}*/
/*func addPlayer(connection: ServerConnection) {
if let freeSlot = firstFreeSlot() {
self.players[freeSlot].connected(connection: connection)
}
}*/
func addPlayer(context: ChannelHandlerContext) {
//if let freeSlot = randomFreeSlot() {
if let player = self.players.first(where: {$0.status == .free}) {
player.connected(context: context)
}
self.setGameMode()
}
public func setGameMode() {
if self.humanPlayers.count >= tModeThreshold {
self.gameState = .tmode
} else {
self.gameState = .intramural
}
}
/*func send(playerid: Int, data: Data) {
guard let player = players[safe: playerid] else {
logger.error("Error \(#file) \(#function) no connection for id \(playerid) ")
return
}
logger.trace("sending \(data.count) bytes to playerid \(playerid)")
player.connection?.send(data: data)
}*/
}
| 57.402244 | 153 | 0.622491 |
f7b2d8102e87b3b4fd187e94a96920522ab223c3 | 2,335 | //
// SceneDelegate.swift
// BeerApp
//
// Created by Andrea on 21/03/2020.
// Copyright © 2020 Andrea. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.903846 | 147 | 0.71349 |
3a52c3a985b2bc22f1e22423a33c406d7a7d7891 | 35,500 | //
// PrecalculationModule.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2019 JamieScanlon
//
// 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 ARKit
import AugmentKitShader
import Foundation
import MetalKit
class PrecalculationModule: PreRenderComputeModule {
weak var computePass: ComputePass<PrecalculatedParameters>?
var device: MTLDevice?
var frameCount: Int = 1
var moduleIdentifier: String {
return "PrecalculationModule"
}
var state: ShaderModuleState = .uninitialized
var renderLayer: Int {
return -3
}
var errors = [AKError]()
var renderDistance: Double = 500
var sharedModuleIdentifiers: [String]? = [SharedBuffersRenderModule.identifier]
func initializeBuffers(withDevice device: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) {
state = .initializing
self.device = device
frameCount = maxInFlightFrames
instanceCount = maxInstances
alignedGeometryInstanceUniformsSize = ((MemoryLayout<AnchorInstanceUniforms>.stride * instanceCount) & ~0xFF) + 0x100
alignedEffectsUniformSize = ((MemoryLayout<AnchorEffectsUniforms>.stride * instanceCount) & ~0xFF) + 0x100
alignedEnvironmentUniformSize = ((MemoryLayout<EnvironmentUniforms>.stride * instanceCount) & ~0xFF) + 0x100
// Calculate our uniform buffer sizes. We allocate `maxInFlightFrames` instances for uniform
// storage in a single buffer. This allows us to update uniforms in a ring (i.e. triple
// buffer the uniforms) so that the GPU reads from one slot in the ring wil the CPU writes
// to another. Geometry uniforms should be specified with a max instance count for instancing.
// Also uniform storage must be aligned (to 256 bytes) to meet the requirements to be an
// argument in the constant address space of our shading functions.
let geometryUniformBufferSize = alignedGeometryInstanceUniformsSize * maxInFlightFrames
let jointTransformBufferSize = Constants.alignedJointTransform * Constants.maxJointCount * maxInFlightFrames
let effectsUniformBufferSize = alignedEffectsUniformSize * maxInFlightFrames
let environmentUniformBufferSize = alignedEnvironmentUniformSize * maxInFlightFrames
// Create and allocate our uniform buffer objects. Indicate shared storage so that both the
// CPU can access the buffer
geometryUniformBuffer = device.makeBuffer(length: geometryUniformBufferSize, options: .storageModeShared)
geometryUniformBuffer?.label = "Geometry Uniform Buffer"
jointTransformBuffer = device.makeBuffer(length: jointTransformBufferSize, options: [])
jointTransformBuffer?.label = "Joint Transform Buffer"
effectsUniformBuffer = device.makeBuffer(length: effectsUniformBufferSize, options: .storageModeShared)
effectsUniformBuffer?.label = "Effects Uniform Buffer"
environmentUniformBuffer = device.makeBuffer(length: environmentUniformBufferSize, options: .storageModeShared)
environmentUniformBuffer?.label = "Environment Uniform Buffer"
}
func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<PrecalculatedParameters>?) -> ThreadGroup? {
guard let computePass = computePass else {
print("Warning (PrecalculationModule) - a ComputePass was not found. Aborting.")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelNotFound, userInfo: nil)
let newError = AKError.warning(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
state = .ready
return nil
}
self.computePass = computePass
self.computePass?.functionName = "precalculationComputeShader"
self.computePass?.initializeBuffers(withDevice: device)
self.computePass?.loadPipeline(withMetalLibrary: metalLibrary, instanceCount: instanceCount, threadgroupDepth: 1)
state = .ready
return self.computePass?.threadGroup
}
func updateBufferState(withBufferIndex bufferIndex: Int) {
geometryUniformBufferOffset = alignedGeometryInstanceUniformsSize * bufferIndex
jointTransformBufferOffset = Constants.alignedJointTransform * Constants.maxJointCount * bufferIndex
effectsUniformBufferOffset = alignedEffectsUniformSize * bufferIndex
environmentUniformBufferOffset = alignedEnvironmentUniformSize * bufferIndex
geometryUniformBufferAddress = geometryUniformBuffer?.contents().advanced(by: geometryUniformBufferOffset)
jointTransformBufferAddress = jointTransformBuffer?.contents().advanced(by: jointTransformBufferOffset)
effectsUniformBufferAddress = effectsUniformBuffer?.contents().advanced(by: effectsUniformBufferOffset)
environmentUniformBufferAddress = environmentUniformBuffer?.contents().advanced(by: environmentUniformBufferOffset)
computePass?.updateBuffers(withFrameIndex: bufferIndex)
}
func prepareToDraw(withAllEntities allEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, computePass: ComputePass<PrecalculatedParameters>, renderPass: RenderPass?) {
var drawCallGroupOffset = 0
var drawCallGroupIndex = 0
let geometryUniforms = geometryUniformBufferAddress?.assumingMemoryBound(to: AnchorInstanceUniforms.self)
let environmentUniforms = environmentUniformBufferAddress?.assumingMemoryBound(to: EnvironmentUniforms.self)
let effectsUniforms = effectsUniformBufferAddress?.assumingMemoryBound(to: AnchorEffectsUniforms.self)
// Get all of the AKGeometricEntity's
var allGeometricEntities: [AKGeometricEntity] = allEntities.compactMap({
if let geoEntity = $0 as? AKGeometricEntity {
return geoEntity
} else {
return nil
}
})
let allGeometricEntityGroups: [AKGeometricEntityGroup] = allEntities.compactMap({
if let geoEntity = $0 as? AKGeometricEntityGroup {
return geoEntity
} else {
return nil
}
})
let groupGeometries = allGeometricEntityGroups.flatMap({$0.geometries})
allGeometricEntities.append(contentsOf: groupGeometries)
renderPass?.drawCallGroups.forEach { drawCallGroup in
let uuid = drawCallGroup.uuid
let geometricEntity = allGeometricEntities.first(where: {$0.identifier == uuid})
var drawCallIndex = 0
for drawCall in drawCallGroup.drawCalls {
//
// Environment Uniform Setup
//
if let environmentUniform = environmentUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesEnvironment {
// See if this anchor is associated with an environment anchor. An environment anchor applies to a region of space which may contain several anchors. The environment anchor that has the smallest volume is assumed to be more localized and therefore be the best for for this anchor
var environmentTexture: MTLTexture?
let environmentProbes: [AREnvironmentProbeAnchor] = environmentProperties.environmentAnchorsWithReatedAnchors.compactMap{
if $0.value.contains(uuid) {
return $0.key
} else {
return nil
}
}
if environmentProbes.count > 1 {
var bestEnvironmentProbe: AREnvironmentProbeAnchor?
environmentProbes.forEach {
if let theBestEnvironmentProbe = bestEnvironmentProbe {
let existingVolume = AKCube(position: AKVector(x: theBestEnvironmentProbe.transform.columns.3.x, y: theBestEnvironmentProbe.transform.columns.3.y, z: theBestEnvironmentProbe.transform.columns.3.z), extent: AKVector(theBestEnvironmentProbe.extent)).volume()
let newVolume = AKCube(position: AKVector(x: $0.transform.columns.3.x, y: $0.transform.columns.3.y, z: $0.transform.columns.3.z), extent: AKVector($0.extent)).volume()
if newVolume < existingVolume {
bestEnvironmentProbe = $0
}
} else {
bestEnvironmentProbe = $0
}
}
if let environmentProbeAnchor = bestEnvironmentProbe, let texture = environmentProbeAnchor.environmentTexture {
environmentTexture = texture
}
} else {
if let environmentProbeAnchor = environmentProbes.first, let texture = environmentProbeAnchor.environmentTexture {
environmentTexture = texture
}
}
let environmentData: EnvironmentData = {
var myEnvironmentData = EnvironmentData()
if let texture = environmentTexture {
myEnvironmentData.environmentTexture = texture
myEnvironmentData.hasEnvironmentMap = true
return myEnvironmentData
} else {
myEnvironmentData.hasEnvironmentMap = false
}
return myEnvironmentData
}()
// Set up lighting for the scene using the ambient intensity if provided
let ambientIntensity: Float = {
if let lightEstimate = environmentProperties.lightEstimate {
return Float(lightEstimate.ambientIntensity) / 1000.0
} else {
return 1
}
}()
let ambientLightColor: SIMD3<Float> = {
if let lightEstimate = environmentProperties.lightEstimate {
// FIXME: Remove
return getRGB(from: lightEstimate.ambientColorTemperature)
} else {
return SIMD3<Float>(0.5, 0.5, 0.5)
}
}()
environmentUniforms?.pointee.ambientLightIntensity = ambientIntensity
environmentUniform.pointee.ambientLightColor = ambientLightColor// * ambientIntensity
var directionalLightDirection : SIMD3<Float> = environmentProperties.directionalLightDirection
directionalLightDirection = simd_normalize(directionalLightDirection)
environmentUniform.pointee.directionalLightDirection = directionalLightDirection
let directionalLightColor: SIMD3<Float> = SIMD3<Float>(0.6, 0.6, 0.6)
environmentUniform.pointee.directionalLightColor = directionalLightColor// * ambientIntensity
environmentUniform.pointee.directionalLightMVP = environmentProperties.directionalLightMVP
environmentUniform.pointee.shadowMVPTransformMatrix = shadowProperties.shadowMVPTransformMatrix
if environmentData.hasEnvironmentMap == true {
environmentUniform.pointee.hasEnvironmentMap = 1
} else {
environmentUniform.pointee.hasEnvironmentMap = 0
}
}
//
// Effects Uniform Setup
//
if let effectsUniform = effectsUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesEnvironment {
var hasSetAlpha = false
var hasSetGlow = false
var hasSetTint = false
var hasSetScale = false
if let effects = geometricEntity?.effects {
let currentTime: TimeInterval = Double(cameraProperties.currentFrame) / cameraProperties.frameRate
for effect in effects {
switch effect.effectType {
case .alpha:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniform.pointee.alpha = value
hasSetAlpha = true
}
case .glow:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniform.pointee.glow = value
hasSetGlow = true
}
case .tint:
if let value = effect.value(forTime: currentTime) as? SIMD3<Float> {
effectsUniform.pointee.tint = value
hasSetTint = true
}
case .scale:
if let value = effect.value(forTime: currentTime) as? Float {
let scaleMatrix = matrix_identity_float4x4
effectsUniform.pointee.scale = scaleMatrix.scale(x: value, y: value, z: value)
hasSetScale = true
}
}
}
}
if !hasSetAlpha {
effectsUniform.pointee.alpha = 1
}
if !hasSetGlow {
effectsUniform.pointee.glow = 0
}
if !hasSetTint {
effectsUniform.pointee.tint = SIMD3<Float>(1,1,1)
}
if !hasSetScale {
effectsUniform.pointee.scale = matrix_identity_float4x4
}
}
//
// Geometry Uniform Setup
//
if let geometryUniform = geometryUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesGeometry {
guard let drawData = drawCall.drawData, drawCallIndex <= instanceCount else {
geometryUniform.pointee.hasGeometry = 0
drawCallIndex += 1
continue
}
// FIXME: - Let the compute shader do most of this
// Apply the world transform (as defined in the imported model) if applicable
let worldTransform: matrix_float4x4 = {
if let pathSegment = geometricEntity as? AKPathSegmentAnchor {
// For path segments, use the segmentTransform as the worldTransform
return pathSegment.segmentTransform
} else if drawData.worldTransformAnimations.count > 0 {
let index = Int(cameraProperties.currentFrame % UInt(drawData.worldTransformAnimations.count))
return drawData.worldTransformAnimations[index]
} else {
return drawData.worldTransform
}
}()
var hasHeading = false
var headingType: HeadingType = .absolute
var headingTransform = matrix_identity_float4x4
var locationTransform = matrix_identity_float4x4
if let akAnchor = geometricEntity as? AKAnchor {
// Update Heading
headingTransform = akAnchor.heading.offsetRotation.quaternion.toMatrix4()
hasHeading = true
headingType = akAnchor.heading.type
// Update postion
locationTransform = akAnchor.worldLocation.transform
} else if let akTarget = geometricEntity as? AKTarget {
// Apply the transform of the target relative to the reference transform
let targetAbsoluteTransform = akTarget.position.referenceTransform * akTarget.position.transform
locationTransform = targetAbsoluteTransform
} else if let akTracker = geometricEntity as? AKTracker {
if let heading = akTracker.position.heading {
// Update Heading
headingTransform = heading.offsetRotation.quaternion.toMatrix4()
hasHeading = true
headingType = heading.type
}
// Update position
// Apply the transform of the target relative to the reference transform
let trackerAbsoluteTransform = akTracker.position.referenceTransform * akTracker.position.transform
locationTransform = trackerAbsoluteTransform
}
// Ignore anchors that are beyond the renderDistance
let distance = anchorDistance(withTransform: locationTransform, cameraProperties: cameraProperties)
guard Double(distance) < renderDistance else {
geometryUniform.pointee.hasGeometry = 0
drawCallIndex += 1
continue
}
// Calculate LOD
let lodMapWeights = computeTextureWeights(for: distance)
geometryUniform.pointee.hasGeometry = 1
geometryUniform.pointee.hasHeading = hasHeading ? 1 : 0
geometryUniform.pointee.headingType = headingType == .absolute ? 0 : 1
geometryUniform.pointee.headingTransform = headingTransform
geometryUniform.pointee.worldTransform = worldTransform
geometryUniform.pointee.locationTransform = locationTransform
geometryUniform.pointee.mapWeights = lodMapWeights
}
drawCallIndex += 1
}
drawCallGroupOffset += drawCallGroup.drawCalls.count
drawCallGroupIndex += 1
}
}
func dispatch(withComputePass computePass: ComputePass<PrecalculatedParameters>?, sharedModules: [SharedRenderModule]?) {
guard let computePass = computePass else {
return
}
guard let computeEncoder = computePass.computeCommandEncoder else {
return
}
guard let threadGroup = computePass.threadGroup else {
return
}
computeEncoder.pushDebugGroup("Dispatch Precalculation")
computeEncoder.setBytes(&instanceCount, length: MemoryLayout<Int>.size, index: Int(kBufferIndexInstanceCount.rawValue))
if let sharedRenderModule = sharedModules?.first(where: {$0.moduleIdentifier == SharedBuffersRenderModule.identifier}), let sharedBuffer = sharedRenderModule.sharedUniformsBuffer?.buffer, let sharedBufferOffset = sharedRenderModule.sharedUniformsBuffer?.currentBufferFrameOffset, computePass.usesSharedBuffer {
computeEncoder.pushDebugGroup("Shared Uniforms")
computeEncoder.setBuffer(sharedBuffer, offset: sharedBufferOffset, index: sharedRenderModule.sharedUniformsBuffer?.shaderAttributeIndex ?? 0)
computeEncoder.popDebugGroup()
}
if let environmentUniformBuffer = environmentUniformBuffer, computePass.usesEnvironment {
computeEncoder.pushDebugGroup("Environment Uniforms")
computeEncoder.setBuffer(environmentUniformBuffer, offset: environmentUniformBufferOffset, index: Int(kBufferIndexEnvironmentUniforms.rawValue))
computeEncoder.popDebugGroup()
}
if let effectsBuffer = effectsUniformBuffer, computePass.usesEffects {
computeEncoder.pushDebugGroup("Effects Uniforms")
computeEncoder.setBuffer(effectsBuffer, offset: effectsUniformBufferOffset, index: Int(kBufferIndexAnchorEffectsUniforms.rawValue))
computeEncoder.popDebugGroup()
}
if computePass.usesGeometry {
computeEncoder.pushDebugGroup("Geometry Uniforms")
computeEncoder.setBuffer(geometryUniformBuffer, offset: geometryUniformBufferOffset, index: Int(kBufferIndexAnchorInstanceUniforms.rawValue))
computeEncoder.popDebugGroup()
if computePass.hasSkeleton {
computeEncoder.pushDebugGroup("Joint Transform Uniforms")
computeEncoder.setBuffer(jointTransformBuffer, offset: jointTransformBufferOffset, index: Int(kBufferIndexMeshJointTransforms.rawValue))
computeEncoder.popDebugGroup()
}
}
// Output Buffer
if let argumentOutputBuffer = computePass.outputBuffer?.buffer, let argumentOutputBufferOffset = computePass.outputBuffer?.currentBufferFrameOffset {
computeEncoder.pushDebugGroup("Output Buffer")
computeEncoder.setBuffer(argumentOutputBuffer, offset: argumentOutputBufferOffset, index: Int(kBufferIndexPrecalculationOutputBuffer.rawValue))
computeEncoder.popDebugGroup()
}
computePass.prepareThreadGroup()
// Requires the device supports non-uniform threadgroup sizes
computeEncoder.dispatchThreads(MTLSize(width: threadGroup.size.width, height: threadGroup.size.height, depth: threadGroup.size.depth), threadsPerThreadgroup: MTLSize(width: threadGroup.threadsPerGroup.width, height: threadGroup.threadsPerGroup.height, depth: 1))
computeEncoder.popDebugGroup()
}
func frameEncodingComplete(renderPasses: [RenderPass]) {
//
}
func recordNewError(_ akError: AKError) {
errors.append(akError)
}
// MARK: - Private
fileprivate enum Constants {
static let maxJointCount = 100
static let alignedJointTransform = (MemoryLayout<matrix_float4x4>.stride & ~0xFF) + 0x100
}
fileprivate var instanceCount: Int = 0
fileprivate var alignedGeometryInstanceUniformsSize: Int = 0
fileprivate var alignedEffectsUniformSize: Int = 0
fileprivate var alignedEnvironmentUniformSize: Int = 0
fileprivate var geometryUniformBuffer: MTLBuffer?
fileprivate var jointTransformBuffer: MTLBuffer?
fileprivate var effectsUniformBuffer: MTLBuffer?
fileprivate var environmentUniformBuffer: MTLBuffer?
// Offset within geometryUniformBuffer to set for the current frame
fileprivate var geometryUniformBufferOffset: Int = 0
// Offset within jointTransformBuffer to set for the current frame
fileprivate var jointTransformBufferOffset = 0
// Offset within effectsUniformBuffer to set for the current frame
fileprivate var effectsUniformBufferOffset: Int = 0
// Offset within environmentUniformBuffer to set for the current frame
fileprivate var environmentUniformBufferOffset: Int = 0
// Addresses to write geometry uniforms to each frame
fileprivate var geometryUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write jointTransform to each frame
fileprivate var jointTransformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write effects uniforms to each frame
fileprivate var effectsUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write environment uniforms to each frame
fileprivate var environmentUniformBufferAddress: UnsafeMutableRawPointer?
// FIXME: Remove - put in compute shader
fileprivate func anchorDistance(withTransform transform: matrix_float4x4, cameraProperties: CameraProperties?) -> Float {
guard let cameraProperties = cameraProperties else {
return 0
}
let point = SIMD3<Float>(transform.columns.3.x, transform.columns.3.x, transform.columns.3.z)
return length(point - cameraProperties.position)
}
fileprivate func computeTextureWeights(for distance: Float) -> (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float) {
guard AKCapabilities.LevelOfDetail else {
return (Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1))
}
let quality = RenderUtilities.getQualityLevel(for: distance)
// Escape hatch for performance. If the quality is low, exit with all 0 values
guard quality.rawValue < 2 else {
return (Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0))
}
var baseMapWeight: Float = 1
var normalMapWeight: Float = 1
var metallicMapWeight: Float = 1
var roughnessMapWeight: Float = 1
var ambientOcclusionMapWeight: Float = 1
var emissionMapWeight: Float = 1
var subsurfaceMapWeight: Float = 1
var specularMapWeight: Float = 1
var specularTintMapWeight: Float = 1
var anisotropicMapWeight: Float = 1
var sheenMapWeight: Float = 1
var sheenTintMapWeight: Float = 1
var clearcoatMapWeight: Float = 1
var clearcoatMapWeightGlossMapWeight: Float = 1
let nextLevel: QualityLevel = {
if quality == kQualityLevelHigh {
return kQualityLevelMedium
} else {
return kQualityLevelLow
}
}()
let mapWeight = getMapWeight(for: quality, distance: distance)
if !RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: quality) {
baseMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: nextLevel) {
baseMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: quality) {
normalMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: nextLevel) {
normalMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: quality) {
metallicMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: nextLevel) {
metallicMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: quality) {
roughnessMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: nextLevel) {
roughnessMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: quality) {
ambientOcclusionMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: nextLevel) {
ambientOcclusionMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: quality) {
emissionMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: nextLevel) {
emissionMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: quality) {
subsurfaceMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: nextLevel) {
subsurfaceMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: quality) {
specularMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: nextLevel) {
specularMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: quality) {
specularTintMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: nextLevel) {
specularTintMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: quality) {
anisotropicMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: nextLevel) {
anisotropicMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: quality) {
sheenMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: nextLevel) {
sheenMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: quality) {
sheenTintMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: nextLevel) {
sheenTintMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: quality) {
clearcoatMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: nextLevel) {
clearcoatMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: quality) {
clearcoatMapWeightGlossMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: nextLevel) {
clearcoatMapWeightGlossMapWeight = mapWeight
}
return (baseMapWeight, normalMapWeight, metallicMapWeight, roughnessMapWeight, ambientOcclusionMapWeight, emissionMapWeight, subsurfaceMapWeight, specularMapWeight, specularTintMapWeight, anisotropicMapWeight, sheenMapWeight, sheenTintMapWeight, clearcoatMapWeight, clearcoatMapWeightGlossMapWeight)
}
fileprivate func getMapWeight(for level: QualityLevel, distance: Float) -> Float {
guard AKCapabilities.LevelOfDetail else {
return 1
}
guard distance > 0 else {
return 1
}
// In meters
let MediumQualityDepth: Float = 15
let LowQualityDepth: Float = 65
let TransitionDepthAmount: Float = 50
if level == kQualityLevelHigh {
let TransitionDepth = MediumQualityDepth - TransitionDepthAmount
if distance > TransitionDepth {
return 1 - ((distance - TransitionDepth) / TransitionDepthAmount)
} else {
return 1
}
} else if level == kQualityLevelMedium {
let TransitionDepth = LowQualityDepth - TransitionDepthAmount
if distance > TransitionDepth {
return 1 - ((distance - TransitionDepth) / TransitionDepthAmount)
} else {
return 1
}
} else {
return 0
}
}
}
| 52.359882 | 318 | 0.616479 |
33e06dad04ad68000a06af50d0d8021e12878590 | 2,695 | //
// OrderDetailView.swift
// Created by jsonshenglong on 2019/1/15.
// Copyright © 2019年 jsonshenglong. All rights reserved.
import UIKit
class OrderDetailView: UIView {
var order: Order? {
didSet {
initLabel(orderNumberLabel, text: ("订 单 号 " + order!.order_no!))
initLabel(consigneeLabel, text: ("收 货 码 " + order!.checknum!))
initLabel(orderBuyTimeLabel, text: ("下单时间 " + order!.create_time!))
initLabel(deliverTimeLabel, text: "配送时间 " + order!.accept_time!)
initLabel(deliverWayLabel, text: "配送方式 送货上门")
initLabel(payWayLabel, text: "支付方式 在线支付")
if order?.postscript != nil {
initLabel(remarksLabel, text: "备注信息 " + order!.postscript!)
} else {
initLabel(remarksLabel, text: "备注信息")
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let orderNumberLabel = UILabel()
let consigneeLabel = UILabel()
let orderBuyTimeLabel = UILabel()
let deliverTimeLabel = UILabel()
let deliverWayLabel = UILabel()
let payWayLabel = UILabel()
let remarksLabel = UILabel()
fileprivate func initLabel(_ label: UILabel, text: String) {
label.text = text
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = LFBTextBlackColor
addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
let leftMargin: CGFloat = 10
let labelWidth: CGFloat = width - 2 * leftMargin
let labelHeight: CGFloat = 25
orderNumberLabel.frame = CGRect(x: leftMargin, y: 5, width: labelWidth, height: labelHeight)
consigneeLabel.frame = CGRect(x: leftMargin, y: orderNumberLabel.frame.maxY, width: labelWidth, height: labelHeight)
orderBuyTimeLabel.frame = CGRect(x: leftMargin, y: consigneeLabel.frame.maxY, width: labelWidth, height: labelHeight)
deliverTimeLabel.frame = CGRect(x: leftMargin, y: orderBuyTimeLabel.frame.maxY, width: labelWidth, height: labelHeight)
deliverWayLabel.frame = CGRect(x: leftMargin, y: deliverTimeLabel.frame.maxY, width: labelWidth, height: labelHeight)
payWayLabel.frame = CGRect(x: leftMargin, y: deliverWayLabel.frame.maxY, width: labelWidth, height: labelHeight)
remarksLabel.frame = CGRect(x: leftMargin, y: payWayLabel.frame.maxY, width: labelWidth, height: labelHeight)
}
}
| 40.223881 | 128 | 0.634508 |
ff50a5f597c894c353c3e88fe8942f202ceb5f08 | 925 | //
// Intersect.swift
// LeetCodeDemo
//
// Created by Yangdongwu on 2020/12/7.
//
import Foundation
class Intersect {
/// 350 两个数组的交集 II
func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
guard nums1.count <= nums2.count else {
return intersect(nums2, nums1)
}
var hs = [Int: Int](), res = [Int]()
for num in nums1 {
if let record = hs[num] {
hs[num] = record + 1
} else {
hs[num] = 1
}
}
for num in nums2 {
if let record = hs[num] {
if record > 0 {
res.append(num)
hs[num] = record - 1
}
}
}
return res
}
func test() {
let nums1 = [1,2,2,1]
let nums2 = [2,2]
let result = intersect(nums1, nums2)
print(result)
}
}
| 22.02381 | 61 | 0.423784 |
281b3b283c018789eacd0883de07c8bf4a895e03 | 1,814 | #if os(macOS)
import Darwin
#else
import Glibc
#endif
import Foundation
import Socket
extension Socket.Address: CustomStringConvertible {
init?(ipv4 presentation: String) {
var sin = sockaddr_in()
guard inet_pton(AF_INET, presentation, &sin.sin_addr) == 1 else {
return nil
}
self = .ipv4(sin)
}
public var port: UInt16 {
get {
switch self {
case .ipv4(let sin):
return sin.sin_port.bigEndian
case .ipv6(let sin6):
return sin6.sin6_port.bigEndian
default: abort()
}
}
set {
switch self {
case .ipv4(var sin):
sin.sin_port = newValue.bigEndian
self = .ipv4(sin)
case .ipv6(var sin6):
sin6.sin6_port = newValue.bigEndian
self = .ipv6(sin6)
default: abort()
}
}
}
var presentation: String {
var buffer = Data(count: Int(INET6_ADDRSTRLEN))
switch self {
case .ipv4(var sin):
let ptr = buffer.withUnsafeMutableBytes {
inet_ntop(AF_INET, &sin.sin_addr, $0, socklen_t(buffer.count))
}
return String(cString: ptr!)
case .ipv6(var sin6):
let ptr = buffer.withUnsafeMutableBytes {
inet_ntop(AF_INET6, &sin6.sin6_addr, $0, socklen_t(buffer.count))
}
return String(cString: ptr!)
default: abort()
}
}
public var description: String {
switch self {
case .ipv4(_):
return "\(presentation):\(port)"
case .ipv6(_):
return "[\(presentation)]:\(port)"
default: abort()
}
}
}
| 26.289855 | 81 | 0.506064 |
29fcbd24bb9a2162e9184f60016ee3d019a08cea | 7,334 | import Log
import Time
import Event
import Platform
import ListEntry
@_exported import enum Event.IOEvent
public class FiberLoop {
var poller = Poller()
var watchers: UnsafeMutableBufferPointer<Watchers>
var sleeping: UnsafeMutablePointer<WatcherEntry>
struct Watchers {
var read: UnsafeMutablePointer<Fiber>?
var write: UnsafeMutablePointer<Fiber>?
var isEmpty: Bool { read == nil && write == nil }
}
@usableFromInline
var scheduler = Scheduler.current
var currentFiber: UnsafeMutablePointer<Fiber> {
@inline (__always) get {
return scheduler.running
}
}
public private(set) static var main = FiberLoop()
private static var _current = ThreadSpecific<FiberLoop>()
public class var current: FiberLoop {
Thread.isMain
? main
: FiberLoop._current.get() { FiberLoop() }
}
var deadline = Time.distantFuture
var nextDeadline: Time {
if scheduler.hasReady {
return now
}
assert(!sleeping.isEmpty)
return sleeping.first!.pointee.payload.pointee.deadline
}
public init() {
watchers = UnsafeMutableBufferPointer.allocate(
repeating: Watchers(),
count: Descriptor.maxLimit)
sleeping = UnsafeMutablePointer.allocate(
payload: scheduler.running)
}
deinit {
watchers.deallocate()
sleeping.deallocate()
}
var readyCount = 0
@usableFromInline
var now = Time()
var canceled = false
public var isCanceled: Bool {
return canceled
}
var running = false
public func run(until deadline: Time = .distantFuture) {
guard !self.running else {
return
}
self.running = true
self.deadline = deadline
while !canceled {
do {
guard now < deadline else {
break
}
guard sleeping.count > 0 || scheduler.hasReady else {
#if DEBUG_FIBER
Log.debug("No fiber to schedule, shutting down.")
#endif
break
}
let events = try poller.poll(deadline: nextDeadline)
now = Time()
scheduleReady(events)
scheduleExpired()
runScheduled()
} catch {
Log.error("poll error \(error)")
}
}
scheduler.cancelReady()
wakeupSuspended()
runScheduled()
self.running = false
self.canceled = false
}
public func `break`() {
canceled = true
}
func wakeupSuspended() {
for watcher in sleeping.pointee {
scheduler.schedule(fiber: watcher.pointee.payload, state: .canceled)
}
}
func scheduleReady(_ events: ArraySlice<Event>) {
for event in events {
let pair = watchers[event.descriptor]
guard !pair.isEmpty else { continue }
if event.typeOptions.contains(.read), let fiber = pair.read {
scheduler.schedule(fiber: fiber, state: .ready)
}
if event.typeOptions.contains(.write), let fiber = pair.write {
scheduler.schedule(fiber: fiber, state: .ready)
}
}
}
func scheduleExpired() {
for watcher in sleeping.pointee {
let fiber = watcher.pointee.payload
guard fiber.pointee.deadline <= now else {
break
}
scheduler.schedule(fiber: fiber, state: .expired)
}
}
func runScheduled() {
while scheduler.hasReady {
scheduler.runReadyChain()
}
}
@discardableResult
public func wait(for deadline: Time) -> Fiber.State {
insertWatcher(deadline: deadline)
scheduler.suspend()
removeWatcher()
return currentFiber.pointee.state
}
@discardableResult
public func wait(
for socket: Descriptor,
event: IOEvent,
deadline: Time) throws -> Fiber.State
{
try insertWatcher(for: socket, event: event, deadline: deadline)
scheduler.suspend()
removeWatcher(for: socket, event: event)
if currentFiber.pointee.state == .expired {
throw Error.timeout
}
return currentFiber.pointee.state
}
func insertWatcher(
for descriptor: Descriptor,
event: IOEvent,
deadline: Time
) throws {
switch event {
case .read:
guard watchers[descriptor].read == nil else {
throw Error.descriptorAlreadyInUse
}
watchers[descriptor].read = currentFiber
case .write:
guard watchers[descriptor].write == nil else {
throw Error.descriptorAlreadyInUse
}
watchers[descriptor].write = currentFiber
}
insertWatcher(deadline: deadline)
poller.add(socket: descriptor, event: event)
}
func removeWatcher(for descriptor: Descriptor, event: IOEvent) {
switch event {
case .read: watchers[descriptor].read = nil
case .write: watchers[descriptor].write = nil
}
// TODO: investigate & test more
poller.remove(socket: descriptor, event: event)
removeWatcher()
}
func insertWatcher(deadline: Time) {
currentFiber.pointee.deadline = deadline
if sleeping.isEmpty || deadline >= sleeping.maxDeadline! {
sleeping.append(currentFiber.pointee.watcherEntry)
} else if deadline < sleeping.minDeadline! {
sleeping.insert(currentFiber.pointee.watcherEntry)
} else {
for watcher in sleeping.pointee {
if deadline < watcher.deadline {
watcher.insert(currentFiber.pointee.watcherEntry)
return
}
}
fatalError("unreachable")
}
}
func removeWatcher() {
currentFiber.pointee.watcherEntry.remove()
}
}
extension UnsafeMutableBufferPointer where Element == FiberLoop.Watchers {
typealias Watchers = FiberLoop.Watchers
subscript(_ descriptor: Descriptor) -> Watchers{
get { self[Int(descriptor.rawValue)] }
set { self[Int(descriptor.rawValue)] = newValue }
}
static func allocate(
repeating element: Watchers,
count: Int) -> UnsafeMutableBufferPointer<Watchers>
{
let pointer = UnsafeMutablePointer<Watchers>.allocate(capacity: count)
pointer.initialize(repeating: element, count: count)
return UnsafeMutableBufferPointer(
start: pointer,
count: Descriptor.maxLimit)
}
}
extension UnsafeMutablePointer
where Pointee == ListEntry<UnsafeMutablePointer<Fiber>> {
var deadline: Time {
pointee.payload.pointee.deadline
}
var minDeadline: Time? {
first?.payload.pointee.deadline
}
var maxDeadline: Time? {
last?.payload.pointee.deadline
}
}
extension FiberLoop: Equatable {
public static func ==(lhs: FiberLoop, rhs: FiberLoop) -> Bool {
return lhs.poller == rhs.poller
}
}
| 27.062731 | 80 | 0.581674 |
3ae7c35c1b757b8a6c2046ecd5e1c6ba82987f89 | 412 | //
// Collection+UtilsTests.swift
// SwiftToolboxTests
//
// Created by Ben Davis on 12/02/2018.
// Copyright © 2018 bendavisapps. All rights reserved.
//
import XCTest
@testable import SwiftToolbox
class Collection_UtilsTests: XCTestCase {
func test_countWhere() {
let array = [1,2,3,4,5]
let result = array.count(where: { $0 > 2 })
XCTAssertEqual(result, 3)
}
}
| 19.619048 | 55 | 0.640777 |
33d17cdc417af5b992899f636e30e6fb530f175b | 1,108 | //
// EgnytePickerCellViewModel.swift
// SampleApp
//
// Created by Adam Kędzia on 23.11.2016.
// Copyright © 2017 Egnyte. All rights reserved.
//
import Foundation
import EgnyteSDK
struct EgnytePickerCellViewModel {
let mimeIcon: EgnyteMimeIcon
let itemName: String
let lastModified: String?
init(item: EgnyteItem) {
self.mimeIcon = EgnyteMimeIcon.init(item: item)
self.itemName = item.name
if let item = item as? EgnyteFile {
self.lastModified = EgnytePickerCellViewModel.modifiedDataFrom(timeStamp: item.lastModified)
} else if let item = item as? EgnyteSearchedFile{
self.lastModified = EgnytePickerCellViewModel.modifiedDataFrom(timeStamp: item.lastModified)
} else {
self.lastModified = nil
}
}
static private func modifiedDataFrom(timeStamp: TimeInterval) -> String {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "dd.MM.YYYY, HH:mm"
return dateFormatter.string(from: Date.init(timeIntervalSince1970: timeStamp))
}
}
| 30.777778 | 104 | 0.675993 |
4ba685706b6b9a5a4d6f0f5c3aa1c83665119bd2 | 1,785 | //
// ViewControllerButtonFunctions.swift
// Lumina
//
// Created by David Okun on 11/20/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import Foundation
extension LuminaViewController {
@objc func cancelButtonTapped() {
delegate?.dismissed(controller: self)
}
@objc func shutterButtonTapped() {
shutterButton.takePhoto()
previewLayer.opacity = 0
UIView.animate(withDuration: 0.25) {
self.previewLayer.opacity = 1
}
guard let camera = self.camera else {
return
}
camera.captureStillImage()
}
@objc func shutterButtonLongPressed(_ sender: UILongPressGestureRecognizer) {
guard let camera = self.camera else {
return
}
switch sender.state {
case .began:
if recordsVideo && !camera.recordingVideo {
shutterButton.startRecordingVideo()
camera.startVideoRecording()
feedbackGenerator.startRecordingVideoFeedback()
}
case .ended:
if recordsVideo && camera.recordingVideo {
shutterButton.stopRecordingVideo()
camera.stopVideoRecording()
feedbackGenerator.endRecordingVideoFeedback()
} else {
feedbackGenerator.errorFeedback()
}
default:
break
}
}
@objc func switchButtonTapped() {
switch self.position {
case .back:
self.position = .front
default:
self.position = .back
}
}
@objc func torchButtonTapped() {
guard let camera = self.camera else {
return
}
camera.torchState = !camera.torchState
}
}
| 26.25 | 81 | 0.569188 |
5b552c2dfa1b365aedd527098e4124e6c6664911 | 2,658 | //
// personalisePlanCalculator.swift
// Food Diary App!
//
// Created by Ben Shih on 19/03/2018.
// Copyright © 2018 BenShih. All rights reserved.
//
import Foundation
struct personalisePlanCalculator
{
var calorie: Double?
var plan: [Double] = []
init(calorie: Double)
{
self.calorie = calorie
customisePlanCalculator()
}
private mutating func customisePlanCalculator()
{
var personPlan = [0.0,0.0,0.0,0.0,0.0] // Grain,Vegetable,Protein,Fruit,Dairy
let locale = NSLocale.current.identifier
if (locale == "zh-Hans" || locale == "zh-Hant")
{
if calorie! < 1350
{
personPlan = [1.5,3.0,3.0,2.0,1.5]
}else if calorie! >= 1350 && calorie! < 1650
{
personPlan = [2.5,3.0,4.0,2.0,1.5]
}else if calorie! >= 1650 && calorie! < 1900
{
personPlan = [3.0,3.0,5.0,2.0,1.5]
}else if calorie! >= 1900 && calorie! < 2100
{
personPlan = [3.0,4.0,6.0,3.0,1.5]
}else if calorie! >= 2100 && calorie! < 2350
{
personPlan = [3.5,4.0,6.0,3.5,1.5]
}else if calorie! >= 2350 && calorie! < 2600
{
personPlan = [4.0,5.0,7.0,4.0,1.5]
}else
{
personPlan = [4.0,5.0,8.0,4.0,2.0]
}
}else
{
// Plan in MyPlate
if calorie! < 1700.00
{
personPlan = [5.0,2.0,5.0,1.5,3.0]
}else if calorie! >= 1700 && calorie! < 1900
{
personPlan = [6.0,2.5,5.0,1.5,3.0]
}else if calorie! >= 1900 && calorie! < 2100
{
personPlan = [6.0,2.5,5.5,2.0,3.0]
}else if calorie! >= 2100 && calorie! < 2300
{
personPlan = [7.0,3.0,6.0,2.0,3.0]
}else if calorie! >= 2300 && calorie! < 2500
{
personPlan = [8.0,3.0,6.5,2.0,3.0]
}else if calorie! >= 2500 && calorie! < 2700
{
personPlan = [9.0,3.5,6.5,2.0,3.0]
}else if calorie! >= 2700 && calorie! < 2900
{
personPlan = [10.0,3.5,7.0,2.5,3.0]
}else if calorie! >= 2900 && calorie! < 3100
{
personPlan = [10.0,4.0,7.0,2.5,3.0]
}else
{
personPlan = [10.0,4.0,7.0,2.5,3.0]
}
}
plan = personPlan
}
func getPlan() -> [Double]
{
return plan
}
}
| 29.533333 | 85 | 0.431904 |
d72b8a7e6cf203b59f9c88f43cd9450f542cd4b5 | 2,451 | //
// SceneDelegate.swift
// GoldenDish
//
// Created by נדב אבנון on 15/02/2021.
//
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.
// Save changes in the application's managed object context when the application transitions to the background.
CoreData.shared.saveContext()
}
}
| 43.767857 | 147 | 0.714402 |
fed3f2ded6079d438524fe772e39681c4b8efe0c | 3,715 | /*
* Copyright 2020 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 CoreFoundation
import FlatBuffers
struct Benchmark {
var name: String
var value: Double
var description: String { "\(String(format: "|\t%@\t\t|\t\t%fs\t|", name, value))"}
}
func run(name: String, runs: Int, action: () -> Void) -> Benchmark {
action()
let start = CFAbsoluteTimeGetCurrent()
for _ in 0..<runs {
action()
}
let ends = CFAbsoluteTimeGetCurrent()
let value = Double(ends - start) / Double(runs)
print("done \(name): in \(value)")
return Benchmark(name: name, value: value)
}
func createDocument(Benchmarks: [Benchmark]) -> String {
let separator = "-------------------------------------"
var document = "\(separator)\n"
document += "\(String(format: "|\t%@\t\t|\t\t%@\t\t|", "Name", "Scores"))\n"
document += "\(separator)\n"
for i in Benchmarks {
document += "\(i.description) \n"
document += "\(separator)\n"
}
return document
}
@inlinable
func create10Strings() {
var fb = FlatBufferBuilder(initialSize: 1<<20)
for _ in 0..<10_000 {
_ = fb.create(string: "foobarbaz")
}
}
@inlinable
func create100Strings(str: String) {
var fb = FlatBufferBuilder(initialSize: 1<<20)
for _ in 0..<10_000 {
_ = fb.create(string: str)
}
}
@inlinable
func benchmarkFiveHundredAdds() {
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
for _ in 0..<500_000 {
let off = fb.create(string: "T")
let s = fb.startTable(with: 4)
fb.add(element: 3.2, def: 0, at: 2)
fb.add(element: 4.2, def: 0, at: 4)
fb.add(element: 5.2, def: 0, at: 6)
fb.add(offset: off, at: 8)
_ = fb.endTable(at: s)
}
}
@inlinable
func benchmarkThreeMillionStructs() {
let structCount = 3_000_000
let rawSize = ((16 * 5) * structCount) / 1024
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
var offsets: [Offset<UOffset>] = []
for _ in 0..<structCount {
fb.startVectorOfStructs(count: 5, size: 16, alignment: 8)
for _ in 0..<5 {
fb.createStructOf(size: 16, alignment: 8)
fb.reverseAdd(v: 2.4, postion: 0)
fb.reverseAdd(v: 2.4, postion: 8)
fb.endStruct()
}
let vector = fb.endVectorOfStructs(count: 5)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
offsets.append(Offset<UOffset>(offset: fb.endTable(at: start)))
}
let vector = fb.createVector(ofOffsets: offsets)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
let root = Offset<UOffset>(offset: fb.endTable(at: start))
fb.finish(offset: root)
}
func benchmark(numberOfRuns runs: Int) {
var benchmarks: [Benchmark] = []
let str = (0...99).map { _ -> String in "x" }.joined()
benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds))
benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings))
let hundredStr = run(name: "100 str", runs: runs) {
create100Strings(str: str)
}
benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs))
benchmarks.append(hundredStr)
print(createDocument(Benchmarks: benchmarks))
}
benchmark(numberOfRuns: 20)
| 29.72 | 88 | 0.659758 |
29cc674e0dfc8292fadb9ca93dc04ebd8e6c2651 | 1,326 | //
// ProfileViewController.swift
// Instagram
//
// Created by Joey Singer on 3/20/17.
// Copyright © 2017 Joey Singer. All rights reserved.
//
import UIKit
import Parse
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSignOut(_ sender: Any) {
PFUser.logOutInBackground { (error) in
print("Logged out")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nextView = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(nextView, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 26 | 126 | 0.647059 |
91d3d9b3cb321e9bd93de9ff259c82e18c2de993 | 241 | // 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 e<l{
{(())->a in
protocol f{
class func c
}
class e:f{
class func c | 21.909091 | 87 | 0.73029 |
390b52eef52168f9650bb1e984d555a8e089367c | 112 | import XCTest
import UtilsTests
var tests = [XCTestCaseEntry]()
tests += UtilsTests.allTests()
XCTMain(tests)
| 14 | 31 | 0.767857 |
e06c0e7f8ef617cdbec241a5701d000072c58476 | 254 | //
// Todo.swift
// CodyFireExample
//
// Created by Mihael Isaev on 27/10/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
class Todo: Codable {
var id, userId: Int
var title: String
var completed: Bool
}
| 15.875 | 52 | 0.665354 |
fc61292bc546e30d75f5497d9c596ec9819762a3 | 756 | //
// ContentView.swift
// SampleApp
//
// Created by Tran Thien Khiem on 2019-10-09.
// Copyright © 2019 Tran Thien Khiem. All rights reserved.
//
import SwiftUI
import AppKit
struct ContentView: View {
/// The Content View
var body: some View {
SuperApp(applications: [
Application(
icon: Image(systemName: "creditcard"), title: "Payment"
)
{ _ in
AnyView(
Text("Sample Application")
.navigationBarTitle("Sample Application", displayMode: .inline)
)
}
])
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 21 | 87 | 0.541005 |
50f7a048d1bfa970827d113b34256770163fc930 | 1,445 | //
// prework_michaelUITests.swift
// prework-michaelUITests
//
// Created by user212297 on 1/5/22.
//
import XCTest
class prework_michaelUITests: XCTestCase {
override func setUpWithError() throws {
// 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
// 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 tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.604651 | 182 | 0.660208 |
fc64156ff0e20e19db676ad798dfabe0646009b4 | 3,661 | //
// FlightStruct.swift
// TripKey
//
// Created by Peter on 10/02/19.
// Copyright © 2019 Fontaine. All rights reserved.
//
import Foundation
public struct FlightStruct: CustomStringConvertible {
let sharedFrom:String
let lastUpdated:String
let flightNumber:String
let publishedDepartureUtc:String
let airlineCode:String
let arrivalAirportCode:String
let arrivalCity:String
let arrivalDate:String
let arrivalGate:String
let arrivalLat:Double
let arrivalLon:Double
let arrivalTerminal:String
let arrivalUtcOffset:Double
let baggageClaim:String
let departureAirport:String
let departureCity:String
let departureGate:String
let departureLat:Double
let departureLon:Double
let departureTerminal:String
let departureDate:String
let departureUtcOffset:Double
let flightDuration:String
let airplaneType:String
let flightId:String
let flightStatus:String
let identifier:String
let phoneNumber:String
let primaryCarrier:String
let publishedArrival:String
let publishedDeparture:String
let urlArrivalDate:String
init(dictionary: [String: Any]) {
self.flightNumber = dictionary["flightNumber"] as? String ?? ""
self.publishedDepartureUtc = dictionary["publishedDepartureUtc"] as? String ?? ""
self.airlineCode = dictionary["airlineCode"] as? String ?? ""
self.arrivalAirportCode = dictionary["arrivalAirportCode"] as? String ?? ""
self.arrivalCity = dictionary["arrivalCity"] as? String ?? ""
self.arrivalDate = dictionary["arrivalDate"] as? String ?? ""
self.arrivalGate = dictionary["arrivalGate"] as? String ?? ""
self.arrivalLat = dictionary["arrivalLat"] as? Double ?? 0
self.arrivalLon = dictionary["arrivalLon"] as? Double ?? 0
self.arrivalTerminal = dictionary["arrivalTerminal"] as? String ?? ""
self.arrivalUtcOffset = dictionary["arrivalUtcOffset"] as? Double ?? 0
self.baggageClaim = dictionary["baggageClaim"] as? String ?? ""
self.departureAirport = dictionary["departureAirport"] as? String ?? ""
self.departureCity = dictionary["departureCity"] as? String ?? ""
self.departureGate = dictionary["departureGate"] as? String ?? ""
self.departureLat = dictionary["departureLat"] as? Double ?? 0
self.departureLon = dictionary["departureLon"] as? Double ?? 0
self.departureTerminal = dictionary["departureTerminal"] as? String ?? ""
self.departureDate = dictionary["departureTime"] as? String ?? ""
self.departureUtcOffset = dictionary["departureUtcOffset"] as? Double ?? 0
self.flightDuration = dictionary["flightDuration"] as? String ?? ""
self.airplaneType = dictionary["flightEquipment"] as? String ?? ""
self.flightId = dictionary["flightId"] as? String ?? ""
self.flightStatus = dictionary["flightStatus"] as? String ?? ""
self.identifier = dictionary["identifier"] as? String ?? ""
self.phoneNumber = dictionary["phoneNumber"] as? String ?? ""
self.primaryCarrier = dictionary["primaryCarrier"] as? String ?? ""
self.publishedArrival = dictionary["publishedArrival"] as? String ?? ""
self.publishedDeparture = dictionary["publishedDeparture"] as? String ?? ""
self.urlArrivalDate = dictionary["urlArrivalDate"] as? String ?? ""
self.lastUpdated = dictionary["lastUpdated"] as? String ?? ""
self.sharedFrom = dictionary["sharedFrom"] as? String ?? ""
}
public var description: String {
return ""
}
}
| 41.134831 | 89 | 0.674406 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.