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
|
---|---|---|---|---|---|
9057dcacb9a2a84906292f5451571811cc402461 | 2,521 | //
// AccountDetailsIdentityDataCellView.swift
// ConcordiumWallet
//
// Created by Concordium on 4/5/20.
// Copyright © 2020 concordium. All rights reserved.
//
import Foundation
import UIKit
protocol AccountTransactionsDataCellViewDelegate: AnyObject {
func lockButtonPressed(from cell: AccountTransactionsDataCellView)
}
class AccountTransactionsDataCellView: UITableViewCell {
@IBOutlet weak var recipientName: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var memoLabel: UILabel!
@IBOutlet weak var transactionIconStatusView: UIImageView!
@IBOutlet weak var costLabel: UILabel!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var statusIconImageView: UIImageView!
@IBOutlet weak var amountCostStackView: UIStackView!
@IBOutlet weak var lockButton: UIButton!
weak var delegate: AccountTransactionsDataCellViewDelegate?
var transactionHash: String?
func updateUIBasedOn(_ viewModel: TransactionCellViewModel, useFullDate: Bool = false) {
recipientName?.text = viewModel.title
if useFullDate {
timeLabel.text = viewModel.fullDate
} else {
timeLabel?.text = viewModel.date
}
totalLabel?.text = viewModel.total
amountLabel.text = viewModel.amount
recipientName.textColor = viewModel.titleColor
statusIconImageView.image = viewModel.statusIcon
totalLabel.textColor = viewModel.totalColor
amountLabel.textColor = viewModel.amountColor
costLabel.textColor = viewModel.costColor
amountLabel.isHidden = !viewModel.showCostAndAmount
costLabel.isHidden = !viewModel.showCostAndAmount
amountCostStackView.isHidden = amountLabel.isHidden && costLabel.isHidden
transactionIconStatusView.isHidden = !viewModel.showErrorIcon
statusIconImageView.isHidden = !viewModel.showStatusIcon
costLabel.text = viewModel.cost
lockButton.isUserInteractionEnabled = viewModel.showLock
memoLabel.text = viewModel.memo
memoLabel.isHidden = viewModel.memo == nil
if viewModel.showLock {
lockButton.setImage(UIImage(named: "Icon_Shield"), for: .normal)
} else {
lockButton.setImage(nil, for: .normal)
}
layoutIfNeeded()
}
@IBAction func lockButtonPressed(_ sender: Any) {
self.delegate?.lockButtonPressed(from: self)
}
}
| 36.536232 | 92 | 0.704879 |
146b0ae774ab78acc1fb0c6c580ffade3c55748a | 765 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Blockchain-Server",
products: [
.library(name: "App", targets: ["App"]),
.executable(name: "Run", targets: ["Run"])
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
.package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")),
],
targets: [
.target(
name: "App",
dependencies: ["Vapor", "FluentProvider"],
exclude: ["Config", "Public", "Resources"]
),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App", "Testing"])
]
)
| 29.423077 | 101 | 0.555556 |
fc040e85cdfd558ee7e83456cba67ed7381165a4 | 2,163 | //
// AppDelegate.swift
// BEER
//
// Created by Zaw Zin Phyo on 11/17/18.
// Copyright © 2018 PADC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.021277 | 285 | 0.753583 |
d57cc1811fddf11250a4d436bf4a051727414cdb | 266 | //
// ViewController.swift
// CustomTabBar
//
// Created by Ridoan Wibisono on 26/07/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 13.3 | 52 | 0.699248 |
f8293a87188344f187ce72dd25d533800128f072 | 260 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{class A
struct d{enum S<T:T.h
| 28.888889 | 87 | 0.742308 |
28429663615346abb3b821c825e222a195d9d232 | 8,631 | //
// StrokeCollection.swift
// MyProduct
//
// Created by 王雪慧 on 2020/2/10.
// Copyright © 2020 王雪慧. All rights reserved.
//
import Foundation
import UIKit
class StrokeCollection {
var strokes: [Stroke] = []
var activeStroke: Stroke?
func takeActiveStroke() {
if let stroke = activeStroke {
strokes.append(stroke)
activeStroke = nil
}
}
}
enum StrokePhase {
case began
case changed
case ended
case cancelled
}
struct StrokeSample {
// Always.
let timestamp: TimeInterval
let location: CGPoint
// 3D Touch or Pencil.
var force: CGFloat?
// Pencil only.
var estimatedProperties: UITouch.Properties = []
var estimatedPropertiesExpectingUpdates: UITouch.Properties = []
var altitude: CGFloat?
var azimuth: CGFloat?
var azimuthUnitVector: CGVector {
var vector = CGVector(dx: 1.0, dy: 0.0)
if let azimuth = self.azimuth {
vector = vector.applying(CGAffineTransform(rotationAngle: azimuth))
}
return vector
}
init(timestamp: TimeInterval,
location: CGPoint,
coalesced: Bool,
predicted: Bool = false,
force: CGFloat? = nil,
azimuth: CGFloat? = nil,
altitude: CGFloat? = nil,
estimatedProperties: UITouch.Properties = [],
estimatedPropertiesExpectingUpdates: UITouch.Properties = []) {
self.timestamp = timestamp
self.location = location
self.force = force
self.coalesced = coalesced
self.predicted = predicted
self.altitude = altitude
self.azimuth = azimuth
}
/// Convenience accessor returns a non-optional (Default: 1.0)
var forceWithDefault: CGFloat {
return force ?? 1.0
}
/// Returns the force perpendicular to the screen. The regular pencil force is along the pencil axis.
var perpendicularForce: CGFloat {
let force = forceWithDefault
if let altitude = altitude {
let result = force / CGFloat(sin(Double(altitude)))
return result
} else {
return force
}
}
// Values for debug display.
let coalesced: Bool
let predicted: Bool
}
enum StrokeState {
case active
case done
case cancelled
}
class Stroke {
static let calligraphyFallbackAzimuthUnitVector = CGVector(dx: 1.0, dy: 1.0).normalized!
var samples: [StrokeSample] = []
var predictedSamples: [StrokeSample] = []
var previousPredictedSamples: [StrokeSample]?
var state: StrokeState = .active
var sampleIndicesExpectingUpdates = Set<Int>()
var expectsAltitudeAzimuthBackfill = false
var hasUpdatesFromStartTo: Int?
var hasUpdatesAtEndFrom: Int?
var receivedAllNeededUpdatesBlock: (() -> Void)?
func add(sample: StrokeSample) -> Int {
let resultIndex = samples.count
if hasUpdatesAtEndFrom == nil {
hasUpdatesAtEndFrom = resultIndex
}
samples.append(sample)
if previousPredictedSamples == nil {
previousPredictedSamples = predictedSamples
}
if sample.estimatedPropertiesExpectingUpdates != [] {
sampleIndicesExpectingUpdates.insert(resultIndex)
}
predictedSamples.removeAll()
return resultIndex
}
func update(sample: StrokeSample, at index: Int) {
if index == 0 {
hasUpdatesFromStartTo = 0
} else if hasUpdatesFromStartTo != nil && index == hasUpdatesFromStartTo! + 1 {
hasUpdatesFromStartTo = index
} else if hasUpdatesAtEndFrom == nil || hasUpdatesAtEndFrom! > index {
hasUpdatesAtEndFrom = index
}
samples[index] = sample
sampleIndicesExpectingUpdates.remove(index)
if sampleIndicesExpectingUpdates.isEmpty {
if let block = receivedAllNeededUpdatesBlock {
receivedAllNeededUpdatesBlock = nil
block()
}
}
}
func addPredicted(sample: StrokeSample) {
predictedSamples.append(sample)
}
func clearUpdateInfo() {
hasUpdatesFromStartTo = nil
hasUpdatesAtEndFrom = nil
previousPredictedSamples = nil
}
func updatedRanges() -> [CountableClosedRange<Int>] {
var ranges = [CountableClosedRange<Int>]()
if let hasUpdatesFromStartTo = self.hasUpdatesFromStartTo,
let hasUpdatesAtEndFrom = self.hasUpdatesAtEndFrom {
ranges = [0...(hasUpdatesFromStartTo), hasUpdatesAtEndFrom...(samples.count - 1)]
} else if let hasUpdatesFromStartTo = self.hasUpdatesFromStartTo {
ranges = [0...(hasUpdatesFromStartTo)]
} else if let hasUpdatesAtEndFrom = self.hasUpdatesAtEndFrom {
ranges = [(hasUpdatesAtEndFrom)...(samples.count - 1)]
}
return ranges
}
}
extension Stroke: Sequence {
func makeIterator() -> StrokeSegmentIterator {
return StrokeSegmentIterator(stroke: self)
}
}
private func interpolatedNormalUnitVector(between vector1: CGVector, and vector2: CGVector) -> CGVector {
if let result = (vector1.normal + vector2.normal)?.normalized {
return result
} else {
// This means they resulted in a 0,0 vector,
// in this case one of the incoming vectors is a good result.
if let result = vector1.normalized {
return result
} else if let result = vector2.normalized {
return result
} else {
// This case should not happen.
return CGVector(dx: 1.0, dy: 0.0)
}
}
}
class StrokeSegment {
var sampleBefore: StrokeSample?
var fromSample: StrokeSample!
var toSample: StrokeSample!
var sampleAfter: StrokeSample?
var fromSampleIndex: Int
var segmentUnitNormal: CGVector {
return segmentStrokeVector.normal!.normalized!
}
var fromSampleUnitNormal: CGVector {
return interpolatedNormalUnitVector(between: previousSegmentStrokeVector, and: segmentStrokeVector)
}
var toSampleUnitNormal: CGVector {
return interpolatedNormalUnitVector(between: segmentStrokeVector, and: nextSegmentStrokeVector)
}
var previousSegmentStrokeVector: CGVector {
if let sampleBefore = self.sampleBefore {
return fromSample.location - sampleBefore.location
} else {
return segmentStrokeVector
}
}
var segmentStrokeVector: CGVector {
return toSample.location - fromSample.location
}
var nextSegmentStrokeVector: CGVector {
if let sampleAfter = self.sampleAfter {
return sampleAfter.location - toSample.location
} else {
return segmentStrokeVector
}
}
init(sample: StrokeSample) {
self.sampleAfter = sample
self.fromSampleIndex = -2
}
@discardableResult
func advanceWithSample(incomingSample: StrokeSample?) -> Bool {
if let sampleAfter = self.sampleAfter {
self.sampleBefore = fromSample
self.fromSample = toSample
self.toSample = sampleAfter
self.sampleAfter = incomingSample
self.fromSampleIndex += 1
return true
}
return false
}
}
class StrokeSegmentIterator: IteratorProtocol {
private let stroke: Stroke
private var nextIndex: Int
private let sampleCount: Int
private let predictedSampleCount: Int
private var segment: StrokeSegment!
init(stroke: Stroke) {
self.stroke = stroke
nextIndex = 1
sampleCount = stroke.samples.count
predictedSampleCount = stroke.predictedSamples.count
if (predictedSampleCount + sampleCount) > 1 {
segment = StrokeSegment(sample: sampleAt(0)!)
segment.advanceWithSample(incomingSample: sampleAt(1))
}
}
func sampleAt(_ index: Int) -> StrokeSample? {
if index < sampleCount {
return stroke.samples[index]
}
let predictedIndex = index - sampleCount
if predictedIndex < predictedSampleCount {
return stroke.predictedSamples[predictedIndex]
} else {
return nil
}
}
func next() -> StrokeSegment? {
nextIndex += 1
if let segment = self.segment {
if segment.advanceWithSample(incomingSample: sampleAt(nextIndex)) {
return segment
}
}
return nil
}
}
| 28.963087 | 107 | 0.623566 |
d70453a6e81933932841d48aaaa0ef5943427cbf | 979 | //
// UIAlertController+Snippet.swift
// Snippet
//
// Created by sunny on 2017/11/12.
// Copyright © 2017年 CepheusSun. All rights reserved.
//
import UIKit
typealias AlertActionHandler = ((UIAlertAction) -> Void)
extension UIAlertControllerStyle {
func controller(title: String?,
message: String?,
actions: [UIAlertAction]
) -> UIAlertController {
let _controller = UIAlertController(
title: title,
message: message,
preferredStyle: self
)
actions.forEach{ _controller.addAction($0) }
return _controller
}
}
extension String {
func alertAction(
style: UIAlertActionStyle = .default,
handler: AlertActionHandler? = nil
) -> UIAlertAction {
return UIAlertAction(
title: self,
style: style,
handler: handler
)
}
}
| 22.767442 | 56 | 0.551583 |
286ceeadd4406c60c20ab5e0f1512592443b171f | 1,548 | import AAA
import ZZZ
import BBB
import CCC
public class TestDifferent3 {
class VCCC: UIViewController {
override func viewWillAppear(_ animated: Bool) {
self.method()
}
}
enum Numbers: String {
case one = "one"
case two = "two"
}
func foo() -> Void {}
func abc()-> Int {}
var myVar: Int? = nil
func aaaaa() {
let image = UIImage(named: "foo")
foo = foo - 1
let foo = 1+2
if _ = foo() { let _ = bar()
}else if true {}
var myVar: Int? = nil; myVar ?? nil
myList.sorted().first
}
func abc(){
}
func <|(lhs: Int, rhs: Int) -> Int {}
}
extension Person {
override var age: Int { return 42 }
}
switch foo {
case (let x, let y): break
}
public class Foo {
@IBOutlet var label: UILabel?
}
fileprivate class MyClass {
fileprivate(set) var myInt: Int = 4
}
private class VDDC: UIViewController {
override func loadView() {
super.loadView()
}
}
public protocol Foo {
var bar: String { set get }
}
private class TotoTests {
override func spec() {
describe("foo") {
let foo = Foo()
}
}
}
private class TotoTests: QuickSpec {
override func spec() {
describe("foo") {
let foo = Foo()
}
}
}
private class TotoTests: QuickSpec {
override func spec() {
fdescribe("foo") { }
}
}
public class TotoTests: QuickSpec {
override func spec() {
xdescribe("foo") { }
}
}
| 16.468085 | 56 | 0.537468 |
0e2529568dd097d55b34d94dfc1bfe637693aba2 | 1,403 | /// Stores information about `Migration`s that have been run.
public final class MigrationLog: Model {
public static let schema = "_fluent_migrations"
public static var migration: Migration {
return MigrationLogMigration()
}
@ID(key: .id)
public var id: UUID?
@Field(key: "name")
public var name: String
@Field(key: "batch")
public var batch: Int
@Timestamp(key: "created_at", on: .create)
public var createdAt: Date?
@Timestamp(key: "updated_at", on: .update)
public var updatedAt: Date?
public init() { }
public init(id: IDValue? = nil, name: String, batch: Int) {
self.id = id
self.name = name
self.batch = batch
self.createdAt = nil
self.updatedAt = nil
}
}
private struct MigrationLogMigration: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("_fluent_migrations")
.field(.id, .uuid, .identifier(auto: false))
.field("name", .string, .required)
.field("batch", .int, .required)
.field("created_at", .datetime)
.field("updated_at", .datetime)
.unique(on: "name")
.ignoreExisting()
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("_fluent_migrations").delete()
}
}
| 26.980769 | 66 | 0.600143 |
e00ec91512c596e3152acb6d3cb75f5d4085c8bd | 1,636 | //
// ArCameraManager+ext.swift
// YaPlace
//
// Created by Andrei Okoneshnikov on 24.07.2020.
// Copyright © 2020 SKZ. All rights reserved.
//
import Foundation
import UIKit
extension ArCameraManager {
func clearArkitSceneWithContentStickers(clearAnchors: Bool = true) {
if let childs = arKitSceneView?.scene.rootNode.childNodes {
for child in childs {
if let node = child as? ARFVideoNode {
node.cleanup()
node.removeFromParentNode()
}
}
}
self.clearArkitScene(clearAnchors: clearAnchors)
}
func clearArNodes(clearAnchors: Bool = true, clearContent: Bool = true) {
if let childs = arKitSceneView?.scene.rootNode.childNodes {
for child in childs {
if child is ARFVideoNode, !clearContent {
continue
}
if child is ARFNode {
child.removeFromParentNode()
}
}
}
// remove anchors
if clearAnchors {
for anchor in arKitSceneView?.session.currentFrame?.anchors ?? [] {
if !(anchor is ArCameraPoseAnchor) {
arKitSceneView?.session.remove(anchor: anchor)
}
}
}
self.clearDebugInfo()
}
func arSnapshot() -> UIImage? {
guard let arkitView = arKitSceneView else {
return nil
}
let fixImage = arkitView.snapshot()
return fixImage
}
}
| 26.819672 | 79 | 0.520171 |
ab0b43d43b0af5a3355406bf3a4f70ec55558a8c | 4,290 | //
// XCTUIAyeAyeUITests.swift
// XCTUIAyeAyeUITests
//
// Created by My3 Shenoy on 11/16/21.
//
import XCTest
class XCTUIAyeAyeUITests: XCTestCase {
let app = XCUIApplication()
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.
app.launch()
}
// Check if static text exists
func testWelcome() throws {
let welcome = app.staticTexts["Welcome!"]
XCTAssert(welcome.exists)
}
func testWelcomeLabel() throws {
let welcome = app.staticTexts.element
XCTAssertEqual(welcome.label, "Welcome!")
}
// The UI Element's text becomes it's default accessibility identfier
// Test breaks if text changes because accessibility ID is now different
func testLoginButtonWithNoAccessibilityId() throws {
let login = app.buttons["Login"]
XCTAssert(login.exists)
}
func testLoginButtonWithAccessibilityId() throws {
let login = app.buttons["loginButton"]
XCTAssert(login.exists)
}
func testLoginAppearance() throws {
// Load the LoginView
app.buttons["loginButton"].tap()
let loginNavBarTitle = app.staticTexts["Login"]
XCTAssert(loginNavBarTitle.waitForExistence(timeout: 0.5))
}
func testLoginForm() throws {
app.buttons["loginButton"].tap()
let userName = app.textFields["Username"]
XCTAssert(userName.exists)
let password = app.secureTextFields["Password"]
XCTAssert(password.exists)
let loginButton = app.buttons["loginNow"]
XCTAssert(loginButton.exists)
XCTAssertEqual(loginButton.label, "Login")
let dismiss = app.buttons["Dismiss"]
XCTAssert(dismiss.exists)
}
func testNavBarAppearance() {
app.buttons["loginButton"].tap()
let navBar = app.navigationBars.element
let navBarTitle = app.navigationBars.staticTexts["Login"]
XCTAssert(navBar.exists)
XCTAssert(navBarTitle.waitForExistence(timeout: 0.5))
}
// Check if dismiss button is not present after x seconds
func testLoginDismiss() throws {
app.buttons["Login"].tap()
let dismissButton = app.buttons["Dismiss"]
dismissButton.tap()
XCTAssertFalse(dismissButton.waitForExistence(timeout: 0.5))
}
// TypeText method
func testUserNameFieldInput() {
app.buttons["Login"].tap()
app.textFields.element.tap()
app.typeText("test")
XCTAssertNotEqual(app.textFields.element.value as! String, "")
}
// Use individual key method
func testPasswordInput() {
app.buttons["Login"].tap()
app.secureTextFields.element.tap()
app.keys["p"].tap()
app.keys["a"].tap()
app.keys["s"].tap()
app.keys["s"].tap()
app.keyboards.buttons["Return"].tap()
XCTAssertNotEqual(app.secureTextFields.element.value as! String, "")
}
// Login Action
func testLoginAction() {
app.buttons["Login"].tap()
app.textFields.element.tap()
app.textFields.element.typeText("test")
app.secureTextFields.element.tap()
app.secureTextFields.element.typeText("pass")
app.keyboards.buttons["Return"].tap()
let loginButton = app.buttons["loginNow"]
loginButton.tap()
XCTAssertFalse(loginButton.waitForExistence(timeout: 0.5))
}
func testAlertForLoginFailure() {
app.buttons["Login"].tap()
app.buttons["loginNow"].tap()
XCTAssertTrue(app.alerts.element.waitForExistence(timeout: 0.5))
app.alerts.element.buttons["OK"].tap()
XCTAssertFalse(app.alerts.element.waitForExistence(timeout: 0.5))
}
}
| 30.863309 | 182 | 0.620746 |
bf00b75aeeaae21baca42fe317317a2f7f14501b | 7,885 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import RealmSwift
import XCTest
class ObjectiveCSupportTests: TestCase {
#if swift(>=3.0)
func testSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
return
}
let results = realm.objects(SwiftObject.self)
let rlmResults = ObjectiveCSupport.convert(object: results)
XCTAssert(rlmResults.isKind(of: RLMResults.self))
XCTAssertEqual(rlmResults.count, 1)
XCTAssertEqual(unsafeBitCast(rlmResults.firstObject(), to: SwiftObject.self).intCol, 123)
let list = List<SwiftObject>()
list.append(SwiftObject())
let rlmArray = ObjectiveCSupport.convert(object: list)
XCTAssert(rlmArray.isKind(of: RLMArray.self))
XCTAssertEqual(unsafeBitCast(rlmArray.firstObject(), to: SwiftObject.self).floatCol, 1.23)
XCTAssertEqual(rlmArray.count, 1)
let rlmRealm = ObjectiveCSupport.convert(object: realm)
XCTAssert(rlmRealm.isKind(of: RLMRealm.self))
XCTAssertEqual(rlmRealm.allObjects("SwiftObject").count, 1)
let sortDescriptor: RealmSwift.SortDescriptor = "property"
XCTAssertEqual(sortDescriptor.property,
ObjectiveCSupport.convert(object: sortDescriptor).property,
"SortDescriptor.property must be equal to RLMSortDescriptor.property")
XCTAssertEqual(sortDescriptor.ascending,
ObjectiveCSupport.convert(object: sortDescriptor).ascending,
"SortDescriptor.ascending must be equal to RLMSortDescriptor.ascending")
}
func testConfigurationSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
return
}
XCTAssertEqual(realm.configuration.fileURL,
ObjectiveCSupport.convert(object: realm.configuration).fileURL,
"Configuration.fileURL must be equal to RLMConfiguration.fileURL")
XCTAssertEqual(realm.configuration.inMemoryIdentifier,
ObjectiveCSupport.convert(object: realm.configuration).inMemoryIdentifier,
"Configuration.inMemoryIdentifier must be equal to RLMConfiguration.inMemoryIdentifier")
XCTAssertEqual(realm.configuration.syncConfiguration?.realmURL,
ObjectiveCSupport.convert(object: realm.configuration).syncConfiguration?.realmURL,
"Configuration.syncConfiguration must be equal to RLMConfiguration.syncConfiguration")
XCTAssertEqual(realm.configuration.encryptionKey,
ObjectiveCSupport.convert(object: realm.configuration).encryptionKey,
"Configuration.encryptionKey must be equal to RLMConfiguration.encryptionKey")
XCTAssertEqual(realm.configuration.readOnly,
ObjectiveCSupport.convert(object: realm.configuration).readOnly,
"Configuration.readOnly must be equal to RLMConfiguration.readOnly")
XCTAssertEqual(realm.configuration.schemaVersion,
ObjectiveCSupport.convert(object: realm.configuration).schemaVersion,
"Configuration.schemaVersion must be equal to RLMConfiguration.schemaVersion")
XCTAssertEqual(realm.configuration.deleteRealmIfMigrationNeeded,
ObjectiveCSupport.convert(object: realm.configuration).deleteRealmIfMigrationNeeded,
"Configuration.deleteRealmIfMigrationNeeded must be equal to RLMConfiguration.deleteRealmIfMigrationNeeded")
}
#else
func testSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
return
}
let results = realm.objects(SwiftObject.self)
let rlmResults = ObjectiveCSupport.convert(results)
XCTAssert(rlmResults.isKindOfClass(RLMResults.self))
XCTAssertEqual(rlmResults.count, 1)
XCTAssertEqual(unsafeBitCast(rlmResults.firstObject(), SwiftObject.self).intCol, 123)
let list = List<SwiftObject>()
list.append(SwiftObject())
let rlmArray = ObjectiveCSupport.convert(list)
XCTAssert(rlmArray.isKindOfClass(RLMArray.self))
XCTAssertEqual(unsafeBitCast(rlmArray.firstObject(), SwiftObject.self).floatCol, 1.23)
XCTAssertEqual(rlmArray.count, 1)
let rlmRealm = ObjectiveCSupport.convert(realm)
XCTAssert(rlmRealm.isKindOfClass(RLMRealm.self))
XCTAssertEqual(rlmRealm.allObjects("SwiftObject").count, 1)
let sortDescriptor: RealmSwift.SortDescriptor = "property"
XCTAssertEqual(sortDescriptor.property,
ObjectiveCSupport.convert(sortDescriptor).property,
"SortDescriptor.property must be equal to RLMSortDescriptor.property")
XCTAssertEqual(sortDescriptor.ascending,
ObjectiveCSupport.convert(sortDescriptor).ascending,
"SortDescriptor.ascending must be equal to RLMSortDescriptor.ascending")
}
func testConfigurationSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
return
}
XCTAssertEqual(realm.configuration.fileURL,
ObjectiveCSupport.convert(realm.configuration).fileURL,
"Configuration.fileURL must be equal to RLMConfiguration.fileURL")
XCTAssertEqual(realm.configuration.inMemoryIdentifier,
ObjectiveCSupport.convert(realm.configuration).inMemoryIdentifier,
"Configuration.inMemoryIdentifier must be equal to RLMConfiguration.inMemoryIdentifier")
XCTAssertEqual(realm.configuration.syncConfiguration?.realmURL,
ObjectiveCSupport.convert(realm.configuration).syncConfiguration?.realmURL,
"Configuration.syncConfiguration must be equal to RLMConfiguration.syncConfiguration")
XCTAssertEqual(realm.configuration.encryptionKey,
ObjectiveCSupport.convert(realm.configuration).encryptionKey,
"Configuration.encryptionKey must be equal to RLMConfiguration.encryptionKey")
XCTAssertEqual(realm.configuration.readOnly,
ObjectiveCSupport.convert(realm.configuration).readOnly,
"Configuration.readOnly must be equal to RLMConfiguration.readOnly")
XCTAssertEqual(realm.configuration.schemaVersion,
ObjectiveCSupport.convert(realm.configuration).schemaVersion,
"Configuration.schemaVersion must be equal to RLMConfiguration.schemaVersion")
XCTAssertEqual(realm.configuration.deleteRealmIfMigrationNeeded,
ObjectiveCSupport.convert(realm.configuration).deleteRealmIfMigrationNeeded,
"Configuration.deleteRealmIfMigrationNeeded must be equal to RLMConfiguration.deleteRealmIfMigrationNeeded")
}
#endif
}
| 44.297753 | 131 | 0.664299 |
6991ef53ccccfd2c7f335a7b909bcd607383aee6 | 2,211 | //
// HeadphoneDispatcher.swift
// Triggertrap
//
// Created by Valentin Kalchev on 02/07/2015.
// Copyright (c) 2015 Triggertrap Limited. All rights reserved.
//
open class HeadphoneDispatcher: NSObject, Dispatcher {
public static let sharedInstance = HeadphoneDispatcher()
fileprivate var dispatchable: Dispatchable!
fileprivate override init() {
super.init()
}
open func dispatch(_ dispatchable: Dispatchable) {
self.dispatchable = dispatchable
OutputDispatcher.sharedInstance.audioPlayer?.start()
switch dispatchable.type {
case .Pulse:
// Audio buffer is only precise for less than 15 seconds duration (less than 50ms discrepancy). Otherwise use the precise timer to get accurate duration.
if dispatchable.time.durationInMilliseconds > Time(duration: 15, unit: .seconds).durationInMilliseconds {
OutputDispatcher.sharedInstance.audioPlayer?.delegate = nil
PreciseTimer.scheduleAction(#selector(HeadphoneDispatcher.didDispatchAudio), target: self, inTimeInterval: dispatchable.time.durationInSeconds)
OutputDispatcher.sharedInstance.audioPlayer?.playAudio(forDuration: UInt64.max)
} else {
OutputDispatcher.sharedInstance.audioPlayer?.delegate = self
OutputDispatcher.sharedInstance.audioPlayer?.playAudio(forDuration: UInt64(dispatchable.time.durationInMilliseconds))
}
case .Delay:
OutputDispatcher.sharedInstance.audioPlayer?.delegate = nil
PreciseTimer.scheduleAction(#selector(HeadphoneDispatcher.didDispatch), target: self, inTimeInterval: dispatchable.time.durationInSeconds)
}
}
@objc func didDispatchAudio() {
OutputDispatcher.sharedInstance.audioPlayer?.stop()
self.didDispatch()
}
@objc func didDispatch() {
if SequenceManager.sharedInstance.isCurrentlyTriggering {
self.dispatchable.didUnwrap()
}
}
}
extension HeadphoneDispatcher: AudioPlayerDelegate {
public func audioPlayerlDidFinishPlayingAudio() {
self.didDispatch()
}
}
| 38.12069 | 165 | 0.68521 |
22693e27299701c9d22697749cb83482908cba07 | 913 | import Cocoa
import Carbon
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow?
@IBOutlet var parentView: NSView?
@IBOutlet var menu: NSMenu?
var statusItem: NSStatusItem?
@objc let keyHandler = KeyHandler()
override init() {
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
//WM2Helper.requestAccessibility()
WM2Helper.setupWindow(window)
keyHandler.setWindow(window!)
keyHandler.setupView(parentView!)
statusItem = NSStatusBar.system.statusItem(withLength: -1)
statusItem!.menu = menu
statusItem!.image = Bundle.main.image(forResource: "icon")
statusItem!.highlightMode = true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 26.085714 | 71 | 0.661555 |
bb72dd3b2ceab457d3f09a5198796dbfc861c5db | 356 | //
// Channel.swift
// Twurl-iOS
//
// Created by James Rhodes on 6/21/15.
// Copyright (c) 2015 James Rhodes. All rights reserved.
//
import Foundation
import CoreData
class Channel: NSManagedObject {
@NSManaged var id: NSNumber
@NSManaged var name: String
@NSManaged var category: Category
@NSManaged var influencer: Influencer
}
| 17.8 | 57 | 0.702247 |
e9a03f1e21353fb41215db8ef45d2b6a9738318f | 3,060 | //
// BdCoreDataImg.swift
// Calculator Notes
//
// Created by Joao Flores on 11/04/20.
// Copyright © 2020 MakeSchool. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class ImageController {
static let shared = ImageController()
let fileManager = FileManager.default
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
func saveImage(image: UIImage) -> String? {
let date = String( Date.timeIntervalSinceReferenceDate )
let imageName = date.replacingOccurrences(of: ".", with: "-") + ".png"
if let imageData = UIImagePNGRepresentation(image) {
do {
let filePath = documentsPath.appendingPathComponent(imageName)
try imageData.write(to: filePath)
print("\(imageName) was saved.")
return imageName
} catch let error as NSError {
print("\(imageName) could not be saved: \(error)")
return nil
}
} else {
print("Could not convert UIImage to png data.")
return nil
}
}
func saveVideo(image: NSData) -> String? {
let date = String( Date.timeIntervalSinceReferenceDate )
let imageName = date.replacingOccurrences(of: ".", with: "-") + ".mp4"
let imageData = image
do {
let filePath = documentsPath.appendingPathComponent(imageName)
try imageData.write(to: filePath)
print("\(imageName) was saved.")
return imageName
} catch let error as NSError {
print("\(imageName) could not be saved: \(error)")
return nil
}
}
func fetchImage(imageName: String) -> UIImage? {
let imagePath = documentsPath.appendingPathComponent(imageName).path
guard fileManager.fileExists(atPath: imagePath) else {
print("Image does not exist at path: \(imagePath)")
return nil
}
if let imageData = UIImage(contentsOfFile: imagePath) {
return imageData
} else {
print("UIImage could not be created.")
return nil
}
}
func deleteImage(imageName: String) {
let imagePath = documentsPath.appendingPathComponent(imageName)
guard fileManager.fileExists(atPath: imagePath.path) else {
print("Image does not exist at path: \(imagePath)")
return
}
do {
try fileManager.removeItem(at: imagePath)
print("\(imageName) was deleted.")
} catch let error as NSError {
print("Could not delete \(imageName): \(error)")
}
}
}
| 30 | 101 | 0.526144 |
ac4c1a8586a72b4aa54e857d67840cfd44771633 | 229 | //
// ExampleCollectionViewCell.swift
// VOKUtilities
//
// Copyright © 2019 Vokal. All rights reserved.
//
import UIKit
class ExampleCollectionViewCell: UICollectionViewCell {
// Empty cell used for testing purposes.
}
| 17.615385 | 55 | 0.737991 |
162e42c428f291cfbcc8e410cb25ba60906ccae9 | 1,787 | //
// SupportingViews.swift
// FoodTracker
//
// Copyright © 2020 UWAppDev. All rights reserved.
//
import SwiftUI
struct RatingStars: View {
@Binding var rating: Int
var body: some View {
HStack(alignment: .center, spacing: 0.5) {
Button(action: {self.rating = (self.rating != 1) ? 1 : 0}) {
Image(systemName: ((1...5).contains(rating)) ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 35)
}
Button(action: {self.rating = (self.rating != 2) ? 2 : 0}) {
Image(systemName: ((2...5).contains(rating)) ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 35)
}
Button(action: {self.rating = (self.rating != 3) ? 3 : 0}) {
Image(systemName: ((3...5).contains(rating)) ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 35)
}
Button(action: {self.rating = (self.rating != 4) ? 4 : 0}) {
Image(systemName: ((4...5).contains(rating)) ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 35)
}
Button(action: {self.rating = (self.rating != 5) ? 5 : 0}) {
Image(systemName: (rating == 5) ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 35)
}
}
}
}
struct SupportingViews_Previews: PreviewProvider {
static var previews: some View {
RatingStars(rating: .constant(0))
}
}
| 33.716981 | 84 | 0.449916 |
fc569d0ed81bf5e8082bff245888b5ef20619e13 | 3,350 | import Foundation
import StorageP2P
/// The config options for fuzzing
public struct Config {
/// The randomness precision
static let randomPrecision = 1_000_000_000
/// The error probability
static let pError = 0.1
/// The retry interval in milliseconds
static let retryIntervalMS = 37
/// The amount of client threads to spawn
static let threadCount = 23
/// The fuzz iterations per thread until a validation is performed
static let fuzzIterations = 167
/// The amount of fuzzing rounds (i.e. the amount of `fuzzIterations * threadCount -> finish -> verify` rounds)
static let fuzzRounds = 4
}
// Implement a `random` function for bools
public extension Bool {
/// Creates a random boolean with a `probability` for `true` where `probability` ranges from `0` to `1`
static func random(probability: Double) -> Self {
let randomPrecision = 1_000_000_000
return Int.random(in: 0 ..< randomPrecision) < Int(probability * Double(randomPrecision))
}
}
/// Retries `f` until it succeeds
public func retry<R>(_ block: () throws -> R) -> R {
while true {
do {
return try block()
} catch {
usleep(UInt32(Config.retryIntervalMS) * 1000)
}
}
}
/// Asserts a condition
@inline(__always)
public func assert(_ block: @autoclosure () -> Bool, _ message: String..., file: StaticString = #file,
line: Int = #line) {
guard block() else {
let message = "\(message.joined()) @\(file):\(line)".data(using: .utf8)!
_ = message.withUnsafeBytes({ fwrite($0.baseAddress!, 1, $0.count, stdout) })
fflush(stdout)
abort()
}
}
/// Prints to `stdout` without newline and flushes afterwards
@inline(__always)
public func stdout(_ string: StaticString) {
fwrite(string.utf8Start, 1, string.utf8CodeUnitCount, stdout)
fflush(stdout)
}
/// Prints to `stdout` without newline and flushes afterwards
@inline(__always)
public func stdout(string: String) {
string.data(using: .utf8)!.withUnsafeBytes({
fwrite($0.baseAddress!, 1, $0.count, stdout)
fflush(stdout)
})
}
/// Performs the fuzzing
func fuzz() {
// Create connections and collect all IDs
let clients = (0 ..< Config.threadCount).map({ _ in Client() })
let ids = clients.map({ $0.id })
// Set peers
clients.forEach({ client in
ids.filter({ $0 != client.id })
.map({ ConnectionID(local: client.id, remote: $0) })
.forEach({ client.db.store(connection: $0, state: ConnectionStateObject()) })
})
// Start fuzzing
for i in 1 ... Config.fuzzRounds {
// Print the iteration information
stdout(string: "\(i) of \(Config.fuzzRounds): ")
// Start all fuzzing threads
let threads: [Thread<()>] = clients.map({ client in
defer { stdout("+") }
return Thread(run: { client.fuzz() })
})
threads.forEach({
$0.join()
stdout("-")
})
// Perform a final receive and ensure that the storage is empty
clients.forEach({
$0.receive()
stdout("*")
})
precondition(StorageImpl.isEmpty, "The storage is not empty")
stdout("\n")
}
}
// -- MARK: Main block
fuzz()
| 29.130435 | 115 | 0.60597 |
9c4e032092fe58b349386e4fdb2fbca88199e1f7 | 13,399 | //
// SavedPaymentMethodCollectionView.swift
// Stripe
//
// Created by Yuki Tokuhiro on 9/3/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Constants
/// Entire cell size
private let cellSize: CGSize = CGSize(width: 100, height: 88)
/// Size of the rounded rectangle that contains the PM logo
let roundedRectangleSize = CGSize(width: 100, height: 64)
private let paymentMethodLogoSize: CGSize = CGSize(width: 54, height: 40)
// MARK: - SavedPaymentMethodCollectionView
class SavedPaymentMethodCollectionView: UICollectionView {
init() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets(
top: 0, left: PaymentSheetUI.defaultPadding, bottom: 0,
right: PaymentSheetUI.defaultPadding)
layout.itemSize = cellSize
layout.minimumInteritemSpacing = 12
super.init(frame: .zero, collectionViewLayout: layout)
showsHorizontalScrollIndicator = false
backgroundColor = CompatibleColor.systemBackground
register(
PaymentOptionCell.self, forCellWithReuseIdentifier: PaymentOptionCell.reuseIdentifier)
}
var isRemovingPaymentMethods: Bool = false
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: 100)
}
}
// MARK: - Cells
protocol PaymentOptionCellDelegate: AnyObject {
func paymentOptionCellDidSelectRemove(
_ paymentOptionCell: SavedPaymentMethodCollectionView.PaymentOptionCell)
}
extension SavedPaymentMethodCollectionView {
/// A rounded, shadowed cell with an icon (e.g. Apple Pay, VISA, ➕) and some text at the bottom.
/// Has a green outline when selected
class PaymentOptionCell: UICollectionViewCell, EventHandler {
static let reuseIdentifier = "PaymentOptionCell"
lazy var label: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .footnote, weight: .medium)
label.textColor = CompatibleColor.label
return label
}()
let paymentMethodLogo: UIImageView = UIImageView()
let plus: CircleIconView = CircleIconView(icon: .plus)
let selectedIcon: CircleIconView = CircleIconView(icon: .checkmark)
lazy var shadowRoundedRectangle: ShadowedRoundedRectangle = {
let shadowRoundedRectangle = ShadowedRoundedRectangle()
shadowRoundedRectangle.layoutMargins = UIEdgeInsets(
top: 15, left: 24, bottom: 15, right: 24)
return shadowRoundedRectangle
}()
let deleteButton = CircularButton(style: .remove)
fileprivate var viewModel: SavedPaymentOptionsViewController.Selection? = nil
var isRemovingPaymentMethods: Bool = false {
didSet {
update()
}
}
weak var delegate: PaymentOptionCellDelegate? = nil
// MARK: - UICollectionViewCell
override init(frame: CGRect) {
super.init(frame: frame)
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = PaymentSheetUI.defaultShadowOpacity
layer.shadowRadius = PaymentSheetUI.defaultShadowRadius
layer.shadowOffset = CGSize(width: 0, height: 1)
[paymentMethodLogo, plus, selectedIcon].forEach {
shadowRoundedRectangle.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
isAccessibilityElement = true
paymentMethodLogo.contentMode = .scaleAspectFit
deleteButton.addTarget(self, action: #selector(didSelectDelete), for: .touchUpInside)
let views = [
label, shadowRoundedRectangle, paymentMethodLogo, plus, selectedIcon, deleteButton,
]
views.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview($0)
}
NSLayoutConstraint.activate([
shadowRoundedRectangle.topAnchor.constraint(equalTo: contentView.topAnchor),
shadowRoundedRectangle.leftAnchor.constraint(equalTo: contentView.leftAnchor),
shadowRoundedRectangle.rightAnchor.constraint(equalTo: contentView.rightAnchor),
shadowRoundedRectangle.widthAnchor.constraint(
equalToConstant: roundedRectangleSize.width),
shadowRoundedRectangle.heightAnchor.constraint(
equalToConstant: roundedRectangleSize.height),
label.topAnchor.constraint(
equalTo: shadowRoundedRectangle.bottomAnchor, constant: 4),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
label.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 2),
label.rightAnchor.constraint(equalTo: contentView.rightAnchor),
paymentMethodLogo.centerXAnchor.constraint(
equalTo: shadowRoundedRectangle.centerXAnchor),
paymentMethodLogo.centerYAnchor.constraint(
equalTo: shadowRoundedRectangle.centerYAnchor),
paymentMethodLogo.widthAnchor.constraint(
equalToConstant: paymentMethodLogoSize.width),
paymentMethodLogo.heightAnchor.constraint(
equalToConstant: paymentMethodLogoSize.height),
plus.centerXAnchor.constraint(equalTo: shadowRoundedRectangle.centerXAnchor),
plus.centerYAnchor.constraint(equalTo: shadowRoundedRectangle.centerYAnchor),
plus.widthAnchor.constraint(equalToConstant: 32),
plus.heightAnchor.constraint(equalToConstant: 32),
selectedIcon.widthAnchor.constraint(equalToConstant: 26),
selectedIcon.heightAnchor.constraint(equalToConstant: 26),
selectedIcon.trailingAnchor.constraint(
equalTo: shadowRoundedRectangle.trailingAnchor, constant: 6),
selectedIcon.bottomAnchor.constraint(
equalTo: shadowRoundedRectangle.bottomAnchor, constant: 6),
deleteButton.trailingAnchor.constraint(
equalTo: shadowRoundedRectangle.trailingAnchor, constant: 6),
deleteButton.topAnchor.constraint(
equalTo: shadowRoundedRectangle.topAnchor, constant: -6),
])
}
override func layoutSubviews() {
super.layoutSubviews()
layer.shadowPath = CGPath(ellipseIn: selectedIcon.frame, transform: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
update()
}
override var isSelected: Bool {
didSet {
update()
}
}
// MARK: - Internal Methods
func setViewModel(_ viewModel: SavedPaymentOptionsViewController.Selection) {
paymentMethodLogo.isHidden = false
plus.isHidden = true
shadowRoundedRectangle.isHidden = false
self.viewModel = viewModel
switch viewModel {
case .saved(paymentMethod: _, label: let text, let image):
label.text = text
paymentMethodLogo.image = image
case .applePay:
// TODO (cleanup) - get this from PaymentOptionDisplayData?
label.text = STPLocalizedString("Apple Pay", "Text for Apple Pay payment method")
paymentMethodLogo.image = PaymentOption.applePay.makeCarouselImage()
case .add:
label.text = STPLocalizedString(
"+ Add",
"Text for a button that, when tapped, displays another screen where the customer can add payment method details"
)
paymentMethodLogo.isHidden = true
plus.isHidden = false
plus.setNeedsDisplay()
}
update()
}
func handleEvent(_ event: STPEvent) {
UIView.animate(withDuration: PaymentSheetUI.defaultAnimationDuration) {
switch event {
case .shouldDisableUserInteraction:
self.label.alpha = 0.6
case .shouldEnableUserInteraction:
self.label.alpha = 1
default:
break
}
}
}
// MARK: - Private Methods
@objc
private func didSelectDelete() {
delegate?.paymentOptionCellDidSelectRemove(self)
}
private func update() {
let applyDefaultStyle: () -> Void = { [self] in
shadowRoundedRectangle.isEnabled = true
label.textColor = CompatibleColor.label
paymentMethodLogo.alpha = 1
plus.alpha = 1
selectedIcon.isHidden = true
layer.shadowOpacity = 0
// Draw a outline in dark mode
if #available(iOS 12.0, *) {
if traitCollection.userInterfaceStyle == .dark {
shadowRoundedRectangle.layer.borderWidth = 1
shadowRoundedRectangle.layer.borderColor =
CompatibleColor.systemGray4.cgColor
} else {
shadowRoundedRectangle.layer.borderWidth = 0
}
}
}
if isRemovingPaymentMethods {
if case .saved(let paymentMethod, _, _) = viewModel,
paymentMethod.isDetachableInPaymentSheet
{
deleteButton.isHidden = false
contentView.bringSubviewToFront(deleteButton)
applyDefaultStyle()
} else {
deleteButton.isHidden = true
// apply disabled style
shadowRoundedRectangle.isEnabled = false
paymentMethodLogo.alpha = 0.6
plus.alpha = 0.6
label.textColor = STPInputFormColors.disabledTextColor
// Draw a outline in dark mode
if #available(iOS 12.0, *) {
if traitCollection.userInterfaceStyle == .dark {
shadowRoundedRectangle.layer.borderWidth = 1
shadowRoundedRectangle.layer.borderColor =
CompatibleColor.systemGray4.cgColor
} else {
shadowRoundedRectangle.layer.borderWidth = 0
}
}
}
} else if isSelected {
deleteButton.isHidden = true
shadowRoundedRectangle.isEnabled = true
label.textColor = CompatibleColor.label
paymentMethodLogo.alpha = 1
plus.alpha = 1
selectedIcon.isHidden = false
layer.shadowOpacity = PaymentSheetUI.defaultShadowOpacity
// Draw a green border
shadowRoundedRectangle.layer.borderWidth = 2
shadowRoundedRectangle.layer.borderColor = UIColor.systemGreen.cgColor
} else {
deleteButton.isHidden = true
shadowRoundedRectangle.isEnabled = true
applyDefaultStyle()
}
accessibilityLabel = label.text
accessibilityTraits = isSelected && !isRemovingPaymentMethods ? [.selected] : []
}
}
// A circle with an image in the middle
class CircleIconView: UIView {
let imageView: UIImageView
required init(icon: Icon) {
imageView = UIImageView(image: icon.makeImage())
super.init(frame: .zero)
// Set colors according to the icon
switch icon {
case .plus:
imageView.tintColor = CompatibleColor.secondaryLabel
backgroundColor = UIColor.dynamic(
light: CompatibleColor.systemGray5, dark: CompatibleColor.tertiaryLabel)
case .checkmark:
imageView.tintColor = .white
backgroundColor = .systemGreen
default:
break
}
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
])
layer.masksToBounds = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.width / 2
}
}
}
| 40.116766 | 132 | 0.595492 |
ed57f302a3f30782841bd6dddd4378b25c07afc5 | 252 | //
// OpenWeatherMapTests.swift
// OpenWeatherMapTests
//
// Created by Varodom Nualplub on 1/30/18.
// Copyright © 2018 creativeme. All rights reserved.
//
import XCTest
@testable import OpenWeatherMap
class OpenWeatherMapTests: XCTestCase {
}
| 16.8 | 53 | 0.746032 |
20446e32bc5fb53ef3048120d8bbc844825fd102 | 4,604 | //
// ContentView.swift
// CocoapodsCheck
//
// Created by Oleksandr Orlov on 06.02.2021.
//
import SwiftUI
import AnyFormatKit
import AnyFormatKitSwiftUI
struct ContentView: View {
// MARK: - Data
@State var phoneNumberText = ""
@State var cardNumberText = ""
@State var cardExpirationText = ""
@State var cardCvvText = ""
@State var moneyText = ""
@State var money: NSNumber?
// MARK: - Body
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
VStack(spacing: 1) {
phoneNumberField
cardNumberField
HStack(spacing: 1) {
cardExpirationField
cardCvvField
Spacer()
}
moneyField
printTextButton
Spacer()
}.background(Color.black)
}
}
private var phoneNumberField: some View {
VStack(alignment: .leading, spacing: 1, content: {
Text("Phone number")
.foregroundColor(.white)
.padding(.leading)
FormatTextField(
unformattedText: $phoneNumberText,
placeholder: "+1",
textPattern: "+1 (###)-###-####"
)
.font(UIFont.monospacedSystemFont(ofSize: 18, weight: .regular))
.placeholderColor(UIColor.white)
.foregroundColor(UIColor.white)
.keyboardType(.numberPad)
.frame(height: 44)
.background(Color(.darkGray))
.padding(.horizontal)
})
}
private var cardNumberField: some View {
VStack(alignment: .leading, spacing: 1, content: {
Text("Card number")
.foregroundColor(.white)
.padding(.horizontal)
FormatStartTextField(
unformattedText: $cardNumberText,
formatter: PlaceholderTextInputFormatter(textPattern: "#### #### #### ####")
)
.font(UIFont.monospacedSystemFont(ofSize: 18, weight: .regular))
.foregroundColor(UIColor.white)
.keyboardType(.numberPad)
.frame(height: 44)
.background(Color(.darkGray))
.padding(.horizontal)
})
.padding(.top, 15)
}
private var cardExpirationField: some View {
FormatStartTextField(
unformattedText: $cardExpirationText,
formatter: PlaceholderTextInputFormatter(textPattern: "__/__", patternSymbol: "_")
)
.font(UIFont.monospacedSystemFont(ofSize: 18, weight: .regular))
.foregroundColor(UIColor.white)
.keyboardType(.numberPad)
.frame(width: 120, height: 44)
.background(Color(.darkGray))
.padding(.leading)
}
private var cardCvvField: some View {
FormatStartTextField(
unformattedText: $cardCvvText,
formatter: PlaceholderTextInputFormatter(textPattern: "***", patternSymbol: "*")
)
.font(UIFont.monospacedSystemFont(ofSize: 18, weight: .regular))
.foregroundColor(UIColor.white)
.keyboardType(.numberPad)
.frame(width: 70, height: 44)
.background(Color(.darkGray))
.padding(.trailing)
}
private var moneyField: some View {
VStack(alignment: .leading, spacing: 1) {
Text("Money")
.foregroundColor(.white)
.padding(.horizontal)
FormatSumTextField(
numberValue: $money, textPattern: "# ###.## $"
)
.font(UIFont.monospacedSystemFont(ofSize: 18, weight: .regular))
.foregroundColor(UIColor.white)
.keyboardType(.numberPad)
.frame(height: 44)
.background(Color(.darkGray))
.padding(.horizontal)
}
.padding(.top, 15)
}
private var printTextButton: some View {
Button("Print values", action: {
print("phone number: " + phoneNumberText)
print("card number: " + cardNumberText)
print("card exp: " + cardExpirationText)
print("card cvv: " + cardCvvText)
print("money: \(String(describing: money))")
})
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 32.422535 | 94 | 0.530843 |
f4254110db51023267b44ed0be0bc660369f4de9 | 251 | //
// Configuration.swift
// WookieMovies
//
// Created by lee on 2021/1/25.
//
import Foundation
let WM_FAVORITES_KEY = "WM_FAVORITES_KEY"
let BASE_URL = URL(string: "https://wookie.codesubmit.io/movies")!
let AUTH_HEADER = "Bearer Wookie2019"
| 17.928571 | 66 | 0.721116 |
f8d24f97266c7a62fd76515869f0aa9e7d8e2c63 | 1,448 | // Please keep this file in alphabetical order!
// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -emit-module -o %t %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -parse-as-library %t/imports.swiftmodule -parse -emit-objc-header-path %t/imports.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: FileCheck %s < %t/imports.h
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t/imports.h
// RUN: %check-in-clang %t/imports.h -I %S/Inputs/custom-modules/
// REQUIRES: objc_interop
// CHECK-DAG: @import ctypes.bits;
// CHECK-DAG: @import Foundation;
// CHECK-DAG: @import Base;
// CHECK-DAG: @import Base.ImplicitSub.ExSub;
// CHECK-DAG: @import Base.ExplicitSub;
// CHECK-DAG: @import Base.ExplicitSub.ExSub;
// NEGATIVE-NOT: ctypes;
// NEGATIVE-NOT: ImSub;
// NEGATIVE-NOT: ImplicitSub;
import ctypes.bits
import Foundation
import Base
import Base.ImplicitSub
import Base.ImplicitSub.ImSub
import Base.ImplicitSub.ExSub
import Base.ExplicitSub
import Base.ExplicitSub.ImSub
import Base.ExplicitSub.ExSub
@objc class Test {
let word: DWORD = 0
let number: NSTimeInterval = 0.0
let baseI: BaseI = 0
let baseII: BaseII = 0
let baseIE: BaseIE = 0
let baseE: BaseE = 0
let baseEI: BaseEI = 0
let baseEE: BaseEE = 0
}
| 31.478261 | 261 | 0.723757 |
e6e0b457def68ad0b82c0e9b6d86846b43c02959 | 1,240 | //
// PlayerSummary.swift
// Ranger
//
// Created by Geri Borbás on 2019. 12. 16..
// Copyright © 2019. Geri Borbás. All rights reserved.
//
import Foundation
public struct PlayerSummary: RootResponse, Equatable
{ public let Response: PlayerSummaryResponse }
public struct PlayerSummaryResponse: Response, Equatable
{
public let metadataHash: String
public let timestamp: StringFor<Date>
public let success: StringFor<Bool>
public let PlayerResponse: PlayerSummaryResponse.PlayerResponse
public let UserInfo: UserInfo
public struct PlayerResponse: Decodable, Equatable
{
public let PlayerView: PlayerView
public struct PlayerView: Decodable, Equatable
{
// let Filter: String
public let Player: Player
public struct Player: Decodable, Equatable
{
public let country: String
public let countryName: String
public let lastActivity: StringFor<Date>
public let name: String
public let network: String
public let Statistics: Statistics
// RecentTournaments
}
}
}
}
| 21.37931 | 67 | 0.618548 |
bb73e7e04c30b2831e1d04ba65dbebc7cfad2ac9 | 11,374 | /*
* Copyright IBM Corporation 2019
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import KituraWebSocket
import XCTest
import NIO
import NIOWebSocket
import NIOHTTP1
@testable import WebSocketClient
import NIOFoundationCompat
class ProtocolError: WebSocketClientTests {
let uint8Code: Data = Data([UInt8(WebSocketCloseReasonCode.protocolError.code() >> 8),
UInt8(WebSocketCloseReasonCode.protocolError.code() & 0xff)])
func testBinaryAndTextFrames() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let bytes:[UInt8] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e]
let textPayload = "testing 1 2 3"
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
client.sendBinary(Data(bytes), finalFrame: false)
client.sendText(textPayload, finalFrame: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "A text frame must be the first in the message"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testPingWithOversizedPayload() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let oversizedPayload = [UInt8](repeating: 0x00, count: 126)
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
client.ping(data: Data(oversizedPayload))
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "Control frames are only allowed to have payload up to and including 125 octets"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testFragmentedPing() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
let text = "Testing, testing 1, 2, 3. "
client.sendMessage(data:text.data(using: .utf8)!, opcode: .ping, finalFrame: false)
client.sendMessage(data: text.data(using: .utf8)!, opcode: .continuation, finalFrame: false)
client.sendMessage(data: text.data(using: .utf8)!, opcode: .continuation, finalFrame: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "Control frames must not be fragmented"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testCloseWithOversizedPayload() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let oversizedPayload = [UInt8](repeating: 0x00, count: 126)
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
client.close(data: Data(oversizedPayload))
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "Control frames are only allowed to have payload up to and including 125 octets"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testJustContinuationFrame() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
let text = "Testing, testing 1, 2, 3. "
client.sendMessage(data:text.data(using: .utf8)!, opcode: .continuation, finalFrame: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "Continuation sent with prior binary or text frame"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testTextAndBinaryFrames() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let bytes:[UInt8] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e]
let textPayload = "testing 1 2 3"
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.connect()
client.sendText(textPayload, finalFrame: false)
client.sendBinary(Data(bytes), finalFrame: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "A binary frame must be the first in the message"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testUnmaskedFrame() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let bytes:[UInt8] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e]
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.maskFrame = false
client.connect()
client.sendBinary(Data(bytes), finalFrame: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "Received a frame from a client that wasn't masked"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testInvalidRSV() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let bytes:[UInt8] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e]
guard let client = WebSocketClient(host: "localhost", port: 8080, uri: self.servicePath, requestKey: self.secWebKey) else {
XCTFail("Unable to create WebSocketClient")
return
}
client.maskFrame = false
client.connect()
client.sendBinary(Data(bytes), finalFrame: true, compressed: true)
client.onClose {_, data in
var expectedData = self.uint8Code
let text = "RSV1 must be 0 unless negotiated to define meaning for non-zero values"
expectedData.append(contentsOf: text.data(using: .utf8)!)
XCTAssertEqual(data, expectedData, "The payload \(data) is not equal to the expected payload \(expectedData).")
expectation.fulfill()
}
}
}
func testInvalidUTFCloseMessage() {
let echoDelegate = EchoService()
WebSocket.register(service: echoDelegate, onPath: self.servicePath)
performServerTest { expectation in
let testString = "Testing, 1,2,3"
var payload = ByteBufferAllocator().buffer(capacity: 8)
payload.writeInteger(WebSocketCloseReasonCode.normal.code())
payload.writeBytes(testString.data(using: .utf16)!)
guard let client = WebSocketClient("http://localhost:8080/wstester") else { return }
client.connect()
client.close(data: payload.getData(at: 0, length: payload.readableBytes)!)
client.onClose { channel, data in
var expectedPayload = ByteBufferAllocator().buffer(capacity: 8)
expectedPayload.writeInteger(WebSocketCloseReasonCode.invalidDataContents.code())
expectedPayload.writeString("Failed to convert received close message to UTF-8 String")
let expected = expectedPayload.getData(at: 0, length: expectedPayload.readableBytes)
XCTAssertEqual(data, expected, "The payload \(data) is not equal to the expected payload \(expected).")
expectation.fulfill()
}
}
}
}
| 49.668122 | 135 | 0.61579 |
c1cd74c8b6ebc3fad7d05af4c0628733de0c6195 | 749 | import XCTest
import TestAplikasi
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.827586 | 111 | 0.602136 |
897eb817e45ec80650753951ac0720934cb824b5 | 333 | //
// RickMortyApp.swift
// RickMorty
//
// Created by Silvia España on 4/11/21.
//
import SwiftUI
@main
struct RickMortyApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
TabBar()
}
}
}
}
| 13.32 | 40 | 0.417417 |
212fa7eadefa9f2ff0a7049cb77b92f7993ade4a | 1,801 | //
// Van.swift
// CatBreeds
//
// Created by Joshua Adams on 2/17/18.
// Copyright © 2018 Josh Adams. All rights reserved.
//
struct Van: Breed {
var name: String {
return "Van"
}
var fullDescription: String {
return """
The Van cat is a distinctive landrace of domestic cat, found in the Lake Van region of eastern Turkey. It is relatively large, has a chalky white coat, sometimes with ruddy coloration on the head and hindquarters, and has blue or amber eyes or is odd-eyed (having one eye of each colour). The variety has been referred to as "the swimming cat", and observed to swim in Lake Van.
The naturally occurring Van cat type is popularly believed to be the basis of the Turkish Van breed, as standardised and recognised by many cat fancier organizations; it has been internationally selectively bred to consistently produce the ruddy head-and-tail colouring pattern on the white coat. However, one of the breed founders' own writings indicate that the four original cats used to found the formal breed came from other parts of Turkey than the Lake Van area. The capitalised and run-together term "Turkish Vankedisi" is confusingly used by some organisations as a name for all-white specimens of the formal Turkish Van breed.
The cats are notable for their lean, long-legged appearance.[citation needed] They are all-white, or sometimes mostly white with amber markings around the tail and ears. Locals to the Van area identify only the all-white type as the Van cat, according to a 1991 BBC documentary, Cats, written and presented by Roger Tabor.
Their most notable genetic characteristic is their almond-shaped eyes that often are mismatched colours. The most valued and valuable members of the type generally have one amber-green eye and one blue eye.
"""
}
}
| 69.269231 | 636 | 0.776235 |
569ef7e2a20d3a1f599f826be6529f31a5527583 | 2,929 | /*
MenuBarSample.swift
This source file is part of the SDGInterface open source project.
https://sdggiesbrecht.github.io/SDGInterface
Copyright ©2019–2021 Jeremy David Giesbrecht and the SDGInterface project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
#if canImport(AppKit)
import ObjectiveC
import SDGText
import SDGLocalization
import SDGInterface
import SDGInterfaceLocalizations
extension MenuBar {
private static func error() -> MenuEntry<InterfaceLocalization> {
return MenuEntry(
label: UserFacing<StrictString, InterfaceLocalization>({ localization in
switch localization {
case .englishCanada:
return "Error"
}
}),
selector: #selector(MenuBarTarget.demonstrateError),
target: MenuBarTarget.shared
)
}
internal static func sample() -> Menu<
InterfaceLocalization,
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuEntry<InterfaceLocalization>,
Menu<
InterfaceLocalization,
MenuComponentsConcatenation<
MenuComponentsConcatenation<MenuEntry<InterfaceLocalization>, Divider>,
Menu<InterfaceLocalization, MenuEntry<InterfaceLocalization>>
>
>
>,
Menu<
InterfaceLocalization,
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuComponentsConcatenation<
MenuEntry<InterfaceLocalization>, MenuEntry<InterfaceLocalization>
>, MenuEntry<InterfaceLocalization>
>, MenuEntry<InterfaceLocalization>
>, MenuEntry<InterfaceLocalization>
>, MenuEntry<InterfaceLocalization>
>, MenuEntry<InterfaceLocalization>
>,
Menu<
InterfaceLocalization,
MenuComponentsConcatenation<
MenuEntry<InterfaceLocalization>, MenuEntry<InterfaceLocalization>
>
>
>
>
>, Menu<InterfaceLocalization, MenuEntry<InterfaceLocalization>>
>
> {
return Menu(
label: UserFacing<StrictString, InterfaceLocalization>({ localization in
switch localization {
case .englishCanada:
return "Sample"
}
}),
entries: {
error()
menu()
view()
window()
}
)
}
}
#endif
| 29.887755 | 92 | 0.594742 |
f50f157ce8327a7db3f53099099c239effa428f8 | 14,352 | //
// URLSessionClientTests.swift
// ConduitTests
//
// Created by Eneko Alonso on 5/16/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
import Conduit
class URLSessionClientTests: XCTestCase {
func testBlocking() throws {
let client = URLSessionClient(delegateQueue: OperationQueue())
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/1"))
let then = Date()
let result = try client.begin(request: request)
XCTAssertNotNil(result.data)
XCTAssertEqual(result.response.statusCode, 200)
XCTAssertGreaterThanOrEqual(Date().timeIntervalSince(then), 1)
}
/// Verify sesson client throws error for unresolvable domain
/// - Note: This test will fail if Charles is open, as it will generate an HTTP response
func testBlockingBadHost() throws {
let client = URLSessionClient(delegateQueue: OperationQueue())
let request = try URLRequest(url: URL(absoluteString: "http://badlocalhost/invalid/url"))
XCTAssertThrowsError(try client.begin(request: request))
}
/// Verify sesson client throws error for timeout
func testBlockingTimeout() throws {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 0.5
let client = URLSessionClient(sessionConfiguration: configuration, delegateQueue: OperationQueue())
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/1"))
XCTAssertThrowsError(try client.begin(request: request), "Request did not timeout") { error in
XCTAssertEqual(error as? URLSessionClientError, .requestTimeout)
}
}
func testTransformsRequestsThroughRequestMiddlewarePipeline() throws {
let originalURL = try URL(absoluteString: "https://httpbin.org/put")
let modifiedURL = try URL(absoluteString: "https://httpbin.org/get")
let originalHTTPHeaders = ["Accept-Language": "en-US"]
let modifiedHTTPHeaders = ["Accept-Language": "vulcan"]
var originalRequest = URLRequest(url: originalURL)
originalRequest.allHTTPHeaderFields = originalHTTPHeaders
let middleware1 = TransformingRequestMiddleware1(url: modifiedURL)
let middleware2 = TransformingRequestMiddleware2(HTTPHeaders: modifiedHTTPHeaders)
let client = URLSessionClient(requestMiddleware: [middleware1, middleware2])
let processedRequestExpectation = expectation(description: "processed request")
client.begin(request: originalRequest) { _, _, _ in
processedRequestExpectation.fulfill()
}
waitForExpectations(timeout: 5)
guard let headers = middleware2.transformedRequest?.allHTTPHeaderFields else {
XCTFail("Expected headers")
return
}
XCTAssertEqual(middleware2.transformedRequest?.url, modifiedURL)
XCTAssertEqual(headers, modifiedHTTPHeaders)
}
func testPausesAndEmptiesPipelineIfRequestMiddlewareRequiresIt() throws {
let blockingMiddleware = BlockingRequestMiddleware()
let client = URLSessionClient(requestMiddleware: [blockingMiddleware])
let delayedRequest = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/2"))
let numDelayedRequests = 5
var completedDelayedRequests = 0
for _ in 0..<numDelayedRequests {
client.begin(request: delayedRequest) { _, _, _ in
completedDelayedRequests += 1
}
}
let immediateRequest = try URLRequest(url: URL(absoluteString: "https://httpbin.org/get"))
let requestSentExpectation = expectation(description: "request sent")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
blockingMiddleware.pipelineBehaviorOptions = .awaitsOutgoingCompletion
client.begin(request: immediateRequest) { _, _, _ in
XCTAssert(completedDelayedRequests == numDelayedRequests)
requestSentExpectation.fulfill()
}
}
waitForExpectations(timeout: 7)
}
func testCancelsRequestIfRequestMiddlewareFails() throws {
let client = URLSessionClient(requestMiddleware: [BadRequestMiddleware()])
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/get"))
let requestProcessedMiddleware = expectation(description: "request processed")
client.begin(request: request) { _, _, error in
XCTAssertNotNil(error)
requestProcessedMiddleware.fulfill()
}
waitForExpectations(timeout: 1)
}
func testSeriallyProcessesResponseMiddleware() throws {
let baseResponseText = "test"
let base64EncodedResponseText = "dGVzdA=="
let transformerMiddleware1 = TransformingResponseMiddleware { taskResponse in
guard let data = taskResponse.data, let text = String(data: data, encoding: .utf8) else {
return TaskResponse()
}
let transformedText = text + "a"
var taskResponse = taskResponse
taskResponse.data = transformedText.data(using: .utf8)
return taskResponse
}
let transformerMiddleware2 = TransformingResponseMiddleware { taskResponse in
guard let data = taskResponse.data, let text = String(data: data, encoding: .utf8) else {
return TaskResponse()
}
let transformedText = text + "b"
var taskResponse = taskResponse
taskResponse.data = transformedText.data(using: .utf8)
return taskResponse
}
let transformerMiddleware3 = TransformingResponseMiddleware { taskResponse in
guard let data = taskResponse.data, let text = String(data: data, encoding: .utf8) else {
return TaskResponse()
}
let transformedText = text + "c"
var taskResponse = taskResponse
taskResponse.data = transformedText.data(using: .utf8)
return taskResponse
}
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/base64/\(base64EncodedResponseText)"))
let client = URLSessionClient(responseMiddleware: [transformerMiddleware1, transformerMiddleware2, transformerMiddleware3],
delegateQueue: OperationQueue())
let (data, _) = try client.begin(request: request)
guard let transformedData = data, let text = String(data: transformedData, encoding: .utf8) else {
XCTFail("Transform failed")
return
}
XCTAssertEqual(text, "\(baseResponseText)abc")
}
@available(iOS 10, macOS 10.12, tvOS 10, watchOS 3, *)
func testRequestMetrics() throws {
let expectation = self.expectation(description: "Middleware gets called")
let responseMiddleware = TransformingResponseMiddleware { taskResponse in
var taskResponse = taskResponse
XCTAssertGreaterThanOrEqual(taskResponse.metrics?.taskInterval.duration ?? 0, 2)
expectation.fulfill()
return taskResponse
}
let client = URLSessionClient(responseMiddleware: [responseMiddleware], delegateQueue: OperationQueue())
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/2"))
try client.begin(request: request)
waitForExpectations(timeout: 0, handler: nil)
}
func testSessionTaskProxyAllowsCancellingRequestsBeforeTransport() throws {
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/2"))
let client: URLSessionClient = URLSessionClient()
let requestProcessedMiddleware = expectation(description: "request processed")
let sessionProxy = client.begin(request: request) { _, _, error in
XCTAssertNotNil(error)
requestProcessedMiddleware.fulfill()
}
sessionProxy.cancel()
waitForExpectations(timeout: 3)
}
func testSessionTaskProxyAllowsSuspendingRequestsBeforeTransport() throws {
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/delay/2"))
let client: URLSessionClient = URLSessionClient()
let dispatchExecutedExpectation = expectation(description: "passed response deadline")
let sessionProxy = client.begin(request: request) { _, _, _ in
XCTFail("Request should not have been executed")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
dispatchExecutedExpectation.fulfill()
}
// Suspending a task immediately after resuming it has no effect
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
sessionProxy.suspend()
}
waitForExpectations(timeout: 5)
}
func testReportsDownloadProgressForLargerTasks() throws {
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/stream-bytes/1500000"))
let client: URLSessionClient = URLSessionClient()
var progress: Progress?
let requestFinishedExpectation = expectation(description: "request finished")
var sessionProxy = client.begin(request: request) { _, _, _ in
XCTAssertNotNil(progress)
requestFinishedExpectation.fulfill()
}
sessionProxy.downloadProgressHandler = { progress = $0 }
waitForExpectations(timeout: 5)
}
func testReportsUploadProgressForLargerTasks() throws {
let serializer = MultipartFormRequestSerializer()
let client: URLSessionClient = URLSessionClient()
guard let videoData = MockResource.sampleVideo.base64EncodedData else {
throw TestError.invalidTest
}
let formPart = FormPart(name: "test-video", filename: "test-video.mov", content: .video(videoData, .mov))
serializer.append(formPart: formPart)
let requestBuilder = HTTPRequestBuilder(url: try URL(absoluteString: "https://httpbin.org/post"))
requestBuilder.serializer = serializer
requestBuilder.method = .POST
guard let request = try? requestBuilder.build() else {
XCTFail("Failed to build rerquest")
return
}
var progress: Progress?
let requestFinishedExpectation = expectation(description: "request finished")
var sessionProxy = client.begin(request: request) { _, _, _ in
XCTAssertNotNil(progress)
requestFinishedExpectation.fulfill()
}
sessionProxy.uploadProgressHandler = { progress = $0 }
waitForExpectations(timeout: 5)
}
func testHandlesConcurrentRequests() throws {
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/get"))
let client = URLSessionClient()
let numConcurrentRequests = 20
var completedRequests = 0
for _ in 0..<numConcurrentRequests {
let requestFinishedExpectation = expectation(description: "request finished")
DispatchQueue.global().async {
client.begin(request: request) { _, _, _ in
requestFinishedExpectation.fulfill()
completedRequests += 1
}
}
}
waitForExpectations(timeout: 5)
XCTAssert(completedRequests == numConcurrentRequests)
}
func testHTTPStatusCodes() throws {
let client = URLSessionClient(delegateQueue: OperationQueue())
let codes = [200, 304, 400, 403, 412, 500, 501]
for code in codes {
let request = try URLRequest(url: URL(absoluteString: "https://httpbin.org/status/\(code)"))
let result = try client.begin(request: request)
XCTAssertEqual(result.response.statusCode, code)
}
}
}
private class BadRequestMiddleware: RequestPipelineMiddleware {
enum WhyAreYouUsingThisMiddlewareError: Error {
case userError
}
let pipelineBehaviorOptions: RequestPipelineBehaviorOptions = .none
func prepareForTransport(request: URLRequest, completion: @escaping Result<URLRequest>.Block) {
completion(.error(WhyAreYouUsingThisMiddlewareError.userError))
}
}
private class TransformingRequestMiddleware1: RequestPipelineMiddleware {
let pipelineBehaviorOptions: RequestPipelineBehaviorOptions = .none
let modifiedURL: URL
init(url: URL) {
modifiedURL = url
}
func prepareForTransport(request: URLRequest, completion: @escaping Result<URLRequest>.Block) {
var mutableRequest = request
mutableRequest.url = modifiedURL
completion(.value(mutableRequest))
}
}
private class TransformingRequestMiddleware2: RequestPipelineMiddleware {
var transformedRequest: URLRequest?
var pipelineBehaviorOptions: RequestPipelineBehaviorOptions = .none
let modifiedHTTPHeaders: [String: String]
init(HTTPHeaders: [String: String]) {
modifiedHTTPHeaders = HTTPHeaders
}
func prepareForTransport(request: URLRequest, completion: @escaping Result<URLRequest>.Block) {
var mutableRequest = request
mutableRequest.allHTTPHeaderFields = modifiedHTTPHeaders
transformedRequest = mutableRequest
completion(.value(mutableRequest))
}
}
private class BlockingRequestMiddleware: RequestPipelineMiddleware {
var pipelineBehaviorOptions: RequestPipelineBehaviorOptions = .none
func prepareForTransport(request: URLRequest, completion: @escaping Result<URLRequest>.Block) {
completion(.value(request))
}
}
private class TransformingResponseMiddleware: ResponsePipelineMiddleware {
typealias Transformer = (TaskResponse) -> TaskResponse
private let transformer: Transformer
init(transformer: @escaping Transformer) {
self.transformer = transformer
}
func prepare(request: URLRequest, taskResponse: inout TaskResponse, completion: @escaping () -> Void) {
taskResponse = transformer(taskResponse)
let randomTimeInterval = TimeInterval.random(in: 0...1)
DispatchQueue.global().asyncAfter(deadline: .now() + randomTimeInterval) {
completion()
}
}
}
| 39.756233 | 131 | 0.675237 |
f4dba52e932bf57a38c84731b4a186a7c7b075e5 | 8,725 | import KsApi
import Library
import Prelude
import UIKit
private typealias Line = (start: CGPoint, end: CGPoint)
public final class FundingGraphView: UIView {
fileprivate let goalLabel = UILabel()
public override init(frame: CGRect) {
super.init(frame: frame)
self.setUp()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUp()
}
fileprivate func setUp() {
self.backgroundColor = .clear
self.addSubview(self.goalLabel)
_ = self.goalLabel
|> UILabel.lens.font .~ .ksr_headline(size: 12)
|> UILabel.lens.textColor .~ .ksr_white
|> UILabel.lens.backgroundColor .~ .ksr_create_700
|> UILabel.lens.textAlignment .~ .center
}
internal var fundedPointRadius: CGFloat = 12.0 {
didSet {
self.setNeedsDisplay()
}
}
internal var lineThickness: CGFloat = 1.5 {
didSet {
self.setNeedsDisplay()
}
}
internal var project: Project! {
didSet {
self.setNeedsDisplay()
}
}
internal var stats: [ProjectStatsEnvelope.FundingDateStats]! {
didSet {
self.setNeedsDisplay()
}
}
internal var yAxisTickSize: CGFloat = 1.0 {
didSet {
self.setNeedsDisplay()
}
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
// Map the date and pledged amount to (dayNumber, pledgedAmount).
let datePledgedPoints = self.stats
.enumerated()
.map { index, stat in CGPoint(x: index, y: stat.cumulativePledged) }
let durationInDays = dateToDayNumber(
launchDate: project.dates.launchedAt,
currentDate: self.project.dates.deadline
)
let goal = self.project.stats.goal
let pointsPerDay = (self.bounds.width - self.layoutMargins.left) / durationInDays
let pointsPerDollar = self.bounds.height /
(CGFloat(DashboardFundingCellViewModel.tickCount) * self.yAxisTickSize)
// Draw the funding progress grey line and fill.
let line = UIBezierPath()
line.lineWidth = self.lineThickness
var lastPoint = CGPoint(x: self.layoutMargins.left, y: self.bounds.height)
line.move(to: lastPoint)
datePledgedPoints.forEach { point in
let x = point.x * pointsPerDay + self.layoutMargins.left
let y = self.bounds.height - min(point.y * pointsPerDollar, self.bounds.height)
line.addLine(to: CGPoint(x: x, y: y))
lastPoint = CGPoint(x: x, y: y)
}
// Stroke the darker graph line before filling with lighter color.
UIColor.ksr_support_400.setStroke()
line.stroke()
line.addLine(to: CGPoint(x: lastPoint.x, y: self.bounds.height))
line.close()
UIColor.ksr_support_300.setFill()
line.fill(with: .color, alpha: 0.4)
let projectHasFunded = self.stats.last?.cumulativePledged ?? 0 >= goal
if projectHasFunded {
let rightFundedStat = self.stats.split { $0.cumulativePledged < goal }.last?.first
let rightFundedPoint = CGPoint(
x: dateToDayNumber(
launchDate: stats.first?.date ?? 0,
currentDate: rightFundedStat?.date ?? 0
),
y: CGFloat(rightFundedStat?.cumulativePledged ?? 0)
)
let leftFundedStat = self.stats.filter { $0.cumulativePledged < goal }.last
let leftFundedPoint = isNil(leftFundedStat) ?
CGPoint(x: 0.0, y: 0.0) :
CGPoint(
x: dateToDayNumber(
launchDate: self.stats.first?.date ?? 0,
currentDate: leftFundedStat?.date ?? 0
),
y: CGFloat(leftFundedStat?.cumulativePledged ?? 0)
)
let leftPointX = leftFundedPoint.x * pointsPerDay + self.layoutMargins.left
let leftPointY = self.bounds.height - min(leftFundedPoint.y * pointsPerDollar, self.bounds.height)
let rightPointX = rightFundedPoint.x * pointsPerDay + self.layoutMargins.left
let rightPointY = self.bounds.height - min(rightFundedPoint.y * pointsPerDollar, self.bounds.height)
// Surrounding left and right points, used to find slope of line containing funded point.
let lineAPoint1 = CGPoint(x: leftPointX, y: leftPointY)
let lineAPoint2 = CGPoint(x: rightPointX, y: rightPointY)
let lineA = Line(start: lineAPoint1, end: lineAPoint2)
// Intersecting funded horizontal line.
let lineBPoint1 = CGPoint(
x: self.layoutMargins.left,
y: self.bounds.height -
min(CGFloat(goal) * pointsPerDollar, self.bounds.height)
)
let lineBPoint2 = CGPoint(
x: self.bounds.width,
y: self.bounds.height -
min(CGFloat(goal) * pointsPerDollar, self.bounds.height)
)
let lineB = Line(start: lineBPoint1, end: lineBPoint2)
let fundedPoint = intersection(ofLine: lineA, withLine: lineB)
let fundedDotOutline = UIBezierPath(
ovalIn: CGRect(
x: fundedPoint.x - (self.fundedPointRadius / 2),
y: fundedPoint.y - (self.fundedPointRadius / 2),
width: self.fundedPointRadius,
height: self.fundedPointRadius
)
)
let fundedDotFill = UIBezierPath(
ovalIn: CGRect(
x: fundedPoint.x - (self.fundedPointRadius / 2 / 2),
y: fundedPoint.y - (self.fundedPointRadius / 2 / 2),
width: self.fundedPointRadius / 2,
height: self.fundedPointRadius / 2
)
)
// Draw funding progress line in green from funding point on.
let fundedProgressLine = UIBezierPath()
fundedProgressLine.lineWidth = self.lineThickness
var lastFundedPoint = CGPoint(x: fundedPoint.x, y: fundedPoint.y)
fundedProgressLine.move(to: lastFundedPoint)
datePledgedPoints.forEach { point in
let x = point.x * pointsPerDay + self.layoutMargins.left
if x >= fundedPoint.x {
let y = self.bounds.height - point.y * pointsPerDollar
fundedProgressLine.addLine(to: CGPoint(x: x, y: y))
lastFundedPoint = CGPoint(x: x, y: y)
}
}
// Stroke the darker graph line before filling with lighter color.
UIColor.ksr_create_700.setStroke()
fundedProgressLine.stroke()
fundedProgressLine.addLine(to: CGPoint(x: lastFundedPoint.x, y: self.bounds.height))
fundedProgressLine.addLine(to: CGPoint(x: fundedPoint.x, y: self.bounds.height))
fundedProgressLine.close()
UIColor.ksr_create_500.setFill()
fundedProgressLine.fill(with: .color, alpha: 0.4)
UIColor.ksr_create_700.set()
fundedDotOutline.stroke()
fundedDotFill.fill()
} else {
let goalLine = Line(
start: CGPoint(x: 0.0, y: self.bounds.height - CGFloat(goal) * pointsPerDollar),
end: CGPoint(
x: self.bounds.width,
y: self.bounds.height - CGFloat(goal) * pointsPerDollar
)
)
let goalPath = UIBezierPath()
goalPath.lineWidth = self.lineThickness / 2
goalPath.move(to: goalLine.start)
goalPath.addLine(to: goalLine.end)
UIColor.ksr_create_700.setStroke()
goalPath.stroke()
self.goalLabel.text = Strings.dashboard_graphs_funding_goal()
self.goalLabel.sizeToFit()
self.goalLabel.frame = self.goalLabel.frame.insetBy(dx: -6, dy: -3).integral
self.goalLabel.center = CGPoint(
x: self.bounds.width - 16 - self.goalLabel.frame.width / 2,
y: goalLine.end.y - self.goalLabel.frame.height / 2
)
}
self.goalLabel.isHidden = projectHasFunded
}
}
// Calculates the point of intersection of Line 1 and Line 2.
private func intersection(ofLine line1: Line, withLine line2: Line) -> CGPoint {
guard line1.start.x != line1.end.x else {
return CGPoint(x: line1.start.x, y: line2.start.y)
}
let line1Slope = slope(ofLine: line1)
let line1YIntercept = yIntercept(ofLine: line1)
let line2Slope = slope(ofLine: line2)
let line2YIntercept = yIntercept(ofLine: line2)
let x = (line2YIntercept - line1YIntercept) / (line1Slope - line2Slope)
let y = line1Slope * x + line1YIntercept
return CGPoint(x: x, y: y)
}
// Calculates where a given line will intercept the y-axis, if ever.
private func yIntercept(ofLine line: Line) -> CGFloat {
return slope(ofLine: line) * (-line.start.x) + line.start.y
}
// Calculates the slope between two given points, if any.
private func slope(ofLine line: Line) -> CGFloat {
if line.start.x == line.end.x {
fatalError()
}
return (line.end.y - line.start.y) / (line.end.x - line.start.x)
}
// Returns the day number, given the start and current date in seconds.
private func dateToDayNumber(
launchDate: TimeInterval,
currentDate: TimeInterval,
calendar _: Calendar = AppEnvironment.current.calendar
) -> CGFloat {
return CGFloat((currentDate - launchDate) / 60.0 / 60.0 / 24.0)
}
| 32.077206 | 106 | 0.661891 |
209f0a1f6cad75b4cda40dabaed689e2d7d12236 | 906 | import Realm
import RealmSwift
final class UserEntity: Object {
// MARK: Properties
@objc dynamic var email: String = ""
@objc dynamic var image: String?
@objc dynamic var firstName: String = ""
@objc dynamic var lastName: String = ""
@objc dynamic var favourite: Bool = false
override static func primaryKey() -> String? {
return "email"
}
convenience init(user: User) {
self.init()
email = user.email
image = user.image?.medium.absoluteString
firstName = user.name.first
lastName = user.name.last
favourite = user.favourite
}
required init() {
super.init()
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
| 23.230769 | 61 | 0.615894 |
4a21023a37fdd8ecbce275d8edc2b9b8aa392e51 | 211 | //
// InterruptCommand.swift
// Core
//
// Created by Camelia Ignat on 28.10.2021.
// Copyright © 2021 Andrei Moldovan. All rights reserved.
//
import Foundation
public class InterruptCommand: Command {
}
| 16.230769 | 58 | 0.7109 |
7a35e0b7cc1535700efca931ed0d178015b0fca6 | 1,771 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SPSafeSymbol {
public static var _20: TwoZero { .init(name: "20") }
open class TwoZero: SPSafeSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circle: SPSafeSymbol { ext(.start.circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circleFill: SPSafeSymbol { ext(.start.circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var square: SPSafeSymbol { ext(.start.square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var squareFill: SPSafeSymbol { ext(.start.square.fill) }
}
}
| 45.410256 | 81 | 0.734049 |
4baa6ae19e600544320ca64b9e696eb384b0ffef | 514 | //
// Removable.swift
// edX
//
// Created by Akiva Leffert on 6/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public protocol Removable {
func remove()
}
// Simple removable that just executes an action on remove
open class BlockRemovable : Removable {
fileprivate var action : (() -> Void)?
public init(action : @escaping () -> Void) {
self.action = action
}
open func remove() {
self.action?()
action = nil
}
}
| 17.724138 | 58 | 0.599222 |
f901a933fa921e59e3f9ad8b1f1a7a82a251d494 | 547 |
extension Interval {
var stringValue: String {
switch self {
case let .seconds(value):
return value.description + "s"
case let .minutes(value):
return value.description + "m"
case let .hours(value):
return value.description + "h"
case let .days(value):
return value.description + "d"
case let .weeks(value):
return value.description + "w"
case let .years(value):
return value.description + "y"
}
}
}
| 24.863636 | 42 | 0.530165 |
e611039c044dc928ed0698aa44b9483417dc007d | 316 | //
// Main3.swift
// BookCore
//
// Created by Eduarda Mello on 12/04/21.
//
import Foundation
import PlaygroundSupport
import SpriteKit
public class Main3 : SKScene {
public override func didMove(to view: SKView) {
SoundManager.sharedInstance().playBackgroundMusic(.page3, mustLoop: false)
}
}
| 18.588235 | 82 | 0.708861 |
f4826345ffa964e99d9ad729d5a710c8c559dbd9 | 3,579 | // Copyright (c) 2015 Massimo Peri (@massimoksi)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Ticker
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Setup logger.
#if DEBUG
Ticker.setup()
#endif
// Register user defaults.
Settings.registerDefaults()
// Check and update app version.
if let actVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
if actVersion != Settings.bundleVersion {
Settings.bundleVersion = actVersion
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 49.027397 | 285 | 0.738754 |
5dc1fc4c4f7773c63e3772ba52b5e5d3027a5096 | 3,293 | /*
* Copyright 2019 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import GoogleDataTransport
// iOS and tvOS specifics.
#if os(iOS) || os(tvOS)
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
public class ViewController: UIViewController {
let cctTransport: GDTCORTransport = GDTCORTransport(mappingID: "1018", transformers: nil, target: GDTCORTarget.CCT.rawValue)!
let fllTransport: GDTCORTransport = GDTCORTransport(mappingID: "1018", transformers: nil, target: GDTCORTarget.FLL.rawValue)!
@IBOutlet var backendSwitch: UISegmentedControl?
var transport: GDTCORTransport {
var theTransport: GDTCORTransport = fllTransport
if !Thread.current.isMainThread {
DispatchQueue.main.sync {
if Globals.IsMonkeyTesting {
backendSwitch?.selectedSegmentIndex = Int(arc4random_uniform(2))
}
theTransport = backendSwitch?.selectedSegmentIndex == 0 ? cctTransport : fllTransport
}
} else {
if Globals.IsMonkeyTesting {
backendSwitch?.selectedSegmentIndex = Int(arc4random_uniform(2))
}
theTransport = backendSwitch?.selectedSegmentIndex == 0 ? cctTransport : fllTransport
}
return theTransport
}
}
// macOS specifics.
#elseif os(macOS)
import Cocoa
@NSApplicationMain class Main: NSObject, NSApplicationDelegate {
var windowController: NSWindowController!
func applicationDidFinishLaunching(aNotification: NSNotification) {}
}
public class ViewController: NSViewController {
let cctTransport: GDTCORTransport = GDTCORTransport(mappingID: "1018", transformers: nil, target: GDTCORTarget.CCT.rawValue)!
let fllTransport: GDTCORTransport = GDTCORTransport(mappingID: "1018", transformers: nil, target: GDTCORTarget.FLL.rawValue)!
@IBOutlet var backendSwitch: NSSegmentedControl?
var transport: GDTCORTransport {
var theTransport: GDTCORTransport = fllTransport
if !Thread.current.isMainThread {
DispatchQueue.main.sync {
if Globals.IsMonkeyTesting {
backendSwitch?.selectedSegmentIndex = Int(arc4random_uniform(2))
}
theTransport = backendSwitch?.selectedSegment == 0 ? cctTransport : fllTransport
}
} else {
if Globals.IsMonkeyTesting {
backendSwitch?.selectedSegmentIndex = Int(arc4random_uniform(2))
}
theTransport = backendSwitch?.selectedSegment == 0 ? cctTransport : fllTransport
}
return theTransport
}
}
#endif
| 35.408602 | 145 | 0.71242 |
9b55fb16448b687d3d6eb0015afc792ae54b89b3 | 2,290 | //
// SceneDelegate.swift
// CombineTest1
//
// Created by MBA0283F on 2/26/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.207547 | 147 | 0.7131 |
edc7aa61bbd8c83c067534b4297b5477879ac6f9 | 3,686 | //
// Substrate+Constructors.swift
//
//
// Created by Yehor Popovych on 1/11/21.
//
import Foundation
import SubstrateRpc
extension Substrate {
public static func create<R: Runtime, C: RpcClient>(
client: C, runtime: R, signer: SubstrateSigner? = nil, _ cb: @escaping SRpcApiCallback<Substrate<R, C>>
) {
_getRuntimeInfo(client: client, subs: Substrate<R, C>.self) { res in
let result = res.flatMap { (meta, hash, version, props) -> SRpcApiResult<Substrate<R, C>> in
let runtimeCheck = runtime.supportedSpecVersions.contains(version.specVersion)
? Result.success(())
: Result.failure(SubstrateRpcApiError.unsupportedRuntimeVersion(version.specVersion))
return runtimeCheck.flatMap {
_createRegistry(meta: meta, runtime: runtime).map { registry in
Substrate<R, C>(
registry: registry, genesisHash: hash,
runtimeVersion: version, properties: props,
client: client, signer: signer)
}
}
}
cb(result)
}
}
}
private extension Substrate {
static func _createRegistry<R: Runtime>(meta: Metadata, runtime: R) -> SRpcApiResult<TypeRegistry> {
return Result {
let registry = TypeRegistry(metadata: meta)
try runtime.registerEventsCallsAndTypes(in: registry)
try registry.validate(modules: runtime.modules)
return registry
}.mapError(SubstrateRpcApiError.from)
}
static func _getRuntimeInfo<S: SubstrateProtocol>(
client: RpcClient, subs: S.Type,
cb: @escaping SRpcApiCallback<(Metadata, S.R.THash, RuntimeVersion, SystemProperties)>
) {
_getRuntimeVersionInfo(client: client, subs: subs) { res in
switch res {
case .failure(let err): cb(.failure(err))
case .success((let meta, let hash, let version)):
print("Version", version)
SubstrateRpcSystemApi<S>.properties(client: client, timeout: 60) { res in
cb(res.map {(meta, hash, version, $0)})
}
}
}
}
static func _getRuntimeVersionInfo<S: SubstrateProtocol>(
client: RpcClient, subs: S.Type,
cb: @escaping SRpcApiCallback<(Metadata, S.R.THash, RuntimeVersion)>
) {
_getRuntimeHashInfo(client: client, subs: subs) { res in
switch res {
case .failure(let err): cb(.failure(err))
case .success((let meta, let hash)):
SubstrateRpcStateApi<S>.getRuntimeVersion(at: nil, with: client, timeout: 60) { res in
cb(res.map {(meta, hash, $0)})
}
}
}
}
static func _getRuntimeHashInfo<S: SubstrateProtocol>(
client: RpcClient, subs: S.Type,
cb: @escaping SRpcApiCallback<(Metadata, S.R.THash)>
) {
_getRuntimeMetaInfo(client: client, subs: subs) { res in
switch res {
case .failure(let err): cb(.failure(err))
case .success(let meta):
SubstrateRpcChainApi<S>.getBlockHash(block: .firstBlock, client: client, timeout: 60) { res in
cb(res.map {(meta, $0)})
}
}
}
}
static func _getRuntimeMetaInfo<S: SubstrateProtocol>(
client: RpcClient, subs: S.Type,
cb: @escaping SRpcApiCallback<Metadata>
) {
SubstrateRpcStateApi<S>.getMetadata(client: client, timeout: 60, cb)
}
}
| 37.612245 | 111 | 0.569452 |
d7aaee07728c7a474498905896b8ac675eaa3400 | 1,761 | //
// CustomPaginationLayout.swift
// CollectionViewPagination
//
// Created by dos Santos, Diego on 06/12/18.
// Copyright © 2018 Diego. All rights reserved.
//
import UIKit
class CustomPaginationLayout: UICollectionViewFlowLayout {
private let itemWidth = CGFloat(60)
private let lineSpacing = CGFloat(8)
override func awakeFromNib() {
super.awakeFromNib()
itemSize = CGSize(width: itemWidth, height: itemWidth)
minimumLineSpacing = lineSpacing
scrollDirection = .horizontal
collectionView?.decelerationRate = UIScrollView.DecelerationRate.fast
collectionView?.isPagingEnabled = false
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var offset = collectionView!.contentOffset
let sections = collectionView?.numberOfSections
let itemsOnFirstSection = collectionView!.numberOfItems(inSection: 0)
let pageMinWidth = CGFloat((itemsOnFirstSection * Int(itemWidth + lineSpacing)))
let pageMaxWidth = collectionView!.contentSize.width / CGFloat(sections!)
let pageWidth = max(pageMinWidth, pageMaxWidth)
let frameMidX = collectionView!.frame.width / 2
let pagesOnProposedOffset = ((offset.x + frameMidX) / pageWidth).rounded(.down)
if velocity.x > 0 {
// Swipping To Right
offset.x = pageWidth * (pagesOnProposedOffset + 1)
} else if velocity.x < 0 {
// Swipping To left
offset.x = pageWidth * (pagesOnProposedOffset - 1)
} else {
// Dragging
offset.x = pageWidth * pagesOnProposedOffset
}
return offset
}
}
| 35.938776 | 148 | 0.674617 |
39816340db57de7481cfec45de85cefb6b99b348 | 214 | //
// NilServiceHook.swift
// Squid
//
// Created by Oliver Borchert on 3/8/20.
// Copyright © 2020 Oliver Borchert. All rights reserved.
//
import Foundation
internal struct NilServiceHook: ServiceHook {
}
| 15.285714 | 58 | 0.71028 |
7118f7aebe5163d2b11f781e9004dc1a7a17c79a | 5,709 | //
// TweakViewData+TweaksTests.swift
// SwiftTweaks
//
// Created by Bryan Clark on 10/6/16.
// Copyright © 2016 Khan Academy. All rights reserved.
//
import XCTest
class TweakViewData_TweaksTests: XCTestCase {
private struct StepperTestCase {
let defaultValue: Double
let currentValue: Double
let customMin: Double?
let customMax: Double?
let customStep: Double?
let expectedStep: Double?
let expectedBounds: (Double, Double)?
var intTweakViewData: TweakViewData {
return .integer(
value: Int(currentValue),
defaultValue: Int(defaultValue),
min: customMin.map(Int.init),
max: customMax.map(Int.init),
stepSize: customStep.map(Int.init)
)
}
var floatTweakViewData: TweakViewData {
return .float(
value: CGFloat(currentValue),
defaultValue: CGFloat(defaultValue),
min: customMin.map { CGFloat.init($0) },
max: customMax.map { CGFloat.init($0) },
stepSize: customStep.map { CGFloat.init($0) }
)
}
var doubleTweakViewData: TweakViewData {
return .doubleTweak(
value: currentValue,
defaultValue: defaultValue,
min: customMin,
max: customMax,
stepSize: customStep
)
}
static func verifyNonIntegerStepSizeForTestCase(testCase: StepperTestCase) {
let floatStepSize = testCase.floatTweakViewData.stepperValues!.stepSize
XCTAssertEqual(
floatStepSize,
testCase.expectedStep!,
accuracy: .ulpOfOne
)
let doubleStepSize = testCase.doubleTweakViewData.stepperValues!.stepSize
XCTAssertEqual(
doubleStepSize,
testCase.expectedStep!,
accuracy: .ulpOfOne
)
}
static func verifyIntegerStepSizeForTestCase(testCase: StepperTestCase) {
let intStepSize = testCase.intTweakViewData.stepperValues!.stepSize
XCTAssertEqual(Int(intStepSize), Int(testCase.expectedStep!))
}
static func verifyStepperBoundsTestCase(testCase: StepperTestCase) {
XCTAssertEqual(
testCase.expectedBounds!.0,
testCase.floatTweakViewData.stepperValues!.stepperMin,
accuracy: .ulpOfOne
)
XCTAssertEqual(
testCase.expectedBounds!.1,
testCase.floatTweakViewData.stepperValues!.stepperMax,
accuracy: .ulpOfOne
)
XCTAssertEqual(
testCase.expectedBounds!.0,
testCase.doubleTweakViewData.stepperValues!.stepperMin,
accuracy: .ulpOfOne
)
XCTAssertEqual(
testCase.expectedBounds!.1,
testCase.doubleTweakViewData.stepperValues!.stepperMax,
accuracy: .ulpOfOne
)
}
}
func testNonIntegerStepSize() {
let tests: [(defaultValue: Double, customMin: Double?, customMax: Double?, customStep: Double?, expectedStep: Double)] = [
(0, nil, nil, nil, 0.01),
(0.5, nil, nil, nil, 0.01),
(0.01, nil, nil, nil, 0.01),
(100, nil, nil, nil, 1),
(10, nil, nil, nil, 1),
(2, nil, nil, nil, 1),
(1.01, nil, nil, nil, 1),
(0, 0, 100, nil, 1),
(0, 0, 10, nil, 1),
(0, 0, 0.1, nil, 0.01),
(10, 0, 10, nil, 1),
(0.5, nil, nil, 0.5, 0.5),
(1.0, nil, nil, 0.1, 0.1),
(10, 10, 20, 5, 5),
]
tests
.map { StepperTestCase(
defaultValue: $0,
currentValue: $0, // NOTE: We don't currently care about currentValue for stepSize calculations.
customMin: $1,
customMax: $2,
customStep: $3,
expectedStep: $4,
expectedBounds: nil)
}
.forEach(StepperTestCase.verifyNonIntegerStepSizeForTestCase)
}
func testIntegerStepSize() {
let tests: [(defaultValue: Int, customMin: Int?, customMax: Int?, customStep: Int?, expectedStep: Int)] = [
(0, nil, nil, nil, 1),
(1, nil, nil, nil, 1),
(2, nil, nil, nil, 1),
(100, nil, nil, nil, 1),
(10, nil, nil, nil, 1),
(0, 0, 100, nil, 1),
(0, 0, 10, nil, 1),
(10, 0, 10, nil, 1),
(1, nil, nil, 1, 1),
(1, nil, nil, 4, 4),
(10, 10, 20, 5, 5),
]
tests
.map { StepperTestCase(
defaultValue: Double($0),
currentValue: Double($0), // NOTE: We don't currently care about currentValue for stepSize calculations.
customMin: $1.map(Double.init),
customMax: $2.map(Double.init),
customStep: $3.map(Double.init),
expectedStep: Double($4),
expectedBounds: nil)
}
.forEach(StepperTestCase.verifyIntegerStepSizeForTestCase)
}
func testStepperLimits() {
let defaultMin = TweakViewData.stepperDefaultMinimum
let defaultMaxLarge = TweakViewData.stepperDefaultMaximumLarge
let defaultBoundsLarge = (defaultMin, defaultMaxLarge)
let defaultMaxSmall = TweakViewData.stepperDefaultMaximumSmall
let defaultBoundsSmall = (defaultMin, defaultMaxSmall)
let boundsMultipler = TweakViewData.stepperBoundsMultiplier
let tests : [(current: Double, def: Double, min: Double?, max: Double?, expected: (Double, Double))] = [
(10, 10, nil, nil, defaultBoundsLarge),
(10, 40, nil, nil, defaultBoundsLarge),
(40, 10, nil, nil, defaultBoundsLarge),
(0, 0, nil, nil, defaultBoundsSmall),
(0.2, 0.3, nil, nil, defaultBoundsSmall),
(0, 0.05, nil, nil, defaultBoundsSmall),
(50, 101, nil, nil, (defaultMin, 101 * boundsMultipler)),
(-10, -1, nil, nil, (-10 * boundsMultipler, defaultMaxLarge)),
(165, 165, nil, nil, (defaultMin, 165 * boundsMultipler)),
(60, -20, nil, nil, (-20 * boundsMultipler, defaultMaxLarge)),
(-30, -40, -100, 0, (-100, 0)),
(600, 500, 400, 1000, (400, 1000)),
(400, 200, nil, nil, (defaultMin, 400 * boundsMultipler)),
]
tests
.map { test in
StepperTestCase(
defaultValue: test.def,
currentValue: test.current,
customMin: test.min,
customMax: test.max,
customStep: nil,
expectedStep: nil,
expectedBounds: test.expected
)
}
.forEach(StepperTestCase.verifyStepperBoundsTestCase)
}
}
| 27.185714 | 124 | 0.663339 |
abc7d90fe38bb6670db732efd3f6eac8bf05d83d | 514 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Canon {
public struct PowerShotS70: CameraModel {
public init() {}
public let name = "Canon PowerShot S70"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Canon.self
}
}
public typealias CanonPowerShotS70 = Cameras.Manufacturers.Canon.PowerShotS70
| 28.555556 | 95 | 0.7393 |
fea5de2c7a21ecfff887b29bf08ec50704f6da68 | 2,512 | //
// EventSourceSessionRunner.swift
// EventSource
//
// Created by Mike Yu on 26/03/2018.
// Copyright © 2018 Inaka. All rights reserved.
//
import Foundation
public protocol EventSourceHTTPClientBridging: HTTPURLRequestExecutable {
weak var taskEventDelegate: URLSessionTaskEventDelegate? {get set}
}
public class EventSourceSessionRunner: NSObject, URLSessionTaskEventDelegate {
let httpClientBridge: EventSourceHTTPClientBridging
var runningSessions = Set<EventSourceSession>()
public init(httpClientWrapper: EventSourceHTTPClientBridging = URLSessionBridge()) {
self.httpClientBridge = httpClientWrapper
super.init()
httpClientWrapper.taskEventDelegate = self
}
public func checkAndRun(_ eventSource: EventSourceSession) throws {
try checkSessionIsClean(eventSource)
runningSessions.insert(eventSource)
eventSource.httpURLRequestExecutor = httpClientBridge
eventSource.connect()
}
private func checkSessionIsClean(_ eventSource: EventSourceSession) throws {
let error = NSError(domain: "com.inaka.EventSource", code: -999, userInfo: [NSLocalizedDescriptionKey: "Session isn't clean"])
guard eventSource.httpURLRequestExecutor == nil, eventSource.readyState == .closed else {
throw error
}
}
public func run(_ eventSource: EventSourceSession) {
do {
try checkAndRun(eventSource)
} catch let error {
assertionFailure(error.localizedDescription)
}
}
public func stop(_ eventSource: EventSourceSession) {
guard let session = runningSessions.remove(eventSource) else {
return
}
session.close()
session.httpURLRequestExecutor = nil
}
public func didReceiveData(_ data: Data, forTask dataTask: URLSessionDataTask) {
taskEventDelegate(for: dataTask)?.didReceiveData(data, forTask: dataTask)
}
private func taskEventDelegate(for task: URLSessionTask) -> URLSessionTaskEventDelegate? {
return runningSessions.first{$0.task == task}
}
public func didCompleteTask(_ task: URLSessionTask, withError error: Error?) {
taskEventDelegate(for: task)?.didCompleteTask(task, withError: error)
}
public func didReceiveResponse(_ response: URLResponse, forTask dataTask: URLSessionDataTask) {
taskEventDelegate(for: dataTask)?.didReceiveResponse(response, forTask: dataTask)
}
}
| 34.888889 | 134 | 0.701831 |
5d6b81cc48ef07a26679bf3f4778b57d46d79054 | 1,472 | //
// UIImage+Rounded.swift
// StackViewDemo
//
// Created by Jonathan Engelsma on 5/26/16.
// Copyright © 2016 Jonathan Engelsma. All rights reserved.
//
import UIKit
extension UIImage {
var rounded: UIImage? {
let imageView = UIImageView(image: self)
imageView.layer.cornerRadius = min(size.height/2, size.width/2)
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.renderInContext(context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
var circle: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .ScaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.renderInContext(context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
} | 39.783784 | 102 | 0.697011 |
20139fc0f8e6101903c64d55d788ca721df4f272 | 782 | /// A type that can produce `Routeable`s from an external representation.
public protocol CanCreateRepresentedRouteable {
/// The external representation that can be used to initialize instances of the `RepresentedRouteable` type.
associatedtype Representation
/// The type of `Routeable` this factory can produce.
associatedtype RepresentedRouteable: Routeable
/// Attempts to create an instance of the `RepresentedRouteable` initialized to the given `Representation` value.
/// - Parameter representation: The value of the new instance.
/// - Returns: An instance of the initialized `RepresentedRouteable`, or `nil` if the initialization failed.
func makeRouteable(for representation: Representation) -> RepresentedRouteable?
}
| 48.875 | 117 | 0.750639 |
9b1d928ac2108d60c8711402befca1d303334410 | 7,202 | //
// PictureViewController.swift
// Unsplash
//
// Created by 范东 on 17/2/6.
// Copyright © 2017年 范东. All rights reserved.
//
import UIKit
import SDWebImage
import MBProgressHUD
class PictureViewController: UIViewController {
var model : UnsplashPictureModel!
var finalImage : UIImage!
lazy var progressView:UIProgressView = {
let progressView = UIProgressView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: 2))
progressView.progressViewStyle = UIProgressViewStyle.bar
progressView.tintColor = UIColor.white
return progressView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.black
self.finalImage = nil;
//Log
log.info("图片宽:" + (self.model?.width)! + "高:" + (self.model?.height)!)
//初始化滚动视图坐标
var scrollViewHeight : CGFloat = 0.0
scrollViewHeight = screenHeight - statusBarHeight
var scrollViewWidth : CGFloat = 0.0
scrollViewWidth = self.stringToFloat(str: (self.model?.width)!) * scrollViewHeight / self.stringToFloat(str: (self.model?.height)!)
log.info("适应后图片宽:" + String.init(format: "%.2f", scrollViewWidth) + "高:" + String.init(format: "%.2f", scrollViewHeight))
//滚动视图
let scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: screenHeight - statusBarHeight))
scrollView.contentSize = CGSize.init(width: scrollViewWidth, height: scrollViewHeight)
self.view.addSubview(scrollView)
//图片
let imageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height))
imageView.contentMode = UIViewContentMode.scaleAspectFill
scrollView.addSubview(imageView)
log.info("图片地址" + (self.model?.urls.regular)!)
imageView.sd_setImage(with: URL.init(string: (self.model?.urls.regular)!), placeholderImage: nil, options: SDWebImageOptions.progressiveDownload, progress: { (complete, total) in
// log.info("已完成" + String.init(format: "%dKB", complete / 1024))
// log.info("总共" + String.init(format: "%dKB", total / 1024))
// log.info("图片下载进度" + String.init(format: "%.2f", Float(complete) / Float(total)))
self.progressView.setProgress(Float(complete) / Float(total), animated: true)
}, completed: { (image, error, cacheType, url) in
self.progressView.progress = 0
self.finalImage = image;
})
self.view.addSubview(self.progressView)
//下滑手势
let swipe = UISwipeGestureRecognizer.init(target: self, action: #selector(dismissVC))
swipe.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipe)
// //工具栏
// let toolView = UIView.init(frame: CGRect.init(x: 10, y: screenHeight - 60, width: screenWidth - 20, height: 50))
// toolView.backgroundColor = UIColor.white
// toolView.layer.cornerRadius = 5
// toolView.clipsToBounds = true
// self.view.addSubview(toolView)
// //下载按钮
// let downloadBtn = UIButton.init(frame: CGRect.init(x: 5, y: 5, width: 40, height: 40))
// downloadBtn.setImage(UIImage.init(named: "picture_btn_download"), for: UIControlState.normal)
// downloadBtn.setImage(UIImage.init(named: "picture_btn_download"), for: UIControlState.highlighted)
// downloadBtn.addTarget(self, action: #selector(downloadBtnAction), for: UIControlEvents.touchUpInside)
// toolView.addSubview(downloadBtn)
// //分享按钮
// let shareBtn = UIButton.init(frame: CGRect.init(x: 50, y: 5, width: 40, height: 40))
// shareBtn.setImage(UIImage.init(named: "picture_btn_share"), for: UIControlState.normal)
// shareBtn.setImage(UIImage.init(named: "picture_btn_share"), for: UIControlState.highlighted)
// shareBtn.addTarget(self, action: #selector(shareBtnAction), for: UIControlEvents.touchUpInside)
// toolView.addSubview(shareBtn)
}
func dismissVC() {
self.dismiss(animated: true, completion: nil)
}
func downloadBtnAction() {
log.info("点击下载图片"+self.model.urls.raw)
if self.finalImage != nil {
UIImageWriteToSavedPhotosAlbum(self.finalImage, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
}else{
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.text
hud.label.text = "未完成下载"
hud.label.numberOfLines = 0;
hud.hide(animated: true, afterDelay: 1)
}
}
func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject)
{
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.text
if didFinishSavingWithError != nil {
log.info("保存失败"+String.init(format: "%@", didFinishSavingWithError!))
hud.label.text = String.init(format: "%@", didFinishSavingWithError!)
} else {
log.info("保存成功")
hud.label.text = "保存成功"
}
hud.label.numberOfLines = 0;
hud.hide(animated: true, afterDelay: 1)
}
func shareBtnAction() {
log.info("分享图片"+self.model.urls.raw)
if self.finalImage != nil {
let activityItems = NSArray.init(object:self.finalImage)
let activityVC:UIActivityViewController = UIActivityViewController.init(activityItems: activityItems as! [Any], applicationActivities: nil)
activityVC.excludedActivityTypes = NSArray.init(objects:UIActivityType.airDrop,UIActivityType.postToWeibo,UIActivityType.mail,UIActivityType.saveToCameraRoll) as? [UIActivityType]
self.present(activityVC, animated: true, completion: nil)
}else{
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.text
hud.label.text = "未完成下载"
hud.label.numberOfLines = 0;
hud.hide(animated: true, afterDelay: 1)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
//String to Float
func stringToFloat(str:String)->(CGFloat){
let string = str
var cgFloat: CGFloat = 0
if let doubleValue = Double(string)
{
cgFloat = CGFloat(doubleValue)
}
return cgFloat
}
/*
// 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.
}
*/
}
| 45.0125 | 191 | 0.653291 |
f4f574ded93df2580558c364b0aa61c7240e7d7a | 615 | //
// ZYFEightViewController.swift
// swiftStudy
//
// Created by 张亚峰 on 2018/8/15.
// Copyright © 2018年 zhangyafeng. All rights reserved.
//
import UIKit
class ZYFEightViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let p = ZYFStudent()
// print(p.name + p.no)
// let p1 = ZYFPerson(name: "fengfeng111")
// print(p1)
// let s = ZYFStudent(name: "fengfeng", no: "001")
// print(s)
let p = ZYFPerson1(dict: ["name" : "fengfeng","age" : 100])
print(p.name,p.age)
}
}
| 20.5 | 67 | 0.557724 |
62fd82d611e6d28225df77c296659bba2e5716ae | 8,749 | //
// Tweet.swift
// Zirpen
//
// Created by Oscar Bonilla on 9/26/17.
// Copyright © 2017 Oscar Bonilla. All rights reserved.
//
import UIKit
enum Media {
case photo(URL)
// case quoted(Tweet)
}
struct EntityURL {
let display_url: String
let expanded_url: String
let indices: [Int]
}
struct UserMention {
let user: User
let indices: [Int]
}
struct HashTag {
let text: String
let indices: [Int]
}
enum Entities {
case urls([EntityURL])
case userMentions([UserMention])
}
class Tweet: NSObject {
var text: String?
var truncated: Bool?
var id: Int?
var idStr: String?
var inReplyToUserIdStr: String?
var retweetCount: Int?
var user: User?
var retweetedTweet: Tweet?
var favouritesCount: Int?
var quotedTweet: Tweet?
var createdAt: Date?
var media: Media?
var source: String?
var retweeted: Bool
var favorited: Bool
var inReplyToIdStr: String?
var urls: [String]?
var prettyInterval: String? {
get {
guard let createdAt = createdAt else {
return nil
}
var start = createdAt
var end = Date()
if start > end {
let tmp = start
start = end
end = tmp
}
let seconds = DateInterval(start: start, end: end).duration
let formatter = DateComponentsFormatter()
var format = "%@"
if seconds < 60 {
formatter.allowedUnits = .second
format = "%@s"
} else if seconds < 3600 {
formatter.allowedUnits = .minute
format = "%@m"
} else if seconds < 86_400 {
formatter.allowedUnits = .hour
format = "%@h"
} else if seconds < 86_400 * 30 {
formatter.allowedUnits = .day
} else if seconds < 86_400 * 365 {
formatter.allowedUnits = .month
} else {
formatter.allowedUnits = .year
}
return String(format: format, formatter.string(from: seconds)!)
}
}
var prettySource: NSAttributedString? {
get {
guard let source = source else {
return nil
}
// https://stackoverflow.com/questions/37048759/swift-display-html-data-in-a-label-or-textview
if let data = source.data(using: String.Encoding.utf16, allowLossyConversion: true),
let link = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
let newLink = NSMutableAttributedString(attributedString: link)
newLink.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17.0),
NSAttributedStringKey.foregroundColor: UIColor.black,
NSAttributedStringKey.strokeColor: UIColor.black], range: NSMakeRange(0, newLink.length))
newLink.removeAttribute(NSAttributedStringKey.underlineStyle, range: NSMakeRange(0, newLink.length))
// Swift crashes here.
// newLink.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleNone, range: NSMakeRange(0, newLink.length))
let prefix = NSMutableAttributedString(string: "via ")
prefix.append(newLink)
return prefix
}
return nil
}
}
var prettyLiked: NSAttributedString? {
get {
guard let favouritesCount = self.favouritesCount else {
return nil
}
let astr = NSMutableAttributedString(string: String(favouritesCount))
let favs = NSAttributedString(string: " Likes")
astr.addAttributes([NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 17.0)], range: NSMakeRange(0, astr.length))
astr.append(favs)
return astr
}
}
var prettyRetweets: NSAttributedString? {
get {
guard let retweetCount = retweetCount else {
return nil
}
let astr = NSMutableAttributedString(string: String(retweetCount))
let retweets = NSAttributedString(string: " Retweets")
astr.addAttributes([NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 17.0)], range: NSMakeRange(0, astr.length))
astr.append(retweets)
return astr
}
}
init(user: User, text: String, inReplyTo: Tweet?) {
self.text = text
self.user = user
self.inReplyToIdStr = inReplyTo?.idStr
self.retweeted = false
self.favorited = false
}
init(dictionary: NSDictionary) {
// print(dictionary)
// "coordinates": null,
truncated = dictionary["truncated"] as? Bool
text = dictionary["text"] as? String
if let created_at = dictionary["created_at"] as? String {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
createdAt = formatter.date(from: created_at)
}
// "created_at": "Tue Aug 28 21:16:23 +0000 2012",
idStr = dictionary["id_str"] as? String
inReplyToUserIdStr = dictionary["in_reply_to_user_id_str"] as? String
if let userDict = dictionary["user"] as? NSDictionary {
user = User(dictionary: userDict)
}
if let retweetDict = dictionary["retweeted_status"] as? NSDictionary {
retweetedTweet = Tweet.init(dictionary: retweetDict)
}
if let quotedDict = dictionary["quoted_tweet"] as? NSDictionary {
quotedTweet = Tweet.init(dictionary: quotedDict)
}
if let entitiesDict = dictionary["entities"] as? NSDictionary,
let mediaList = entitiesDict["media"] as? NSArray {
for media in mediaList {
guard let mediaDict = media as? NSDictionary else {
continue
}
guard let type = mediaDict["type"] as? String else {
continue
}
if type == "photo" {
if let urlString = mediaDict["media_url_https"] as? String,
let url = URL(string: urlString) {
self.media = Media.photo(url)
}
}
}
}
id = dictionary["id"] as? Int
retweetCount = dictionary["retweet_count"] as? Int
favouritesCount = dictionary["favorite_count"] as? Int
source = dictionary["source"] as? String
retweeted = dictionary["retweeted"] as? Bool ?? false
favorited = dictionary["favorited"] as? Bool ?? false
inReplyToIdStr = dictionary["in_reply_to_status_id_str"] as? String
// "geo": null,
// "in_reply_to_user_id": null,
// "place": null,
// "default_profile": false,
// "url": "http://bit.ly/oauth-dancer",
// "contributors_enabled": false,
// "utc_offset": null,
// "profile_image_url_https": "https://si0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg",
// "id": 119476949,
// "listed_count": 1,
// "profile_use_background_image": true,
// "profile_text_color": "333333",
// "followers_count": 28,
// "lang": "en",
// "protected": false,
// "geo_enabled": true,
// "notifications": false,
// "description": "",
// "profile_background_color": "C0DEED",
// "verified": false,
// "time_zone": null,
// "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/80151733/oauth-dance.png",
// "statuses_count": 166,
// "profile_background_image_url": "http://a0.twimg.com/profile_background_images/80151733/oauth-dance.png",
// "default_profile_image": false,
// "friends_count": 14,
// "following": false,
// "show_all_inline_media": false,
// "screen_name": "oauth_dancer"
// },
// "in_reply_to_screen_name": null,
// "in_reply_to_status_id": null
}
class func fromDictionaryArray(dictionaryArray: [NSDictionary]) -> [Tweet] {
var tweets: [Tweet] = [Tweet]()
for dictionary in dictionaryArray {
let tweet = Tweet(dictionary: dictionary)
tweets.append(tweet)
}
return tweets
}
}
| 35.856557 | 153 | 0.564636 |
729faf278c410b7477cb5a40db0c7ae58f20931d | 1,242 | //
// Tip_CalculatorTests.swift
// Tip CalculatorTests
//
// Created by Sabrina Chen on 1/22/22.
//
import XCTest
@testable import Tip_Calculator
class Tip_CalculatorTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
// Any test you write for XCTest can be annotated as throws and async.
// Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
// Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 33.567568 | 130 | 0.688406 |
e22dd6fb69943bc872f3aa552f7d453bcca789ea | 1,814 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity
/// Request payload for sending a read receipt.
public struct SendReadReceiptRequest: Codable {
// MARK: Properties
/// Id of the latest chat message read by the user.
public let chatMessageId: String
// MARK: Initializers
/// Initialize a `SendReadReceiptRequest` structure.
/// - Parameters:
/// - chatMessageId: Id of the latest chat message read by the user.
public init(
chatMessageId: String
) {
self.chatMessageId = chatMessageId
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case chatMessageId = "chatMessageId"
}
/// Initialize a `SendReadReceiptRequest` structure from decoder
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.chatMessageId = try container.decode(String.self, forKey: .chatMessageId)
}
/// Encode a `SendReadReceiptRequest` structure
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(chatMessageId, forKey: .chatMessageId)
}
}
| 33.592593 | 86 | 0.653804 |
012678f3b584c8985397b439b03ec5d46027ffeb | 4,717 | import FastStyleTransfer
import Foundation
import ModelSupport
import TensorFlow
extension TransformerNet: ImportableLayer {}
/// Updates `obj` with values from command line arguments according to `params` map.
func parseArguments<T>(into obj: inout T, with params: [String: WritableKeyPath<T, String?>]) {
for arg in CommandLine.arguments.dropFirst() {
if !arg.starts(with: "--") { continue }
let parts = arg.split(separator: "=", maxSplits: 2)
let name = String(parts[0][parts[0].index(parts[0].startIndex, offsetBy: 2)...])
if let path = params[name], parts.count == 2 {
obj[keyPath: path] = String(parts[1])
}
}
}
enum FileError: Error {
case fileNotFound
}
/// Updates `model` with parameters from a checkpoint for a matching style.
func importWeights(_ model: inout TransformerNet, for style: String) throws {
let remoteCheckpoint: URL
let modelName: String
switch style {
case "candy":
remoteCheckpoint = URL(
string:
"https://storage.googleapis.com/s4tf-hosted-binaries/checkpoints/FastStyleTransfer/candy"
)!
modelName = "FastStyleTransfer_candy"
case "mosaic":
remoteCheckpoint = URL(
string:
"https://storage.googleapis.com/s4tf-hosted-binaries/checkpoints/FastStyleTransfer/mosaic"
)!
modelName = "FastStyleTransfer_mosaic"
case "udnie":
remoteCheckpoint = URL(
string:
"https://storage.googleapis.com/s4tf-hosted-binaries/checkpoints/FastStyleTransfer/udnie"
)!
modelName = "FastStyleTransfer_udnie"
default:
print("Please select one of the three currently supported styles: candy, mosaic, or udnie.")
exit(-1)
}
let reader = CheckpointReader(checkpointLocation: remoteCheckpoint, modelName: modelName)
// Names don't match exactly, and axes in filters need to be reversed.
let map = [
"conv1.conv2d.filter": ("conv1.conv2d.weight", [3, 2, 1, 0]),
"conv2.conv2d.filter": ("conv2.conv2d.weight", [3, 2, 1, 0]),
"conv3.conv2d.filter": ("conv3.conv2d.weight", [3, 2, 1, 0]),
"deconv1.conv2d.filter": ("deconv1.conv2d.weight", [3, 2, 1, 0]),
"deconv2.conv2d.filter": ("deconv2.conv2d.weight", [3, 2, 1, 0]),
"deconv3.conv2d.filter": ("deconv3.conv2d.weight", [3, 2, 1, 0]),
"res1.conv1.conv2d.filter": ("res1.conv1.conv2d.weight", [3, 2, 1, 0]),
"res1.conv2.conv2d.filter": ("res1.conv2.conv2d.weight", [3, 2, 1, 0]),
"res1.in1.scale": ("res1.in1.weight", nil),
"res1.in1.offset": ("res1.in1.bias", nil),
"res1.in2.scale": ("res1.in2.weight", nil),
"res1.in2.offset": ("res1.in2.bias", nil),
"res2.conv1.conv2d.filter": ("res2.conv1.conv2d.weight", [3, 2, 1, 0]),
"res2.conv2.conv2d.filter": ("res2.conv2.conv2d.weight", [3, 2, 1, 0]),
"res2.in1.scale": ("res2.in1.weight", nil),
"res2.in1.offset": ("res2.in1.bias", nil),
"res2.in2.scale": ("res2.in2.weight", nil),
"res2.in2.offset": ("res2.in2.bias", nil),
"res3.conv1.conv2d.filter": ("res3.conv1.conv2d.weight", [3, 2, 1, 0]),
"res3.conv2.conv2d.filter": ("res3.conv2.conv2d.weight", [3, 2, 1, 0]),
"res3.in1.scale": ("res3.in1.weight", nil),
"res3.in1.offset": ("res3.in1.bias", nil),
"res3.in2.scale": ("res3.in2.weight", nil),
"res3.in2.offset": ("res3.in2.bias", nil),
"res4.conv1.conv2d.filter": ("res4.conv1.conv2d.weight", [3, 2, 1, 0]),
"res4.conv2.conv2d.filter": ("res4.conv2.conv2d.weight", [3, 2, 1, 0]),
"res4.in1.scale": ("res4.in1.weight", nil),
"res4.in1.offset": ("res4.in1.bias", nil),
"res4.in2.scale": ("res4.in2.weight", nil),
"res4.in2.offset": ("res4.in2.bias", nil),
"res5.conv1.conv2d.filter": ("res5.conv1.conv2d.weight", [3, 2, 1, 0]),
"res5.conv2.conv2d.filter": ("res5.conv2.conv2d.weight", [3, 2, 1, 0]),
"res5.in1.scale": ("res5.in1.weight", nil),
"res5.in1.offset": ("res5.in1.bias", nil),
"res5.in2.scale": ("res5.in2.weight", nil),
"res5.in2.offset": ("res5.in2.bias", nil),
"in1.scale": ("in1.weight", nil),
"in1.offset": ("in1.bias", nil),
"in2.scale": ("in2.weight", nil),
"in2.offset": ("in2.bias", nil),
"in3.scale": ("in3.weight", nil),
"in3.offset": ("in3.bias", nil),
"in4.scale": ("in4.weight", nil),
"in4.offset": ("in4.bias", nil),
"in5.scale": ("in5.weight", nil),
"in5.offset": ("in5.bias", nil),
]
model.unsafeImport(from: reader, map: map)
}
| 44.92381 | 106 | 0.589994 |
ff81fdc77e2a7c609a760ff80aa1a050842e020b | 882 | //
// SwitchCell.swift
// Yelp
//
// Created by Phương Nguyễn on 10/19/16.
// Copyright © 2016 CoderSchool. All rights reserved.
//
import UIKit
@objc protocol SwitchCellDelegate {
@objc optional func switchCell(switchCell: SwitchCell, didChangeValue value: Bool)
}
class SwitchCell: UITableViewCell {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var switchButton: UISwitch!
weak var delegate: SwitchCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func onSwitch(_ sender: UISwitch) {
delegate?.switchCell!(switchCell: self, didChangeValue: sender.isOn)
}
}
| 23.210526 | 86 | 0.685941 |
28272629577360b7de84faf3aac06c984c1dc141 | 349 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "CLibraryiquote",
targets: [
.target(name: "Bar", dependencies: ["Foo"]),
.target(name: "Baz", dependencies: ["Foo", "Bar"]),
.target(name: "Foo", dependencies: []),
.target(name: "Bar with spaces", dependencies: []),
]
)
| 26.846154 | 59 | 0.584527 |
3ac1995d015169724c7cc9b08deb9b5aa2146023 | 295 | //
// FlatRequest.swift
// Flat
//
// Created by xuyunshi on 2021/10/22.
// Copyright © 2021 agora.io. All rights reserved.
//
import Foundation
protocol FlatRequest: Request {}
extension FlatRequest {
var method: HttpMethod { .post }
var decoder: JSONDecoder { .flatDecoder }
}
| 16.388889 | 51 | 0.681356 |
f5ba2977e79f280a396b992f20b173f455ac454a | 359 | //
// ControlCenter.swift
// Maze
//
// Created by Jarrod Parkes on 8/14/15.
// Copyright © 2015 Udacity, Inc. All rights reserved.
//
class ControlCenter {
func moveComplexRobot(robot: ComplexRobot) {
robot.move(2)
robot.rotateLeft()
robot.move(3)
robot.rotateLeft()
robot.move(1)
}
}
| 16.318182 | 55 | 0.571031 |
3a62350bfdd6c8ccadaca31de94b0871e1ddbd72 | 15,050 | //
// RNAudioRecorderPlayer.swift
// RNAudioRecorderPlayer
//
// Created by hyochan on 2021/05/05.
//
import Foundation
import AVFoundation
@objc(RNAudioRecorderPlayer)
class RNAudioRecorderPlayer: RCTEventEmitter, AVAudioRecorderDelegate {
var subscriptionDuration: Double = 0.5
var audioFileURL: URL?
// Recorder
var audioRecorder: AVAudioRecorder!
var audioSession: AVAudioSession!
var recordTimer: Timer?
var _meteringEnabled: Bool = false
// Player
var pausedPlayTime: CMTime?
var audioPlayerAsset: AVURLAsset!
var audioPlayerItem: AVPlayerItem!
var audioPlayer: AVPlayer!
var playTimer: Timer?
var timeObserverToken: Any?
override static func requiresMainQueueSetup() -> Bool {
return true
}
override func supportedEvents() -> [String]! {
return ["rn-playback", "rn-recordback"]
}
func setAudioFileURL(path: String) {
if (path == "DEFAULT") {
let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
audioFileURL = cachesDirectory.appendingPathComponent("sound.m4a")
} else if (path.hasPrefix("http://") || path.hasPrefix("https://") || path.hasPrefix("file://")) {
audioFileURL = URL(string: path)
} else {
let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
audioFileURL = cachesDirectory.appendingPathComponent(path)
}
}
/********** Recorder **********/
@objc(updateRecorderProgress:)
public func updateRecorderProgress(timer: Timer) -> Void {
if (audioRecorder != nil) {
var currentMetering: Float = 0
if (_meteringEnabled) {
audioRecorder.updateMeters()
currentMetering = audioRecorder.averagePower(forChannel: 0)
}
let status = [
"isRecording": audioRecorder.isRecording,
"currentPosition": audioRecorder.currentTime * 1000,
"currentMetering": currentMetering,
] as [String : Any];
sendEvent(withName: "rn-recordback", body: status)
}
}
@objc(startRecorderTimer)
func startRecorderTimer() -> Void {
DispatchQueue.main.async {
self.recordTimer = Timer.scheduledTimer(
timeInterval: self.subscriptionDuration,
target: self,
selector: #selector(self.updateRecorderProgress),
userInfo: nil,
repeats: true
)
}
}
@objc(pauseRecorder:rejecter:)
public func pauseRecorder(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioRecorder == nil) {
return reject("RNAudioPlayerRecorder", "Recorder is not recording", nil)
}
recordTimer?.invalidate()
recordTimer = nil;
audioRecorder.pause()
resolve("Recorder paused!")
}
@objc(resumeRecorder:rejecter:)
public func resumeRecorder(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioRecorder == nil) {
return reject("RNAudioPlayerRecorder", "Recorder is nil", nil)
}
audioRecorder.record()
if (recordTimer == nil) {
startRecorderTimer()
}
resolve("Recorder paused!")
}
@objc
func construct() {
self.subscriptionDuration = 0.1
}
@objc(audioPlayerDidFinishPlaying:)
public static func audioPlayerDidFinishPlaying(player: AVAudioRecorder) -> Bool {
return true
}
@objc(setSubscriptionDuration:)
func setSubscriptionDuration(duration: Double) -> Void {
subscriptionDuration = duration
}
/********** Player **********/
@objc(startRecorder:audioSets:meteringEnabled:resolve:reject:)
func startRecorder(path: String, audioSets: [String: Any], meteringEnabled: Bool, resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) -> Void {
_meteringEnabled = meteringEnabled;
let encoding = audioSets["AVFormatIDKeyIOS"] as? String
let mode = audioSets["AVModeIOS"] as? String
let avLPCMBitDepth = audioSets["AVLinearPCMBitDepthKeyIOS"] as? Int
let avLPCMIsBigEndian = audioSets["AVLinearPCMIsBigEndianKeyIOS"] as? Bool
let avLPCMIsFloatKey = audioSets["AVLinearPCMIsFloatKeyIOS"] as? Bool
let avLPCMIsNonInterleaved = audioSets["AVLinearPCMIsNonInterleavedIOS"] as? Bool
var avFormat: Int? = nil
var avMode: AVAudioSession.Mode = AVAudioSession.Mode.default
var sampleRate = audioSets["AVSampleRateKeyIOS"] as? Int
var numberOfChannel = audioSets["AVNumberOfChannelsKeyIOS"] as? Int
var audioQuality = audioSets["AVEncoderAudioQualityKeyIOS"] as? Int
setAudioFileURL(path: path)
if (sampleRate == nil) {
sampleRate = 44100;
}
if (encoding == nil) {
avFormat = Int(kAudioFormatAppleLossless)
} else {
if (encoding == "lpcm") {
avFormat = Int(kAudioFormatAppleIMA4)
} else if (encoding == "ima4") {
avFormat = Int(kAudioFormatAppleIMA4)
} else if (encoding == "aac") {
avFormat = Int(kAudioFormatMPEG4AAC)
} else if (encoding == "MAC3") {
avFormat = Int(kAudioFormatMACE3)
} else if (encoding == "MAC6") {
avFormat = Int(kAudioFormatMACE6)
} else if (encoding == "ulaw") {
avFormat = Int(kAudioFormatULaw)
} else if (encoding == "alaw") {
avFormat = Int(kAudioFormatALaw)
} else if (encoding == "mp1") {
avFormat = Int(kAudioFormatMPEGLayer1)
} else if (encoding == "mp2") {
avFormat = Int(kAudioFormatMPEGLayer2)
} else if (encoding == "mp4") {
avFormat = Int(kAudioFormatMPEG4AAC)
} else if (encoding == "alac") {
avFormat = Int(kAudioFormatAppleLossless)
} else if (encoding == "amr") {
avFormat = Int(kAudioFormatAMR)
} else if (encoding == "flac") {
if #available(iOS 11.0, *) {
avFormat = Int(kAudioFormatFLAC)
}
} else if (encoding == "opus") {
avFormat = Int(kAudioFormatOpus)
}
}
if (mode == "measurement") {
avMode = AVAudioSession.Mode.measurement
} else if (mode == "gamechat") {
avMode = AVAudioSession.Mode.gameChat
} else if (mode == "movieplayback") {
avMode = AVAudioSession.Mode.moviePlayback
} else if (mode == "spokenaudio") {
avMode = AVAudioSession.Mode.spokenAudio
} else if (mode == "videochat") {
avMode = AVAudioSession.Mode.videoChat
} else if (mode == "videorecording") {
avMode = AVAudioSession.Mode.videoRecording
} else if (mode == "voicechat") {
avMode = AVAudioSession.Mode.voiceChat
} else if (mode == "voiceprompt") {
if #available(iOS 12.0, *) {
avMode = AVAudioSession.Mode.voicePrompt
} else {
// Fallback on earlier versions
}
}
if (numberOfChannel == nil) {
numberOfChannel = 2
}
if (audioQuality == nil) {
audioQuality = AVAudioQuality.medium.rawValue
}
func startRecording() {
let settings = [
AVSampleRateKey: sampleRate!,
AVFormatIDKey: avFormat!,
AVNumberOfChannelsKey: numberOfChannel!,
AVEncoderAudioQualityKey: audioQuality!,
AVLinearPCMBitDepthKey: avLPCMBitDepth ?? AVLinearPCMBitDepthKey.count,
AVLinearPCMIsBigEndianKey: avLPCMIsBigEndian ?? true,
AVLinearPCMIsFloatKey: avLPCMIsFloatKey ?? false,
AVLinearPCMIsNonInterleaved: avLPCMIsNonInterleaved ?? false
] as [String : Any]
do {
audioRecorder = try AVAudioRecorder(url: audioFileURL!, settings: settings)
if (audioRecorder != nil) {
audioRecorder.prepareToRecord()
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = _meteringEnabled
let isRecordStarted = audioRecorder.record()
if !isRecordStarted {
reject("RNAudioPlayerRecorder", "Error occured during initiating recorder", nil)
return
}
startRecorderTimer()
resolve(audioFileURL?.absoluteString)
return
}
reject("RNAudioPlayerRecorder", "Error occured during initiating recorder", nil)
} catch {
reject("RNAudioPlayerRecorder", "Error occured during recording", nil)
}
}
audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playAndRecord, mode: avMode, options: [AVAudioSession.CategoryOptions.defaultToSpeaker, AVAudioSession.CategoryOptions.allowBluetooth])
try audioSession.setActive(true)
audioSession.requestRecordPermission { granted in
DispatchQueue.main.async {
if granted {
startRecording()
} else {
reject("RNAudioPlayerRecorder", "Record permission not granted", nil)
}
}
}
} catch {
reject("RNAudioPlayerRecorder", "Failed to record", nil)
}
}
@objc(stopRecorder:rejecter:)
public func stopRecorder(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioRecorder == nil) {
reject("RNAudioPlayerRecorder", "Failed to stop recorder. It is already nil.", nil)
return
}
audioRecorder.stop()
if (recordTimer != nil) {
recordTimer!.invalidate()
recordTimer = nil
}
resolve(audioFileURL?.absoluteString)
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
print("Failed to stop recorder")
}
}
/********** Player **********/
func addPeriodicTimeObserver() {
let timeScale = CMTimeScale(NSEC_PER_SEC)
let time = CMTime(seconds: subscriptionDuration, preferredTimescale: timeScale)
timeObserverToken = audioPlayer.addPeriodicTimeObserver(forInterval: time,
queue: .main) {_ in
if (self.audioPlayer != nil) {
self.sendEvent(withName: "rn-playback", body: [
"isMuted": self.audioPlayer.isMuted,
"currentPosition": self.audioPlayerItem.currentTime().seconds * 1000,
"duration": self.audioPlayerItem.asset.duration.seconds * 1000,
])
}
}
}
func removePeriodicTimeObserver() {
if let timeObserverToken = timeObserverToken {
audioPlayer.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
@objc(startPlayer:httpHeaders:resolve:rejecter:)
public func startPlayer(
path: String,
httpHeaders: [String: String],
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playAndRecord, mode: .default, options: [AVAudioSession.CategoryOptions.defaultToSpeaker, AVAudioSession.CategoryOptions.allowBluetooth])
try audioSession.setActive(true)
} catch {
reject("RNAudioPlayerRecorder", "Failed to play", nil)
}
setAudioFileURL(path: path)
audioPlayerAsset = AVURLAsset(url: audioFileURL!, options:["AVURLAssetHTTPHeaderFieldsKey": httpHeaders])
audioPlayerItem = AVPlayerItem(asset: audioPlayerAsset!)
if (audioPlayer == nil) {
audioPlayer = AVPlayer(playerItem: audioPlayerItem)
} else {
audioPlayer.replaceCurrentItem(with: audioPlayerItem)
}
addPeriodicTimeObserver()
audioPlayer.play()
resolve(audioFileURL?.absoluteString)
}
@objc(stopPlayer:rejecter:)
public func stopPlayer(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioPlayer == nil) {
return reject("RNAudioPlayerRecorder", "Player is already stopped.", nil)
}
audioPlayer.pause()
self.removePeriodicTimeObserver()
self.audioPlayer = nil;
resolve(audioFileURL?.absoluteString)
}
@objc(pausePlayer:rejecter:)
public func pausePlayer(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioPlayer == nil) {
return reject("RNAudioPlayerRecorder", "Player is not playing", nil)
}
audioPlayer.pause()
resolve("Player paused!")
}
@objc(resumePlayer:rejecter:)
public func resumePlayer(
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioPlayer == nil) {
return reject("RNAudioPlayerRecorder", "Player is null", nil)
}
audioPlayer.play()
resolve("Resumed!")
}
@objc(seekToPlayer:resolve:rejecter:)
public func seekToPlayer(
time: Double,
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
if (audioPlayer == nil) {
return reject("RNAudioPlayerRecorder", "Player is null", nil)
}
audioPlayer.seek(to: CMTime(seconds: time / 1000, preferredTimescale: CMTimeScale(NSEC_PER_SEC)))
resolve("Resumed!")
}
@objc(setVolume:resolve:rejecter:)
public func setVolume(
volume: Float,
resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock
) -> Void {
audioPlayer.volume = volume
resolve(volume)
}
}
| 34.597701 | 179 | 0.587176 |
145cd0cf9e4b0fbe8f29ae86feab11f2a1866ef2 | 332 | //
// TrackerMisconfiguration.swift
// swift-demo
//
// Created by Nicholas Cromwell on 9/29/20.
// Copyright © 2020 RangerLabs. All rights reserved.
//
public enum TrackerMisconfiguration : Error {
case deviceIdMustNotBeNilOrEmpty
case externalUserIdMustNotBeNilOrEmpty
case breadcrumbApiKeyMustNotBeNilOrEmpty
}
| 23.714286 | 53 | 0.76506 |
481e15f5f54be30a77abbf5901b7cb247d04dd28 | 2,502 | //
// IvGraphMemoModifyService.swift
// inventorybox_iOS
//
// Created by 황지은 on 2020/10/12.
// Copyright © 2020 jaeyong Lee. All rights reserved.
//
import Foundation
import Alamofire
struct IvGraphMemoModifyService {
static let shared = IvGraphMemoModifyService()
private func makeParameter(itemIdx: Int) -> Parameters{
return [ "itemIdx" : itemIdx]
}
func postGraphModify(itemIdx: Int,alarmCnt: Int,memoCnt:Int, completion: @escaping (NetworkResult<Any>) -> Void) {
let token = UserDefaults.standard.string(forKey: "token") ?? ""
let header: HTTPHeaders = ["Content-Type":"application/json", "token":token]
let body: Parameters = [
"alarmCnt" : alarmCnt,
"memoCnt" : memoCnt
]
let url = APIConstants.baseURL + "dashboard/" + String(itemIdx) + "/modifyCnt"
print(url)
let dataRequest = Alamofire.request(url, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header)
dataRequest.responseData { (dataResponse) in
switch dataResponse.result {
case .success:
guard let statusCode = dataResponse.response?.statusCode else { return }
guard let value = dataResponse.result.value else { return }
print(statusCode)
let networkResult = self.judge(by: statusCode, value)
completion(networkResult)
case .failure(let error):
print(error.localizedDescription)
completion(.networkFail)
}
}
}
private func judge(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
switch statusCode {
case 200: return postModifyData(by: data)
case 400: return .pathErr
case 500: return .serverErr
default: return .networkFail
}
}
private func postModifyData(by data: Data) -> NetworkResult<Any> {
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(IvRecordSuccessData.self, from: data) else { return .pathErr }
if decodedData.success {
return .success(decodedData.message)
} else {
return .requestErr(decodedData.message)
}
}
}
| 28.758621 | 130 | 0.563149 |
f9d09864566396a266ef944e8fa026397bd7b616 | 592 | //
// StickerSetPickerModel.swift
// YellowModule
//
// Created by Nattapong Unaregul on 9/13/17.
// Copyright © 2017 Nattapong Unaregul. All rights reserved.
//
import UIKit
class StickerSetPickerModel: NSObject {
var iconName : String!
var highLightColor : UIColor?
init(iconName : String , highLightColor : UIColor?) {
super.init()
self.iconName = iconName
self.highLightColor = highLightColor
}
var iconImage : UIImage? {
get{
return UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate)
}
}
}
| 22.769231 | 79 | 0.646959 |
227e213047f481ad2ba02b880f22b3f8da47baa2 | 302 | //
// ViewController.swift
// LHBExtension-Swift
//
// Created by LHB on 16/8/15.
// Copyright © 2016年 LHB. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
LHBPrint("hello swift")
}
}
| 13.727273 | 47 | 0.635762 |
614fe50286da302ef41cd1671849490e072c01a8 | 7,338 | import Foundation
import RxBlocking
import TSCBasic
import struct TSCUtility.Version
import TuistAutomation
import TuistCache
import TuistCore
import TuistGraph
import TuistLoader
import TuistSupport
enum TestServiceError: FatalError {
case schemeNotFound(scheme: String, existing: [String])
case schemeWithoutTestableTargets(scheme: String)
// Error description
var description: String {
switch self {
case let .schemeNotFound(scheme, existing):
return "Couldn't find scheme \(scheme). The available schemes are: \(existing.joined(separator: ", "))."
case let .schemeWithoutTestableTargets(scheme):
return "The scheme \(scheme) cannot be built because it contains no buildable targets."
}
}
// Error type
var type: ErrorType {
switch self {
case .schemeNotFound:
return .abort
case .schemeWithoutTestableTargets:
return .abort
}
}
}
final class TestService {
/// Project generator
let generator: Generating
/// Xcode build controller.
let xcodebuildController: XcodeBuildControlling
/// Build graph inspector.
let buildGraphInspector: BuildGraphInspecting
/// Simulator controller
let simulatorController: SimulatorControlling
private let temporaryDirectory: TemporaryDirectory
convenience init(
xcodebuildController _: XcodeBuildControlling = XcodeBuildController(),
buildGraphInspector _: BuildGraphInspecting = BuildGraphInspector(),
simulatorController _: SimulatorControlling = SimulatorController()
) throws {
let temporaryDirectory = try TemporaryDirectory(removeTreeOnDeinit: true)
self.init(
temporaryDirectory: temporaryDirectory,
generator: Generator(
projectMapperProvider: AutomationProjectMapperProvider(),
graphMapperProvider: GraphMapperProvider(),
workspaceMapperProvider: AutomationWorkspaceMapperProvider(
workspaceDirectory: temporaryDirectory.path
),
manifestLoaderFactory: ManifestLoaderFactory()
)
)
}
init(
temporaryDirectory: TemporaryDirectory,
generator: Generating,
xcodebuildController: XcodeBuildControlling = XcodeBuildController(),
buildGraphInspector: BuildGraphInspecting = BuildGraphInspector(),
simulatorController: SimulatorControlling = SimulatorController()
) {
self.temporaryDirectory = temporaryDirectory
self.generator = generator
self.xcodebuildController = xcodebuildController
self.buildGraphInspector = buildGraphInspector
self.simulatorController = simulatorController
}
func run(
schemeName: String?,
clean: Bool,
configuration: String?,
path: AbsolutePath,
deviceName: String?,
osVersion: String?
) throws {
logger.notice("Generating project for testing", metadata: .section)
let graph: Graph = try generator.generateWithGraph(
path: path,
projectOnly: false
).1
let version = osVersion?.version()
let testableSchemes = buildGraphInspector.testableSchemes(graph: graph)
logger.log(
level: .debug,
"Found the following testable schemes: \(testableSchemes.map(\.name).joined(separator: ", "))"
)
let testSchemes: [Scheme]
if let schemeName = schemeName {
guard
let scheme = testableSchemes.first(where: { $0.name == schemeName })
else {
throw TestServiceError.schemeNotFound(
scheme: schemeName,
existing: testableSchemes.map(\.name)
)
}
testSchemes = [scheme]
} else {
testSchemes = buildGraphInspector.projectSchemes(graph: graph)
guard
!testSchemes.isEmpty
else {
throw TestServiceError.schemeNotFound(
scheme: "\(graph.workspace.name)-Project",
existing: testableSchemes.map(\.name)
)
}
}
try testSchemes.forEach { testScheme in
try self.testScheme(
scheme: testScheme,
graph: graph,
path: path,
clean: clean,
configuration: configuration,
version: version,
deviceName: deviceName
)
}
logger.log(level: .notice, "The project tests ran successfully", metadata: .success)
}
// MARK: - private
private func testScheme(
scheme: Scheme,
graph: Graph,
path _: AbsolutePath,
clean: Bool,
configuration: String?,
version: Version?,
deviceName: String?
) throws {
logger.log(level: .notice, "Testing scheme \(scheme.name)", metadata: .section)
guard let buildableTarget = buildGraphInspector.testableTarget(scheme: scheme, graph: graph) else {
throw TestServiceError.schemeWithoutTestableTargets(scheme: scheme.name)
}
let destination = try findDestination(
buildableTarget: buildableTarget,
scheme: scheme,
graph: graph,
version: version,
deviceName: deviceName
)
_ = try xcodebuildController.test(
.workspace(graph.workspace.xcWorkspacePath),
scheme: scheme.name,
clean: clean,
destination: destination,
arguments: buildGraphInspector.buildArguments(
target: buildableTarget,
configuration: configuration,
skipSigning: true
)
)
.printFormattedOutput()
.toBlocking()
.last()
}
private func findDestination(
buildableTarget: Target,
scheme: Scheme,
graph: Graph,
version: Version?,
deviceName: String?
) throws -> XcodeBuildDestination {
switch buildableTarget.platform {
case .iOS, .tvOS, .watchOS:
let minVersion: Version?
if let deploymentTarget = buildableTarget.deploymentTarget {
minVersion = deploymentTarget.version.version()
} else {
minVersion = scheme.targetDependencies()
.compactMap { graph.findTargetNode(path: $0.projectPath, name: $0.name) }
.flatMap {
$0.targetDependencies
.compactMap { $0.target.deploymentTarget?.version }
}
.compactMap { $0.version() }
.sorted()
.first
}
let deviceAndRuntime = try simulatorController.findAvailableDevice(
platform: buildableTarget.platform,
version: version,
minVersion: minVersion,
deviceName: deviceName
)
.toBlocking()
.single()
return .device(deviceAndRuntime.device.udid)
case .macOS:
return .mac
}
}
}
| 33.354545 | 116 | 0.591578 |
915354e4132e06612c4f2e254b4e60de2f42b8a3 | 359 | //
// InstallmentPresentable.swift
// PagaMe
//
// Created by German on 11/21/20.
// Copyright © 2020 German Lopez. All rights reserved.
//
import Foundation
protocol InstallmentPayerCostPresentable {
var installmentCount: Int { get }
var fullMessage: String { get }
var installmentAmount: Double { get }
var totalAmount: Double { get }
}
| 18.894737 | 55 | 0.70195 |
331c11b33cfdba39d92f28f1ee2bb8ccea8f276e | 376 | //
// TableViewProtocol.swift
//
//
// Created by Vladimir Espinola on 2/28/19.
// Copyright © 2019 vel. All rights reserved.
//
import UIKit
protocol TableViewProtocol where Self: UITableViewCell {
associatedtype Cell
static func register(in tableView: UITableView)
static func instante(from tableView: UITableView, at indexPath: IndexPath) -> Cell
}
| 22.117647 | 86 | 0.720745 |
f43ea822625757f320b9f9f1a3efb0367dcc61f0 | 202 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
for c : c
[ {
class
case ,
| 20.2 | 87 | 0.732673 |
03796742552ec4602b786daac55195dcb80d0312 | 1,118 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
@testable import Amplify
@testable import AmplifyTestCommon
@testable import AWSDataStoreCategoryPlugin
class AWSDataStorePluginSubscribeBehaviorTests: BaseDataStoreTests {
func testObserveQuery() throws {
let snapshotReceived = expectation(description: "query snapshot received")
let predicate = Post.keys.content.contains("someValue")
let sink = Amplify.DataStore.observeQuery(for: Post.self,
where: predicate,
sort: .ascending(Post.keys.createdAt))
.sink { completed in
switch completed {
case .finished:
break
case .failure(let error):
XCTFail("\(error)")
}
} receiveValue: { _ in
snapshotReceived.fulfill()
}
wait(for: [snapshotReceived], timeout: 3)
sink.cancel()
}
}
| 29.421053 | 88 | 0.561717 |
dd6626aa99f7105d07a0c2a162636674205a1fe7 | 1,279 | //
// AHFMDownloadListManager.swift
// AHFMDownloadList
//
// Created by Andy Tong on 10/1/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import AHFMDownloadListServices
import AHFMModuleManager
import AHServiceRouter
public struct AHFMDownloadListManager: AHFMModuleManager {
public static func activate() {
AHServiceRouter.registerVC(AHFMDownloadListService.service, taskName: AHFMDownloadListService.taskNavigation) { (userInfo) -> UIViewController? in
let vcStr = "AHFMDownloadList.AHFMDownloadListVC"
guard let vcType = NSClassFromString(vcStr) as? UIViewController.Type else {
return nil
}
guard let showId = userInfo[AHFMDownloadListService.keyShowId] as? Int else {
return nil
}
let vc = vcType.init()
let manager = Manager()
if let showCenter = userInfo[AHFMDownloadListService.keyShouldShowRightNavBarButton] as? Bool {
vc.setValue(showCenter, forKey: "shouldShowRightNavBarButton")
}
manager.showId = showId
vc.setValue(manager, forKey: "manager")
return vc
}
}
}
| 32.794872 | 154 | 0.631744 |
6a0c17cb0c54fe740a34369b8911a6818c751014 | 22,151 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: WhisperTextProtocol.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
/// iOS - since we use a modern proto-compiler, we must specify
/// the legacy proto format.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct SPKProtos_TSProtoWhisperMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// @required
var ratchetKey: Data {
get {return _ratchetKey ?? SwiftProtobuf.Internal.emptyData}
set {_ratchetKey = newValue}
}
/// Returns true if `ratchetKey` has been explicitly set.
var hasRatchetKey: Bool {return self._ratchetKey != nil}
/// Clears the value of `ratchetKey`. Subsequent reads from it will return its default value.
mutating func clearRatchetKey() {self._ratchetKey = nil}
/// @required
var counter: UInt32 {
get {return _counter ?? 0}
set {_counter = newValue}
}
/// Returns true if `counter` has been explicitly set.
var hasCounter: Bool {return self._counter != nil}
/// Clears the value of `counter`. Subsequent reads from it will return its default value.
mutating func clearCounter() {self._counter = nil}
var previousCounter: UInt32 {
get {return _previousCounter ?? 0}
set {_previousCounter = newValue}
}
/// Returns true if `previousCounter` has been explicitly set.
var hasPreviousCounter: Bool {return self._previousCounter != nil}
/// Clears the value of `previousCounter`. Subsequent reads from it will return its default value.
mutating func clearPreviousCounter() {self._previousCounter = nil}
/// @required
var ciphertext: Data {
get {return _ciphertext ?? SwiftProtobuf.Internal.emptyData}
set {_ciphertext = newValue}
}
/// Returns true if `ciphertext` has been explicitly set.
var hasCiphertext: Bool {return self._ciphertext != nil}
/// Clears the value of `ciphertext`. Subsequent reads from it will return its default value.
mutating func clearCiphertext() {self._ciphertext = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _ratchetKey: Data? = nil
fileprivate var _counter: UInt32? = nil
fileprivate var _previousCounter: UInt32? = nil
fileprivate var _ciphertext: Data? = nil
}
struct SPKProtos_TSProtoPreKeyWhisperMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var registrationID: UInt32 {
get {return _registrationID ?? 0}
set {_registrationID = newValue}
}
/// Returns true if `registrationID` has been explicitly set.
var hasRegistrationID: Bool {return self._registrationID != nil}
/// Clears the value of `registrationID`. Subsequent reads from it will return its default value.
mutating func clearRegistrationID() {self._registrationID = nil}
var preKeyID: UInt32 {
get {return _preKeyID ?? 0}
set {_preKeyID = newValue}
}
/// Returns true if `preKeyID` has been explicitly set.
var hasPreKeyID: Bool {return self._preKeyID != nil}
/// Clears the value of `preKeyID`. Subsequent reads from it will return its default value.
mutating func clearPreKeyID() {self._preKeyID = nil}
/// @required
var signedPreKeyID: UInt32 {
get {return _signedPreKeyID ?? 0}
set {_signedPreKeyID = newValue}
}
/// Returns true if `signedPreKeyID` has been explicitly set.
var hasSignedPreKeyID: Bool {return self._signedPreKeyID != nil}
/// Clears the value of `signedPreKeyID`. Subsequent reads from it will return its default value.
mutating func clearSignedPreKeyID() {self._signedPreKeyID = nil}
/// @required
var baseKey: Data {
get {return _baseKey ?? SwiftProtobuf.Internal.emptyData}
set {_baseKey = newValue}
}
/// Returns true if `baseKey` has been explicitly set.
var hasBaseKey: Bool {return self._baseKey != nil}
/// Clears the value of `baseKey`. Subsequent reads from it will return its default value.
mutating func clearBaseKey() {self._baseKey = nil}
/// @required
var identityKey: Data {
get {return _identityKey ?? SwiftProtobuf.Internal.emptyData}
set {_identityKey = newValue}
}
/// Returns true if `identityKey` has been explicitly set.
var hasIdentityKey: Bool {return self._identityKey != nil}
/// Clears the value of `identityKey`. Subsequent reads from it will return its default value.
mutating func clearIdentityKey() {self._identityKey = nil}
/// @required
var message: Data {
get {return _message ?? SwiftProtobuf.Internal.emptyData}
set {_message = newValue}
}
/// Returns true if `message` has been explicitly set.
var hasMessage: Bool {return self._message != nil}
/// Clears the value of `message`. Subsequent reads from it will return its default value.
mutating func clearMessage() {self._message = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _registrationID: UInt32? = nil
fileprivate var _preKeyID: UInt32? = nil
fileprivate var _signedPreKeyID: UInt32? = nil
fileprivate var _baseKey: Data? = nil
fileprivate var _identityKey: Data? = nil
fileprivate var _message: Data? = nil
}
struct SPKProtos_TSProtoKeyExchangeMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: UInt32 {
get {return _id ?? 0}
set {_id = newValue}
}
/// Returns true if `id` has been explicitly set.
var hasID: Bool {return self._id != nil}
/// Clears the value of `id`. Subsequent reads from it will return its default value.
mutating func clearID() {self._id = nil}
var baseKey: Data {
get {return _baseKey ?? SwiftProtobuf.Internal.emptyData}
set {_baseKey = newValue}
}
/// Returns true if `baseKey` has been explicitly set.
var hasBaseKey: Bool {return self._baseKey != nil}
/// Clears the value of `baseKey`. Subsequent reads from it will return its default value.
mutating func clearBaseKey() {self._baseKey = nil}
var ratchetKey: Data {
get {return _ratchetKey ?? SwiftProtobuf.Internal.emptyData}
set {_ratchetKey = newValue}
}
/// Returns true if `ratchetKey` has been explicitly set.
var hasRatchetKey: Bool {return self._ratchetKey != nil}
/// Clears the value of `ratchetKey`. Subsequent reads from it will return its default value.
mutating func clearRatchetKey() {self._ratchetKey = nil}
var identityKey: Data {
get {return _identityKey ?? SwiftProtobuf.Internal.emptyData}
set {_identityKey = newValue}
}
/// Returns true if `identityKey` has been explicitly set.
var hasIdentityKey: Bool {return self._identityKey != nil}
/// Clears the value of `identityKey`. Subsequent reads from it will return its default value.
mutating func clearIdentityKey() {self._identityKey = nil}
var baseKeySignature: Data {
get {return _baseKeySignature ?? SwiftProtobuf.Internal.emptyData}
set {_baseKeySignature = newValue}
}
/// Returns true if `baseKeySignature` has been explicitly set.
var hasBaseKeySignature: Bool {return self._baseKeySignature != nil}
/// Clears the value of `baseKeySignature`. Subsequent reads from it will return its default value.
mutating func clearBaseKeySignature() {self._baseKeySignature = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _id: UInt32? = nil
fileprivate var _baseKey: Data? = nil
fileprivate var _ratchetKey: Data? = nil
fileprivate var _identityKey: Data? = nil
fileprivate var _baseKeySignature: Data? = nil
}
struct SPKProtos_TSProtoSenderKeyMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: UInt32 {
get {return _id ?? 0}
set {_id = newValue}
}
/// Returns true if `id` has been explicitly set.
var hasID: Bool {return self._id != nil}
/// Clears the value of `id`. Subsequent reads from it will return its default value.
mutating func clearID() {self._id = nil}
var iteration: UInt32 {
get {return _iteration ?? 0}
set {_iteration = newValue}
}
/// Returns true if `iteration` has been explicitly set.
var hasIteration: Bool {return self._iteration != nil}
/// Clears the value of `iteration`. Subsequent reads from it will return its default value.
mutating func clearIteration() {self._iteration = nil}
var ciphertext: Data {
get {return _ciphertext ?? SwiftProtobuf.Internal.emptyData}
set {_ciphertext = newValue}
}
/// Returns true if `ciphertext` has been explicitly set.
var hasCiphertext: Bool {return self._ciphertext != nil}
/// Clears the value of `ciphertext`. Subsequent reads from it will return its default value.
mutating func clearCiphertext() {self._ciphertext = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _id: UInt32? = nil
fileprivate var _iteration: UInt32? = nil
fileprivate var _ciphertext: Data? = nil
}
struct SPKProtos_TSProtoSenderKeyDistributionMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: UInt32 {
get {return _id ?? 0}
set {_id = newValue}
}
/// Returns true if `id` has been explicitly set.
var hasID: Bool {return self._id != nil}
/// Clears the value of `id`. Subsequent reads from it will return its default value.
mutating func clearID() {self._id = nil}
var iteration: UInt32 {
get {return _iteration ?? 0}
set {_iteration = newValue}
}
/// Returns true if `iteration` has been explicitly set.
var hasIteration: Bool {return self._iteration != nil}
/// Clears the value of `iteration`. Subsequent reads from it will return its default value.
mutating func clearIteration() {self._iteration = nil}
var chainKey: Data {
get {return _chainKey ?? SwiftProtobuf.Internal.emptyData}
set {_chainKey = newValue}
}
/// Returns true if `chainKey` has been explicitly set.
var hasChainKey: Bool {return self._chainKey != nil}
/// Clears the value of `chainKey`. Subsequent reads from it will return its default value.
mutating func clearChainKey() {self._chainKey = nil}
var signingKey: Data {
get {return _signingKey ?? SwiftProtobuf.Internal.emptyData}
set {_signingKey = newValue}
}
/// Returns true if `signingKey` has been explicitly set.
var hasSigningKey: Bool {return self._signingKey != nil}
/// Clears the value of `signingKey`. Subsequent reads from it will return its default value.
mutating func clearSigningKey() {self._signingKey = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _id: UInt32? = nil
fileprivate var _iteration: UInt32? = nil
fileprivate var _chainKey: Data? = nil
fileprivate var _signingKey: Data? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "SPKProtos"
extension SPKProtos_TSProtoWhisperMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TSProtoWhisperMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ratchetKey"),
2: .same(proto: "counter"),
3: .same(proto: "previousCounter"),
4: .same(proto: "ciphertext"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularBytesField(value: &self._ratchetKey)
case 2: try decoder.decodeSingularUInt32Field(value: &self._counter)
case 3: try decoder.decodeSingularUInt32Field(value: &self._previousCounter)
case 4: try decoder.decodeSingularBytesField(value: &self._ciphertext)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._ratchetKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 1)
}
if let v = self._counter {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2)
}
if let v = self._previousCounter {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)
}
if let v = self._ciphertext {
try visitor.visitSingularBytesField(value: v, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: SPKProtos_TSProtoWhisperMessage) -> Bool {
if self._ratchetKey != other._ratchetKey {return false}
if self._counter != other._counter {return false}
if self._previousCounter != other._previousCounter {return false}
if self._ciphertext != other._ciphertext {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension SPKProtos_TSProtoPreKeyWhisperMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TSProtoPreKeyWhisperMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
5: .same(proto: "registrationId"),
1: .same(proto: "preKeyId"),
6: .same(proto: "signedPreKeyId"),
2: .same(proto: "baseKey"),
3: .same(proto: "identityKey"),
4: .same(proto: "message"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &self._preKeyID)
case 2: try decoder.decodeSingularBytesField(value: &self._baseKey)
case 3: try decoder.decodeSingularBytesField(value: &self._identityKey)
case 4: try decoder.decodeSingularBytesField(value: &self._message)
case 5: try decoder.decodeSingularUInt32Field(value: &self._registrationID)
case 6: try decoder.decodeSingularUInt32Field(value: &self._signedPreKeyID)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._preKeyID {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1)
}
if let v = self._baseKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 2)
}
if let v = self._identityKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 3)
}
if let v = self._message {
try visitor.visitSingularBytesField(value: v, fieldNumber: 4)
}
if let v = self._registrationID {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5)
}
if let v = self._signedPreKeyID {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: SPKProtos_TSProtoPreKeyWhisperMessage) -> Bool {
if self._registrationID != other._registrationID {return false}
if self._preKeyID != other._preKeyID {return false}
if self._signedPreKeyID != other._signedPreKeyID {return false}
if self._baseKey != other._baseKey {return false}
if self._identityKey != other._identityKey {return false}
if self._message != other._message {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension SPKProtos_TSProtoKeyExchangeMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TSProtoKeyExchangeMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"),
2: .same(proto: "baseKey"),
3: .same(proto: "ratchetKey"),
4: .same(proto: "identityKey"),
5: .same(proto: "baseKeySignature"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &self._id)
case 2: try decoder.decodeSingularBytesField(value: &self._baseKey)
case 3: try decoder.decodeSingularBytesField(value: &self._ratchetKey)
case 4: try decoder.decodeSingularBytesField(value: &self._identityKey)
case 5: try decoder.decodeSingularBytesField(value: &self._baseKeySignature)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._id {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1)
}
if let v = self._baseKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 2)
}
if let v = self._ratchetKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 3)
}
if let v = self._identityKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 4)
}
if let v = self._baseKeySignature {
try visitor.visitSingularBytesField(value: v, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: SPKProtos_TSProtoKeyExchangeMessage) -> Bool {
if self._id != other._id {return false}
if self._baseKey != other._baseKey {return false}
if self._ratchetKey != other._ratchetKey {return false}
if self._identityKey != other._identityKey {return false}
if self._baseKeySignature != other._baseKeySignature {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension SPKProtos_TSProtoSenderKeyMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TSProtoSenderKeyMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"),
2: .same(proto: "iteration"),
3: .same(proto: "ciphertext"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &self._id)
case 2: try decoder.decodeSingularUInt32Field(value: &self._iteration)
case 3: try decoder.decodeSingularBytesField(value: &self._ciphertext)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._id {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1)
}
if let v = self._iteration {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2)
}
if let v = self._ciphertext {
try visitor.visitSingularBytesField(value: v, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: SPKProtos_TSProtoSenderKeyMessage) -> Bool {
if self._id != other._id {return false}
if self._iteration != other._iteration {return false}
if self._ciphertext != other._ciphertext {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension SPKProtos_TSProtoSenderKeyDistributionMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TSProtoSenderKeyDistributionMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"),
2: .same(proto: "iteration"),
3: .same(proto: "chainKey"),
4: .same(proto: "signingKey"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &self._id)
case 2: try decoder.decodeSingularUInt32Field(value: &self._iteration)
case 3: try decoder.decodeSingularBytesField(value: &self._chainKey)
case 4: try decoder.decodeSingularBytesField(value: &self._signingKey)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._id {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1)
}
if let v = self._iteration {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2)
}
if let v = self._chainKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 3)
}
if let v = self._signingKey {
try visitor.visitSingularBytesField(value: v, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: SPKProtos_TSProtoSenderKeyDistributionMessage) -> Bool {
if self._id != other._id {return false}
if self._iteration != other._iteration {return false}
if self._chainKey != other._chainKey {return false}
if self._signingKey != other._signingKey {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
| 39.768402 | 157 | 0.723398 |
abca5b92aa2795c528a5c583e82e545f66c795cd | 399 | // RUN: %target-swift-frontend -disable-objc-interop -typecheck %s -verify
class C {}
func test(c: AnyClass) {
let _: AnyObject = c // expected-error {{value of type 'AnyClass' (aka 'AnyObject.Type') expected to be instance of class or class-constrained type}}
let _: AnyObject = C.self // expected-error {{value of type 'C.Type' expected to be instance of class or class-constrained type}}
}
| 44.333333 | 151 | 0.716792 |
c12db5815c3d5122d6c62bedb8e2cd27200c86cc | 1,361 | //=----------------------------------------------------------------------------=
// This source file is part of the DiffableTextViews open source project.
//
// Copyright (c) 2022 Oscar Byström Ericsson
// Licensed under Apache License, Version 2.0
//
// See http://www.apache.org/licenses/LICENSE-2.0 for license information.
//=----------------------------------------------------------------------------=
#if DEBUG
@testable import DiffableTextKit
import XCTest
//*============================================================================*
// MARK: * Style x Constant
//*============================================================================*
final class StyleTestsXConstant: XCTestCase {
//=------------------------------------------------------------------------=
// MARK: Tests
//=------------------------------------------------------------------------=
func test() {
//=--------------------------------------=
// Setup
//=--------------------------------------=
let mock0 = Mock(locale: en_US).constant()
let mock1 = mock0.locale(sv_SE)
//=--------------------------------------=
// Assert
//=--------------------------------------=
XCTAssertEqual(mock0, mock1)
XCTAssertEqual(mock0.style.locale, mock1.style.locale)
}
}
#endif
| 33.195122 | 80 | 0.32917 |
1a559ee494052954b4f45f7dd9616e0175653435 | 1,689 | // 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 SIL
import XCTest
import Foundation
import LibTFP
@available(macOS 10.13, *)
extension XCTestCase {
func withTemporaryFile(_ f: (URL) -> ()) {
do {
try LibTFP.withTemporaryFile(f)
} catch {
return XCTFail("Failed to create temporary directory")
}
}
func withSIL(forFile: String, _ f: (Module, URL) throws -> ()) {
do {
try LibTFP.withSIL(forFile: forFile) { module, silPath in
do {
try f(module, silPath)
} catch {
return XCTFail("An error has been thrown: \(error)")
}
}
} catch {
return XCTFail("Failed to retrieve SIL for \(forFile)")
}
}
func withSIL(forSource code: String, _ f: (Module, URL) throws -> ()) {
let preamble = """
import TensorFlow
"""
withTemporaryFile { tempFile in
let fullCode = preamble + code
do {
try fullCode.write(to: tempFile, atomically: false, encoding: .utf8)
withSIL(forFile: tempFile.path, f)
} catch {
return XCTFail("Failed to write the source to a temporary file!")
}
}
}
}
| 28.15 | 76 | 0.64476 |
bbefd131ffe9c7234df2ed55dda3e52aa60a9947 | 2,293 | //
// SceneDelegate.swift
// FirebaseLogin
//
// Created by Ignacio on 11/01/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.
}
}
| 43.264151 | 147 | 0.713476 |
629176e29f3478fea059138795fd1498d8b70f8a | 388 | //
// UserListRoutingProtocol.swift
// PhotoAlbum
//
// Created by Onur Torna on 10.04.2019.
// Copyright © 2019 Onur Torna. All rights reserved.
//
import UIKit
protocol UserListRoutingProtocol {
/// Routes to user detail with given user
func viewControllerDidRequestUserDetail(_ viewController: UIViewController,
user: User)
}
| 22.823529 | 79 | 0.657216 |
76e963963b284d5fab44fcebb60d18b69f7c3669 | 597 | //
// BracketContextCheck.swift
// Moulinette
//
// Created by Jonathan Samudio on 5/31/17.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
import Foundation
class BracketContextCheck: Check {
var bracketsArray = [String]()
var lineContext: LineContext
init(lineContext: LineContext) {
self.lineContext = lineContext
}
func check(fileLine: String) {
if fileLine.contains("{") {
bracketsArray.append(fileLine)
} else if fileLine.contains("}") {
_ = bracketsArray.removeFirst()
}
}
}
| 21.321429 | 63 | 0.624791 |
1848023633ca6289c5230a6c85079a4ba434869e | 3,194 | import Console
import Fluent
/**
Runs the droplet's `Preparation`s.
*/
public struct Prepare: Command {
public let id: String = "prepare"
public let signature: [Argument] = [
Option(name: "revert"),
]
public let help: [String] = [
"runs the droplet's preparations"
]
public let console: ConsoleProtocol
public let preparations: [Preparation.Type]
public let database: Database?
public init(
console: ConsoleProtocol,
preparations: [Preparation.Type],
database: Database?
) {
self.console = console
self.preparations = preparations
self.database = database
}
public func run(arguments: [String]) throws {
guard preparations.count > 0 else {
console.info("No preparations.")
return
}
guard let database = database else {
throw CommandError.general("Can not run preparations, droplet has no database")
}
if arguments.option("revert")?.bool == true {
guard console.confirm("Are you sure you want to revert the database?", style: .warning) else {
console.error("Reversion cancelled")
return
}
for preparation in preparations {
let name = preparation.name
let hasPrepared: Bool
do {
hasPrepared = try database.hasPrepared(preparation)
} catch {
console.error("Failed to start preparation")
throw CommandError.general("\(error)")
}
if hasPrepared {
print("Reverting \(name)")
try preparation.revert(database)
console.success("Reverted \(name)")
}
}
console.print("Removing metadata")
let schema = Schema.delete(entity: "fluent")
try database.driver.schema(schema)
console.success("Reversion complete")
} else {
for preparation in preparations {
let name = preparation.name
let hasPrepared: Bool
do {
hasPrepared = try database.hasPrepared(preparation)
} catch {
console.error("Failed to start preparation")
throw CommandError.general("\(error)")
}
if !hasPrepared {
print("Preparing \(name)")
do {
try database.prepare(preparation)
console.success("Prepared \(name)")
} catch PreparationError.automationFailed(let string) {
console.error("Automatic preparation for \(name) failed.")
throw CommandError.general("\(string)")
} catch {
console.error("Failed to prepare \(name)")
throw CommandError.general("\(error)")
}
}
}
console.info("Database prepared")
}
}
}
| 31.313725 | 106 | 0.508766 |
f582daa6124ae3f53a7da7d6c5634ec63584a750 | 743 | class Bip69Sorter: ITransactionDataSorter {
func sort(outputs: [Output]) -> [Output] {
outputs.sorted(by: Bip69.outputComparator)
}
func sort(unspentOutputs: [UnspentOutput]) -> [UnspentOutput] {
unspentOutputs.sorted(by: Bip69.inputComparator)
}
}
class ShuffleSorter: ITransactionDataSorter {
func sort(outputs: [Output]) -> [Output] {
outputs.shuffled()
}
func sort(unspentOutputs: [UnspentOutput]) -> [UnspentOutput] {
unspentOutputs.shuffled()
}
}
class StraightSorter: ITransactionDataSorter {
func sort(outputs: [Output]) -> [Output] {
outputs
}
func sort(unspentOutputs: [UnspentOutput]) -> [UnspentOutput] {
unspentOutputs
}
}
| 20.638889 | 67 | 0.64603 |
757b4ac1c1f96d84190aae1805a436e18e861aae | 2,968 | //
// ActionsCell.swift
// Heartbeat Messenger
//
// Created by Pushpsen on 30/04/20.
// Copyright © 2020 pushpsen airekar. All rights reserved.
//
import UIKit
class ActionsCell: UITableViewCell {
var presentable = ActionPresentable(name: "", icon: UIImage(named: "more", in: UIKitSettings.bundle, compatibleWith: nil)!)
@IBOutlet weak var name: UILabel!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var fullScreenSwitch: UISwitch!
@IBOutlet weak var badgeCountSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
if let fullScreen = UserDefaults.standard.value(forKey: "fullScreen") as? Int{
if fullScreen == 1 {
fullScreenSwitch.setOn(true, animated: true)
}else{
fullScreenSwitch.setOn(false, animated: true)
}
}else{
fullScreenSwitch.setOn(false, animated: true)
}
if let badgeCount = UserDefaults.standard.value(forKey: "badgeCount") as? Int{
if badgeCount == 1 {
badgeCountSwitch.setOn(true, animated: true)
}else{
badgeCountSwitch.setOn(false, animated: true)
}
}else{
badgeCountSwitch.setOn(false, animated: true)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(with presentable: ActionPresentable) {
self.presentable = presentable
name.text = presentable.name
icon.image = presentable.icon
}
@IBAction func fullScreenSwitchPressed(_ sender: Any) {
if let fullScreen = UserDefaults.standard.value(forKey: "fullScreen") as? Int{
if fullScreen == 1 {
fullScreenSwitch.setOn(false, animated: true)
UserDefaults.standard.set(0, forKey: "fullScreen")
}
if fullScreen == 0 {
fullScreenSwitch.setOn(true, animated: true)
UserDefaults.standard.set(1, forKey: "fullScreen")
}
}else{
fullScreenSwitch.setOn(false, animated: true)
UserDefaults.standard.set(0, forKey: "fullScreen")
}
}
@IBAction func badgeCountSwitchPressed(_ sender: Any) {
if let badgeCount = UserDefaults.standard.value(forKey: "badgeCount") as? Int{
if badgeCount == 1 {
badgeCountSwitch.setOn(false, animated: true)
UserDefaults.standard.set(0, forKey: "badgeCount")
}
if badgeCount == 0 {
badgeCountSwitch.setOn(true, animated: true)
UserDefaults.standard.set(1, forKey: "badgeCount")
}
}else{
badgeCountSwitch.setOn(false, animated: true)
UserDefaults.standard.set(0, forKey: "badgeCount")
}
}
}
| 33.348315 | 127 | 0.600741 |
e2f0fdab9cad10d4992123bcc5146929eeb6feb0 | 7,744 | //
// IndexBar.swift
// Rescue
//
// Created by rainedAllNight on 2020/8/17.
// Copyright © 2020 luowei. All rights reserved.
//
import UIKit
import Hue
public protocol IndexBarDelegate: AnyObject {
func indexBar(_ indexBar: IndexBar, didSelected index: Int)
}
private enum IndexSectionState {
case normal
case selected
}
public struct IndexBarConfigure {
/// section normal title color
public var titleColor: UIColor = UIColor(hex: "#646566")
/// section title font
public var titleFont: UIFont = UIFont.systemFont(ofSize: 12)
/// section selected title color
public var titleColorForSelected: UIColor = UIColor(hex: "#EE0A24")
/// section selected background color
public var backgroundColorForSelected: UIColor = .clear
/// section width&height
public var sectionWH: CGFloat = 16
/// section vertical spacing
public var sectionSpacing: CGFloat = 4
/// show bubble view, default is true
public var showBubble = true
/// the configure of the bubble view
public var bubbleConfigure = BubbleConfigure()
}
public class IndexBar: UIView, UITableViewDelegate {
@IBInspectable private var titleColor: UIColor? {
willSet {
guard let new = newValue else {return}
_configure.titleColor = new
}
}
@IBInspectable private var selectedTitleColor: UIColor? {
willSet {
guard let new = newValue else {return}
_configure.titleColorForSelected = new
}
}
@IBInspectable private var selectedBackgroundColor: UIColor? {
willSet {
guard let new = newValue else {return}
_configure.backgroundColorForSelected = new
}
}
@IBInspectable private var showBubble: Bool = true {
willSet {
_configure.showBubble = newValue
}
}
@IBInspectable private var sectionWH: CGFloat = 0 {
willSet {
_configure.sectionWH = newValue
}
}
@IBInspectable private var sectionSpacing: CGFloat = 0 {
willSet {
_configure.sectionSpacing = newValue
}
}
// if you want to listen the callback of section seleced, please set the delegate(如果想监听切换section的回调可实现此代理)
public weak var delegate: IndexBarDelegate?
/// configure index bar
public var configure: ((inout IndexBarConfigure) -> Void)? {
willSet {
newValue?(&_configure)
initUI()
}
}
private var dataSource = [String]()
private var lastSelectedLabel: UILabel?
private var lastSelectedIndex = -1
private var subLabels = [UILabel]()
private var tableView: UITableView?
private var observe: NSKeyValueObservation?
private var bubbleView: IndexBarBubbleView?
private var _configure = IndexBarConfigure()
// MARK: - Init data
/// Use this function to init data
@objc public func setData(_ titles: [String], tableView: UITableView) {
self.dataSource = titles
self.tableView = tableView
layoutIfNeeded()
initUI()
}
// MARK: - UI
private func initUI() {
backgroundColor = .clear
guard !dataSource.isEmpty else {return}
reset()
let redundantHeight = bounds.height - (_configure.sectionWH + _configure.sectionSpacing) * CGFloat(dataSource.count)
var originY: CGFloat = redundantHeight > 0 ? redundantHeight/2 : 0
dataSource.forEach({
let label = UILabel(frame: CGRect(x: 0, y: originY, width: _configure.sectionWH, height: _configure.sectionWH))
originY += _configure.sectionWH + _configure.sectionSpacing
label.text = $0
label.textAlignment = .center
label.layer.cornerRadius = _configure.sectionWH/2
label.font = _configure.titleFont
setIndexSection(label)
subLabels.append(label)
addSubview(label)
})
/// default select first
selectSection(index: 0)
addObserver()
addBubbleView()
}
private func reset() {
lastSelectedIndex = -1
lastSelectedLabel = nil
subLabels.removeAll()
observe = nil
subviews.forEach({$0.removeFromSuperview()})
}
private func addBubbleView() {
guard _configure.showBubble else {return}
self.bubbleView?.removeFromSuperview()
let bubbleView = IndexBarBubbleView.init(frame: CGRect(x: -80, y: 0, width: 60, height: 60), configure: _configure.bubbleConfigure)
addSubview(bubbleView)
bubbleView.alpha = 0
self.bubbleView = bubbleView
}
private func addObserver() {
observe = tableView?.observe(\.contentOffset, options: .new, changeHandler: { [unowned self] (tableView, change) in
guard let point = change.newValue else {return}
guard let indexPath = tableView.indexPathForRow(at: point), indexPath.section < self.dataSource.count else {return}
guard tableView.isDragging || tableView.isDecelerating else {return}
self.selectSection(index: indexPath.section)
})
}
private func setIndexSection(_ label: UILabel,
with state: IndexSectionState = .normal) {
switch state {
case .normal:
label.textColor = _configure.titleColor
label.layer.backgroundColor = UIColor.clear.cgColor
case.selected:
label.textColor = _configure.titleColorForSelected
label.layer.backgroundColor = _configure.backgroundColorForSelected.cgColor
lastSelectedLabel = label
if let index = subLabels.firstIndex(of: label) {
delegate?.indexBar(self, didSelected: index)
}
}
}
private func selectSection(point: CGPoint) {
guard point.x <= bounds.width,
point.y <= bounds.height,
point.y > 0 else {return}
var index = -1
guard let label = subLabels.first(where: {
index += 1
return point.y < $0.frame.maxY
}) else {return}
if let last = lastSelectedLabel {
setIndexSection(last, with: .normal)
}
setIndexSection(label, with: .selected)
if lastSelectedIndex != index {
addImpactFeedback()
bubbleView?.show(label.text, on: CGPoint(x: bubbleView?.center.x ?? label.center.x, y: label.center.y))
tableView?.scrollToRow(at: IndexPath(item: 0, section: index), at: .top, animated: true)
lastSelectedIndex = index
}
}
private func selectSection(index: Int) {
if let last = lastSelectedLabel {
setIndexSection(last, with: .normal)
}
setIndexSection(subLabels[index], with: .selected)
}
private func addImpactFeedback() {
let impact = UIImpactFeedbackGenerator(style: .light)
impact.prepare()
impact.impactOccurred()
}
// MARK: - Touch Event
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let point = event?.touches(for: self)?.first?.location(in: self) else {return}
selectSection(point: point)
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard let point = event?.touches(for: self)?.first?.location(in: self) else {return}
selectSection(point: point)
bubbleView?.hide()
}
}
| 34.417778 | 139 | 0.631586 |
16a48326ed160607a94948f51a09ef9f5438edb6 | 888 | //
// TileView.swift
// Petulia
//
// Created by Johandre Delgado on 12.12.2020.
// Copyright © 2020 Johandre Delgado . All rights reserved.
//
import SwiftUI
struct TileView: View {
var title = "Pet"
var imagePath = "no-image"
var body: some View {
ZStack(alignment: .bottom) {
Color(UIColor.systemGray6)
.overlay(
AsyncImageView(urlString: imagePath)
.foregroundColor(.accentColor)
.scaledToFill()
)
VStack {
Text(title.prefix(24).capitalized)
.font(.callout)
.fontWeight(.bold)
.minimumScaleFactor(0.8)
.lineLimit(2)
.multilineTextAlignment(.center)
.padding(.horizontal)
}
.frame(maxWidth: .infinity, maxHeight: 50)
.foregroundColor(.white).opacity(0.8)
.background(Color.black.opacity(0.5))
}
}
}
| 22.769231 | 60 | 0.585586 |
62d6172257dc058d466fe409cce3c1cf5084921e | 600 | //
// Recipe.swift
// Recipes
//
// Created by Paweł Brzozowski on 01/02/2022.
//
import Foundation
class Recipe: Identifiable, Decodable {
var id: UUID?
var name: String
var featured: Bool
var image: String
var description: String
var prepTime: String
var cookTime: String
var totalTime: String
var servings: Int
var highlights: [String]
var ingredients: [Ingredient]
var directions: [String]
}
class Ingredient: Identifiable, Decodable {
var id: UUID?
var name: String
var num: Int?
var denom: Int?
var unit: String?
}
| 18.181818 | 46 | 0.65 |
2958d8026dbf052fab981124bc47e5d006b4f0ec | 539 | // Auto-generated code. Do not edit.
import Foundation
// MARK: - RemoveVoteOp
extension Horizon {
public struct RemoveVoteOp: Decodable {
public enum CodingKeys: String, CodingKey {
// attributes
case pollId
}
// MARK: Attributes
public let pollId: Int64
// MARK: -
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.pollId = try container.decode(Int64.self, forKey: .pollId)
}
}
}
| 18.586207 | 71 | 0.621521 |
21d8b600dbecc03d50e63a05e017d054feba3dc4 | 1,261 | //
// DataDriven.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 7/21/20.
// Copyright © 2020 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
// MARK: - AssetData
struct AssetData: GenericAssetData {
var id:String
var type:String
var value:String
var views:[MainViewAsset]
func renderView() -> AnyView {
return views.first?.loadAsset().eraseToAnyView()
?? Color.red.frame(width: 30, height: 30).eraseToAnyView()
}
}
// MARK: - Asset details
struct MainViewAsset:Decodable,Hashable {
var heading:AssetWrapper?
var subHeading:AssetWrapper?
var image:AssetWrapper?
func loadAsset() -> some View {
VStack(alignment: .leading) {
self.heading?.render()
.font(.headline)
self.subHeading?.render()
.font(.subheadline)
self.image?.render()
}
}
}
struct DataDrivenView: View {
var data = JSONLoader.decode(for: JSONLoader.unbox(for: "sample"))
var body: some View {
return loadView(for: data)
}
}
struct DataDrivenView_Previews: PreviewProvider {
static var previews: some View {
DataDrivenView()
}
}
| 22.122807 | 72 | 0.62728 |
91ec216219baaea9571e783498b1961d174f5d17 | 471 | //
// ActionButton.swift
// RNAlertController
//
// Created by Rayhan Nabi on 4/24/19.
// Copyright © 2019 Rayhan. All rights reserved.
//
import UIKit
class ActionButton: NSObject {
let text : String
let action : AlertAction
let type : AlertButtonType
init(text: String, type: AlertButtonType, action: @escaping AlertAction) {
self.text = text
self.action = action
self.type = type
}
}
| 19.625 | 78 | 0.605096 |
38bd2618ea25f3c3418dab60f784e55e455d08e2 | 6,277 | //
// NbaNewsViewController.swift
// relex_swift
//
// Created by Darren on 16/10/18.
// Copyright © 2016年 darren. All rights reserved.
//
import UIKit
import MJRefresh
class NbaNewsViewController: UIViewController {
var dataArray = [nbaModel]()
var timeStr = ""
var str3 = ""
var str4 = ""
var index = 1
/**网络请求失败*/
fileprivate lazy var failedView :requestFailedView = {
let failedView = requestFailedView.show()
failedView.frame = CGRect(x: 0, y: 0, width: APPW, height: APPH-NavHeight)
failedView.myClosure = { () -> Void in
self.setupNBAData(isFooter: false)
}
return failedView
}()
/**tableView*/
lazy var tableView :UITableView = {
let tableView = UITableView(frame:CGRect(x: 0, y: 0, width: APPW, height: APPH-64-49), style: UITableViewStyle.grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 192
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
tableView.showsVerticalScrollIndicator = false
tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(homeHeaderRefresh))
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(homeFootRefresh))
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupNBAData(isFooter: false)
}
// 视图消失时移除通知,不然在下一个页面发送通知这个地方还是可以收到
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
CLNotificationCenter.addObserver(self, selector: #selector(self.RotationIconBeginRotationFunc), name: NSNotification.Name(rawValue: RotationIconBeginRotation), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
CLNotificationCenter.removeObserver(self)
self.tableView.mj_header.endRefreshing()
}
@objc private func RotationIconBeginRotationFunc(){
self.tableView.mj_header.beginRefreshing()
}
deinit {
CLNotificationCenter.removeObserver(self)
}
}
//MARK: - 数据解析
extension NbaNewsViewController{
fileprivate func setupNBAData(isFooter:Bool){
//获取当前时间
let now = NSDate()
let timeInterval:TimeInterval = now.timeIntervalSince1970
let timeStamp = Int(timeInterval)
print("当前时间的时间戳:\(timeStamp)")
self.timeStr = "\(timeStamp)"
self.str3 = "partner=clear"
self.str4 = ""
let str2 = "timestamp"+":"+self.timeStr
let urlStr = "http://platform.sina.com.cn/sports_client/feed?ad=1&pos=nba&sport_tour=nba&__os__=iphone&"+self.str3+"&pdps_params="+str2+"&feed_id=653"+self.str4+"&__version__=3.2.0&client_weibouid=&f=stitle,wapsummary,img,images,comment_show,comment_total,ctime,video_info&client_deviceid=ea636e803fb7ca97ea250f9d6dee1648&app_key=2923419926"
let dict = [String:AnyObject]()
NetTools.shareInstance.getHomeInfo(requestUrl: urlStr, parameters: dict) { (result, error) in
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.failedView.removeFromSuperview()
// 结束通知tabbar结束转动
CLNotificationCenter.post(name: NSNotification.Name(rawValue: refreshIsDidEnd), object: self.index)
// 1.网络请求失败
if error != nil {
if isFooter==false {
self.view.addSubview(self.failedView)
}
return
}
// 2.获取可选类型中的数据
guard let resultArray = result else {
return
}
let dicResult = resultArray["result"] as! NSDictionary
let dicData = dicResult["data"] as! NSDictionary
let dicFeed = dicData["feed"] as! NSDictionary
let dataDic = dicFeed
let dataArr = dataDic["data"] as! NSArray
for item in dataArr {
let model = nbaModel(dict: item as! [String:AnyObject])
self.dataArray.append(model)
}
self.view.addSubview(self.tableView)
self.tableView.reloadData()
}
}
func setupMoreNBA() {
self.str3 = "partner="
let preTime = self.timeStr.hashValue-3600*16 // 加载16小时之前的数据
let s = "\(preTime)"
self.str4 = "&ctime="+s
self.timeStr = s
self.setupNBAData(isFooter: true)
}
// 下拉刷新
func homeHeaderRefresh() {
// 手动下拉时通知tabbar转动
CLNotificationCenter.post(name: NSNotification.Name(rawValue: refreshBegin), object: nil)
setupNBAData(isFooter: false)
}
// 上拉加载
func homeFootRefresh() {
setupMoreNBA()
}
}
//MARK: - UITableViewDelegate,UITableViewDataSource
extension NbaNewsViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = rightTypeOneCell.cellWithTableView(tableView: tableView)
cell.NBAModel = self.dataArray[indexPath.section]
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let webVC = NewsWebViewController()
let nbaModel = dataArray[indexPath.section]
webVC.url = nbaModel.url!
webVC.webTitle = nbaModel.stitle!
webVC.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(webVC, animated: true)
}
}
| 34.300546 | 349 | 0.638681 |
9c3cf29bd5438d0215051f86998226ab50d4017b | 7,120 | //
// EnumSpecification.swift
// Synopsis
//
// Created by incetro on 11/23/20.
// Copyright © 2020 Incetro Inc. All rights reserved.
//
import Foundation
// MARK: - EnumSpecification
public struct EnumSpecification {
// MARK: - Properties
/// Nested enums
public let enums: [EnumSpecification]
/// Nested structs
public let structs: [StructureSpecification]
/// Nested classes
public let classes: [ClassSpecification]
/// Nested protocols
public let protocols: [ProtocolSpecification]
/// Enum comment value
public let comment: String?
/// Enum annotations which are located inside
/// the block comment above the enum declaration.
public let annotations: [AnnotationSpecification]
/// Enum declaration line
public let declaration: Declaration
/// Access visibility
public let accessibility: AccessibilitySpecification
/// Method attributes (like `indirect` etc.)
public let attributes: [AttributeSpecification]
/// Enum name
public let name: String
/// Inherited protocols, classes, structs etc.
public let inheritedTypes: [String]
/// Cases
public let cases: [EnumCaseSpecification]
/// List of enum properties.
public let properties: [PropertySpecification]
/// Enum methods
public let methods: [MethodSpecification]
// MARK: - Initializers
/// Default initializer
/// - Parameters:
/// - comment: enum comment value
/// - annotations: enum annotations
/// - declaration: enum declaration line
/// - accessibility: access visibility
/// - name: enum name
/// - inheritedTypes: inherited protocols, classes, structs etc.
/// - cases: cases
/// - properties: list of enum properties
/// - methods: enum methods
public init(
enums: [EnumSpecification] = [],
structs: [StructureSpecification] = [],
classes: [ClassSpecification] = [],
protocols: [ProtocolSpecification] = [],
comment: String?,
annotations: [AnnotationSpecification],
declaration: Declaration,
accessibility: AccessibilitySpecification,
attributes: [AttributeSpecification],
name: String,
inheritedTypes: [String],
cases: [EnumCaseSpecification],
properties: [PropertySpecification],
methods: [MethodSpecification]
) {
self.enums = enums
self.structs = structs
self.classes = classes
self.protocols = protocols
self.comment = comment
self.annotations = annotations
self.declaration = declaration
self.accessibility = accessibility
self.attributes = attributes
self.name = name
self.inheritedTypes = inheritedTypes
self.cases = cases
self.properties = properties
self.methods = methods
}
// MARK: - Template
/// Make a template enum for later code generation.
public static func template(
comment: String?,
accessibility: AccessibilitySpecification,
attributes: [AttributeSpecification],
name: String,
inheritedTypes: [String],
cases: [EnumCaseSpecification],
properties: [PropertySpecification],
methods: [MethodSpecification]
) -> EnumSpecification {
return EnumSpecification(
comment: comment,
annotations: [],
declaration: Declaration.mock,
accessibility: accessibility,
attributes: attributes,
name: name,
inheritedTypes: inheritedTypes,
cases: cases,
properties: properties,
methods: methods
)
}
}
// MARK: - Specification
extension EnumSpecification: Specification {
public var verse: String {
let enums = self.enums.map(\.verse).joined(separator: "\n\n")
let enumsStr = enums.isEmpty ? "" : "\n\n" + enums
let structs = self.structs.map(\.verse).joined(separator: "\n\n")
let structsStr = structs.isEmpty ? "" : "\n\n" + structs
let classes = self.classes.map(\.verse).joined(separator: "\n\n")
let classesStr = classes.isEmpty ? "" : "\n\n" + classes
let protocols = self.protocols.map(\.verse).joined(separator: "\n\n")
let protocolsStr = protocols.isEmpty ? "" : "\n\n" + protocols
let enumMarkStr = "// MARK: - \(name)\n\n"
let casesMarkStr = "\n\n// MARK: - Cases".indent
let propertiesMarkStr = properties.isEmpty ? "" : "\n// MARK: - Properties\n".indent
let methodsMarkStr = methods.isEmpty ? "" : "\n// MARK: - Useful\n".indent
let commentStr: String
if let commentExpl = comment, !commentExpl.isEmpty {
commentStr = commentExpl.prefixEachLine(with: "/// ") + "\n"
} else {
commentStr = ""
}
let accessibilityStr = accessibility.verse.isEmpty ? "" : "\(accessibility.verse) "
let attributesStr = attributes.filter { [.indirect].contains($0) }.map(\.verse).joined(separator: " ")
let inheritedTypesStr = inheritedTypes.isEmpty ? "" : ": " + inheritedTypes.joined(separator: ", ")
let enumStr = (attributesStr.isEmpty ? "" : " ") + "enum "
let casesStr: String
if cases.isEmpty {
casesStr = ""
} else {
casesStr = cases.reduce("\n") { (result, enumCase) in
if cases.first == enumCase {
return (enumCase.comment == nil ? "\n\n" : "\n") + enumCase.verse.indent + "\n"
}
return result + enumCase.verse.indent + "\n"
}
}
let propertiesStr: String
if properties.isEmpty {
propertiesStr = ""
} else {
propertiesStr = properties.reduce("\n") { (result, property) in
if properties.last == property {
return result + property.verse.indent + "\n"
}
return result + property.verse.indent + "\n\n"
}
}
let methodsStr: String
if methods.isEmpty {
methodsStr = "\n"
} else {
methodsStr = methods.reduce("\n") { (result: String, method: MethodSpecification) -> String in
methods.last == method
? result + method.verse.indent + "\n"
: result + method.verse.indent + "\n\n"
}
}
return "\(enumMarkStr)\(commentStr)"
+ "\(accessibilityStr)\(attributesStr)\(enumStr)\(name)\(inheritedTypesStr) "
+ "{\(enumsStr.indent)\(structsStr.indent)\(classesStr.indent)\(protocolsStr.indent)\(casesMarkStr)\(casesStr)"
+ "\(propertiesMarkStr)\(propertiesStr)"
+ "\(methodsMarkStr)\(methodsStr)}"
}
}
// MARK: - Hashable
extension EnumSpecification: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(verse)
}
}
| 32.511416 | 123 | 0.585393 |
ef69b29b99c9139907ae172b78d0da5f6cd008f1 | 8,657 | //
// BoardView.swift
// game
//
// Created by Peijie Li on 4/30/18.
// Copyright © 2018 Peijie Li. All rights reserved.
//
import UIKit
class BoardView: UIView {
//Step One: Draw the Board
let chessPiecesNumber = 19
var blackorwhite = 1
var chessarray = Array(repeating: Array(repeating: 0, count: 19), count: 19)
var allchessview = Array<UIView>()
var allchessposition = Array<(Int, Int)>()
var textfield = UITextField()
func start() {
self.blackorwhite = 1
var i = 0
var j = 0
while (i < 19) {
while (j < 19) {
self.chessarray[i][j] = 0
j += 1
}
i += 1
}
}
func check_win(positionx: Int, positiony: Int) -> Bool {
//black = 1, white =2
// check horizontal
if (check_win_horizontal(positionx: positionx, positiony: positiony)) {
return true
}
if (check_win_vertical(positionx: positionx, positiony: positiony)) {
return true
}
if (check_win_diagonal(positionx: positionx, positiony: positiony)) {
return true
}
return false
}
func check_win_diagonal(positionx: Int, positiony: Int) -> Bool {
var count = 1
var currx = positionx - 1
var curry = positiony - 1
while (currx >= 0 && curry >= 0 && chessarray[currx][curry] == blackorwhite) {
count += 1
currx = currx - 1
curry = curry - 1
}
if (count >= 5) {
return true
}
currx = positionx + 1
curry = positiony + 1
while (currx < 19 && curry < 19 && chessarray[currx][curry] == blackorwhite) {
count += 1
currx = currx + 1
curry = curry + 1
}
if (count >= 5) {
return true
}
currx = positionx + 1
curry = positiony - 1
count = 1
while (currx < 19 && curry >= 0 && chessarray[currx][curry] == blackorwhite) {
count += 1
currx = currx + 1
curry = curry - 1
}
if (count >= 5) {
return true
}
currx = positionx - 1
curry = positiony + 1
while (currx >= 0 && curry < 19 && chessarray[currx][curry] == blackorwhite) {
count += 1
currx = currx - 1
curry = curry + 1
}
if (count >= 5) {
return true
}
return false
}
func check_win_horizontal(positionx: Int, positiony: Int) -> Bool {
var count = 1
var left = positionx-1
while (left >= 0 && chessarray[left][positiony] == blackorwhite) {
count += 1
if (count >= 5) {
return true
}
left = left - 1
}
var right = positionx + 1
while (right < 19 && chessarray[right][positiony] == blackorwhite) {
count += 1
if (count >= 5) {
return true
}
right = right + 1
}
return false
}
func check_win_vertical(positionx: Int, positiony: Int) -> Bool {
var count = 1
var lower = positiony-1
while (lower >= 0) {
if (chessarray[positionx][lower] == blackorwhite) {
count += 1
if (count >= 5) {
return true
}
lower = lower - 1
} else {
break
}
}
var higher = positiony + 1
while (higher < 19) {
if (chessarray[positionx][higher] == blackorwhite) {
count += 1
if (count >= 5) {
return true
}
higher = higher + 1
} else {
break
}
}
return false
}
func update_turn() {
if (blackorwhite == 1) {
textfield.placeholder = "White Turn"
} else {
textfield.placeholder = "Black Turn"
}
}
func undo() {
allchessview.popLast()?.isHidden = true
update_turn()
var lastaction: (Int, Int)
lastaction = (allchessposition.popLast())!
blackorwhite = chessarray[lastaction.0][lastaction.1]
chessarray[lastaction.0][lastaction.1] = 0
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = UIColor(red: 240.0 / 255.0, green: 211.0 / 255.0, blue: 159.0 / 255.0, alpha: 1.0)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
let boardsize = Double(frame.size.width - 20)
let interval = boardsize / Double(chessPiecesNumber - 1)
context?.setLineWidth(1.0)
for i in 0..<chessPiecesNumber {
context?.move(to: CGPoint(x: 10, y: 10 + interval * Double(i)))
context?.addLine(to: CGPoint(x: boardsize + 10,y: 10 + interval * Double(i)))
context?.strokePath()
}
for i in 0..<chessPiecesNumber {
context?.move(to: CGPoint(x: 10 + interval * Double(i), y: 10))
context?.addLine(to: CGPoint(x: 10 + interval * Double(i), y: boardsize + 10))
context?.strokePath()
}
for i in 0...2{
for j in 0...2{
context?.beginPath()
context?.addArc(center: CGPoint(x:Double(3+6*i)*interval+0.5 * interval-0.5,y:Double(3+6*j)*interval+0.5 * interval-0.5), radius: 3, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
context?.strokePath()
}
}
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapBoard)))
}
func restart() {
chessarray = Array(repeating: Array(repeating: 0, count: 19), count: 19)
// how to init a new view?
for each in subviews {
each.isHidden = true
}
}
@objc func tapBoard(tap: UITapGestureRecognizer) {
let boardsize = Double(frame.size.width - 20)
let interval = boardsize / Double(19 - 1)
//black = 1, white = 2
let point = tap.location(in: tap.view)
var y = Int(floor((Double(lroundf(Float(Double(point.x - 10)/interval))) * interval+2 - 2) / ((386 - 2) / 19)))
var x = Int(floor((Double(lroundf(Float(Double(point.y - 10)/interval))) * interval+2 - 2) / ((386 - 2) / 19)))
if x == 19 {
x = 18
}
if y == 19 {
y = 18
}
if chessarray[x][y] == 0 {
let chessView = UIView()
let chesspoint = CGPoint(x: Double(lroundf(Float(Double(point.x - 10)/interval))) * interval+2, y: Double(lroundf(Float(Double(point.y - 10)/interval))) * interval + 2)
chessView.frame = CGRect(origin: chesspoint,
size: CGSize(width: Double(15), height: Double(15)))
chessView.layer.cornerRadius = 7.5
chessarray[x][y] = blackorwhite
allchessview.append(chessView)
allchessposition.append((x, y))
addSubview(chessView)
update_turn()
if (check_win(positionx: x, positiony: y)) {
restart()
if (blackorwhite == 1) {
let alert = UIAlertView(title: "Black Win", message: "Black has won!", delegate: self, cancelButtonTitle: "Restart")
alert.show()
} else {
let alert = UIAlertView(title: "White Win", message: "White has won!", delegate: self, cancelButtonTitle: "Restart")
alert.show()
}
// restart and set blackorwhite to 1
blackorwhite = 1
} else {
if blackorwhite == 1{
chessView.backgroundColor = UIColor.black
blackorwhite = 2
}else{
chessView.backgroundColor = UIColor.white
blackorwhite = 1
}
}
}else{
let alert = UIAlertView(title: "Error", message: "Position already been taken", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
}
}
| 31.827206 | 212 | 0.483308 |
fe269d87d082bce069a4a408a61b2a3ad55e9d00 | 2,980 | import AppArchitecture
import ComposableArchitecture
import Utility
import Types
// MARK: - State
public struct BlockerState: Equatable {
public var locationAlways: LocationAlwaysPermissions
public var pushStatus: PushStatus
public init(locationAlways: LocationAlwaysPermissions, pushStatus: PushStatus) {
self.locationAlways = locationAlways; self.pushStatus = pushStatus
}
}
// MARK: - Action
public enum BlockerAction: Equatable {
case openSettings
case requestWhenInUseLocationPermissions
case requestAlwaysLocationPermissions
case requestMotionPermissions
case requestPushAuthorization
case userHandledPushAuthorization
case statusUpdated(SDKStatusUpdate)
}
// MARK: - Environment
public struct BlockerEnvironment {
public var openSettings: () -> Effect<Never, Never>
public var requestAlwaysLocationPermissions: () -> Effect<Never, Never>
public var requestPushAuthorization: () -> Effect<Void, Never>
public var requestWhenInUseLocationPermissions: () -> Effect<Never, Never>
public var requestMotionPermissions: () -> Effect<SDKStatusUpdate, Never>
public init(
openSettings: @escaping () -> Effect<Never, Never>,
requestAlwaysLocationPermissions: @escaping () -> Effect<Never, Never>,
requestPushAuthorization: @escaping () -> Effect<Void, Never>,
requestWhenInUseLocationPermissions: @escaping () -> Effect<Never, Never>,
requestMotionPermissions: @escaping () -> Effect<SDKStatusUpdate, Never>
) {
self.openSettings = openSettings
self.requestAlwaysLocationPermissions = requestAlwaysLocationPermissions
self.requestPushAuthorization = requestPushAuthorization
self.requestWhenInUseLocationPermissions = requestWhenInUseLocationPermissions
self.requestMotionPermissions = requestMotionPermissions
}
}
// MARK: - Reducer
public let blockerReducer = Reducer<
BlockerState,
BlockerAction,
SystemEnvironment<BlockerEnvironment>
> { state, action, environment in
switch action {
case .openSettings:
return environment.openSettings().fireAndForget()
case .requestWhenInUseLocationPermissions:
return environment.requestWhenInUseLocationPermissions().fireAndForget()
case .requestAlwaysLocationPermissions:
state.locationAlways = .requestedAfterWhenInUse
return environment.requestAlwaysLocationPermissions().fireAndForget()
case .requestMotionPermissions:
return environment.requestMotionPermissions()
.receive(on: environment.mainQueue)
.eraseToEffect()
.map(BlockerAction.statusUpdated)
case .requestPushAuthorization:
state.pushStatus = .dialogSplash(.waitingForUserAction)
return environment.requestPushAuthorization()
.receive(on: environment.mainQueue)
.map(constant(BlockerAction.userHandledPushAuthorization))
.eraseToEffect()
case .userHandledPushAuthorization:
state.pushStatus = .dialogSplash(.shown)
return .none
case .statusUpdated:
return .none
}
}
| 33.111111 | 82 | 0.773826 |
5da53b4b11e6342325e74919b9e847ea5e6321f0 | 524 | //
// Scenario.swift
// UpdraftUITests
//
// Created by David Weiss on 1/23/18.
// Copyright © 2018 David Weiss. All rights reserved.
//
// based on: https://github.com/kylef/Ploughman
import Foundation
public struct Scenario {
public let name: String
public var steps: [Step]
public let file: URL
public let line: Int
init(name: String, steps: [Step], file: URL, line: Int) {
self.name = name
self.steps = steps
self.file = file
self.line = line
}
}
| 20.153846 | 61 | 0.610687 |
757e8edca44dfd5b58a6f219dc0cfa990c32f8d8 | 7,256 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Synth Audio Unit - should be converted to an InternalAU
public class SynthAudioUnit: AudioUnitBase {
var masterVolume: AUParameter!
var pitchBend: AUParameter!
var vibratoDepth: AUParameter!
var filterCutoff: AUParameter!
var filterStrength: AUParameter!
var filterResonance: AUParameter!
var attackDuration: AUParameter!
var decayDuration: AUParameter!
var sustainLevel: AUParameter!
var releaseDuration: AUParameter!
var filterAttackDuration: AUParameter!
var filterDecayDuration: AUParameter!
var filterSustainLevel: AUParameter!
var filterReleaseDuration: AUParameter!
/// Create the synth DSP
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
return akSynthCreateDSP()
}
override init(componentDescription: AudioComponentDescription,
options: AudioComponentInstantiationOptions = []) throws {
try super.init(componentDescription: componentDescription, options: options)
let nonRampFlags: AudioUnitParameterOptions = [.flag_IsReadable, .flag_IsWritable]
var parameterAddress: AUParameterAddress = 0
masterVolume = AUParameter(
identifier: "masterVolume",
name: "Master Volume",
address: parameterAddress,
range: 0.0...1.0,
unit: .generic,
flags: .default)
parameterAddress += 1
pitchBend = AUParameter(
identifier: "pitchBend",
name: "Pitch Offset (semitones)",
address: parameterAddress,
range: -1_000.0...1_000.0,
unit: .relativeSemiTones,
flags: .default)
parameterAddress += 1
vibratoDepth = AUParameter(
identifier: "vibratoDepth",
name: "Vibrato amount (semitones)",
address: parameterAddress,
range: 0.0...24.0,
unit: .relativeSemiTones,
flags: .default)
parameterAddress += 1
filterCutoff = AUParameter(
identifier: "filterCutoff",
name: "Filter cutoff (harmonic))",
address: parameterAddress,
range: 1.0...1_000.0,
unit: .ratio,
flags: .default)
parameterAddress += 1
filterStrength = AUParameter(
identifier: "filterStrength",
name: "Filter EG strength",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .ratio,
flags: .default)
parameterAddress += 1
filterResonance = AUParameter(
identifier: "filterResonance",
name: "Filter resonance (dB))",
address: parameterAddress,
range: -20.0...20.0,
unit: .decibels,
flags: .default)
parameterAddress += 1
attackDuration = AUParameter(
identifier: "attackDuration",
name: "Amplitude Attack duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterAddress += 1
decayDuration = AUParameter(
identifier: "decayDuration",
name: "Amplitude Decay duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterAddress += 1
sustainLevel = AUParameter(
identifier: "sustainLevel",
name: "Amplitude Sustain level (fraction)",
address: parameterAddress,
range: 0.0...1.0,
unit: .generic,
flags: nonRampFlags)
parameterAddress += 1
releaseDuration = AUParameter(
identifier: "releaseDuration",
name: "Amplitude Release duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterAddress += 1
filterAttackDuration = AUParameter(
identifier: "filterAttackDuration",
name: "Filter Attack duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterAddress += 1
filterDecayDuration = AUParameter(
identifier: "filterDecayDuration",
name: "Filter Decay duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterAddress += 1
filterSustainLevel = AUParameter(
identifier: "filterSustainLevel",
name: "Filter Sustain level (fraction)",
address: parameterAddress,
range: 0.0...1.0,
unit: .generic,
flags: nonRampFlags)
parameterAddress += 1
filterReleaseDuration = AUParameter(
identifier: "filterReleaseDuration",
name: "Filter Release duration (seconds)",
address: parameterAddress,
range: 0.0...1_000.0,
unit: .seconds,
flags: nonRampFlags)
parameterTree = AUParameterTree.createTree(withChildren: [
masterVolume,
pitchBend,
vibratoDepth,
filterCutoff,
filterStrength,
filterResonance,
attackDuration,
decayDuration,
sustainLevel,
releaseDuration,
filterAttackDuration,
filterDecayDuration,
filterSustainLevel,
filterReleaseDuration
])
masterVolume.value = 1.0
pitchBend.value = 0.0
vibratoDepth.value = 0.0
filterCutoff.value = 4.0
filterStrength.value = 20.0
filterResonance.value = 0.0
attackDuration.value = 0.0
decayDuration.value = 0.0
sustainLevel.value = 1.0
releaseDuration.value = 0.0
filterAttackDuration.value = 0.0
filterDecayDuration.value = 0.0
filterSustainLevel.value = 1.0
filterReleaseDuration.value = 0.0
}
/// Play a note
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
/// - frequency: Frequency
public func playNote(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
frequency: Float) {
akSynthPlayNote(dsp, noteNumber, velocity, frequency)
}
/// Stop a note
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - immediate: Stop and allow to release or stop immediately
public func stopNote(noteNumber: MIDINoteNumber, immediate: Bool) {
akSynthStopNote(dsp, noteNumber, immediate)
}
/// Set the sustain pedal position
/// - Parameter down: True for pedal activation
public func sustainPedal(down: Bool) {
akSynthSustainPedal(dsp, down)
}
}
| 29.495935 | 100 | 0.580899 |
f8c9fa21b199ede14918ff646539e7facd7968ca | 1,208 | //
// PersonPhoneTest.swift
// PersonTests
//
import XCTest
@testable import Example
class Person_mock: Person {
var checkInternetConnectionCount: Int = 0
var downloadAppCount: Int = 0
var downloadAppValue: Bool = true
override func checkInternetConnection() {
checkInternetConnectionCount += 1
}
override func downloadApp() -> Bool {
downloadAppCount += 1
return downloadAppValue
}
}
class PhoneTest: XCTestCase {
func test_internet_connection() {
//Arrange
let person = Person_mock(firstName: "Jack", lastName: "Blum", yearBirth: 1990)
let phone = Phone(phoneOwner: person)
//Act
phone.checkInternetConnection()
//Assert
XCTAssertTrue(person.checkInternetConnectionCount == 1)
}
func test_downloading_app(){
//Arrange
let person = Person_mock(firstName: "Jack", lastName: "Blum", yearBirth: 1990)
let phone = Phone(phoneOwner: person)
//Act
person.downloadAppValue = true
let result = phone.downloadApp()
//Assert
XCTAssertTrue(result)
XCTAssertTrue(person.downloadAppCount == 1)
}
}
| 23.230769 | 86 | 0.633278 |
48c20e6ce86962832345278d46acff26d126a91c | 2,752 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Records movies using AVAssetWriter.
*/
import Foundation
import AVFoundation
class MovieRecorder {
private var assetWriter: AVAssetWriter?
private var assetWriterVideoInput: AVAssetWriterInput?
private var assetWriterAudioInput: AVAssetWriterInput?
private var videoTransform: CGAffineTransform
private var videoSettings: [String: Any]
private var audioSettings: [String: Any]
private(set) var isRecording = false
init(audioSettings: [String: Any], videoSettings: [String: Any], videoTransform: CGAffineTransform) {
self.audioSettings = audioSettings
self.videoSettings = videoSettings
self.videoTransform = videoTransform
}
func startRecording() {
// Create an asset writer that records to a temporary file
let outputFileName = NSUUID().uuidString
let outputFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(outputFileName).appendingPathExtension("MOV")
guard let assetWriter = try? AVAssetWriter(url: outputFileURL, fileType: .mov) else {
return
}
// Add an audio input
let assetWriterAudioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioSettings)
assetWriterAudioInput.expectsMediaDataInRealTime = true
assetWriter.add(assetWriterAudioInput)
// Add a video input
let assetWriterVideoInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
assetWriterVideoInput.expectsMediaDataInRealTime = true
assetWriterVideoInput.transform = videoTransform
assetWriter.add(assetWriterVideoInput)
self.assetWriter = assetWriter
self.assetWriterAudioInput = assetWriterAudioInput
self.assetWriterVideoInput = assetWriterVideoInput
isRecording = true
}
func stopRecording(completion: @escaping (URL) -> Void) {
guard let assetWriter = assetWriter else {
return
}
self.isRecording = false
self.assetWriter = nil
assetWriter.finishWriting {
completion(assetWriter.outputURL)
}
}
func recordVideo(sampleBuffer: CMSampleBuffer) {
guard isRecording,
let assetWriter = assetWriter else {
return
}
if assetWriter.status == .unknown {
assetWriter.startWriting()
assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))
} else if assetWriter.status == .writing {
if let input = assetWriterVideoInput,
input.isReadyForMoreMediaData {
input.append(sampleBuffer)
}
}
}
func recordAudio(sampleBuffer: CMSampleBuffer) {
guard isRecording,
let assetWriter = assetWriter,
assetWriter.status == .writing,
let input = assetWriterAudioInput,
input.isReadyForMoreMediaData else {
return
}
input.append(sampleBuffer)
}
}
| 27.247525 | 135 | 0.768169 |
094b511f2f4bf5d7c1c2bb3e568a7c83108c38dc | 1,565 | import UIKit
class SavedVideos: UIView {
lazy var videoCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize.init(width: 200, height: Constants.savedVideoCollectionViewCellNonExpandedHeight)
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
let cv = UICollectionView.init(frame: UIScreen.main.bounds, collectionViewLayout: layout)
cv.backgroundColor = Constants.perceptionNavyColor
return cv
}()
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
commonInit()
}
func commonInit() {
backgroundColor = Constants.perceptionNavyColor
addSubview(videoCollectionView)
videoCollectionView.register(FavoriteCollectionCell.self, forCellWithReuseIdentifier: "FavoriteCell")
cvConstrains()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func cvConstrains() {
videoCollectionView.translatesAutoresizingMaskIntoConstraints = false
[videoCollectionView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), videoCollectionView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor), videoCollectionView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor), videoCollectionView.bottomAnchor.constraint(equalTo: bottomAnchor)]
.forEach{$0.isActive = true }
}
}
| 40.128205 | 340 | 0.715655 |
905688df5dd72418ad81c9def96fde5239bd5850 | 262 | import Foundation
public struct Redirect: Equatable {
public let ipAddress: String
public let port: UInt16
}
extension Redirect: CustomStringConvertible {
public var description: String {
"{IP Address: \(ipAddress), Port: \(port)}"
}
}
| 20.153846 | 51 | 0.687023 |
d75bc8bd380e1b1698f6f03061bbbd45f3ec92c9 | 843 | //
// SplashView.swift
// CWSDKExample
//
// Created by Sergey Muravev on 12.04.2022.
//
import SwiftUI
struct SplashView: View {
var body: some View {
VStack {
Spacer()
ProgressView()
.progressViewStyle(CircularProgressViewStyle())
Spacer()
HStack {
Spacer()
Text("v\(AppEnvironment.buildConfig.versionName)")
.font(.footnote)
.foregroundColor(Color.secondary)
}
.padding(.vertical)
}
.padding(.horizontal)
}
}
#if DEBUG
struct SplashView_Previews: PreviewProvider {
static var previews: some View {
let appEnvironment = AppEnvironment()
return SplashView()
.environmentObject(appEnvironment)
}
}
#endif
| 20.071429 | 66 | 0.54567 |
299a89511fc081da452bec29b06477d2b5fdb3db | 2,989 | //
// SmallAnimator.swift
// AppStoreToday
//
// Created by ljb48229 on 2017/11/30.
// Copyright © 2017年 ljb48229. All rights reserved.
//
import UIKit
class SmallAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from) as! DetailViewController
let toViewController = transitionContext.viewController(forKey: .to) as! UITabBarController
let containerView = transitionContext.containerView
let fromView = transitionContext.view(forKey: .from)
let toView = transitionContext.view(forKey: .to)
fromView?.layer.cornerRadius = 20
fromView?.layer.masksToBounds = true
let todayVC = toViewController.childViewControllers[0] as! TodayController
var H: CGFloat
if ISIPHONE_X() {
H = UIScreen.main.bounds.height - 83
} else {
H = UIScreen.main.bounds.height - 49
}
if (fromViewController.cellRect?.maxY)! > H {
print("大")
containerView.insertSubview(toView!, at: 0)
toView?.addSubview(fromView!)
} else {
print("小")
containerView.insertSubview(toView!, belowSubview: fromView!)
}
let tabBar = toViewController.tabBar
containerView.addSubview(tabBar)
tabBar.frame = CGRect(x: 0, y: UIScreen.main.bounds.height, width: tabBar.frame.width, height: tabBar.frame.height)
UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: {
var tabFrame = tabBar.frame
print("last \(tabFrame)")
tabFrame.origin.y = tabFrame.minY - tabFrame.height
tabBar.frame = tabFrame
print("last \(tabBar.frame)")
}) { (_) in
}
let transitionDuration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: transitionDuration, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {
fromView?.frame = CGRect(x: (fromViewController.cellRect?.origin.x)! + 10, y: (fromViewController.cellRect?.origin.y)! + 10, width: (fromViewController.cellRect?.width)! - 20, height: (fromViewController.cellRect?.height)! - 20)
print(fromView?.frame)
}) { (_) in
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dissmissOver"), object: nil)
fromView?.removeFromSuperview()
let wasCancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!wasCancelled)
}
}
}
| 40.391892 | 240 | 0.643694 |
4b0dd20f290c3ae6d29e436a0f8b8353b35f7674 | 2,288 | //
// NetworkService.swift
// WonderfullIndonesia
//
// Created by ArifRachman on 08/01/22.
// Copyright © 2022 AriifRach. All rights reserved.
//
import Foundation
import Alamofire
import Moya
import ObjectMapper
import RxSwift
import SystemConfiguration.CaptiveNetwork
final class NetworkService {
static let shared = NetworkService()
static func getNetworkManager() -> Alamofire.SessionManager {
#if DEVELOPMENT || NETFOX
return NetfoxService.sharedManager
#else
let configuration = URLSessionConfiguration.default
return Alamofire.SessionManager(configuration: configuration)
#endif
}
func connect<T: Mappable>(api: BaseApi, mappableType: T.Type) -> Observable<T> {
let networkManager = NetworkService.getNetworkManager()
let provider = MoyaProvider<BaseApi>(endpointClosure: api.endpointClosure, manager: networkManager)
let subject = ReplaySubject<T>.createUnbounded()
// queue.addOperation {
provider.request(api) { (result) in
switch result {
case .success(let value):
do {
guard let jsonResponse = try value.mapJSON() as? [String: Any] else {
subject.onError(ApiError.invalidJSONError)
return
}
if let success = jsonResponse["status"] as? String {
if success != "ok" {
subject.onError(ApiError.middlewareError(code: value.statusCode, message: jsonResponse["message"] as? String))
return
}
} else if let resultMessage = jsonResponse["resultMessage"] as? String {
if resultMessage != "success" {
subject.onError(ApiError.middlewareError(code: value.statusCode, message: jsonResponse["message"] as? String))
return
}
}
let map = Map(mappingType: .fromJSON, JSON: jsonResponse)
guard let responseObject = mappableType.init(map: map) else {
subject.onError(ApiError.failedMappingError)
return
}
subject.onNext(responseObject)
subject.onCompleted()
} catch {
subject.onError(ApiError.invalidJSONError)
}
case .failure:
subject.onError(ApiError.connectionError)
}
}
return subject
}
}
| 30.918919 | 124 | 0.648601 |
69d31d712719ad7b053fb6aab857c53f6d9498c5 | 54,035 | //
// PlaylistViewController.swift
// Helium
//
// Created by Carlos D. Santiago on 2/15/17.
// Copyright (c) 2017 Carlos D. Santiago. All rights reserved.
//
import Foundation
import AVFoundation
import AudioToolbox
class PlayTableView : NSTableView {
override func keyDown(with event: NSEvent) {
if event.charactersIgnoringModifiers! == String(Character(UnicodeScalar(NSDeleteCharacter)!)) ||
event.charactersIgnoringModifiers! == String(Character(UnicodeScalar(NSDeleteFunctionKey)!)) {
// Take action in the delegate.
let delegate: PlaylistViewController = self.delegate as! PlaylistViewController
delegate.removePlaylist(self)
}
else
{
// still here?
super.keyDown(with: event)
}
}
override func mouseDragged(with event: NSEvent) {
let dragPosition = self.convert(event.locationInWindow, to: nil)
let imageLocation = NSMakeRect(dragPosition.x - 16.0, dragPosition.y - 16.0, 32.0, 32.0)
_ = self.dragPromisedFiles(ofTypes: ["h3w"], from: imageLocation, source: self, slideBack: true, event: event)
}
override func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
return .copy
}
override func dragImageForRows(with dragRows: IndexSet, tableColumns: [NSTableColumn], event dragEvent: NSEvent, offset dragImageOffset: NSPointPointer) -> NSImage {
return NSApp.applicationIconImage.resize(w: 32, h: 32)
}
override func draggingEntered(_ info: NSDraggingInfo) -> NSDragOperation {
let pasteboard = info.draggingPasteboard()
if pasteboard.canReadItem(withDataConformingToTypes: [NSPasteboardURLReadingFileURLsOnlyKey]) {
return .copy
}
return .copy
}
func tableViewColumnDidResize(notification: NSNotification ) {
// Pay attention to column resizes and aggressively force the tableview's cornerview to redraw.
self.cornerView?.needsDisplay = true
}
}
class PlayItemCornerView : NSView {
@IBOutlet weak var playlistArrayController: NSArrayController!
@IBOutlet weak var playitemArrayController: NSArrayController!
@IBOutlet weak var playitemTableView: PlayTableView!
var shiftKeyDown: Bool {
get {
return (NSApp.delegate as! AppDelegate).shiftKeyDown
}
}
var menuIconName: String {
get {
if shiftKeyDown {
return "NSTouchBarSearchTemplate"
}
else
{
return "NSRefreshTemplate"
}
}
}
override func draw(_ dirtyRect: NSRect) {
let tote = NSImage.init(imageLiteralResourceName: self.menuIconName)
let alignRect = tote.alignmentRect
NSGraphicsContext.saveGraphicsState()
tote.draw(in: NSMakeRect(2, 5, 7, 11), from: alignRect, operation: .sourceOver, fraction: 1)
NSGraphicsContext.restoreGraphicsState()
}
override func mouseDown(with event: NSEvent) {
// Renumber playlist items via array controller
playitemTableView.beginUpdates()
// True - prune duplicates, false resequence
switch shiftKeyDown {
case true:
var seen = [String:PlayItem]()
for (row,item) in (playitemArrayController.arrangedObjects as! [PlayItem]).enumerated().reversed() {
if seen[item.name] == nil {
seen[item.name] = item
}
else
{
(self.window?.contentViewController as! PlaylistViewController).removePlay(item, atIndex: row)
}
}
self.setNeedsDisplay(self.frame)
break
case false:
for (row,item) in (playitemArrayController.arrangedObjects as! [PlayItem]).enumerated() {
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: { [oldValue = item.rank] (PlaylistViewController) -> () in
(item as AnyObject).setValue(oldValue, forKey: "rank")
if !undo.isUndoing {
undo.setActionName(String.init(format: "Reseq %@", "rank"))
}
})
}
item.rank = row + 1
}
}
playitemTableView.endUpdates()
}
}
class PlayHeaderView : NSTableHeaderView {
override func menu(for event: NSEvent) -> NSMenu? {
let action = #selector(PlaylistViewController.toggleColumnVisiblity(_ :))
let target = self.tableView?.delegate
let menu = NSMenu.init()
var item: NSMenuItem
// We auto enable items as views present them
menu.autoenablesItems = true
// TableView level column customizations
for col in (self.tableView?.tableColumns)! {
let title = col.headerCell.stringValue
let state = col.isHidden
item = NSMenuItem.init(title: title, action: action, keyEquivalent: "")
item.image = NSImage.init(named: (state) ? "NSOnImage" : "NSOffImage")
item.state = (state ? NSOffState : NSOnState)
item.representedObject = col
item.isEnabled = true
item.target = target
menu.addItem(item)
}
return menu
}
}
extension NSURL {
func compare(_ other: URL ) -> ComparisonResult {
return (self.absoluteString?.compare(other.absoluteString))!
}
// https://stackoverflow.com/a/44908669/564870
func resolvedFinderAlias() -> URL? {
if (self.fileReferenceURL() != nil) { // item exists
do {
// Get information about the file alias.
// If the file is not an alias files, an exception is thrown
// and execution continues in the catch clause.
let data = try NSURL.bookmarkData(withContentsOf: self as URL)
// NSURLPathKey contains the target path.
let rv = NSURL.resourceValues(forKeys: [ URLResourceKey.pathKey ], fromBookmarkData: data)
var urlString = rv![URLResourceKey.pathKey] as! String
if !urlString.hasPrefix("file://") {
urlString = "file://" + urlString
}
return URL(string: urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
} catch {
// We know that the input path exists, but treating it as an alias
// file failed, so we assume it's not an alias file so return nil.
return nil
}
}
return nil
}
}
class PlaylistViewController: NSViewController,NSTableViewDataSource,NSTableViewDelegate,NSMenuDelegate,NSWindowDelegate {
@IBOutlet var playlistArrayController: NSArrayController!
@IBOutlet var playitemArrayController: NSArrayController!
@IBOutlet var playlistTableView: PlayTableView!
@IBOutlet var playitemTableView: PlayTableView!
@IBOutlet var playlistSplitView: NSSplitView!
// cache playlists read and saved to defaults
var appDelegate: AppDelegate = NSApp.delegate as! AppDelegate
var defaults = UserDefaults.standard
// delegate keeps our parsing dict to keeps names unique
// PlayList.name.willSet will track changes in playdicts
dynamic var playlists : [PlayList] {
get {
return appDelegate.playlists
}
set (array) {
appDelegate.playlists = array
}
}
dynamic var playCache = [PlayList]()
// MARK:- Undo
// keys to watch for undo: PlayList and PlayItem
var listIvars : [String] {
get {
return ["name", "list"]
}
}
var itemIvars : [String] {
get {
return ["name", "link", "time", "rank", "rect", "label", "hover", "alpha", "trans", "temp"]
}
}
internal func observe(_ item: AnyObject, keyArray keys: [String], observing state: Bool) {
switch state {
case true:
for keyPath in keys {
item.addObserver(self, forKeyPath: keyPath, options: [.old,.new], context: nil)
}
break
case false:
for keyPath in keys {
item.removeObserver(self, forKeyPath: keyPath)
}
}
// Swift.print("%@ -> %@", item.className, (state ? "YES" : "NO"))
}
// Start or forget observing any changes
internal func setObserving(_ state: Bool) {
if state {
NotificationCenter.default.addObserver(
self,
selector: #selector(shiftKeyDown(_:)),
name: NSNotification.Name(rawValue: "shiftKeyDown"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(gotNewHistoryItem(_:)),
name: NSNotification.Name(rawValue: k.item),
object: nil)
}
else
{
NotificationCenter.default.removeObserver(self)
}
self.observe(self, keyArray: [k.Playlists], observing: state)
for playlist in playlists {
self.observe(playlist, keyArray: listIvars, observing: state)
for item in playlist.list {
self.observe(item, keyArray: itemIvars, observing: state)
}
}
}
internal func shiftKeyDown(_ note: Notification) {
if let pcv : PlayItemCornerView = playitemTableView.cornerView as? PlayItemCornerView {
DispatchQueue.main.async {
pcv.setNeedsDisplay(pcv.bounds)
}
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let oldValue = change?[NSKeyValueChangeKey(rawValue: "old")]
let newValue = change?[NSKeyValueChangeKey(rawValue: "new")]
switch keyPath {
case k.Playlists?, k.list?:
// arrays handled by [add,remove]<List,Play> callback closure block
if (newValue != nil) {
Swift.print(String.init(format: "%p:%@ + %@", object! as! CVarArg, keyPath!, newValue as! CVarArg))
}
else
if (oldValue != nil) {
Swift.print(String.init(format: "%p:%@ - %@", object! as! CVarArg, keyPath!, oldValue as! CVarArg))
}
else
{
Swift.print(String.init(format: "%p:%@ ? %@", object! as! CVarArg, keyPath!, "*no* values?"))
}
break
default:
if let undo = self.undoManager {
// scalars handled here with its matching closure block
undo.registerUndo(withTarget: self, handler: { [oldValue] (PlaylistViewController) -> () in
(object as AnyObject).setValue(oldValue, forKey: keyPath!)
if !undo.isUndoing {
undo.setActionName(String.init(format: "Edit %@", keyPath!))
}
})
Swift.print(String.init(format: "%@ %@ -> %@", keyPath!, oldValue as! CVarArg, newValue as! CVarArg))
}
break
}
}
// A bad (duplicate) value was attempted
@objc fileprivate func badPlayLitName(_ notification: Notification) {
DispatchQueue.main.async {
self.playlistTableView.reloadData()
NSSound(named: "Sosumi")?.play()
}
}
var canRedo : Bool {
if let redo = self.undoManager {
return redo.canRedo
}
else
{
return false
}
}
@IBAction func redo(_ sender: Any) {
if let undo = self.undoManager, undo.canRedo {
undo.redo()
Swift.print("redo:");
}
}
var canUndo : Bool {
if let undo = self.undoManager {
return undo.canUndo
}
else
{
return false
}
}
@IBAction func undo(_ sender: Any) {
if let undo = self.undoManager, undo.canUndo {
undo.undo()
Swift.print("undo:");
}
}
// MARK:- View lifecycle
fileprivate func setupHiddenColumns(_ tableView: NSTableView, hideit: [String]) {
let table : String = tableView.identifier!
for col in tableView.tableColumns {
let column = col.identifier
let pref = String(format: "hide.%@.%@", table, column)
var isHidden = false
// If have a preference, honor it, else apply hidden default
if defaults.value(forKey: pref) != nil
{
isHidden = defaults.bool(forKey: pref)
hiddenColumns[pref] = String(isHidden)
}
else
if hideit.contains(column)
{
isHidden = true
}
col.isHidden = isHidden
}
}
override func viewDidLoad() {
let types = [kUTTypeData as String,
kUTTypeURL as String,
kUTTypeFileURL as String,
PlayList.className(),
PlayItem.className(),
NSFilenamesPboardType,
NSFilesPromisePboardType,
NSURLPboardType]
playlistTableView.register(forDraggedTypes: types)
playitemTableView.register(forDraggedTypes: types)
playlistTableView.doubleAction = #selector(playPlaylist(_:))
playitemTableView.doubleAction = #selector(playPlaylist(_:))
// Load playlists shared by all document; our delegate maintains history
self.restorePlaylists(nil)
// Restore hidden columns in tableviews using defaults
setupHiddenColumns(playlistTableView, hideit: ["date"])
setupHiddenColumns(playitemTableView, hideit: ["date","link","rect","label","hover","alpha","trans"])
}
var historyCache: PlayList = PlayList.init(name: UserSettings.HistoryName.value,
list: [PlayItem]())
override func viewWillAppear() {
// update existing history entry if any AVQueuePlayer
// Do not allow duplicate history entries
while let oldHistory = appDelegate.playlists.item(UserSettings.HistoryName.value)
{
playlistArrayController.removeObject(oldHistory)
}
historyCache = PlayList.init(name: UserSettings.HistoryName.value,
list: appDelegate.histories)
playlistArrayController.addObject(historyCache)
// cache our list before editing
playCache = playlists
// Reset split view dimensions
self.playlistSplitView.setPosition(120, ofDividerAt: 0)
// Watch for bad (duplicate) playlist names
NotificationCenter.default.addObserver(
self,
selector: #selector(badPlayLitName(_:)),
name: NSNotification.Name(rawValue: "BadPlayListName"),
object: nil)
// Start observing any changes
self.setObserving(true)
}
func windowShouldClose(_ sender: Any) -> Bool {
// We didn't dismiss but so undo observing now
if let window : NSWindow = sender as? NSWindow, let index = appDelegate.playlistWindows.index(of: window) {
let pvc = window.contentViewController as! PlaylistViewController
pvc.setObserving(false)
appDelegate.playlistWindows.remove(at: index)
}
return true
}
// MARK:- Playlist Actions
//
// internal are also used by undo manager callback and by IBActions
//
// Since we do *not* undo movements, we remove object *not* by their index
// but use their index to update the controller scrolling only initially.
// "Play" items are individual PlayItem items, part of a playlist
internal func addPlay(_ item: PlayItem, atIndex p_index: Int) {
var index = p_index
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: {[oldVals = ["item": item, "index": index] as [String : Any]] (PlaylistViewController) -> () in
self.removePlay(oldVals["item"] as! PlayItem, atIndex: oldVals["index"] as! Int)
if !undo.isUndoing {
undo.setActionName("Add PlayItem")
}
})
}
observe(item, keyArray: itemIvars, observing: true)
if index > 0 && index < (playitemArrayController.arrangedObjects as! [PlayItem]).count {
playitemArrayController.insert(item, atArrangedObjectIndex: index)
}
else
{
playitemArrayController.addObject(item)
playitemArrayController.rearrangeObjects()
let row = playitemTableView.selectedRow
if row >= 0 {
index = row
}
else
{
index = (playitemArrayController.arrangedObjects as! [PlayItem]).count
}
}
DispatchQueue.main.async {
self.playitemTableView.scrollRowToVisible(index)
}
}
internal func removePlay(_ item: PlayItem, atIndex p_index: Int) {
var index = p_index
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: {[oldVals = ["item": item, "index": index] as [String : Any]] (PlaylistViewController) -> () in
self.addPlay(oldVals["item"] as! PlayItem, atIndex: oldVals["index"] as! Int)
if !undo.isUndoing {
undo.setActionName("Remove PlayItem")
}
})
}
observe(item, keyArray: itemIvars, observing: false)
playitemArrayController.removeObject(item)
let row = playitemTableView.selectedRow
if row >= 0 {
index = row
}
else
{
index = max(0,min(index,(playitemArrayController.arrangedObjects as! [PlayItem]).count))
}
DispatchQueue.main.async {
self.playitemTableView.scrollRowToVisible(index)
}
}
// "List" items are PlayList objects
internal func addList(_ item: PlayList, atIndex p_index: Int) {
var index = p_index
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: {[oldVals = ["item": item, "index": index] as [String : Any]] (PlaylistViewController) -> () in
self.removeList(oldVals["item"] as! PlayList, atIndex: oldVals["index"] as! Int)
if !undo.isUndoing {
undo.setActionName("Add PlayList")
}
})
}
observe(item, keyArray: listIvars, observing: true)
if index > 0 && index < (playlistArrayController.arrangedObjects as! [PlayItem]).count {
playlistArrayController.insert(item, atArrangedObjectIndex: index)
}
else
{
playlistArrayController.addObject(item)
playlistArrayController.rearrangeObjects()
index = (playlistArrayController.arrangedObjects as! [PlayItem]).count - 1
}
DispatchQueue.main.async {
self.playlistTableView.scrollRowToVisible(index)
}
}
internal func removeList(_ item: PlayList, atIndex index: Int) {
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: {[oldVals = ["item": item, "index": index] as [String : Any]] (PlaylistViewController) -> () in
self.addList(oldVals["item"] as! PlayList, atIndex: oldVals["index"] as! Int)
if !undo.isUndoing {
undo.setActionName("Remove PlayList")
}
})
}
observe(item, keyArray: listIvars, observing: false)
playlistArrayController.removeObject(item)
DispatchQueue.main.async {
self.playlistTableView.scrollRowToVisible(index)
}
}
// published actions - first responder tells us who called
@IBAction func addPlaylist(_ sender: AnyObject) {
let whoAmI = self.view.window?.firstResponder
// We want to add to existing play item list
if whoAmI == playlistTableView {
let item = PlayList()
self.addList(item, atIndex: -1)
}
else
if let selectedPlaylist = playlistArrayController.selectedObjects.first as? PlayList {
let list: Array<PlayItem> = selectedPlaylist.list.sorted(by: { (lhs, rhs) -> Bool in
return lhs.rank < rhs.rank
})
let item = PlayItem()
item.rank = (list.count > 0) ? (list.last?.rank)! + 1 : 1
self.addPlay(item, atIndex: -1)
}
else
{
Swift.print("firstResponder: \(String(describing: whoAmI))")
}
}
@IBAction func removePlaylist(_ sender: AnyObject) {
let whoAmI = self.view.window?.firstResponder
if playlistTableView == whoAmI {
for item in (playlistArrayController.selectedObjects as! [PlayList]).reversed() {
let index = (playlistArrayController.arrangedObjects as! [PlayList]).index(of: item)
self.removeList(item, atIndex: index!)
}
return
}
if playitemTableView == whoAmI {
for item in (playitemArrayController.selectedObjects as! [PlayItem]).reversed() {
let index = (playitemArrayController.arrangedObjects as! [PlayItem]).index(of: item)
self.removePlay(item, atIndex: index!)
}
return
}
if playitemArrayController.selectedObjects.count > 0 {
for item in (playitemArrayController.selectedObjects as! [PlayItem]) {
let index = (playitemArrayController.arrangedObjects as! [PlayItem]).index(of: item)
self.removePlay(item, atIndex: index!)
}
}
else
if playlistArrayController.selectedObjects.count > 0 {
for item in (playlistArrayController.selectedObjects as! [PlayList]) {
let index = (playlistArrayController.arrangedObjects as! [PlayList]).index(of: item)
self.removeList(item, atIndex: index!)
}
}
else
{
Swift.print("firstResponder: \(String(describing: whoAmI))")
NSSound(named: "Sosumi")?.play()
}
}
// Our playlist panel return point if any
var webViewController: WebViewController? = nil
internal func play(_ sender: Any, items: Array<PlayItem>, maxSize: Int) {
// first window might be reused, others no
let newWindows = UserSettings.createNewWindows.value
// Unless we're the standalone helium playlist window dismiss all
if !(self.view.window?.isKind(of: HeliumPanel.self))! {
/// dismiss whatever got us here
super.dismiss(sender)
// If we were run modally as a window, close it
if let ppc = self.view.window?.windowController, ppc.isKind(of: PlaylistPanelController.self) {
NSApp.abortModal()
ppc.window?.orderOut(sender)
}
}
// Try to restore item at its last known location
for (i,item) in (items.enumerated()).prefix(maxSize) {
if appDelegate.doOpenFile(fileURL: item.link) && !newWindows {
UserSettings.createNewWindows.value = true
}
print(String(format: "%3d %3d %@", i, item.rank, item.name))
}
// Restore user settings
if UserSettings.createNewWindows.value != newWindows {
UserSettings.createNewWindows.value = newWindows
}
}
// MARK:- IBActions
@IBAction func playPlaylist(_ sender: AnyObject) {
// first responder tells us who called so dispatch
let whoAmI = self.view.window?.firstResponder
// Quietly, do not exceed program / user specified throttle
let throttle = UserSettings.playlistThrottle.value
// Our rank sorted list from which we'll take last 'throttle' to play
var list = Array<PlayItem>()
if playitemTableView == whoAmI {
Swift.print("We are in playitemTableView")
list.append(contentsOf: playitemArrayController.selectedObjects as! Array<PlayItem>)
}
else
if playlistTableView == whoAmI {
Swift.print("We are in playlistTableView")
for selectedPlaylist in (playlistArrayController.selectedObjects as? [PlayList])! {
list.append(contentsOf: selectedPlaylist.list )
}
}
else
{
Swift.print("firstResponder: \(String(describing: whoAmI))")
NSSound(named: "Sosumi")?.play()
return
}
// Do not exceed program / user specified throttle
if list.count > throttle {
let message = String(format: "Limiting playlist(s) %ld items to throttle?", list.count)
let infoMsg = String(format: "User defaults: %@ = %ld",
UserSettings.playlistThrottle.keyPath,
throttle)
appDelegate.sheetOKCancel(message, info: infoMsg,
acceptHandler: { (button) in
if button == NSAlertFirstButtonReturn {
self.play(sender, items:list, maxSize: throttle)
}
})
}
else
{
play(sender, items:list, maxSize: list.count)
}
}
// Return notification from webView controller
@objc func gotNewHistoryItem(_ note: Notification) {
// If history is current playplist, add to the history
if historyCache.name == (playlistArrayController.selectedObjects.first as! PlayList).name {
self.addPlay(note.object as! PlayItem, atIndex: -1)
}
}
@IBOutlet weak var restoreButton: NSButton!
@IBAction func restorePlaylists(_ sender: NSButton?) {
// We're nil when called at view load
if sender != nil { setObserving(false) }
if playCache.count > 0 {
playlists = playCache
}
else
if let playArray = defaults.dictionary(forKey: k.Playlists) {
playlists = [PlayList]()
for (name,plist) in playArray {
guard let items = plist as? [Dictionary<String,Any>] else {
let item = PlayItem.init(with: (plist as? Dictionary<String,Any>)!)
let playlist = PlayList()
playlist.list.append(item)
playlists.append(playlist)
continue
}
var list : [PlayItem] = [PlayItem]()
for playitem in items {
let item = PlayItem.init(with: playitem)
list.append(item)
}
let playlist = PlayList.init(name: name, list: list)
playlistArrayController.addObject(playlist)
}
}
if sender != nil { setObserving(true) }
}
@IBOutlet weak var saveButton: NSButton!
@IBAction func savePlaylists(_ sender: AnyObject) {
let playArray = playlistArrayController.arrangedObjects as! [PlayList]
var temp = Dictionary<String,Any>()
for playlist in playArray {
var list = Array<Any>()
for playitem in playlist.list {
let item : [String:AnyObject] = [k.name:playitem.name as AnyObject, k.link:playitem.link.absoluteString as AnyObject, k.time:playitem.time as AnyObject, k.rank:playitem.rank as AnyObject]
list.append(item as AnyObject)/*
list.append(playitem.dictionary() as AnyObject)*/
}
temp[playlist.name] = list
}
defaults.set(temp, forKey: k.Playlists)
defaults.synchronize()
}
@IBAction override func dismiss(_ sender: Any?) {
super.dismiss(sender)
// Stop observing any changes
setObserving(false)
// If we were run as a window, close it
if let plw = self.view.window, plw.isKind(of: PlaylistsPanel.self) {
plw.orderOut(sender)
}
// Save or go
switch (sender! as AnyObject).tag == 0 {
case true:
// Save history info which might have changed
appDelegate.histories = historyCache.list
UserSettings.HistoryName.value = historyCache.name
// Save to the cache
playCache = playlists
break
case false:
// Restore from cache
playlists = playCache
}
}
dynamic var hiddenColumns = Dictionary<String, Any>()
@IBAction func toggleColumnVisiblity(_ sender: NSMenuItem) {
let col = sender.representedObject as! NSTableColumn
let table : String = (col.tableView?.identifier)!
let column = col.identifier
let pref = String(format: "hide.%@.%@", table, column)
let isHidden = !col.isHidden
hiddenColumns.updateValue(String(isHidden), forKey: pref)
defaults.set(isHidden, forKey: pref)
col.isHidden = isHidden
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.title.hasPrefix("Redo") {
menuItem.isEnabled = self.canRedo
}
else
if menuItem.title.hasPrefix("Undo") {
menuItem.isEnabled = self.canUndo
}
else
if (menuItem.representedObject as AnyObject).isKind(of: NSTableColumn.self)
{
return true
}
else
{
switch menuItem.title {
default:
menuItem.state = UserSettings.disabledMagicURLs.value ? NSOffState : NSOnState
break
}
}
return true;
}
// MARK:- Delegate
// We cannot alter a playitem once time is entered; just set to zero to alter the rest
func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {
if tableView == playlistTableView {
return true
}
else
if tableView == playitemTableView, let item = playitemArrayController.selectedObjects.first {
return tableColumn?.identifier == "time" || (item as! PlayItem).time == 0
}
else
{
return false
}
}
func tableView(_ tableView: NSTableView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, row: Int, mouseLocation: NSPoint) -> String {
if tableView == playlistTableView
{
let play = (playlistArrayController.arrangedObjects as! [PlayList])[row]
return String(format: "%ld item(s)", play.list.count)
}
else
if tableView == playitemTableView
{
let item = (playitemArrayController.arrangedObjects as! [PlayItem])[row]
let temp = item.link.absoluteString
if item.name == "search", let args = temp.split(separator: "=").last?.removingPercentEncoding
{
return args
}
else
{
return temp
}
}
return "no tip for you"
}
// MARK:- Drag-n-Drop
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
if tableView == playlistTableView {
let objects: [PlayList] = playlistArrayController.arrangedObjects as! [PlayList]
var items: [PlayList] = [PlayList]()
var promises = [String]()
for index in rowIndexes {
let item = objects[index]
let dict = item.dictionary()
let promise = dict.xmlString(withElement: item.className, isFirstElement: true)
promises.append(promise)
items.append(item)
}
let data = NSKeyedArchiver.archivedData(withRootObject: items)
pboard.setPropertyList(data, forType: PlayList.className())
pboard.setPropertyList(promises, forType:NSFilesPromisePboardType)
pboard.writeObjects(promises as [NSPasteboardWriting])
}
else
{
let objects: [PlayItem] = playitemArrayController.arrangedObjects as! [PlayItem]
var items: [PlayItem] = [PlayItem]()
var promises = [String]()
for index in rowIndexes {
let item = objects[index]
let dict = item.dictionary()
let promise = dict.xmlString(withElement: item.className, isFirstElement: true)
promises.append(promise)
items.append(item)
}
let data = NSKeyedArchiver.archivedData(withRootObject: items)
pboard.setPropertyList(data, forType: PlayList.className())
pboard.setPropertyList(promises, forType:NSFilesPromisePboardType)
pboard.writeObjects(promises as [NSPasteboardWriting])
}
return true
}
func performDragOperation(info: NSDraggingInfo) -> Bool {
let pboard: NSPasteboard = info.draggingPasteboard()
let types = pboard.types
if (types?.contains(NSFilenamesPboardType))! {
let names = info.namesOfPromisedFilesDropped(atDestination: URL.init(string: "file://~/Desktop/")!)
// Perform operation using the files’ names, but without the
// files actually existing yet
Swift.print("performDragOperation: NSFilenamesPboardType \(String(describing: names))")
}
if (types?.contains(NSFilesPromisePboardType))! {
let names = info.namesOfPromisedFilesDropped(atDestination: URL.init(string: "file://~/Desktop/")!)
// Perform operation using the files’ names, but without the
// files actually existing yet
Swift.print("performDragOperation: NSFilesPromisePboardType \(String(describing: names))")
}
return true
}
func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
var names: [String] = [String]()
// Always marshall an array of items regardless of item count
if tableView == playlistTableView {
let objects: [PlayList] = playlistArrayController.arrangedObjects as! [PlayList]
for index in indexSet {
let playlist = objects[index]
var items: [Any] = [Any]()
let name = playlist.name
for item in playlist.list {
let dict = item.dictionary()
items.append(dict)
}
if let fileURL = NewFileURLForWriting(path: dropDestination.path, name: name, type: "h3w") {
var dict = Dictionary<String,[Any]>()
dict[k.Playitems] = items
dict[k.Playlists] = [name as AnyObject]
dict[name] = items
(dict as NSDictionary).write(to: fileURL, atomically: true)
names.append(fileURL.absoluteString)
}
}
}
else
{
let selection = playlistArrayController.selectedObjects.first as! PlayList
let objects: [PlayItem] = playitemArrayController.arrangedObjects as! [PlayItem]
let name = String(format: "%@+%ld", selection.name, indexSet.count)
var items: [AnyObject] = [AnyObject]()
for index in indexSet {
let item = objects[index]
names.append(item.link.absoluteString)
items.append(item.dictionary() as AnyObject)
}
if let fileURL = NewFileURLForWriting(path: dropDestination.path, name: name, type: "h3w") {
var dict = Dictionary<String,[AnyObject]>()
dict[k.Playitems] = items
dict[k.Playlists] = [name as AnyObject]
dict[name] = items
(dict as NSDictionary).write(to: fileURL, atomically: true)
}
}
return names
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation {
let sourceTableView = info.draggingSource() as? NSTableView
Swift.print("source \(String(describing: sourceTableView?.identifier))")
if dropOperation == .above {
let pboard = info.draggingPasteboard();
let options = [NSPasteboardURLReadingFileURLsOnlyKey : true,
NSPasteboardURLReadingContentsConformToTypesKey : [kUTTypeMovie as String]] as [String : Any]
let items = pboard.readObjects(forClasses: [NSURL.classForCoder()], options: options)
let isSandboxed = appDelegate.isSandboxed()
if items!.count > 0 {
for item in items! {
if (item as! URL).isFileURL {
var fileURL : NSURL? = (item as AnyObject).filePathURL!! as NSURL
// Resolve alias before storing bookmark
if let original = fileURL?.resolvedFinderAlias() { fileURL = original as NSURL }
if isSandboxed != appDelegate.storeBookmark(url: fileURL! as URL) {
Swift.print("Yoink, unable to sandbox \(String(describing: fileURL)))")
}
// if it's a video file, get and set window content size to its dimentions
let track0 = AVURLAsset(url:fileURL! as URL, options:nil).tracks[0]
if track0.mediaType != AVMediaTypeVideo
{
Swift.print("Yoink, unknown media type: \(track0.mediaType) in \(String(describing: fileURL)))")
}
} else {
print("validate item -> \(item)")
}
}
if isSandboxed != appDelegate.saveBookmarks() {
Swift.print("Yoink, unable to save bookmarks")
}
}
return .copy
}
return .every
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool {
let pasteboard = info.draggingPasteboard()
let options = [NSPasteboardURLReadingFileURLsOnlyKey : true,
NSPasteboardURLReadingContentsConformToTypesKey : [kUTTypeMovie as String],
PlayList.className() : true,
PlayItem.className() : true] as [String : Any]
let sourceTableView = info.draggingSource() as? NSTableView
let isSandboxed = appDelegate.isSandboxed()
var play: PlayList? = nil
var oldIndexes = [Int]()
var oldIndexOffset = 0
var newIndexOffset = 0
var sandboxed = 0
// tableView is our destination; act depending on source
tableView.beginUpdates()
// We have intra tableView drag-n-drop ?
if tableView == sourceTableView {
info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) {
if let str = ($0.0.item as! NSPasteboardItem).string(forType: "public.data"), let index = Int(str) {
oldIndexes.append(index)
}
// For simplicity, the code below uses `tableView.moveRowAtIndex` to move rows around directly.
// You may want to move rows in your content array and then call `tableView.reloadData()` instead.
for oldIndex in oldIndexes {
if oldIndex < row {
tableView.moveRow(at: oldIndex + oldIndexOffset, to: row - 1)
oldIndexOffset -= 1
} else {
tableView.moveRow(at: oldIndex, to: row + newIndexOffset)
newIndexOffset += 1
}
}
}
}
else
// We have inter tableView drag-n-drop ?
// if source is a playlist, drag its items into the destination via copy
// if source is a playitem, drag all items into the destination playlist
// creating a new playlist item unless, we're dropping onto an existing.
if sourceTableView == playlistTableView {
let selectedRowIndexes = sourceTableView?.selectedRowIndexes
for index in selectedRowIndexes! {
let playlist = (playlistArrayController.arrangedObjects as! [PlayList])[index]
for playItem in playlist.list {
addPlay(playItem, atIndex: -1)
}
}
}
else
if sourceTableView == playitemTableView {
// These playitems get dropped into a new or append a playlist
let items: [PlayItem] = playitemArrayController.arrangedObjects as! [PlayItem]
var selectedPlaylist: PlayList? = playlistArrayController.selectedObjects.first as? PlayList
let selectedRowIndexes = sourceTableView?.selectedRowIndexes
if selectedPlaylist != nil && row < tableView.numberOfRows {
selectedPlaylist = (playlistArrayController.arrangedObjects as! [PlayList])[row]
for index in selectedRowIndexes! {
let item = items[index]
let togo = selectedPlaylist?.list.count
if let undo = self.undoManager {
undo.registerUndo(withTarget: self, handler: {[oldVals = ["item": item, "index": togo!] as [String : Any]] (PlaylistViewController) -> () in
selectedPlaylist?.list.removeLast()
selectedPlaylist?.list.remove(at: oldVals["index"] as! Int)
if !undo.isUndoing {
undo.setActionName("Add PlayItem")
}
})
}
observe(item, keyArray: itemIvars, observing: true)
selectedPlaylist?.list.append(items[index])
}
}
else
{
addList(PlayList(), atIndex: -1)
tableView.scrollRowToVisible(row)
playlistTableView.reloadData()
}
tableView.selectRowIndexes(IndexSet.init(integer: row), byExtendingSelection: false)
}
else
if pasteboard.canReadItem(withDataConformingToTypes: [PlayList.className(), PlayItem.className()]) {
if let data = pasteboard.data(forType: PlayList.className())
{
let items = NSKeyedUnarchiver.unarchiveObject(with: data)
Swift.print(String(format:"%@ playlist",(items as! [PlayList]).count))
}
else
if let data = pasteboard.data(forType: PlayItem.className())
{
let items = NSKeyedUnarchiver.unarchiveObject(with: data)
Swift.print(String(format:"%@ playlist",(items as! [PlayItem]).count))
}
}
else
// We have a Finder drag-n-drop of file or location URLs ?
if let items: Array<AnyObject> = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: options) as Array<AnyObject>? {
// addList() and addPlay() affect array controller selection,
// so we must alter selection to the drop row for playlist;
// note that we append items so adjust the newIndexOffset
switch tableView {
case playlistTableView:
switch dropOperation {
case .on:
// selected playlist is already set
play = (playlistArrayController.arrangedObjects as! Array)[row]
playlistArrayController.setSelectionIndex(row)
break
default:
play = PlayList()
addList(play!, atIndex: -1)
playlistTableView.reloadData()
// Pick our seleced playlist
let index = playlistArrayController.selectionIndexes.first
let selectionRow = index! + 1
tableView.selectRowIndexes(IndexSet.init(integer: selectionRow), byExtendingSelection: false)
newIndexOffset = -row
Swift.print("selection \(String(describing: playlistArrayController.selectedObjects.first))")
Swift.print(" play \(String(describing: play))")
}
break
default: // playitemTableView:
play = playlistArrayController.selectedObjects.first as? PlayList
break
}
for itemURL in items {
var fileURL : URL? = (itemURL as AnyObject).filePathURL
let dc = NSDocumentController.shared()
var item: PlayItem?
// Resolve alias before storing bookmark
if let original = (fileURL! as NSURL).resolvedFinderAlias() { fileURL = original }
// If we already know this url 1) known document, 2) our global items cache, use its settings
if let doc = dc.document(for: fileURL!) {
item = (doc as! Document).playitem()
}
else
if let dict = defaults.dictionary(forKey: (fileURL?.absoluteString)!) {
item = PlayItem.init(with: dict)
}
else
{
// Unknown files have to be sandboxed
if isSandboxed != appDelegate.storeBookmark(url: fileURL! as URL) {
Swift.print("Yoink, unable to sandbox \(String(describing: fileURL)))")
} else { sandboxed += 1 }
let path = fileURL!.absoluteString//.stringByRemovingPercentEncoding
let attr = appDelegate.metadataDictionaryForFileAt((fileURL?.path)!)
let time = attr?[kMDItemDurationSeconds] as! Double
let fuzz = (itemURL as AnyObject).deletingPathExtension!!.lastPathComponent as NSString
let name = fuzz.removingPercentEncoding
let list: Array<PlayItem> = play!.list.sorted(by: { (lhs, rhs) -> Bool in
return lhs.rank < rhs.rank
})
item = PlayItem(name:name!,
link:URL.init(string: path)!,
time:time,
rank:(list.count > 0) ? (list.last?.rank)! + 1 : 1)
defaults.set(item?.dictionary(), forKey: (item?.link.absoluteString)!)
}
// Insert item at valid offset, else append
if (row+newIndexOffset) < (playitemArrayController.arrangedObjects as AnyObject).count {
addPlay(item!, atIndex: row + newIndexOffset)
// Dropping on from a sourceTableView implies replacement
if dropOperation == .on {
let playitems: [PlayItem] = (playitemArrayController.arrangedObjects as! [PlayItem])
let oldItem = playitems[row+newIndexOffset+1]
// We've shifted so remove old item at new location
removePlay(oldItem, atIndex: row+newIndexOffset+1)
}
}
else
{
addPlay(item!, atIndex: -1)
}
newIndexOffset += 1
}
}
else
{
// Try to pick off whatever they sent us
for element in pasteboard.pasteboardItems! {
for elementType in element.types {
let elementItem = element.string(forType:elementType)
var item: PlayItem?
var url: URL?
// Use first playlist name
if elementItem?.count == 0 { continue }
// if !okydoKey { play?.name = elementType }
switch (elementType) {
case "public.url"://kUTTypeURL
if let testURL = URL(string: elementItem!) {
url = testURL
}
break
case "public.file-url", "public.utf8-plain-text"://kUTTypeFileURL
if let testURL = URL(string: elementItem!)?.standardizedFileURL {
url = testURL
}
break
case "com.apple.finder.node":
continue // handled as public.file-url
case "com.apple.pasteboard.promised-file-content-type":
if let testURL = URL(string: elementItem!)?.standardizedFileURL {
url = testURL
break
}
continue
default:
Swift.print("type \(elementType) \(elementItem!)")
continue
}
if url == nil { continue }
// Resolve finder alias
if let original = (url! as NSURL).resolvedFinderAlias() { url = original }
if isSandboxed != appDelegate.storeBookmark(url: url!) {
Swift.print("Yoink, unable to sandbox \(String(describing: url)))")
} else { sandboxed += 1 }
// If item is in our playitems cache use it
if let dict = defaults.dictionary(forKey: (url?.absoluteString)!) {
item = PlayItem.init(with: dict)
}
else
{
let attr = appDelegate.metadataDictionaryForFileAt((url?.path)!)
let time = attr?[kMDItemDurationSeconds] as? TimeInterval ?? 0.0
let fuzz = url?.deletingPathExtension().lastPathComponent
let name = fuzz?.removingPercentEncoding
// TODO: we should probably set selection to where row here is as above
let selectedPlaylist = playlistArrayController.selectedObjects.first as? PlayList
let list: Array<PlayItem> = selectedPlaylist!.list.sorted(by: { (lhs, rhs) -> Bool in
return lhs.rank < rhs.rank
})
item = PlayItem(name: name!,
link: url!,
time: time,
rank: (list.count > 0) ? (list.last?.rank)! + 1 : 1)
}
if (row+newIndexOffset) < (playitemArrayController.arrangedObjects as AnyObject).count {
addPlay(item!, atIndex: row + newIndexOffset)
// Dropping on from a sourceTableView implies replacement
if dropOperation == .on {
let playitems: [PlayItem] = (playitemArrayController.arrangedObjects as! [PlayItem])
let oldItem = playitems[row+newIndexOffset+1]
// We've shifted so remove old item at new location
removePlay(oldItem, atIndex: row+newIndexOffset+1)
}
}
else
{
addPlay(item!, atIndex: -1)
}
newIndexOffset += 1
}
}
}
tableView.endUpdates()
if sandboxed > 0 && isSandboxed != appDelegate.saveBookmarks() {
Swift.print("Yoink, unable to save bookmarks")
}
return true
}
}
| 41.40613 | 203 | 0.550088 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.