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
|
---|---|---|---|---|---|
299fcb8d6f079b575317294981bbe215dbc8aa7e | 4,011 | import Darwin
extension SysctlNamespace {
@usableFromInline
static func _nameParts() -> [String] {
guard self != SysctlRootNamespace.self else { return [] }
return ParentNamespace._nameParts() + CollectionOfOne(namePart)
}
@inlinable
static func _buildName<T>(for field: Field<T>) -> String {
(_nameParts() + CollectionOfOne(field.namePart)).joined(separator: ".")
}
}
/// A container that gives access to the children namespaces and values of a `SysctlNamespace`.
@frozen
@dynamicMemberLookup
public struct SysctlContainer<Namespace: SysctlNamespace> {
/// The namespace of the container.
@usableFromInline
let namespace: Namespace
/// Creates a new container with the given namespace.
/// - Parameter namespace: The namespace of the new container.
@usableFromInline
init(namespace: Namespace) {
self.namespace = namespace
}
/// Returns a child container for the given child namespace path.
/// - Parameter childSpace: The keypath to the child namespace.
@inlinable
public subscript<ChildSpace: SysctlNamespace>(dynamicMember childSpace: KeyPath<Namespace, ChildSpace>) -> SysctlContainer<ChildSpace>
where ChildSpace.ParentNamespace == Namespace
{
SysctlContainer<ChildSpace>(namespace: namespace[keyPath: childSpace])
}
/// Reads the value for a field on the namespace.
/// - Parameter field: The keypath to the field of the namespace.
@inlinable
public subscript<Value: SysctlValue>(dynamicMember field: KeyPath<Namespace, Namespace.Field<Value>>) -> Value {
_readValue(for: field)
}
/// Reads or writes the value for a field on the namespace.
/// - Parameter field: The keypath to the field of the namespace.
@inlinable
public subscript<Value: SysctlValue>(dynamicMember field: WritableKeyPath<Namespace, Namespace.Field<Value>>) -> Value {
get { _readValue(for: field) }
nonmutating set { _writeValue(newValue, to: field) }
}
@inlinable
func _withName<T, Value: SysctlValue>(for fieldPath: KeyPath<Namespace, Namespace.Field<Value>>,
do work: (UnsafePointer<CChar>) throws -> T) rethrows -> T {
try Namespace._buildName(for: namespace[keyPath: fieldPath]).withCString(work)
}
private func _sysctlFailed(errno: errno_t,
cStringName: UnsafePointer<CChar>,
writing: Bool = false,
file: StaticString = #file,
line: UInt = #line) -> Never {
fatalError("sysctlbyname failed when \(writing ? "writing" : "reading") '\(String(cString: cStringName))' (\(errno))!",
file: file, line: line)
}
@usableFromInline
func _readValue<Value: SysctlValue>(for fieldPath: KeyPath<Namespace, Namespace.Field<Value>>) -> Value {
_withName(for: fieldPath) {
var size = Int()
guard sysctlbyname($0, nil, &size, nil, 0) == 0 else { _sysctlFailed(errno: errno, cStringName: $0) }
let capacity = size / MemoryLayout<Value.SysctlPointerType>.size
let pointer = UnsafeMutablePointer<Value.SysctlPointerType>.allocate(capacity: capacity)
defer { pointer.deallocate() }
guard sysctlbyname($0, pointer, &size, nil, 0) == 0 else { _sysctlFailed(errno: errno, cStringName: $0) }
return Value(sysctlPointer: pointer)
}
}
@usableFromInline
func _writeValue<Value: SysctlValue>(_ value: Value, to fieldPath: WritableKeyPath<Namespace, Namespace.Field<Value>>) {
_withName(for: fieldPath) { sysctlName in
value.withSysctlPointer {
guard sysctlbyname(sysctlName, nil, nil, UnsafeMutableRawPointer(mutating: $0), $1) == 0 else {
_sysctlFailed(errno: errno, cStringName: sysctlName, writing: true)
}
}
}
}
}
| 42.670213 | 138 | 0.641237 |
033faa505886d906338e8185cf853162040eb128 | 7,012 | //
// Bond+UICollectionView.swift
// Bond
//
// Created by Srđan Rašić on 06/03/15.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
@objc class CollectionViewDynamicArrayDataSource: NSObject, UICollectionViewDataSource {
weak var dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>?
@objc weak var nextDataSource: UICollectionViewDataSource?
init(dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>) {
self.dynamic = dynamic
super.init()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dynamic?.count ?? 0
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dynamic?[section].count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return self.dynamic?[indexPath.section][indexPath.item] ?? UICollectionViewCell()
}
// Forwards
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if let result = self.nextDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) {
return result
} else {
fatalError("Defining Supplementary view either in Storyboard or by registering a class or nib file requires you to implement method collectionView:viewForSupplementaryElementOfKind:indexPath in your data soruce! To provide data source, make a class (usually your view controller) adhere to protocol UICollectionViewDataSource and implement method collectionView:viewForSupplementaryElementOfKind:indexPath. Register instance of your class as next data source with UICollectionViewDataSourceBond object by setting its nextDataSource property. Make sure you set it before binding takes place!")
}
}
}
private class UICollectionViewDataSourceSectionBond<T>: ArrayBond<UICollectionViewCell> {
weak var collectionView: UICollectionView?
var section: Int
init(collectionView: UICollectionView?, section: Int) {
self.collectionView = collectionView
self.section = section
super.init()
self.didInsertListener = { [unowned self] a, i in
if let collectionView: UICollectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.insertItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
self.didRemoveListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.deleteItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
self.didUpdateListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.reloadItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
}
deinit {
self.unbindAll()
}
}
public class UICollectionViewDataSourceBond<T>: ArrayBond<DynamicArray<UICollectionViewCell>> {
weak var collectionView: UICollectionView?
private var dataSource: CollectionViewDynamicArrayDataSource?
private var sectionBonds: [UICollectionViewDataSourceSectionBond<Void>] = []
public weak var nextDataSource: UICollectionViewDataSource? {
didSet(newValue) {
dataSource?.nextDataSource = newValue
}
}
public init(collectionView: UICollectionView) {
self.collectionView = collectionView
super.init()
self.didInsertListener = { [weak self] array, i in
if let s = self {
if let collectionView: UICollectionView = self?.collectionView {
collectionView.performBatchUpdates({
collectionView.insertSections(NSIndexSet(array: i))
}, completion: nil)
for section in sorted(i, <) {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
s.sectionBonds.insert(sectionBond, atIndex: section)
for var idx = section + 1; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section += 1
}
}
}
}
}
self.didRemoveListener = { [weak self] array, i in
if let s = self {
if let collectionView = s.collectionView {
collectionView.performBatchUpdates({
collectionView.deleteSections(NSIndexSet(array: i))
}, completion: nil)
for section in sorted(i, >) {
s.sectionBonds[section].unbindAll()
s.sectionBonds.removeAtIndex(section)
for var idx = section; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section -= 1
}
}
}
}
}
self.didUpdateListener = { [weak self] array, i in
if let collectionView = self?.collectionView {
collectionView.performBatchUpdates({
collectionView.reloadSections(NSIndexSet(array: i))
}, completion: nil)
for section in i {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
self?.sectionBonds[section].unbindAll()
self?.sectionBonds[section] = sectionBond
}
}
}
}
public func bind(dynamic: DynamicArray<UICollectionViewCell>) {
bind(DynamicArray([dynamic]))
}
public override func bind(dynamic: Dynamic<Array<DynamicArray<UICollectionViewCell>>>, fire: Bool, strongly: Bool) {
super.bind(dynamic, fire: false, strongly: strongly)
if let dynamic = dynamic as? DynamicArray<DynamicArray<UICollectionViewCell>> {
for section in 0..<dynamic.count {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: self.collectionView, section: section)
let sectionDynamic = dynamic[section]
sectionDynamic.bindTo(sectionBond)
sectionBonds.append(sectionBond)
}
dataSource = CollectionViewDynamicArrayDataSource(dynamic: dynamic)
dataSource?.nextDataSource = self.nextDataSource
collectionView?.dataSource = dataSource
collectionView?.reloadData()
}
}
deinit {
self.unbindAll()
collectionView?.dataSource = nil
self.dataSource = nil
}
}
public func ->> <T>(left: DynamicArray<UICollectionViewCell>, right: UICollectionViewDataSourceBond<T>) {
right.bind(left)
}
| 37.497326 | 598 | 0.688962 |
098c569b6e90c33b5ace074ab50d4087e304fe19 | 5,311 | // https://github.com/Quick/Quick
import Quick
import Nimble
import InterruptibleAction
import ReactiveSwift
import Result
class InterruptibleActionSpec: QuickSpec {
override func spec() {
describe("InterruptibleAction") {
describe("interrupt") {
it("should be enabled if inner action is executing") {
let enabled = MutableProperty<Bool>(true)
let interruptibleAction = InterruptibleAction<Void, Void, NoError>(enabledIf: enabled) { _ in
return SignalProducer.timer(interval: DispatchTimeInterval.seconds(1), on: QueueScheduler.main)
.map { _ in () }
}
interruptibleAction
.apply()
.start()
expect(interruptibleAction.inner.isExecuting.value).toEventually(equal(true))
expect(interruptibleAction.interrupt.isEnabled.value).toEventually(equal(true))
}
it("should be disabled if inner action is not executing") {
let enabled = MutableProperty<Bool>(true)
let interruptibleAction = InterruptibleAction<Void, Void, NoError>(enabledIf: enabled) { _ in
return SignalProducer.timer(interval: DispatchTimeInterval.seconds(1), on: QueueScheduler.main)
.map { _ in () }
}
expect(interruptibleAction.inner.isExecuting.value).toEventually(equal(false))
expect(interruptibleAction.interrupt.isEnabled.value).toEventually(equal(false))
}
it("should terminate the currently executing unit of work") {
let interruptibleAction = InterruptibleAction<Void, Void, NoError> { _ in
return SignalProducer.timer(interval: DispatchTimeInterval.seconds(1), on: QueueScheduler.main)
.map { _ in () }
}
interruptibleAction
.apply()
.start()
var wasInterrupted = false
var anyOtherEvent: Void? = nil
interruptibleAction
.events
.observeValues({ (event) in
switch event {
case .interrupted:
wasInterrupted = true
default:
anyOtherEvent = ()
}
})
interruptibleAction
.interrupt
.apply()
.start()
expect(wasInterrupted).toEventually(equal(true))
expect(anyOtherEvent).toEventually(beNil())
}
}
describe("bindingTarget") {
it("should terminate the executing unit of work and start a new one") {
var innerProducerGeneration = 0
let interruptibleAction = InterruptibleAction<Void, Void, NoError> { _ in
innerProducerGeneration = innerProducerGeneration + 1
return SignalProducer.never
}
var wasInterrupted = false
var anyOtherEvent: Void? = nil
interruptibleAction
.events
.observeValues({ (event) in
switch event {
case .interrupted:
wasInterrupted = true
default:
anyOtherEvent = ()
}
})
interruptibleAction
.apply()
.start()
interruptibleAction.bindingTarget <~ SignalProducer(value: ())
expect(innerProducerGeneration).toEventually(equal(2))
expect(wasInterrupted).toEventually(equal(true))
expect(anyOtherEvent).toEventually(beNil())
}
it("should start a new unit of work") {
var innerProducerGeneration = 0
let interruptibleAction = InterruptibleAction<Void, Void, NoError> { _ in
innerProducerGeneration = innerProducerGeneration + 1
return SignalProducer.never
}
interruptibleAction.bindingTarget <~ SignalProducer(value: ())
expect(innerProducerGeneration).toEventually(equal(1))
expect(interruptibleAction.isExecuting.value).toEventually(equal(true))
}
}
}
}
}
| 44.258333 | 119 | 0.45321 |
ef8635d269e74a2efa560dd9cfa65c7d14f03791 | 3,223 | //
// AppDelegate.swift
// KzSDK-Example
//
// Created by K-zing on 30/5/2018.
// Copyright © 2018 K-zing. All rights reserved.
//
import UIKit
import KzSDK_Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let apiKey = "YOUR_KEY"
let md5Key = "YOUR_KEY"
KzSetting.initialize(apiKey: apiKey, md5Key: md5Key)
ApiAction.GetBasicKey().addListener(ApiListener<ApiAction.GetBasicKey.Result>.init(onSuccess: { (result) in
guard let basicKey = result.body?.data?.basicKeyString else {
self.printResult(result)
return
}
KzSetting.setBasicKey(basicKey)
ApiAction.GetKey().addListener(ApiListener<ApiAction.GetKey.Result>.init(onSuccess: { (result) in
guard let clientPublicKey = result.body?.data?.publicKeyString else {
self.printResult(result)
return
}
//Initialization Completed
KzSetting.setPublicKey(clientPublicKey)
}, onFail: self.printResult)).post()
}, onFail: printResult)).post()
return true
}
func printResult(_ result: ApiResultProtocol) {
print(result)
}
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:.
}
}
| 43.554054 | 285 | 0.694384 |
bfc21d23fd6d06ccb3b5e315e2c72f19c9da4b74 | 8,338 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
// MARK: Paginators
extension RAM {
/// Gets the policies for the specified resources that you own and have shared.
public func getResourcePoliciesPaginator(
_ input: GetResourcePoliciesRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (GetResourcePoliciesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getResourcePolicies,
tokenKey: \GetResourcePoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Gets the resources or principals for the resource shares that you own.
public func getResourceShareAssociationsPaginator(
_ input: GetResourceShareAssociationsRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (GetResourceShareAssociationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getResourceShareAssociations,
tokenKey: \GetResourceShareAssociationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Gets the invitations for resource sharing that you've received.
public func getResourceShareInvitationsPaginator(
_ input: GetResourceShareInvitationsRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (GetResourceShareInvitationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getResourceShareInvitations,
tokenKey: \GetResourceShareInvitationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Gets the resource shares that you own or the resource shares that are shared with you.
public func getResourceSharesPaginator(
_ input: GetResourceSharesRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (GetResourceSharesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getResourceShares,
tokenKey: \GetResourceSharesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the resources in a resource share that is shared with you but that the invitation is still pending for.
public func listPendingInvitationResourcesPaginator(
_ input: ListPendingInvitationResourcesRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListPendingInvitationResourcesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listPendingInvitationResources,
tokenKey: \ListPendingInvitationResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the principals that you have shared resources with or that have shared resources with you.
public func listPrincipalsPaginator(
_ input: ListPrincipalsRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListPrincipalsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listPrincipals,
tokenKey: \ListPrincipalsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the resources that you added to a resource shares or the resources that are shared with you.
public func listResourcesPaginator(
_ input: ListResourcesRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListResourcesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listResources,
tokenKey: \ListResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension RAM.GetResourcePoliciesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.GetResourcePoliciesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
principal: self.principal,
resourceArns: self.resourceArns
)
}
}
extension RAM.GetResourceShareAssociationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.GetResourceShareAssociationsRequest {
return .init(
associationStatus: self.associationStatus,
associationType: self.associationType,
maxResults: self.maxResults,
nextToken: token,
principal: self.principal,
resourceArn: self.resourceArn,
resourceShareArns: self.resourceShareArns
)
}
}
extension RAM.GetResourceShareInvitationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.GetResourceShareInvitationsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceShareArns: self.resourceShareArns,
resourceShareInvitationArns: self.resourceShareInvitationArns
)
}
}
extension RAM.GetResourceSharesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.GetResourceSharesRequest {
return .init(
maxResults: self.maxResults,
name: self.name,
nextToken: token,
resourceOwner: self.resourceOwner,
resourceShareArns: self.resourceShareArns,
resourceShareStatus: self.resourceShareStatus,
tagFilters: self.tagFilters
)
}
}
extension RAM.ListPendingInvitationResourcesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.ListPendingInvitationResourcesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceShareInvitationArn: self.resourceShareInvitationArn
)
}
}
extension RAM.ListPrincipalsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.ListPrincipalsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
principals: self.principals,
resourceArn: self.resourceArn,
resourceOwner: self.resourceOwner,
resourceShareArns: self.resourceShareArns,
resourceType: self.resourceType
)
}
}
extension RAM.ListResourcesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> RAM.ListResourcesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
principal: self.principal,
resourceArns: self.resourceArns,
resourceOwner: self.resourceOwner,
resourceShareArns: self.resourceShareArns,
resourceType: self.resourceType
)
}
}
| 35.939655 | 156 | 0.648237 |
71146dee8cc886c257cedc9c2be630dacb3ce45c | 346 | //
// HealthCellData.swift
// HealthCounter
//
// Created by Wi on 31/12/2018.
// Copyright © 2018 Wi. All rights reserved.
//
import Foundation
struct HealthCellData: Codable{
var isCustomCell: Bool
var isTimerCellOpen: Bool?
let indexPath: IndexPath?
var exerciseName: String?
var count: Int?
var setCount: Int?
}
| 18.210526 | 45 | 0.682081 |
f8b42f39b8548dbbd083a374db20a397e52cbe73 | 540 | //
// BuggyEngineDelegate.swift
// QooBot
//
// Created by Harvey He on 2018/12/18.
// Copyright © 2018 Harvey He. All rights reserved.
//
import Foundation
import CoreBluetooth
@objc public protocol BuggyEngineDelegate: class {
@objc optional func firmataReceviceData(inputData:[UInt8])
@objc optional func buggyEngineState(state:BuggyState)
@objc optional func hexUploadProgess(progess:Int)
@objc optional func managerState(state:CBCentralManagerState)
@objc optional func powerWarning()
}
| 23.478261 | 65 | 0.725926 |
ab7bb203819931bdf0c5198a8498635c9ee1389e | 3,163 | //
// AppDelegate.swift
// PresistentImageGallery
//
// Created by jamfly on 2018/2/1.
// Copyright © 2018年 jamfly. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let cache = URLCache()
URLCache.shared = cache
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open inputURL: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
// Ensure the URL is a file URL
guard inputURL.isFileURL else { return false }
// Reveal / import the document at the URL
guard let documentBrowserViewController = window?.rootViewController as? DocumentBrowserViewController else { return false }
documentBrowserViewController.revealDocument(at: inputURL, importIfNeeded: true) { (revealedDocumentURL, error) in
if let error = error {
// Handle the error appropriately
print("Failed to reveal the document at URL \(inputURL) with error: '\(error)'")
return
}
// Present the Document View Controller for the revealed URL
documentBrowserViewController.presentDocument(at: revealedDocumentURL!)
}
return true
}
}
| 44.549296 | 285 | 0.709769 |
e284e924ccb0a38736444ac35128ee134b017840 | 580 | //
// NativeVideoVIewFactory.swift
// Runner
//
// Created by Luis Jara Castillo on 11/4/19.
//
import Foundation
import Flutter
public class NativeVideoViewFactory:NSObject, FlutterPlatformViewFactory {
private let registrar: FlutterPluginRegistrar
init(registrar:FlutterPluginRegistrar){
self.registrar = registrar
}
public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
return NativeVideoViewController(frame: frame, viewId: viewId, registrar: registrar)
}
}
| 26.363636 | 124 | 0.734483 |
db9039a4cf8f0195facf9749cbf5d8331329ccd5 | 2,164 | //
// Copyright (c) 2016 Keun young Kim <[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.
//
#if os(iOS)
import Foundation
import CoreTelephony
@available(iOS, deprecated, message: "Use KxUI instead.")
public struct KFDevice {
public static var mainScreenWidth: CGFloat {
return UIScreen.main.bounds.width
}
public static var mainScreenHeight: CGFloat {
return UIScreen.main.bounds.height
}
public static var mainScreenBounds: CGRect {
return UIScreen.main.bounds
}
public static func canPhoneCall() -> Bool {
var canCall = false
let url = URL(string: "tel://")
if UIApplication.shared.canOpenURL(url!) {
let info = CTTelephonyNetworkInfo()
guard let carrier = info.subscriberCellularProvider else {
return canCall
}
let mnc = carrier.mobileNetworkCode
if String.isValid(mnc) {
canCall = true
}
}
return canCall
}
}
#endif
| 32.298507 | 81 | 0.661738 |
0918fe097010cc5add986b77f02e54e8deda45b2 | 2,298 | //
// SceneDelegate.swift
// APNsPayloadViewer
//
// Created by iq3AddLi on 2020/10/28.
//
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.358491 | 147 | 0.714099 |
d5db9ec907e13c03349baf26372e89e08242dd2d | 631 | //
// ViewController.swift
// UIKit-Extensions
//
// Created by Oliver Erxleben on 19.04.16.
// Copyright © 2016 Oliver Erxleben. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
delay(3.0, closure: {
imageView.downloadAsync("http://lorempixel.com/image_output/cats-q-c-640-480-2.jpg", contentMode: .Center)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 18.558824 | 110 | 0.660856 |
0adb15f365a0faa4d75fa968dce9c3fd9b22b1b5 | 851 | //
// Profile.swift
// PlayingWithSwiftUI
//
// Created by Michael Vilabrera on 6/19/19.
// Copyright © 2019 Michael Vilabrera. All rights reserved.
//
import Foundation
struct Profile {
var username: String
var prefersNotifications: Bool
var seasonalPhoto: Season
var goalDate: Date
static let `default` = Self(username: "harold_kumar", prefersNotifications: true, seasonalPhoto: .winter)
init(username: String, prefersNotifications: Bool = true, seasonalPhoto: Season = .winter) {
self.username = username
self.prefersNotifications = prefersNotifications
self.seasonalPhoto = seasonalPhoto
self.goalDate = Date()
}
enum Season: String, CaseIterable {
case spring = "🌷"
case summer = "🌞"
case autumn = "🍂"
case winter = "☃️"
}
}
| 25.787879 | 109 | 0.646298 |
910e00227f701a2e3413fa000c2a0d8b4469c2e3 | 828 | // Author: Thomas Nilsson
// Technical University of Denmark
// Copyright © 2017 Thomas Nilsson. All rights reserved.
import Foundation
import UIKit
class UISetter {
func setUI(vc: UIViewController, buttons: [UIButton]) {
roundButtonCorners(buttons: buttons)
setBackground(vc: vc)
}
// Rounds the corners of buttons within the given array of UIButtons.
func roundButtonCorners(buttons: [UIButton]) {
for button in buttons {
let desiredRadius = button.frame.height / 2
button.layer.cornerRadius = desiredRadius
}
}
// Makes background gradient
func setBackground(vc: UIViewController) {
let background = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1)
vc.view.backgroundColor = background
}
}
| 28.551724 | 84 | 0.655797 |
611f989d3f098f18fce874f4c56a26dd2f92bde9 | 6,217 | /*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import Foundation
import AEPServices
///A Type that downloads and caches the Assets(images) associated with a Fullscreen IAM.
struct CampaignMessageAssetsCache {
private let LOG_PREFIX = "CampaignMessageAssetsCache"
let dispatchQueue: DispatchQueue
init() {
dispatchQueue = DispatchQueue(label: "\(CampaignConstants.EXTENSION_NAME).messageassetscache")
}
///Download and Caches the Assets for a given messageId.
///- Parameters:
/// - urls: An array of URL of Assets
/// - messageId: The id of the message
func downloadAssetsForMessage(from urls: [String], messageId: String) {
Log.trace(label: LOG_PREFIX, "\(#function) - Will attempt to download assets for Message (\(messageId) from URLs: \(urls)")
var assetsToRetain: [URL] = []
for urlString in urls {
guard let url = URL(string: urlString) else {
continue
}
assetsToRetain.append(url)
}
let assetToRetainAlphaNumeric = assetsToRetain.map { url in
url.absoluteString.alphanumeric
}
clearCachedAssetsNotInList(filesToRetain: assetToRetainAlphaNumeric, pathRelativeToCacheDir: "\(CampaignConstants.RulesDownloaderConstants.MESSAGE_CACHE_FOLDER)/\(messageId)")
downloadAssets(urls: assetsToRetain, messageId: messageId)
}
///Iterate over the URL's array and triggers the download Network request
private func downloadAssets(urls: [URL], messageId: String) {
let networking = ServiceProvider.shared.networkService
for url in urls {
let networkRequest = NetworkRequest(url: url, httpMethod: .get)
networking.connectAsync(networkRequest: networkRequest) { httpConnection in
self.dispatchQueue.async {
guard httpConnection.responseCode == 200, let data = httpConnection.data else {
Log.debug(label: self.LOG_PREFIX, "\(#function) - Failed to download Asset from URL: \(url)")
return
}
self.cacheAssetData(data, forKey: url, messageId: messageId)
}
}
}
}
///Caches the downloaded `Data` for Assets
/// - Parameters:
/// - data: The downloaded `Data`
/// - forKey: The Asset download URL. Used to name cache folder.
/// - messageId: The id of message
private func cacheAssetData(_ data: Data, forKey url: URL, messageId: String) {
guard var cacheUrl = createDirectoryIfNeeded(messageId: messageId) else {
Log.debug(label: LOG_PREFIX, "Unable to cache Asset for URL: (\(url). Unable to create cache directory.")
return
}
cacheUrl.appendPathComponent(url.absoluteString.alphanumeric)
do {
try data.write(to: cacheUrl)
Log.trace(label: LOG_PREFIX, "Successfully cached Asset for URL: (\(url)")
} catch {
Log.debug(label: LOG_PREFIX, "Unable to cache Asset for URL: (\(url). Unable to write data to file path.")
}
}
///Deletes all the files in `pathRelativeToCacheDir` that are not present in `filesToRetain` array. This is used to delete the cached assets that are no longer required.
/// - Parameters:
/// - filesToRetain: An array of file names that have to retain.
/// - pathRelativeToCacheDir: The path of cache directory relative to `Library/Cache`
func clearCachedAssetsNotInList(filesToRetain: [String], pathRelativeToCacheDir: String) {
Log.trace(label: LOG_PREFIX, "\(#function) - Attempt to delete \(filesToRetain.count) non required cached assets from directory '\(pathRelativeToCacheDir)'")
FileManager.default.deleteCachedFiles(except: filesToRetain, parentFolderRelativeToCache: pathRelativeToCacheDir)
}
/// Creates the directory to store the cache if it does not exist
/// - Parameters messageId: The message Id
/// - Returns the `URL` to the Message Cache folder, Returns nil if cache folder does not exist or unable to create message cache folder
private func createDirectoryIfNeeded(messageId: String) -> URL? {
let fileManager = FileManager.default
guard var cacheUrl = try? fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {
Log.debug(label: LOG_PREFIX, "\(#function) - \(#function) - Failed to retrieve cache directory URL.")
return nil
}
cacheUrl.appendPathComponent("\(CampaignConstants.RulesDownloaderConstants.MESSAGE_CACHE_FOLDER)/\(messageId)/")
let cachePath = cacheUrl.path
guard !fileManager.fileExists(atPath: cachePath) else {
Log.trace(label: LOG_PREFIX, "\(#function) - Assets cache directory for message \(messageId) already exists.")
return cacheUrl
}
Log.trace(label: LOG_PREFIX, "\(#function) - Attempting to create Assets cache directory for message \(messageId) at path: \(cachePath)")
do {
try fileManager.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
return cacheUrl
} catch {
Log.trace(label: LOG_PREFIX, "\(#function) - Error in creating Assets cache directory for message \(messageId) at path: \(cacheUrl.path).")
return nil
}
}
}
extension String {
///Removes non alphanumeric character from `String`
var alphanumeric: String {
return components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased()
}
}
| 48.952756 | 183 | 0.674763 |
e488fbc5c0a571d760d4463b4161ed19bbc6d462 | 2,660 | import Libawc
import Wlroots
public class TestView {
public let id: Int
convenience public init() {
self.init(id: 0)
}
public init(id: Int) {
self.id = id
}
}
extension TestView: Equatable {
public static func ==(lhs: TestView, rhs: TestView) -> Bool {
lhs === rhs
}
}
extension TestView: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
}
extension TestView: CustomStringConvertible {
public var description: String {
String(id)
}
}
extension wlr_box: Equatable {
public static func ==(lhs: wlr_box, rhs: wlr_box) -> Bool {
(lhs.x, lhs.y, lhs.width, lhs.height) == (rhs.x, rhs.y, rhs.width, rhs.height)
}
}
public class NoDataProvider: ExtensionDataProvider {
public init() {
}
public func getExtensionData<D>() -> D? {
nil
}
}
public final class TestLayout: Layout {
public typealias View = TestView
public typealias OutputData = ()
public var description: String {
get {
"TestLayout"
}
}
public var emptyLayoutCalled: Bool = false
public var doLayoutCalled: Bool = false
public var firstLayoutCalled: Bool = false
public var nextLayoutCalled: Bool = false
public var expandCalled: Bool = false
public var shrinkCalled: Bool = false
private let arrangementToReturn: [(TestView, Set<ViewAttribute>, wlr_box)]
public init(arrangementToReturn: [(TestView, Set<ViewAttribute>, wlr_box)] = []) {
self.arrangementToReturn = arrangementToReturn
}
public func emptyLayout<L: Layout>(
dataProvider: ExtensionDataProvider,
output: Output<L>,
box: wlr_box
) -> [(L.View, Set<ViewAttribute>, wlr_box)] where L.View == View, L.OutputData == OutputData {
self.emptyLayoutCalled = true
return []
}
public func doLayout<L: Layout>(
dataProvider: ExtensionDataProvider,
output: Output<L>,
stack: Stack<L.View>,
box: wlr_box
) -> [(L.View, Set<ViewAttribute>, wlr_box)] where L.View == View, L.OutputData == OutputData {
self.doLayoutCalled = true
return arrangementToReturn
}
public func firstLayout() -> TestLayout {
self.firstLayoutCalled = true
return self
}
public func nextLayout() -> TestLayout? {
self.nextLayoutCalled = true
return nil
}
public func expand() -> TestLayout {
self.expandCalled = true
return self
}
public func shrink() -> TestLayout {
self.shrinkCalled = true
return self
}
}
| 23.75 | 99 | 0.619549 |
e8a6dfb301d828210ea420baaebcc0bf39183fb7 | 2,742 | //
// HomeViewController.swift
// Instagram
//
// Created by Chris Martinez on 10/2/18.
// Copyright © 2018 Chris Martinez. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var posts : [Post] = []
var refreshControl : UIRefreshControl!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
if let indexPath = tableView.indexPath(for: cell){
let post = posts[indexPath.row]
let detailViewController = segue.destination as! DetailViewController
detailViewController.post = post
}
}
@objc func fetchPosts(){
let query = Post.query()
query?.order(byDescending: "createdAt")
query?.limit = 20
// fetch data asynchronously
query?.findObjectsInBackground(block: { (posts, error) in
if let posts = posts {
self.posts = posts as! [Post]
self.tableView.reloadData()
self.refreshControl.endRefreshing()
} else {
print(error.debugDescription)
}
} )
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action:#selector(fetchPosts), for: .valueChanged)
tableView.insertSubview(refreshControl, at: 0)
fetchPosts()
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "feedCell", for: indexPath) as! FeedCell
let post = posts[indexPath.row]
if let imageFile : PFFile = post.media {
imageFile.getDataInBackground(block: { (data, error) in
if error == nil {
DispatchQueue.main.async {
// Async main thread
let image = UIImage(data: data!)
cell.postImage.image = image
}
} else {
print(error!.localizedDescription)
}
})
}
cell.postTextLabel.text = post.caption
return cell
}
}
| 32.258824 | 105 | 0.583516 |
62cedaf7e5ffdba3cb44e6b0202b4522a75acfa9 | 1,847 | //: [Previous](@previous)
/*
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
```
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
```
*/
import Foundation
func exist(_ board: [[Character]], _ word: String) -> Bool {
func backtracking(_ board: [[Character]],
_ row: Int,
_ column: Int,
_ index: Int,
_ word: [Character]) -> Bool {
if index == word.count {
return true
}
if row < 0 ||
row >= board.count ||
column < 0 ||
column >= board[row].count ||
board[row][column] != word[index] {
return false
}
var board = board
_ = board[row][column]
board[row][column] = " "
let found = backtracking(board, row+1, column, index+1, word) ||
backtracking(board, row-1, column, index+1, word) ||
backtracking(board, row, column+1, index+1, word) ||
backtracking(board, row, column-1, index+1, word)
return found
}
let arrayWord = Array(word)
for row in 0..<board.count {
for column in 0..<board[row].count {
if board[row][column] == arrayWord[0] && backtracking(board, row, column, 0, arrayWord) {
return true
}
}
}
return false
}
exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"ABCCED")
//: [Next](@next)
| 29.790323 | 191 | 0.495398 |
def132ce29ad475753dbb607a17737fc214a02c9 | 375 | //
// Conversion.swift
// SwiftyBytes
//
// Created by Quentin Berry on 6/28/20.
// Copyright © 2020 Quentin Berry. All rights reserved.
//
import Foundation
func fromByteArray<T>(_ value: [UInt8], _: T.Type) -> T {
return value.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
| 20.833333 | 68 | 0.626667 |
262c0a538583b419d26a32422c10dde2594fa40f | 874 | //
// TopNavigationBarView.swift
// swift-weather-ui
//
// Created by Guven Bolukbasi on 21.12.2019.
// Copyright © 2019 dorianlabs. All rights reserved.
//
import SwiftUI
struct TopNavigationBarView: View {
var body: some View {
HStack(alignment: .center, spacing: 10.0) {
Button(action: {}) {
Image("Location")
}
Text("Suadiye - Kadikoy")
.lineLimit(1)
.foregroundColor(.white)
Spacer()
Button(action: {}) {
Image("LiveMap")
}
Button(action: {}) {
Image("Settings")
}
}
.padding()
}
}
struct TopNavigationBarView_Previews: PreviewProvider {
static var previews: some View {
PreviewFactory.previews(forView: TopNavigationBarView())
}
}
| 22.410256 | 64 | 0.526316 |
4ae6bbaadec04dfd34787744369fffc67413d12a | 645 | //
// Comic.swift
// MarvelApp
//
// Created by Carmine Del Gaudio on 08/04/2020.
// Copyright © 2020 Carmine Del Gaudio. All rights reserved.
//
import Foundation
// I find it useful to separate the network from the features
struct Comic {
let id: Int
let title: String
let description: String?
let imagePath: String
}
enum ComicWorker {
static func format(response: ComicListResponse) -> [Comic] {
response.data.results.map{
let imagePath = $0.thumbnail.path + ($0.thumbnail.thumbnailExtension ?? ".jpg")
return Comic(id: $0.id, title: $0.title, description: $0.description, imagePath: imagePath)
}
}
}
| 23.035714 | 97 | 0.686822 |
e66fcc3879c3f2c3e2f641cf08ba8527583300ff | 27,894 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlow
final class BasicOperatorTests: XCTestCase {
func testGathering() {
let x = Tensor<Float>([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
let y = x.gathering(atIndices: Tensor<Int32>(2), alongAxis: 1)
XCTAssertEqual(y, Tensor<Float>([3.0, 6.0]))
}
func testBatchGathering() {
let x = Tensor<Float>([[
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]]])
let y = x.batchGathering(
atIndices: Tensor<Int32>([[[1], [0]]]),
alongAxis: 2,
batchDimensionCount: 2)
XCTAssertEqual(y, Tensor<Float>([[[2.0], [4.0]]]))
}
func testPadded() {
let x = Tensor<Float>(ones: [2, 2])
let target = Tensor<Float>([[3, 3, 3], [1, 1, 3], [1, 1, 3]])
let paddedTensor = x.padded(forSizes: [(1, 0), (0, 1)], with: 3.0)
XCTAssertEqual(paddedTensor, target)
}
func testPaddedConstant() {
let x = Tensor<Float>(ones: [2, 2])
let target = Tensor<Float>([[3, 3, 3], [1, 1, 3], [1, 1, 3]])
let paddedTensor = x.padded(forSizes: [(1, 0), (0, 1)], mode: .constant(3.0))
XCTAssertEqual(paddedTensor, target)
}
func testPaddedReflect() {
let x = Tensor<Float>([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
let target = Tensor<Float>([
[7, 8, 9, 8, 7],
[4, 5, 6, 5, 4],
[1, 2, 3, 2, 1],
[4, 5, 6, 5, 4],
[7, 8, 9, 8, 7]
])
let paddedTensor = x.padded(forSizes: [(2, 0), (0, 2)], mode: .reflect)
XCTAssertEqual(paddedTensor, target)
}
func testPaddedSymmetric() {
let x = Tensor<Float>([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
let target = Tensor<Float>([
[4, 5, 6, 6, 5],
[1, 2, 3, 3, 2],
[1, 2, 3, 3, 2],
[4, 5, 6, 6, 5],
[7, 8, 9, 9, 8]
])
let paddedTensor = x.padded(forSizes: [(2, 0), (0, 2)], mode: .symmetric)
XCTAssertEqual(paddedTensor, target)
}
func testVJPPadded() {
let x = Tensor<Float>(ones: [3, 2])
let target = Tensor<Float>([[2, 2], [2, 2], [2, 2]])
let grads = x.gradient { a -> Tensor<Float> in
let paddedTensor = a.padded(forSizes: [(1, 0), (0, 1)], with: 3.0)
return (paddedTensor * paddedTensor).sum()
}
XCTAssertEqual(grads, target)
}
func testVJPPaddedConstant() {
let x = Tensor<Float>(ones: [3, 2])
let target = Tensor<Float>([[2, 2], [2, 2], [2, 2]])
let grads = x.gradient { a -> Tensor<Float> in
let paddedTensor = a.padded(forSizes: [(1, 0), (0, 1)], mode: .constant(3.0))
return (paddedTensor * paddedTensor).sum()
}
XCTAssertEqual(grads, target)
}
func testVJPPaddedReflect() {
let x = Tensor<Float>([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
let target = Tensor<Float>([[4, 8, 6], [32, 40, 24], [56, 64, 36]])
let grads = x.gradient { a -> Tensor<Float> in
let paddedTensor = a.padded(forSizes: [(2, 0), (0, 2)], mode: .reflect)
return (paddedTensor * paddedTensor).sum()
}
XCTAssertEqual(grads, target)
}
func testVJPPaddedSymmetric() {
let x = Tensor<Float>([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
let target = Tensor<Float>([[4, 16, 24], [16, 40, 48], [14, 32, 36]])
let grads = x.gradient { a -> Tensor<Float> in
let paddedTensor = a.padded(forSizes: [(2, 0), (0, 2)], mode: .symmetric)
return (paddedTensor * paddedTensor).sum()
}
XCTAssertEqual(grads, target)
}
func testElementIndexing() {
// NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly
// until send and receive are implemented (without writing a bunch of mini
// tests). Instead, `Tensor.array` is called to make a ShapedArray host copy
// and the ShapedArray is tested.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let element2D = tensor3D[2]
let element1D = tensor3D[1][3]
let element0D = tensor3D[2][0][3]
let array2D = element2D.array
let array1D = element1D.array
let array0D = element0D.array
/// Test shapes
XCTAssertEqual(array2D.shape, [4, 5])
XCTAssertEqual(array1D.shape, [5])
XCTAssertEqual(array0D.shape, [])
/// Test scalars
XCTAssertEqual(array2D.scalars, Array(stride(from: 40.0, to: 60, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 35.0, to: 40, by: 1)))
XCTAssertEqual(array0D.scalars, [43])
}
func testElementIndexingAssignment() {
// NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly
// until send and receive are implemented (without writing a bunch of mini
// tests). Instead, `Tensor.array` is called to make a ShapedArray host copy
// and the ShapedArray is tested.
var tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
tensor3D[2] = Tensor<Float>(
shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1)))
let element2D = tensor3D[2]
let element1D = tensor3D[1][3]
let element0D = tensor3D[2][0][3]
let array2D = element2D.array
let array1D = element1D.array
let array0D = element0D.array
/// Test shapes
XCTAssertEqual(array2D.shape, [4, 5])
XCTAssertEqual(array1D.shape, [5])
XCTAssertEqual(array0D.shape, [])
/// Test scalars
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 40, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 35.0, to: 40, by: 1)))
XCTAssertEqual(array0D.scalars, [23])
}
func testNestedElementIndexing() {
// NOTE: This test could use a clearer name, along with other "indexing"
// tests. Note to update corresponding test names in other files
// (shaped_array.test) as well.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let element1D = tensor3D[1, 3]
let element0D = tensor3D[2, 0, 3]
let array1D = element1D.array
let array0D = element0D.array
/// Test shapes
XCTAssertEqual(array1D.shape, [5])
XCTAssertEqual(array0D.shape, [])
/// Test scalars
XCTAssertEqual(array1D.scalars, Array(stride(from: 35.0, to: 40, by: 1)))
XCTAssertEqual(array0D.scalars, [43])
}
func testSliceIndexing() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let slice3D = tensor3D[2...]
let slice2D = tensor3D[1][0..<2]
let slice1D = tensor3D[0][0][3..<5]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 40.0, to: 60, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testSliceIndexingAssignment() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
var tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
tensor3D[2, 0..<5, 0..<6] = Tensor<Float>(
shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1)))
let slice3D = tensor3D[2...]
let slice2D = tensor3D[1][0..<2]
let slice1D = tensor3D[0][0][3..<5]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 20.0, to: 40, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testEllipsisIndexing() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
var tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
tensor3D[2, TensorRange.ellipsis] = Tensor<Float>(
shape: [4, 5], scalars: Array(stride(from: 20.0, to: 40, by: 1)))
let slice3D = tensor3D[2..., TensorRange.ellipsis]
let slice2D = tensor3D[1][0..<2]
let slice1D = tensor3D[0][0][3..<5]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 20.0, to: 40, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testNewAxisIndexing() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let newAxis = TensorRange.newAxis
let ellipsis = TensorRange.ellipsis
let slice3D = tensor3D[2..., newAxis, ellipsis]
let slice2D = tensor3D[1, newAxis][0..<1, 0..<2]
let slice1D = tensor3D[0][newAxis, 0][0..<1, 3..<5, newAxis]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 1, 4, 5])
XCTAssertEqual(array2D.shape, [1, 2, 5])
XCTAssertEqual(array1D.shape, [1, 2, 1])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 40.0, to: 60, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testSqueezeAxisIndexing() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let newAxis = TensorRange.newAxis
let ellipsis = TensorRange.ellipsis
let squeezeAxis = TensorRange.squeezeAxis
let slice3D = tensor3D[2..., newAxis, ellipsis][squeezeAxis, squeezeAxis]
let slice2D = tensor3D[1, newAxis][squeezeAxis, 0..<2]
let slice1D = tensor3D[0..<1, 0, 3..<5, newAxis][
squeezeAxis, ellipsis, squeezeAxis]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 40.0, to: 60, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testStridedSliceIndexing() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let slice3D = tensor3D[2...]
let slice2D = tensor3D[1][0..<3..2]
let slice1D = tensor3D[0][0][1..<5..2]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars, Array(stride(from: 40.0, to: 60, by: 1)))
XCTAssertEqual(
array2D.scalars,
Array(stride(from: 20.0, to: 25, by: 1)) +
Array(stride(from: 30.0, to: 35, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 1.0, to: 5, by: 2)))
}
func testStridedSliceIndexingAssignment() {
// NOTE: cannot test `Tensor.shape` or `Tensor.scalars` directly until send
// and receive are implemented (without writing a bunch of mini tests).
// Instead, `Tensor.array` is called to make a ShapedArray host copy and the
// ShapedArray is tested instead.
var tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
tensor3D[2, 0..<5..2, 0..<6] = Tensor<Float>(
shape: [2, 5], scalars: Array(stride(from: 20.0, to: 40, by: 2)))
let slice3D = tensor3D[2...]
let slice2D = tensor3D[1][0..<2]
let slice1D = tensor3D[0][0][3..<5]
let array3D = slice3D.array
let array2D = slice2D.array
let array1D = slice1D.array
/// Test shapes
XCTAssertEqual(array3D.shape, [1, 4, 5])
XCTAssertEqual(array2D.shape, [2, 5])
XCTAssertEqual(array1D.shape, [2])
/// Test scalars
XCTAssertEqual(array3D.scalars,
[Float](stride(from: 20.0, to: 30, by: 2)) +
[Float](stride(from: 45.0, to: 50, by: 1)) +
[Float](stride(from: 30.0, to: 40, by: 2)) +
[Float](stride(from: 55.0, to: 60, by: 1)))
XCTAssertEqual(array2D.scalars, Array(stride(from: 20.0, to: 30, by: 1)))
XCTAssertEqual(array1D.scalars, Array(stride(from: 3.0, to: 5, by: 1)))
}
func testWholeTensorSlicing() {
let t: Tensor<Int32> = [[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]]
let slice2 = t.slice(lowerBounds: [1, 0, 0], upperBounds: [2, 1, 3])
XCTAssertEqual(slice2.array, ShapedArray(shape: [1, 1, 3], scalars: [3, 3, 3]))
}
func testAdvancedIndexing() {
// NOTE: cannot test multiple `Tensor.shape` or `Tensor.scalars` directly
// until send and receive are implemented (without writing a bunch of mini
// tests). Instead, `Tensor.array` is called to make a ShapedArray host copy
// and the ShapedArray is tested.
let tensor3D = Tensor<Float>(
shape: [3, 4, 5], scalars: Array(stride(from: 0.0, to: 60, by: 1)))
let element2D = tensor3D[1..<3, 0, 3...]
let array2D = element2D.array
// Test shape
XCTAssertEqual(array2D.shape, [2, 2])
// Test scalars
XCTAssertEqual(array2D.scalars, Array([23.0, 24.0, 43.0, 44.0]))
}
func testConcatenation() {
// 2 x 3
let t1 = Tensor<Int32>([[0, 1, 2], [3, 4, 5]])
// 2 x 3
let t2 = Tensor<Int32>([[6, 7, 8], [9, 10, 11]])
let concatenated = t1 ++ t2
let concatenated0 = t1.concatenated(with: t2)
let concatenated1 = t1.concatenated(with: t2, alongAxis: 1)
XCTAssertEqual(concatenated.array, ShapedArray(shape: [4, 3], scalars: Array(0..<12)))
XCTAssertEqual(concatenated0.array, ShapedArray(shape: [4, 3], scalars: Array(0..<12)))
XCTAssertEqual(
concatenated1.array,
ShapedArray(shape: [2, 6], scalars: [0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11]))
}
func testVJPConcatenation() {
let a1 = Tensor<Float>([1,2,3,4])
let b1 = Tensor<Float>([5,6,7,8,9,10])
let a2 = Tensor<Float>([1,1,1,1])
let b2 = Tensor<Float>([1,1,1,1,1,1])
let grads = gradient(at: a2, b2) { a, b in
return ((a1 * a) ++ (b1 * b)).sum()
}
XCTAssertEqual(grads.0, a1)
XCTAssertEqual(grads.1, b1)
}
func testVJPConcatenationNegativeAxis() {
let a1 = Tensor<Float>([1,2,3,4])
let b1 = Tensor<Float>([5,6,7,8,9,10])
let a2 = Tensor<Float>([1,1,1,1])
let b2 = Tensor<Float>([1,1,1,1,1,1])
let grads = gradient(at: a2, b2) { a, b in
return (a1 * a).concatenated(with: b1 * b, alongAxis: -1).sum()
}
XCTAssertEqual(grads.0, a1)
XCTAssertEqual(grads.1, b1)
}
func testTranspose() {
// 3 x 2 -> 2 x 3
let xT = Tensor<Float>([[1, 2], [3, 4], [5, 6]]).transposed()
let xTArray = xT.array
XCTAssertEqual(xTArray.rank, 2)
XCTAssertEqual(xTArray.shape, [2, 3])
XCTAssertEqual(xTArray.scalars, [1, 3, 5, 2, 4, 6])
}
func testReshape() {
// 2 x 3 -> 1 x 3 x 1 x 2 x 1
let matrix = Tensor<Int32>([[0, 1, 2], [3, 4, 5]])
let reshaped = matrix.reshaped(to: [1, 3, 1, 2, 1])
XCTAssertEqual(reshaped.shape, [1, 3, 1, 2, 1])
XCTAssertEqual(reshaped.scalars, Array(0..<6))
}
func testFlatten() {
// 2 x 3 -> 6
let matrix = Tensor<Int32>([[0, 1, 2], [3, 4, 5]])
let flattened = matrix.flattened()
XCTAssertEqual(flattened.shape, [6])
XCTAssertEqual(flattened.scalars, Array(0..<6))
}
func testFlatten0D() {
let scalar = Tensor<Float>(5)
let flattened = scalar.flattened()
XCTAssertEqual(flattened.shape, [1])
XCTAssertEqual(flattened.scalars, [5])
}
func testReshapeToScalar() {
// 1 x 1 -> scalar
let z = Tensor<Float>([[10]]).reshaped(to: [])
XCTAssertEqual(z.shape, [])
}
func testReshapeTensor() {
// 2 x 3 -> 1 x 3 x 1 x 2 x 1
let x = Tensor<Float>(repeating: 0.0, shape: [2, 3])
let y = Tensor<Float>(repeating: 0.0, shape: [1, 3, 1, 2, 1])
let result = x.reshaped(like: y)
XCTAssertEqual(result.shape, [1, 3, 1, 2, 1])
}
func testUnbroadcastRank4ToRank2() {
let x = Tensor<Float>(repeating: 1, shape: [2, 3, 4, 5])
let y = Tensor<Float>(repeating: 1, shape: [4, 5])
let z = x.unbroadcasted(like: y)
XCTAssertEqual(z.array, ShapedArray<Float>(repeating: 6, shape: [4, 5]))
}
func testUnbroadcastRank4ToRank3() {
let x = Tensor<Float>(repeating: 1, shape: [2, 3, 4, 5])
let y = Tensor<Float>(repeating: 1, shape: [3, 1, 5])
let z = x.unbroadcasted(like: y)
XCTAssertEqual(z.array, ShapedArray<Float>(repeating: 8, shape: [3, 1, 5]))
}
func testUnbroadcast3x3To1x3() {
func foo(tensor: Tensor<Float>, shape: Tensor<Int32>) -> Tensor<Float> {
tensor.unbroadcasted(toShape: shape)
}
// [3,3] -> [1,3]
let atTensor: Tensor<Float> = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
let pb: (Tensor<Float>) -> Tensor<Float> = pullback(at: atTensor) { x in
foo(tensor: x, shape: [1, 3])
}
// Same shape as parameter of pullback
var inputTensor: Tensor<Float> = [[1, 2, 3]]
var expected: Tensor<Float> = atTensor
XCTAssertEqual(pb(inputTensor), expected)
// Different shape than parameter of pullback
inputTensor = [2]
expected = [
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]]
XCTAssertEqual(pb(inputTensor), expected)
// Same shape as tensor we are differentiating at
inputTensor = [
[8, 1, 3],
[8, 1, 3],
[8, 1, 3]]
expected = inputTensor
XCTAssertEqual(pb(inputTensor), expected)
}
func testSliceUpdate() {
var t1 = Tensor<Float>([[1, 2, 3], [4, 5, 6]])
t1[0] = Tensor(zeros: [3])
XCTAssertEqual(t1.array, ShapedArray(shape:[2, 3], scalars: [0, 0, 0, 4, 5, 6]))
var t2 = t1
t2[0][2] = Tensor(3)
XCTAssertEqual(t2.array, ShapedArray(shape:[2, 3], scalars: [0, 0, 3, 4, 5, 6]))
var t3 = Tensor<Bool>([[true, true, true], [false, false, false]])
t3[0][1] = Tensor(false)
XCTAssertEqual(t3.array, ShapedArray(
shape:[2, 3], scalars: [true, false, true, false, false, false]))
var t4 = Tensor<Bool>([[true, true, true], [false, false, false]])
t4[0] = Tensor(repeating: false, shape: [3])
XCTAssertEqual(t4.array, ShapedArray(repeating: false, shape: [2, 3]))
}
func testBroadcastTensor() {
// 1 -> 2 x 3 x 4
let one = Tensor<Float>(1)
var target = Tensor<Float>(repeating: 0.0, shape: [2, 3, 4])
let broadcasted = one.broadcasted(like: target)
XCTAssertEqual(broadcasted, Tensor(repeating: 1, shape: [2, 3, 4]))
target .= Tensor(repeating: 1, shape: [1, 3, 1])
XCTAssertEqual(target, Tensor(repeating: 1, shape: [2, 3, 4]))
}
func testBroadcast3x0To3x3() {
func foo(tensor: Tensor<Float>, shape: Tensor<Int32>) -> Tensor<Float> {
tensor.broadcasted(toShape: shape)
}
// [3,] -> [3,3]
let pb: (Tensor<Float>) -> Tensor<Float> = pullback(at: [99, 33, 55]) { x in
foo(tensor: x, shape: [3, 3])
}
// Same shape as parameter of pullback
var inputTensor: Tensor<Float> = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
var expected: Tensor<Float> = [3, 6, 9]
XCTAssertEqual(pb(inputTensor), expected)
// Different shape than parameter of pullback
inputTensor = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
expected = [4, 8, 12]
XCTAssertEqual(pb(inputTensor), expected)
// Same shape as tensor we are differentiating at
inputTensor = [1, 2, 3]
expected = [1, 2, 3]
XCTAssertEqual(pb(inputTensor), expected)
// Extremely padded shape as tensor we are differentiating at
inputTensor = [[[[[[1, 2, 3]]]]]]
expected = [1, 2, 3]
XCTAssertEqual(pb(inputTensor), expected)
}
func testBroadcast3x1To3x3() {
func foo(tensor: Tensor<Float>, shape: Tensor<Int32>) -> Tensor<Float> {
tensor.broadcasted(toShape: shape)
}
// [3,1] -> [3x3]
let pb: (Tensor<Float>) -> Tensor<Float> = pullback(at: [[99, 33, 55]]) { x in
foo(tensor: x, shape: [3, 3])
}
// Same shape as parameter of pullback
var inputTensor: Tensor<Float> = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
var expected: Tensor<Float> = [[3, 6, 9]]
XCTAssertEqual(pb(inputTensor), expected)
// Different shape than parameter of pullback
inputTensor = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
expected = [[4, 8, 12]]
XCTAssertEqual(pb(inputTensor), expected)
// Same shape as tensor we are differentiating at
inputTensor = [[1, 2, 3]]
expected = [[1, 2, 3]]
XCTAssertEqual(pb(inputTensor), expected)
// Extremely padded shape of tensor we are differentiating at
inputTensor = [[[[[[1, 2, 3]]]]]]
expected = [[1, 2, 3]]
XCTAssertEqual(pb(inputTensor), expected)
}
static var allTests = [
("testGathering", testGathering),
("testBatchGathering", testBatchGathering),
("testPadded", testPadded),
("testPaddedConstant", testPaddedConstant),
("testPaddedReflect", testPaddedReflect),
("testPaddedSymmetric", testPaddedSymmetric),
("testVJPPadded", testVJPPadded),
("testVJPPaddedConstant", testVJPPaddedConstant),
("testVJPPaddedReflect", testVJPPaddedReflect),
("testVJPPaddedSymmetric", testVJPPaddedSymmetric),
("testElementIndexing", testElementIndexing),
("testElementIndexingAssignment", testElementIndexingAssignment),
("testNestedElementIndexing", testNestedElementIndexing),
("testSliceIndexing", testSliceIndexing),
("testSliceIndexingAssignment", testSliceIndexingAssignment),
("testEllipsisIndexing", testEllipsisIndexing),
("testNewAxisIndexing", testNewAxisIndexing),
("testSqueezeAxisIndexing", testSqueezeAxisIndexing),
("testStridedSliceIndexing", testStridedSliceIndexing),
("testStridedSliceIndexingAssignment", testStridedSliceIndexingAssignment),
("testWholeTensorSlicing", testWholeTensorSlicing),
("testAdvancedIndexing", testAdvancedIndexing),
("testConcatenation", testConcatenation),
("testVJPConcatenation", testVJPConcatenation),
("testTranspose", testTranspose),
("testReshape", testReshape),
("testFlatten", testFlatten),
("testFlatten0D", testFlatten0D),
("testReshapeToScalar", testReshapeToScalar),
("testReshapeTensor", testReshapeTensor),
("testUnbroadcastRank4ToRank2", testUnbroadcastRank4ToRank2),
("testUnbroadcastRank4ToRank3", testUnbroadcastRank4ToRank3),
("testUnbroadcast3x3To1x3", testUnbroadcast3x3To1x3),
("testSliceUpdate", testSliceUpdate),
("testBroadcast3x0To3x3", testBroadcast3x0To3x3),
("testBroadcast3x1To3x3", testBroadcast3x1To3x3),
("testBroadcastTensor", testBroadcastTensor)
]
}
| 39.791726 | 95 | 0.570517 |
01d0d62fb98c4bc34628b52db017d4b53f9cab2a | 2,132 | //
// FlexibleViewController.swift
// CollectionViewExample
//
// Created by giftbot on 2020/01/24.
// Copyright © 2020 giftbot. All rights reserved.
//
import UIKit
final class FlexibleViewController: UIViewController {
let layout = UICollectionViewFlowLayout()
lazy var collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
var parkImages = ParkManager.imageNames(of: .nationalPark)
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
// MARK: Setup CollectionView
func setupCollectionView() {
setupFlowLayout()
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.identifier)
collectionView.backgroundColor = .systemBackground
collectionView.dataSource = self
view.addSubview(collectionView)
}
func setupFlowLayout() {
let itemsInLine: CGFloat = 2
let spacing: CGFloat = 10
let insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let cvWidth = collectionView.bounds.width
let contentSize = cvWidth - insets.left - insets.right - (spacing * (itemsInLine - 1))
let itemSize = (contentSize / itemsInLine).rounded(.down)
layout.minimumLineSpacing = spacing
layout.minimumInteritemSpacing = spacing
layout.sectionInset = insets
layout.itemSize = CGSize(width: itemSize, height: itemSize)
}
}
// MARK: - UICollectionViewDataSource
extension FlexibleViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return parkImages.count * 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: CustomCell.identifier, for: indexPath
) as! CustomCell
cell.backgroundColor = .black
let item = indexPath.item % parkImages.count
cell.configure(image: UIImage(named: parkImages[item]), title: parkImages[item])
return cell
}
}
| 29.611111 | 119 | 0.732645 |
236002f3d397ab3e2cdd198ae478d17319c55a0c | 1,063 | //
// MCCPlacementTests.swift
// MCCPlacementTests
//
// Created by Kenneth Chew on 10/18/20.
//
import XCTest
@testable import MCCPlacement__iOS_
class MCCPlacementiOSTests: XCTestCase {
let sampleTeam = Team(name: "Test", averageScore: 2000.0, averageWins: 0.3, averageTopTen: 0.25)
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 testTeamJSONRepresentation() throws {
let encoder = JSONEncoder()
guard let encodedData = try? encoder.encode(sampleTeam) else {
XCTFail("Failed to encode the data.")
return
}
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(Team.self, from: encodedData) else {
XCTFail("Failed to decode the data.")
return
}
XCTAssertEqual(sampleTeam, decodedData)
}
}
| 26.575 | 107 | 0.69238 |
2f77d520cdd42fec36ba489049a2ba8ae451302b | 664 | //
// ViewController.swift
// AppOne
//
// Created by Anton Schukin on 11/05/2019.
// Copyright © 2019 Anton Schukin. All rights reserved.
//
import Chat
import Chatto
import ChattoAdditions
import Gallery
import SnapKit
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView()
view.backgroundColor = .red
self.view.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.width.height.equalTo(50)
make.center.equalTo(self.view)
}
let chatClass = ChatClass()
print(chatClass)
}
}
| 18.971429 | 56 | 0.64006 |
267ba9cbf28f0114719d1c80504148274a180e61 | 604 | //
// LaunchesViewInput.swift
// SpaceX
//
// Created by Ibragim Akaev on 16/11/2021.
// Copyright © 2021 Chetech. All rights reserved.
//
import UIKit
protocol LaunchesViewInput: AnyObject {
var activityToggle: Bool { get set }
func setupCollectionView()
func setupSegmentedControl()
func setupActivityIndicator()
func setupAlertView(with title: String, and message: String)
func reload()
}
protocol LaunchCellViewInput {
func configure(with launch: Launch, date: String, location: String, rocket: String, launchResult: Bool)
func configure(with image: UIImage)
}
| 25.166667 | 107 | 0.725166 |
72efa91c8bbf151837c04a7ad4b9f347051a4b18 | 5,108 | import Quick
import Nimble
@testable import SimpleSource
class IndexedUpdateHandlerTests: QuickSpec {
var subscriptions: [IndexedUpdateHandler.Subscription] = []
override func spec() {
describe("An IndexedUpdateHandler") {
let updateHandler = IndexedUpdateHandler()
it("forwards full updates to a subscribed observer") {
var receivedFullUpdates = 0
let subscription = updateHandler.subscribe { update in
if case .full = update {
receivedFullUpdates = receivedFullUpdates + 1
} else {
fail("Unexpected update received.")
}
}
self.subscriptions = [subscription]
updateHandler.sendFullUpdate()
expect(receivedFullUpdates) == 1
updateHandler.send(update: .full)
expect(receivedFullUpdates) == 2
self.subscriptions = []
}
it("forwards delta updates to a subscribed observer") {
var receivedUpdates: [IndexedUpdate] = []
let subscription = updateHandler.subscribe { update in
receivedUpdates.append(update)
}
self.subscriptions = [subscription]
let sentInsertedSections = IndexSet([1, 2])
let sentUpdatedSections = IndexSet([3, 4, 5])
let sentDeletedSections = IndexSet([6, 7])
let sentInsertedRows = [IndexPath(item: 1, section: 20)]
let sentUpdatedRows = [IndexPath(item: 0, section: 1), IndexPath(item: 10, section: 11)]
let sentDeletedRows = [IndexPath(item: 100, section: 100)]
updateHandler.send(update: .delta(
insertedSections: sentInsertedSections,
updatedSections: sentUpdatedSections,
deletedSections: sentDeletedSections,
insertedRows: sentInsertedRows,
updatedRows: sentUpdatedRows,
deletedRows: sentDeletedRows))
expect(receivedUpdates.count) == 1
switch receivedUpdates[0] {
case let .delta(
insertedSections: receivedInsertedSections,
updatedSections: receivedUpdatedSections,
deletedSections: receivedDeletedSections,
insertedRows: receivedInsertedRows,
updatedRows: receivedUpdatedRows,
deletedRows: receivedDeletedRows):
expect(receivedInsertedSections) == sentInsertedSections
expect(receivedUpdatedSections) == sentUpdatedSections
expect(receivedDeletedSections) == sentDeletedSections
expect(receivedInsertedRows) == sentInsertedRows
expect(receivedUpdatedRows) == sentUpdatedRows
expect(receivedDeletedRows) == sentDeletedRows
case .full:
fail("Unexpected update received.")
}
self.subscriptions = []
}
it("stops sending updates to removed observers") {
var updatesForSubscriptionA = 0
var updatesForSubscriptionB = 0
self.subscriptions = []
self.subscriptions.append(updateHandler.subscribe { _ in
updatesForSubscriptionA = updatesForSubscriptionA + 1
})
updateHandler.sendFullUpdate()
expect(updatesForSubscriptionA) == 1
expect(updatesForSubscriptionB) == 0
self.subscriptions.append(updateHandler.subscribe { _ in
updatesForSubscriptionB = updatesForSubscriptionB + 1
})
updateHandler.sendFullUpdate()
expect(updatesForSubscriptionA) == 2
expect(updatesForSubscriptionB) == 1
_ = self.subscriptions.removeLast()
updateHandler.sendFullUpdate()
expect(updatesForSubscriptionA) == 3
expect(updatesForSubscriptionB) == 1
_ = self.subscriptions.removeLast()
updateHandler.sendFullUpdate()
expect(updatesForSubscriptionA) == 3
expect(updatesForSubscriptionB) == 1
expect(self.subscriptions.isEmpty) == true
}
it("properly removes observation closures") {
class TestObject {}
weak var weakObject: TestObject?
do {
let object = TestObject()
weakObject = object
self.subscriptions.append(updateHandler.subscribe { [object] _ in _ = object })
}
expect(weakObject != nil) == true
self.subscriptions = []
expect(weakObject == nil) == true
}
}
}
}
| 38.69697 | 104 | 0.542091 |
8a03c1a5be1eb9310b075e0727ffa300687640e6 | 876 | //
// UserPlaylist.swift
// Nuage
//
// Created by Laurin Brandner on 02.11.20.
// Copyright © 2020 Laurin Brandner. All rights reserved.
//
import Foundation
public class UserPlaylist: Playlist {
public var secretToken: String?
public var isAlbum: Bool
public var date: Date
enum CodingKeys: String, CodingKey {
case secretToken = "secret_token"
case isAlbum = "is_album"
case date = "created_at"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
isAlbum = try container.decode(Bool.self, forKey: .isAlbum)
secretToken = try container.decodeIfPresent(String.self, forKey: .secretToken)
date = try container.decode(Date.self, forKey: .date)
try super.init(from: decoder)
}
}
| 25.764706 | 86 | 0.648402 |
7902c5dab9008177abad0ea52f4e682e95cdef8c | 11,989 | //******************************************************************************
// 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 XCTest
import Foundation
import SwiftRT
class test_arraySyntax: XCTestCase {
//==========================================================================
// support terminal test run
static var allTests = [
("test_initSyntax", test_initSyntax),
("test_array", test_array),
("test_empty", test_empty),
("test_emptyLike", test_emptyLike),
("test_ones", test_ones),
("test_onesLike", test_onesLike),
("test_onesView", test_onesView),
("test_zeros", test_zeros),
("test_zerosLike", test_zerosLike),
("test_full", test_full),
("test_fullLike", test_fullLike),
("test_identity", test_identity),
("test_eye", test_eye),
]
//--------------------------------------------------------------------------
func test_initSyntax() {
// stored bit pattern
let _ = array(stored: [Float16(0), Float16(1)])
let _ = array(stored: [Float16(0), Float16(1)], (1, 2))
// packed types
let _ = array([0, 1, 0, 1], type: UInt1.self)
let _ = array(stored: [0b00001010])
let _ = array([0, 1, 2, 3], type: UInt4.self)
let _ = array(stored: [0x10, 0x32])
// boolean conversion to Element
let _ = array([true, false], type: UInt1.self)
let _ = array([true, false], type: UInt4.self)
let _ = array([true, false], type: UInt8.self)
let _ = array([true, false], type: Int32.self)
let _ = array([true, false], type: Float16.self)
let _ = array([true, false], type: Float.self)
let _ = array([true, false], type: Double.self)
// boolean conversion to shaped Element
let _ = array([true, false], (1, 2), type: UInt1.self)
let _ = array([true, false], (1, 2), type: UInt4.self)
let _ = array([true, false], (1, 2), type: UInt8.self)
let _ = array([true, false], (1, 2), type: Int32.self)
let _ = array([true, false], (1, 2), type: Float16.self)
let _ = array([true, false], (1, 2), type: Float.self)
let _ = array([true, false], (1, 2), type: Double.self)
// implicit vectors
let _ = array([true, false])
let _ = array([0, 1, 2])
let _ = array([Float](arrayLiteral: 0, 1, 2))
let _ = array([0.0, 1.5, 2.5])
let _ = array([RGB<UInt8>(0, 127, 255), RGB<UInt8>(63, 127, 191)])
let _ = array([RGB<Float>(0, 0.5, 1), RGB<Float>(0.25, 0.5, 0.75)])
// implicit shaped
let _ = array([true, false], (1, 2))
let _ = array([RGB<UInt8>(0, 127, 255), RGB<UInt8>(63, 127, 191)], (1, 2))
let _ = array([RGB<Float>(0, 0.5, 1), RGB<Float>(0.25, 0.5, 0.75)], (1, 2))
// integer conversions to Element
let _ = array([0, 1, 2], type: Bool.self)
let _ = array([0, 1, 2], type: UInt8.self)
let _ = array([0, 1, 2], type: Int32.self)
let _ = array([0, 1, 2], type: Float.self)
let _ = array([0, 1, 2], type: Double.self)
// floating conversions to Element
let _ = array([0.0, 1, 2], type: Bool.self)
let _ = array([0.0, 1.5, 2.5], type: UInt8.self)
let _ = array([0.0, 1.5, 2.5], type: Int32.self)
let _ = array([0.0, 1.5, 2.5], type: Float.self)
let _ = array([0.0, 1.5, 2.5], type: Double.self)
// integer conversions to shaped Element
let _ = array([0, 1, 2], (1, 3), type: Bool.self)
let _ = array([0, 1, 2], (1, 3), type: UInt8.self)
let _ = array([0, 1, 2], (1, 3), type: Int32.self)
let _ = array([0, 1, 2], (1, 3), type: Float.self)
let _ = array([0, 1, 2], (1, 3), type: Double.self)
// floating conversions to shaped Element
let _ = array([0.0, 1, 2], (1, 3), type: Bool.self)
let _ = array([0.0, 1.5, 2.5], (1, 3), type: UInt8.self)
let _ = array([0.0, 1.5, 2.5], (1, 3), type: Int32.self)
let _ = array([0.0, 1.5, 2.5], (1, 3), type: Float.self)
let _ = array([0.0, 1.5, 2.5], (1, 3), type: Double.self)
}
//--------------------------------------------------------------------------
// test_array
func test_array() {
// Rank1
let b: [Int8] = [0, 1, 2]
let _ = array(b)
let _ = array(b, type: Int32.self)
let _ = array(b, type: Double.self)
let dt: [DType] = [1.5, 2.5, 3.5]
let _ = array(dt)
let _ = array(dt, type: Int32.self)
let _ = array(dt, type: Double.self)
let d: [Double] = [1.5, 2.5, 3.5]
let _ = array(d)
let _ = array(d, type: Int32.self)
let _ = array([[0, 1, 2], [3, 4, 5]])
let _ = array([0, 1, 2, 3, 4, 5], (2, 3))
let _ = array(0..<6, (2, 3))
}
//--------------------------------------------------------------------------
// test_empty
func test_empty() {
// T0
let _ = empty()
let _ = empty(type: Int32.self)
// T1
let _ = empty(3)
let _ = empty(3, order: .F)
let _ = empty(3, type: Int32.self)
let _ = empty(3, type: Int32.self, order: .F)
// T2
let _ = empty((2, 3))
let _ = empty((2, 3), order: .F)
let _ = empty((2, 3), type: Int32.self)
let _ = empty((2, 3), type: Int32.self, order: .F)
}
//--------------------------------------------------------------------------
// test_emptyLike
func test_emptyLike() {
let proto = empty((2, 3))
let _ = empty(like: proto)
let _ = empty(like: proto, shape: (6))
let _ = empty(like: proto, shape: (1, 2, 3))
let _ = empty(like: proto, order: .F)
let _ = empty(like: proto, order: .F, shape: (1, 2, 3))
let _ = empty(like: proto, type: Int32.self)
let _ = empty(like: proto, type: Int32.self, shape: (1, 2, 3))
let _ = empty(like: proto, type: Int32.self, order: .F, shape: (1, 2, 3))
}
//--------------------------------------------------------------------------
// test_ones
func test_ones() {
// T0
let _ = one()
let _ = one(type: Int32.self)
// T1
let _ = ones(3)
let _ = ones(3, order: .F)
let _ = ones(3, type: Int32.self)
let _ = ones(3, type: Int32.self, order: .F)
// T2
let _ = ones((2, 3))
let _ = ones((2, 3), order: .F)
let _ = ones((2, 3), type: Int32.self)
let _ = ones((2, 3), type: Int32.self, order: .F)
}
//--------------------------------------------------------------------------
// test_onesLike
func test_onesLike() {
let proto = ones((2, 3))
let _ = ones(like: proto)
let _ = ones(like: proto, shape: (6))
let _ = ones(like: proto, shape: (1, 2, 3))
let _ = ones(like: proto, order: .F)
let _ = ones(like: proto, order: .F, shape: (1, 2, 3))
let _ = ones(like: proto, type: Int32.self)
let _ = ones(like: proto, type: Int32.self, shape: (1, 2, 3))
let _ = ones(like: proto, type: Int32.self, order: .F, shape: (1, 2, 3))
}
//--------------------------------------------------------------------------
// test_onesView
func test_onesView() {
let t1 = ones((4, 3), type: Int32.self)
let view = t1[1...2, ...]
XCTAssert(view == [[1, 1, 1], [1, 1, 1]])
}
//--------------------------------------------------------------------------
// test_zeros
func test_zeros() {
// T0
let _ = zero()
let _ = zero(type: Int32.self)
// T1
let _ = zeros(3)
let _ = zeros(3, order: .F)
let _ = zeros(3, type: Int32.self)
let _ = zeros(3, type: Int32.self, order: .F)
// T2
let _ = zeros((2, 3))
let _ = zeros((2, 3), order: .F)
let _ = zeros((2, 3), type: Int32.self)
let _ = zeros((2, 3), type: Int32.self, order: .F)
}
//--------------------------------------------------------------------------
// test_zerosLike
func test_zerosLike() {
let proto = zeros((2, 3))
let _ = zeros(like: proto)
let _ = zeros(like: proto, shape: (6))
let _ = zeros(like: proto, shape: (1, 2, 3))
let _ = zeros(like: proto, order: .F)
let _ = zeros(like: proto, order: .F, shape: (1, 2, 3))
let _ = zeros(like: proto, type: Int32.self)
let _ = zeros(like: proto, type: Int32.self, shape: (1, 2, 3))
let _ = zeros(like: proto, type: Int32.self, order: .F, shape: (1, 2, 3))
}
//--------------------------------------------------------------------------
// test_full
func test_full() {
// T0
let _ = full(42)
let _ = full(42, type: Int32.self)
// T1
let _ = full(3)
let _ = full(3, 42, order: .F)
let _ = full(3, 42, type: Int32.self)
let _ = full(3, 42, type: Int32.self, order: .F)
// T2
let _ = full((2, 3), 42)
let _ = full((2, 3), 42, order: .F)
let _ = full((2, 3), 42, type: Int32.self)
let _ = full((2, 3), 42, type: Int32.self, order: .F)
}
//--------------------------------------------------------------------------
// test_fullLike
func test_fullLike() {
let proto = empty((2, 3))
let _ = full(like: proto, 42)
let _ = full(like: proto, 42, shape: (6))
let _ = full(like: proto, 42, shape: (1, 2, 3))
let _ = full(like: proto, 42, order: .F)
let _ = full(like: proto, 42, order: .F, shape: (1, 2, 3))
let _ = full(like: proto, 42, type: Int32.self)
let _ = full(like: proto, 42, type: Int32.self, shape: (1, 2, 3))
let _ = full(like: proto, 42, type: Int32.self, order: .F, shape: (1, 2, 3))
}
//--------------------------------------------------------------------------
// test_identity
func test_identity() {
// let _ = identity(3)
// let _ = identity(3, order: .F)
// let _ = identity(3, type: Int.self)
// let _ = identity(3, type: Int.self, order: .F)
}
//--------------------------------------------------------------------------
// test_eye
func test_eye() {
// TODO
// // verify signature combinations
// let _ = eye(2)
// let _ = eye(3, k: 1)
// let _ = eye(4, 3, k: -1, type: Int.self)
// let _ = eye(3, type: Int.self, order: .F)
// print(eye(3, k: 0, type: Int.self))
// // check plus
// XCTAssert(eye(3, k: 1) == [
// [0, 1, 0],
// [0, 0, 1],
// [0, 0, 0],
// ])
//
// // check subview plus
// XCTAssert(eye(4, k: 1)[..<3, 1...] == [
// [0, 1, 0],
// [0, 0, 1],
// [0, 0, 0],
// ])
//
// // check minus
// XCTAssert(eye(3, k: -1) == [
// [0, 0, 0],
// [1, 0, 0],
// [0, 1, 0],
// ])
//
// // check subview minus
// XCTAssert(eye(4, k: -1)[1..., ..<3] == [
// [0, 0, 0],
// [1, 0, 0],
// [0, 1, 0],
// ])
}
}
| 36.220544 | 84 | 0.441488 |
91d2c935849e2947485c745ee95ee6ece043261d | 5,952 | //
// BulkEnvelopeStatus.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import AnyCodable
import Foundation
import Vapor
/** */
public final class BulkEnvelopeStatus: Content, Hashable {
/** Identifier used to query the status of an individual bulk recipient batch. */
public var batchId: String?
/** The total number of items in the batch being queried. */
public var batchSize: String?
/** A list of bulk envelope objects. */
public var bulkEnvelopes: [BulkEnvelope]?
/** URI at which you can retrieve the batch envelopes. */
public var bulkEnvelopesBatchUri: String?
/** The last index position in the result set. */
public var endPosition: String?
/** The number of entries with a status of `failed`. */
public var failed: String?
/** The URI for the next chunk of records based on the search request. It is `null` if this is the last set of results for the search. */
public var nextUri: String?
/** The URI for the prior chunk of records based on the search request. It is `null` if this is the first set of results for the search. */
public var previousUri: String?
/** The number of entries with a status of `queued`. */
public var queued: String?
/** The number of results in this response. Because you can filter which entries are included in the response, this value is always less than or equal to the `totalSetSize`. */
public var resultSetSize: String?
/** The number of entries with a status of `sent`. */
public var sent: String?
/** The starting index position of the current result set. */
public var startPosition: String?
/** The date on which the bulk envelope was created. */
public var submittedDate: String?
/** The total number of items in the result set. This value is always greater than or equal to the value of `resultSetSize`. */
public var totalSetSize: String?
public init(batchId: String? = nil, batchSize: String? = nil, bulkEnvelopes: [BulkEnvelope]? = nil, bulkEnvelopesBatchUri: String? = nil, endPosition: String? = nil, failed: String? = nil, nextUri: String? = nil, previousUri: String? = nil, queued: String? = nil, resultSetSize: String? = nil, sent: String? = nil, startPosition: String? = nil, submittedDate: String? = nil, totalSetSize: String? = nil) {
self.batchId = batchId
self.batchSize = batchSize
self.bulkEnvelopes = bulkEnvelopes
self.bulkEnvelopesBatchUri = bulkEnvelopesBatchUri
self.endPosition = endPosition
self.failed = failed
self.nextUri = nextUri
self.previousUri = previousUri
self.queued = queued
self.resultSetSize = resultSetSize
self.sent = sent
self.startPosition = startPosition
self.submittedDate = submittedDate
self.totalSetSize = totalSetSize
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case batchId
case batchSize
case bulkEnvelopes
case bulkEnvelopesBatchUri
case endPosition
case failed
case nextUri
case previousUri
case queued
case resultSetSize
case sent
case startPosition
case submittedDate
case totalSetSize
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(batchId, forKey: .batchId)
try container.encodeIfPresent(batchSize, forKey: .batchSize)
try container.encodeIfPresent(bulkEnvelopes, forKey: .bulkEnvelopes)
try container.encodeIfPresent(bulkEnvelopesBatchUri, forKey: .bulkEnvelopesBatchUri)
try container.encodeIfPresent(endPosition, forKey: .endPosition)
try container.encodeIfPresent(failed, forKey: .failed)
try container.encodeIfPresent(nextUri, forKey: .nextUri)
try container.encodeIfPresent(previousUri, forKey: .previousUri)
try container.encodeIfPresent(queued, forKey: .queued)
try container.encodeIfPresent(resultSetSize, forKey: .resultSetSize)
try container.encodeIfPresent(sent, forKey: .sent)
try container.encodeIfPresent(startPosition, forKey: .startPosition)
try container.encodeIfPresent(submittedDate, forKey: .submittedDate)
try container.encodeIfPresent(totalSetSize, forKey: .totalSetSize)
}
public static func == (lhs: BulkEnvelopeStatus, rhs: BulkEnvelopeStatus) -> Bool {
lhs.batchId == rhs.batchId &&
lhs.batchSize == rhs.batchSize &&
lhs.bulkEnvelopes == rhs.bulkEnvelopes &&
lhs.bulkEnvelopesBatchUri == rhs.bulkEnvelopesBatchUri &&
lhs.endPosition == rhs.endPosition &&
lhs.failed == rhs.failed &&
lhs.nextUri == rhs.nextUri &&
lhs.previousUri == rhs.previousUri &&
lhs.queued == rhs.queued &&
lhs.resultSetSize == rhs.resultSetSize &&
lhs.sent == rhs.sent &&
lhs.startPosition == rhs.startPosition &&
lhs.submittedDate == rhs.submittedDate &&
lhs.totalSetSize == rhs.totalSetSize
}
public func hash(into hasher: inout Hasher) {
hasher.combine(batchId?.hashValue)
hasher.combine(batchSize?.hashValue)
hasher.combine(bulkEnvelopes?.hashValue)
hasher.combine(bulkEnvelopesBatchUri?.hashValue)
hasher.combine(endPosition?.hashValue)
hasher.combine(failed?.hashValue)
hasher.combine(nextUri?.hashValue)
hasher.combine(previousUri?.hashValue)
hasher.combine(queued?.hashValue)
hasher.combine(resultSetSize?.hashValue)
hasher.combine(sent?.hashValue)
hasher.combine(startPosition?.hashValue)
hasher.combine(submittedDate?.hashValue)
hasher.combine(totalSetSize?.hashValue)
}
}
| 45.435115 | 409 | 0.678427 |
b9b1b1ec440383dc7790745c215bc4efbd1d1534 | 1,267 | //
// DIPart.swift
// DITranquillity
//
// Created by Alexander Ivlev on 16/06/16.
// Copyright © 2017 Alexander Ivlev. All rights reserved.
//
/// Class to maintain code hierarchy.
/// It's necessary for it to be convenient to combine some parts of the system into one common class,
/// and in future to include the part, rather than some list components.
public protocol DIPart: class {
/// Method inside of which you can registration a components.
/// It's worth combining the components for some reason.
/// And call a class implementing the protocol according to this characteristics.
///
/// - Parameter container: A container. Don't call the method yourself, but leave it to the method `append(...)` into container.
static func load(container: DIContainer)
}
extension DIContainer {
/// Registers a part in the container.
/// Registration means inclusion of all components indicated within.
///
/// - Parameters:
/// - path: the part type
/// - Returns: self
@discardableResult
public func append(part: DIPart.Type) -> DIContainer {
if includedParts.checkAndInsert(ObjectIdentifier(part)) {
partStack.push(part)
defer { partStack.pop() }
part.load(container: self)
}
return self
}
}
| 31.675 | 130 | 0.696133 |
b9c56c9375873b164606687cb750a8fec0710381 | 182 | //
// foo.swift
// test
//
// Created by Sam Marshall on 3/19/15.
// Copyright (c) 2015 Sam Marshall. All rights reserved.
//
import Foundation
func foo() {
println("foo!");
} | 14 | 57 | 0.626374 |
e834658640e860f847de124214f9e3945877fa24 | 12,000 | //
// DocumentUploader.swift
// StripeIdentity
//
// Created by Mel Ludowise on 12/8/21.
//
import Foundation
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeCameraCore
protocol DocumentUploaderDelegate: AnyObject {
func documentUploaderDidUpdateStatus(_ documentUploader: DocumentUploader)
}
protocol DocumentUploaderProtocol: AnyObject {
/// Tuple of front and back document file data
typealias CombinedFileData = (
front: VerificationPageDataDocumentFileData?,
back: VerificationPageDataDocumentFileData?
)
var delegate: DocumentUploaderDelegate? { get set }
var frontUploadStatus: DocumentUploader.UploadStatus { get }
var backUploadStatus: DocumentUploader.UploadStatus { get }
var frontBackUploadFuture: Future<CombinedFileData> { get }
func uploadImages(
for side: DocumentSide,
originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: VerificationPageDataDocumentFileData.FileUploadMethod
)
func reset()
}
enum DocumentUploaderError: AnalyticLoggableError {
case unableToCrop
case unableToResize
func serializeForLogging() -> [String : Any] {
// TODO(mludowise|IDPROD-2816): Log error
return [:]
}
}
final class DocumentUploader: DocumentUploaderProtocol {
enum UploadStatus {
case notStarted
case inProgress
case complete
case error(Error)
}
struct Configuration {
/// The `purpose` to use when uploading the files
let filePurpose: String
/// JPEG compression quality of the high-res image uploaded to the server
let highResImageCompressionQuality: CGFloat
/// Value between 0–1 that determines how much padding to crop around a region of interest in an image
let highResImageCropPadding: CGFloat
/// Maximum width and height of the high-res image uploaded to the server
let highResImageMaxDimension: Int
/// JPEG compression quality of the low-res image uploaded to the server
let lowResImageCompressionQuality: CGFloat
/// Maximum width and height of the low-res image uploaded to the server
let lowResImageMaxDimension: Int
}
weak var delegate: DocumentUploaderDelegate?
/// Determines padding, compression, and scaling of images uploaded to the server
let configuration: Configuration
let apiClient: IdentityAPIClient
/// Worker queue to encode the image to jpeg
let imageEncodingQueue = DispatchQueue(label: "com.stripe.identity.image-encoding")
/// Future that is fulfilled when front images are uploaded to the server.
/// Value is nil if upload has not been requested.
private(set) var frontUploadFuture: Future<VerificationPageDataDocumentFileData>? {
didSet {
guard oldValue !== frontUploadFuture else {
return
}
frontUploadStatus = (frontUploadFuture == nil) ? .notStarted : .inProgress
frontUploadFuture?.observe { [weak self, weak frontUploadFuture] result in
// Only update `frontUploadStatus` if `frontUploadFuture` has not been reassigned
guard let self = self,
frontUploadFuture === self.frontUploadFuture else {
return
}
switch result {
case .success:
self.frontUploadStatus = .complete
case .failure(let error):
self.frontUploadStatus = .error(error)
}
}
}
}
/// Future that is fulfilled when back images are uploaded to the server.
/// Value is nil if upload has not been requested.
private(set) var backUploadFuture: Future<VerificationPageDataDocumentFileData>? {
didSet {
guard oldValue !== backUploadFuture else {
return
}
backUploadStatus = (backUploadFuture == nil) ? .notStarted : .inProgress
backUploadFuture?.observe { [weak self, weak backUploadFuture] result in
// Only update `backUploadStatus` if `backUploadFuture` has not been reassigned
guard let self = self,
backUploadFuture === self.backUploadFuture else {
return
}
switch result {
case .success:
self.backUploadStatus = .complete
case .failure(let error):
self.backUploadStatus = .error(error)
}
}
}
}
/// Status of whether the front images have finished uploading
private(set) var frontUploadStatus: UploadStatus = .notStarted {
didSet {
delegate?.documentUploaderDidUpdateStatus(self)
}
}
/// Status of whether the back images have finished uploading
private(set) var backUploadStatus: UploadStatus = .notStarted {
didSet {
delegate?.documentUploaderDidUpdateStatus(self)
}
}
/// Combined future that returns a tuple of front & back uploads
var frontBackUploadFuture: Future<CombinedFileData> {
// Unwrap futures by converting
// from Future<VerificationPageDataDocumentFileData>?
// to Future<VerificationPageDataDocumentFileData?>
let unwrappedFrontUploadFuture: Future<VerificationPageDataDocumentFileData?> = frontUploadFuture?.chained { Promise(value: $0) } ?? Promise(value: nil)
let unwrappedBackUploadFuture: Future<VerificationPageDataDocumentFileData?> = backUploadFuture?.chained { Promise(value: $0) } ?? Promise(value: nil)
return unwrappedFrontUploadFuture.chained { frontData in
return unwrappedBackUploadFuture.chained { Promise(value: (front: frontData, back: $0)) }
}
}
init(
configuration: Configuration,
apiClient: IdentityAPIClient
) {
self.configuration = configuration
self.apiClient = apiClient
}
/**
Uploads a high and low resolution image for a specific side of the
document and updates either `frontUploadFuture` or `backUploadFuture`.
- Note: If `idDetectorOutput` is non-nil, the high-res image will be
cropped and an un-cropped image will be uploaded as the low-res image.
If `idDetectorOutput` is nil, then only a high-res image will be
uploaded and it will not be cropped.
- Parameters:
- side: The side of the image (front or back) to upload.
- originalImage: The original image captured or uploaded by the user.
- idDetectorOutput: The output from the IDDetector model
- method: The method the image was obtained.
*/
func uploadImages(
for side: DocumentSide,
originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: VerificationPageDataDocumentFileData.FileUploadMethod
) {
let uploadFuture = uploadImages(
originalImage,
documentScannerOutput: documentScannerOutput,
exifMetadata: exifMetadata,
method: method,
fileNamePrefix: "\(apiClient.verificationSessionId)_\(side.rawValue)"
)
switch side {
case .front:
self.frontUploadFuture = uploadFuture
case .back:
self.backUploadFuture = uploadFuture
}
}
/// Uploads both a high and low resolution image
func uploadImages(
_ originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: VerificationPageDataDocumentFileData.FileUploadMethod,
fileNamePrefix: String
) -> Future<VerificationPageDataDocumentFileData> {
// Only upload a low res image if the high res image will be cropped
let lowResUploadFuture: Future<StripeFile?> = (documentScannerOutput == nil)
? Promise(value: nil)
: uploadLowResImage(
originalImage,
fileNamePrefix: fileNamePrefix
).chained { Promise(value: $0) }
return uploadHighResImage(
originalImage,
regionOfInterest: documentScannerOutput?.idDetectorOutput.documentBounds,
fileNamePrefix: fileNamePrefix
).chained { highResFile in
return lowResUploadFuture.chained { lowResFile in
// Convert promise to a tuple of file IDs
return Promise(value: (
lowRes: lowResFile?.id,
highRes: highResFile.id
))
}
}.chained { (lowRes, highRes) -> Future<VerificationPageDataDocumentFileData> in
return Promise(value: VerificationPageDataDocumentFileData(
documentScannerOutput: documentScannerOutput,
highResImage: highRes,
lowResImage: lowRes,
exifMetadata: exifMetadata,
uploadMethod: method
))
}
}
/// Crops, resizes, and uploads the high resolution image to the server
func uploadHighResImage(
_ image: CGImage,
regionOfInterest: CGRect?,
fileNamePrefix: String
) -> Future<StripeFile> {
// Crop image if there's a region of interest
var imageToResize = image
if let regionOfInterest = regionOfInterest {
guard let croppedImage = image.cropping(
toNormalizedRegion: regionOfInterest,
withPadding: configuration.highResImageCropPadding
) else {
return Promise(error: DocumentUploaderError.unableToCrop)
}
imageToResize = croppedImage
}
guard let resizedImage = imageToResize.scaledDown(toMaxPixelDimension: CGSize(
width: configuration.highResImageMaxDimension,
height: configuration.highResImageMaxDimension
)) else {
return Promise(error: DocumentUploaderError.unableToResize)
}
return uploadJPEG(
image: resizedImage,
fileName: fileNamePrefix,
jpegCompressionQuality: configuration.highResImageCompressionQuality
)
}
/// Resizes and uploads the low resolution image to the server
func uploadLowResImage(
_ image: CGImage,
fileNamePrefix: String
) -> Future<StripeFile> {
guard let resizedImage = image.scaledDown(toMaxPixelDimension: CGSize(
width: configuration.lowResImageMaxDimension,
height: configuration.lowResImageMaxDimension
)) else {
return Promise(error: DocumentUploaderError.unableToResize)
}
return uploadJPEG(
image: resizedImage,
fileName: "\(fileNamePrefix)_full_frame",
jpegCompressionQuality: configuration.lowResImageCompressionQuality
)
}
/// Converts image to JPEG data and uploads it to the server on a worker thread
func uploadJPEG(
image: CGImage,
fileName: String,
jpegCompressionQuality: CGFloat
) -> Future<StripeFile> {
let promise = Promise<StripeFile>()
imageEncodingQueue.async { [weak self] in
guard let self = self else { return }
let uiImage = UIImage(cgImage: image)
self.apiClient.uploadImage(
uiImage,
compressionQuality: jpegCompressionQuality,
purpose: self.configuration.filePurpose,
fileName: fileName
).observe { result in
promise.fullfill(with: result)
}
}
return promise
}
/// Resets the status of the uploader
func reset() {
frontUploadFuture = nil
backUploadFuture = nil
}
}
| 37.037037 | 160 | 0.63775 |
de718a745ce5d48a84d47caa366644647e733109 | 6,650 | import Quick
import Nimble
import CBGPromise
import TethysKit
import FutureHTTP
func itCachesInProgressFutures<T>(factory: @escaping () -> Future<Result<T, TethysError>>,
callChecker: @escaping (Int) -> Void,
resolver: @escaping (TethysError?) -> Result<T, TethysError>,
equator: @escaping (Result<T, TethysError>, Result<T, TethysError>) -> Void) {
var future: Future<Result<T, TethysError>>!
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes a call to the underlying service") {
callChecker(1)
}
it("does not make another call to the underlying service if called before that future resolves") {
_ = factory()
callChecker(1)
}
describe("on success") {
var expectedValue: Result<T, TethysError>!
beforeEach {
expectedValue = resolver(nil)
}
it("resolves the future with the error") {
expect(future.value).toNot(beNil())
guard let received = future.value else { return }
equator(received, expectedValue)
}
describe("if called again") {
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes another call to the underlying service") {
callChecker(2)
}
}
}
describe("on error") {
var expectedValue: Result<T, TethysError>!
beforeEach {
expectedValue = resolver(TethysError.unknown)
}
it("resolves the future with the error") {
expect(future.value?.error).to(equal(expectedValue.error))
}
describe("if called again") {
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes another call to the underlying service") {
callChecker(2)
}
}
}
}
func itBehavesLikeTheRequestFailed<T>(url: URL, shouldParseData: Bool = true, file: String = #file, line: UInt = #line,
httpClient: @escaping () -> FakeHTTPClient,
future: @escaping () -> Future<Result<T, TethysError>>) {
if T.self != Void.self && shouldParseData {
describe("when the request succeeds") {
context("and the data is not valid") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "[\"bad\": \"data\"]".data(using: .utf8)!,
status: .ok,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with a bad response error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .badResponse("[\"bad\": \"data\"]".data(using: .utf8)!))
))
}
}
}
}
describe("when the request fails") {
context("when the request fails with a 400 level error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "403".data(using: .utf8)!,
status: HTTPStatus.init(rawValue: 403)!,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with the error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .http(.forbidden, "403".data(using: .utf8)!))
))
}
}
context("when the request fails with a 500 level error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "502".data(using: .utf8)!,
status: HTTPStatus.init(rawValue: 502)!,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with the error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .http(.badGateway, "502".data(using: .utf8)!))
))
}
}
context("when the request fails with an error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.failure(HTTPClientError.network(.timedOut)))
}
it("resolves the future with an error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .timedOut)
))
}
}
}
}
| 37.784091 | 128 | 0.506617 |
33645c467a569e52ddce77928770cb86e1f72bda | 958 | //
// DRNet_Tests.swift
// DRNet_Tests
//
// Created by Dariusz Rybicki on 08/11/14.
// Copyright (c) 2014 Darrarski. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(OS_X)
import Cocoa
#endif
import XCTest
class DRNet_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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 22.809524 | 111 | 0.613779 |
ebfcfbcc0f7866065d4ca819a505aa33ea686332 | 746 | /*
* 문자열.swift
* Question Link: https://www.acmicpc.net/problem/1120
* Primary idea: <Greedy>
* 1. 앞/뒤로는 무조건 긴 문자열과 같은 값이 되도록 값을 넣는다고 가정
* 2. a의 길이 < b의 길이 : a[i] != b[j]의 개수가 가장 짧은 구간으로 선택
*
* Time Complexity : O(a^b)
* Space Complexity : O(1)
* Runtime: 8 ms
* Memory Usage: 64.048 MB
*
* Created by gunhyeong on 2020/05/06.
*/
import Foundation
var input = readLine()!.split(separator : " ")
var A = Array(input[0])
var B = Array(input[1])
var diff = B.count
for i in 0..<B.count-A.count + 1 {
var count = 0
for j in 0..<A.count {
if A[j] != B[i+j] {
count += 1
}
}
if diff > count {
diff = count
}
}
print(diff)
| 19.631579 | 74 | 0.521448 |
d79016eab9e624fc8d0b94791553d0d6154e9db1 | 454 | // Tests temporary -swift-version 6 behavior in compilers with asserts disabled,
// where we don't allow -swift-version 6 to keep it out of release compilers.
// UNSUPPORTED: asserts
// RUN: not %target-swiftc_driver -swift-version 6 -typecheck %s 2>&1 | %FileCheck --check-prefix ERROR_6 %s
// ERROR_6: <unknown>:0: error: invalid value '6' in '-swift-version 6'
// ERROR_7: <unknown>:0: note: valid arguments to '-swift-version'
// ERROR_7-NOT: '6'
| 41.272727 | 108 | 0.715859 |
fe6df8a24a904cb1a287414fe86bde91ee670495 | 933 | //
// StuffFriendsSayTests.swift
// StuffFriendsSayTests
//
// Created by Mike Gehard on 3/10/20.
// Copyright © 2020 Mike Gehard. All rights reserved.
//
import XCTest
@testable import StuffFriendsSay
class StuffFriendsSayTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.657143 | 111 | 0.664523 |
645054157d799ba1929bd9d9c298c7ad38ad60cb | 364 | //
// AppConstants.swift
// CodingAssessmentApp
//
// Created by Laxman Sahni on 26/06/18.
// Copyright © 2018 Nagarro. All rights reserved.
//
import Foundation
let sampleKey = "54e5496eb75443aea29abca3eda6dbf6"
struct WebUrl
{
static let baseUrl = "http://api.nytimes.com/svc/mostpopular/v2/mostviewed/{section}/{period}.json?api-key={sampleKey}"
}
| 19.157895 | 123 | 0.725275 |
e5632c0169a5b29f52161a92032995dbe8df00ff | 221 | // 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 f {
(
[ {
for {
enum b {
deinit {
class
case ,
| 17 | 87 | 0.719457 |
acc0de5bee1e3a5e6564e66c63f079a510343669 | 2,708 | // Upload.swift
// Copyright (c) 2021 Copilot
import Foundation
import SwiftyJSON
/**
Upload struct
Uploading to Strava is an asynchronous process. A file is uploaded using a multipart/form-data POST request which performs initial checks on the data and enqueues the file for processing. The activity will not appear in other API requests until it has finished processing successfully.
Processing status may be checked by polling Strava. A one-second or longer polling interval is recommended. The mean processing time is currently around 8 seconds. Once processing is complete, Strava will respond to polling requests with the activity’s ID.
Errors can occur during the submission or processing steps and may be due to malformed activity data or duplicate data submission.
- warning: Not yet tested
**/
public struct UploadData {
public var activityType: ActivityType?
public var name: String?
public var description: String?
public var `private`: Bool?
public var trainer: Bool?
public var externalId: String?
public var dataType: DataType
public var file: Data
public init(name: String, dataType: DataType, file: Data) {
self.name = name
self.dataType = dataType
self.file = file
}
public init(activityType: ActivityType?, name: String?, description: String?,
private: Bool?, trainer: Bool?, externalId: String?, dataType: DataType, file: Data)
{
self.activityType = activityType
self.description = description
self.private = `private`
self.trainer = trainer
self.externalId = externalId
self.name = name
self.dataType = dataType
self.file = file
}
internal var params: [String: Any] {
var params: [String: Any] = [:]
params["data_type"] = dataType.rawValue
params["name"] = name
params["description"] = description
if let `private` = `private` {
params["private"] = (`private` as NSNumber).stringValue
}
if let trainer = trainer {
params["trainer"] = (trainer as NSNumber).stringValue
}
params["external_id"] = externalId
return params
}
/**
Upload status
**/
public struct Status: Strava {
let id: Int?
let externalId: String?
let error: String?
let status: String?
let activityId: Int?
public init(_ json: JSON) {
id = json["id"].int
externalId = json["external_id"].string
error = json["error"].string
status = json["status"].string
activityId = json["activity_id"].int
}
}
}
| 32.626506 | 286 | 0.643648 |
fbdd18176120a6945e0e7e051126f7d8c2f197e3 | 18,882 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import NIO
import NIOFoundationCompat
import NIOTLS
private let libressl227HelloNoSNI = """
FgMBATkBAAE1AwNqcHrXsRJKtLx2HC1BXLt+kAk7SnCMk8qK
QPmv7L3u7QAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAdAALAAQDAAECAAoAOgA4
AA4ADQAZABwACwAMABsAGAAJAAoAGgAWABcACAAGAAcAFAAV
AAQABQASABMAAQACAAMADwAQABEAIwAAAA0AJgAkBgEGAgYD
7+8FAQUCBQMEAQQCBAPu7u3tAwEDAgMDAgECAgID
"""
private let libressl227HelloWithSNI = """
FgMBAU0BAAFJAwN/gCauChg0p2XhDp6z2+gRqMeyb5zfxBOW
dtGXsknrcAAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgAAC2h0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let openssl102HelloNoSNI = """
FgMBAS8BAAErAwPmgeNB1uuTN/P5ZlOjLQMHjxgIotE2796Z
ILeQHLg/ZQAArMAwwCzAKMAkwBTACgClAKMAoQCfAGsAagBp
AGgAOQA4ADcANgCIAIcAhgCFwDLALsAqwCbAD8AFAJ0APQA1
AITAL8ArwCfAI8ATwAkApACiAKAAngBnAEAAPwA+ADMAMgAx
ADAAmgCZAJgAlwBFAEQAQwBCwDHALcApwCXADsAEAJwAPAAv
AJYAQQAHwBHAB8AMwAIABQAEwBLACAAWABMAEAANwA3AAwAK
AP8CAQAAVQALAAQDAAECAAoAHAAaABcAGQAcABsAGAAaABYA
DgANAAsADAAJAAoAIwAAAA0AIAAeBgEGAgYDBQEFAgUDBAEE
AgQDAwEDAgMDAgECAgIDAA8AAQE=
"""
private let openssl102HelloWithSNI = """
FgMBAUMBAAE/AwO0rkxuVnE+GcBdNP2UJwTCVSi2H2NbIngp
eTzpoVc+kgAArMAwwCzAKMAkwBTACgClAKMAoQCfAGsAagBp
AGgAOQA4ADcANgCIAIcAhgCFwDLALsAqwCbAD8AFAJ0APQA1
AITAL8ArwCfAI8ATwAkApACiAKAAngBnAEAAPwA+ADMAMgAx
ADAAmgCZAJgAlwBFAEQAQwBCwDHALcApwCXADsAEAJwAPAAv
AJYAQQAHwBHAB8AMwAIABQAEwBLACAAWABMAEAANwA3AAwAK
AP8CAQAAaQAAABAADgAAC2h0dHBiaW4ub3JnAAsABAMAAQIA
CgAcABoAFwAZABwAGwAYABoAFgAOAA0ACwAMAAkACgAjAAAA
DQAgAB4GAQYCBgMFAQUCBQMEAQQCBAMDAQMCAwMCAQICAgMA
DwABAQ==
"""
private let curlWithSecureTransport = """
FgMBAL4BAAC6AwNZ54sY4KDX3NJ7JTk/ER+MdC3dT72bCG8P
wFcIw08qJAAARAD/wCzAK8AkwCPACsAJwAjAMMAvwCjAJ8AU
wBPAEgCfAJ4AawBnADkAMwAWAJ0AnAA9ADwANQAvAAoArwCu
AI0AjACLAQAATQAAABAADgAAC2h0dHBiaW4ub3JnAAoACAAG
ABcAGAAZAAsAAgEAAA0AEgAQBAECAQUBBgEEAwIDBQMGAwAF
AAUBAAAAAAASAAAAFwAA
"""
private let safariWithSecureTransport = """
FgMBAOEBAADdAwP1UKyAyXfMC35xny6EHejdgPt7aPoHdeQG
/1FuKmniSQAAKMAswCvAJMAjwArACcypwDDAL8AowCfAFMAT
zKgAnQCcAD0APAA1AC8BAACM/wEAAQAAAAAQAA4AAAtodHRw
YmluLm9yZwAXAAAADQAUABIEAwgEBAEFAwgFBQEIBgYBAgEA
BQAFAQAAAAAzdAAAABIAAAAQADAALgJoMgVoMi0xNgVoMi0x
NQVoMi0xNAhzcGR5LzMuMQZzcGR5LzMIaHR0cC8xLjEACwAC
AQAACgAIAAYAHQAXABg=
"""
private let chromeWithBoringSSL = """
FgMBAMIBAAC+AwMTXqvA3thIWxHtp1Fpf56+YmWbfaNxMO4f
DSUKnu6d/gAAHBoawCvAL8AswDDMqcyowBPAFACcAJ0ALwA1
AAoBAAB5qqoAAP8BAAEAAAAAEAAOAAALaHR0cGJpbi5vcmcA
FwAAACMAAAANABQAEgQDCAQEAQUDCAUFAQgGBgECAQAFAAUB
AAAAAAASAAAAEAAOAAwCaDIIaHR0cC8xLjF1UAAAAAsAAgEA
AAoACgAIWloAHQAXABjKygABAA==
"""
private let firefoxWithNSS = """
FgMBALcBAACzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO
blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv
ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB
AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho
dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB
BQEGAQIDAgE=
"""
private let alertFatalInternalError = "FQMDAAICUA=="
private let invalidTlsVersion = """
FgQAALcBAACzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO
blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv
ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB
AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho
dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB
BQEGAQIDAgE=
"""
private let clientKeyExchange = """
FgMDAJYQAACSkQQAR/1YL9kZ13n6OWVy6VMLqc++ZTHfZVlt
RlLYoziZSu7tKZ9UUMvZJ5BCcH3juFGM9wftZi0PIjKuRrBZ
erk++KawYtxuaIwDGwinj70hmUxB9jQSa0M9NXXNVHZWgMSX
YVj3N8SBAfmGbWQbH9uONzieFuVYwkmVEidIlE7A04gHP9id
Oy5Badfl6Ab5fDg=
"""
private let invalidHandshakeLength = """
FgMBALcBAQCzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO
blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv
ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB
AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho
dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB
BQEGAQIDAgE=
"""
private let invalidCipherSuitesLength = """
FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/
lEvy1/7zGQDw/8wUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgAAC2h0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let invalidCompressionLength = """
'FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U
/lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawB
qADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQD
AAITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMA
xwC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsA
IABYAE8ANwAMACgAVABIACQD//wAAiAAAABAADgAAC2h0dHB
iaW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwA
YAAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwA
PABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7
u7e0DAQMCAwMCAQICAgM='
"""
private let invalidExtensionLength = """
FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/
lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQDw/wAAABAADgAAC2h0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let invalidIndividualExtensionLength = """
FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/
lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAiAAA8P8ADgAAC2h0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let unknownNameType = """
'FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U
/lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawB
qADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQD
AAITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMA
xwC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsA
IABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgEAC2h0dHB
iaW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwA
YAAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwA
PABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7
u7e0DAQMCAwMCAQICAgM=
"""
private let invalidNameLength = """
FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/
lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgD/8Gh0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let invalidNameExtensionLength = """
FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/
lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq
ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA
AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx
wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI
ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABDw/wAAC2h0dHBi
aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY
AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP
ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u
7e0DAQMCAwMCAQICAgM=
"""
private let ludicrouslyTruncatedPacket = "FgMBAAEB"
private let fuzzingInputOne = "FgMAAAQAAgo="
extension ChannelPipeline {
func contains(handler: ChannelHandler) throws -> Bool {
do {
_ = try self.context(handler: handler).wait()
return true
} catch ChannelPipelineError.notFound {
return false
}
}
func assertDoesNotContain(handler: ChannelHandler) throws {
XCTAssertFalse(try contains(handler: handler))
}
func assertContains(handler: ChannelHandler) throws {
XCTAssertTrue(try contains(handler: handler))
}
}
class SNIHandlerTest: XCTestCase {
private func bufferForBase64String(string: String) -> ByteBuffer {
let data = Data(base64Encoded: string, options: .ignoreUnknownCharacters)!
let allocator = ByteBufferAllocator()
var buffer = allocator.buffer(capacity: data.count)
buffer.writeBytes(data)
return buffer
}
/// Drip-feeds the client hello in one byte at a time.
/// Also asserts that the channel handler does not remove itself from
/// the pipeline or emit its buffered data until the future fires.
func dripFeedHello(clientHello: String, expectedResult: SNIResult) throws {
var called = false
var buffer = bufferForBase64String(string: clientHello)
let channel = EmbeddedChannel()
let loop = channel.eventLoop as! EmbeddedEventLoop
let continuePromise = loop.makePromise(of: Void.self)
let handler = ByteToMessageHandler(SNIHandler { result in
XCTAssertEqual(expectedResult, result)
called = true
return continuePromise.futureResult
})
try channel.pipeline.addHandler(handler).wait()
// The handler will run when the last byte of the extension data is sent.
// We don't know when that is, so don't try to predict it. However,
// for this entire time the handler should remain in the pipeline and not
// forward on any data.
while buffer.readableBytes > 0 {
let writeableData = buffer.readSlice(length: 1)!
try channel.writeInbound(writeableData)
loop.run()
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
try channel.pipeline.assertContains(handler: handler)
}
// The callback should now have fired, but the handler should still not have
// sent on any data and should still be in the pipeline.
XCTAssertTrue(called)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
try channel.pipeline.assertContains(handler: handler)
// Now we're going to complete the promise and run the loop. This should cause the complete
// ClientHello to be sent on, and the SNIHandler to be removed from the pipeline.
continuePromise.succeed(())
loop.run()
let writtenBuffer: ByteBuffer = try channel.readInbound() ?? channel.allocator.buffer(capacity: 0)
let writtenData = writtenBuffer.getData(at: writtenBuffer.readerIndex, length: writtenBuffer.readableBytes)
let expectedData = Data(base64Encoded: clientHello, options: .ignoreUnknownCharacters)!
XCTAssertEqual(writtenData, expectedData)
try channel.pipeline.assertDoesNotContain(handler: handler)
XCTAssertTrue(try channel.finish().isClean)
}
/// Blasts the client hello in as a single string. This is not expected to reveal bugs
/// that the drip feed doesn't hit: it just helps to find more gross logic bugs.
func blastHello(clientHello: String, expectedResult: SNIResult) throws {
var called = false
let buffer = bufferForBase64String(string: clientHello)
let channel = EmbeddedChannel()
let loop = channel.eventLoop as! EmbeddedEventLoop
let continuePromise = loop.makePromise(of: Void.self)
let handler = ByteToMessageHandler(SNIHandler { result in
XCTAssertEqual(expectedResult, result)
called = true
return continuePromise.futureResult
})
try channel.pipeline.addHandler(handler).wait()
// Ok, let's go.
try channel.writeInbound(buffer)
loop.run()
// The callback should have fired, but the handler should not have
// sent on any data and should still be in the pipeline.
XCTAssertTrue(called)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound(as: ByteBuffer.self)))
try channel.pipeline.assertContains(handler: handler)
// Now we're going to complete the promise and run the loop. This should cause the complete
// ClientHello to be sent on, and the SNIHandler to be removed from the pipeline.
continuePromise.succeed(())
loop.run()
let writtenBuffer: ByteBuffer? = try channel.readInbound()
if let writtenBuffer = writtenBuffer {
let writtenData = writtenBuffer.getData(at: writtenBuffer.readerIndex, length: writtenBuffer.readableBytes)
let expectedData = Data(base64Encoded: clientHello, options: .ignoreUnknownCharacters)!
XCTAssertEqual(writtenData, expectedData)
} else {
XCTFail("no inbound data available")
}
try channel.pipeline.assertDoesNotContain(handler: handler)
XCTAssertTrue(try channel.finish().isClean)
}
func assertIncompleteInput(clientHello: String) throws {
let buffer = bufferForBase64String(string: clientHello)
let channel = EmbeddedChannel()
let loop = channel.eventLoop as! EmbeddedEventLoop
let handler = ByteToMessageHandler(SNIHandler { result in
XCTFail("Handler was called")
return loop.makeSucceededFuture(())
})
try channel.pipeline.addHandler(handler).wait()
// Ok, let's go.
try channel.writeInbound(buffer)
loop.run()
// The callback should not have fired, the handler should still be in the pipeline,
// and no data should have been written.
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound(as: ByteBuffer.self)))
try channel.pipeline.assertContains(handler: handler)
XCTAssertNoThrow(try channel.finish())
}
func testLibre227NoSNIDripFeed() throws {
try dripFeedHello(clientHello: libressl227HelloNoSNI, expectedResult: .fallback)
}
func testLibre227WithSNIDripFeed() throws {
try dripFeedHello(clientHello: libressl227HelloWithSNI, expectedResult: .hostname("httpbin.org"))
}
func testOpenSSL102NoSNIDripFeed() throws {
try dripFeedHello(clientHello: openssl102HelloNoSNI, expectedResult: .fallback)
}
func testOpenSSL102WithSNIDripFeed() throws {
try dripFeedHello(clientHello: openssl102HelloWithSNI, expectedResult: .hostname("httpbin.org"))
}
func testCurlSecureTransportDripFeed() throws {
try dripFeedHello(clientHello: curlWithSecureTransport, expectedResult: .hostname("httpbin.org"))
}
func testSafariDripFeed() throws {
try dripFeedHello(clientHello: safariWithSecureTransport, expectedResult: .hostname("httpbin.org"))
}
func testChromeDripFeed() throws {
try dripFeedHello(clientHello: chromeWithBoringSSL, expectedResult: .hostname("httpbin.org"))
}
func testFirefoxDripFeed() throws {
try dripFeedHello(clientHello: firefoxWithNSS, expectedResult: .hostname("httpbin.org"))
}
func testLibre227NoSNIBlast() throws {
try blastHello(clientHello: libressl227HelloNoSNI, expectedResult: .fallback)
}
func testLibre227WithSNIBlast() throws {
try blastHello(clientHello: libressl227HelloWithSNI, expectedResult: .hostname("httpbin.org"))
}
func testOpenSSL102NoSNIBlast() throws {
try blastHello(clientHello: openssl102HelloNoSNI, expectedResult: .fallback)
}
func testOpenSSL102WithSNIBlast() throws {
try blastHello(clientHello: openssl102HelloWithSNI, expectedResult: .hostname("httpbin.org"))
}
func testCurlSecureTransportBlast() throws {
try blastHello(clientHello: curlWithSecureTransport, expectedResult: .hostname("httpbin.org"))
}
func testSafariBlast() throws {
try blastHello(clientHello: safariWithSecureTransport, expectedResult: .hostname("httpbin.org"))
}
func testChromeBlast() throws {
try blastHello(clientHello: chromeWithBoringSSL, expectedResult: .hostname("httpbin.org"))
}
func testFirefoxBlast() throws {
try blastHello(clientHello: firefoxWithNSS, expectedResult: .hostname("httpbin.org"))
}
func testIgnoresUnknownRecordTypes() throws {
try blastHello(clientHello: alertFatalInternalError, expectedResult: .fallback)
}
func testIgnoresUnknownTlsVersions() throws {
try blastHello(clientHello: invalidTlsVersion, expectedResult: .fallback)
}
func testIgnoresNonClientHelloHandshakeMessages() throws {
try blastHello(clientHello: clientKeyExchange, expectedResult: .fallback)
}
func testIgnoresInvalidHandshakeLength() throws {
try blastHello(clientHello: invalidHandshakeLength, expectedResult: .fallback)
}
func testIgnoresInvalidCipherSuiteLength() throws {
try blastHello(clientHello: invalidCipherSuitesLength, expectedResult: .fallback)
}
func testIgnoresInvalidCompressionLength() throws {
try blastHello(clientHello: invalidCompressionLength, expectedResult: .fallback)
}
func testIgnoresInvalidExtensionLength() throws {
try blastHello(clientHello: invalidExtensionLength, expectedResult: .fallback)
}
func testIgnoresInvalidIndividualExtensionLength() throws {
try blastHello(clientHello: invalidIndividualExtensionLength, expectedResult: .fallback)
}
func testIgnoresUnknownNameType() throws {
try blastHello(clientHello: unknownNameType, expectedResult: .fallback)
}
func testIgnoresInvalidNameLength() throws {
try blastHello(clientHello: invalidNameLength, expectedResult: .fallback)
}
func testIgnoresInvalidNameExtensionLength() throws {
try blastHello(clientHello: invalidNameExtensionLength, expectedResult: .fallback)
}
func testLudicrouslyTruncatedPacket() throws {
try blastHello(clientHello: ludicrouslyTruncatedPacket, expectedResult: .fallback)
}
func testFuzzingInputOne() throws {
try assertIncompleteInput(clientHello: fuzzingInputOne)
}
}
| 38.222672 | 119 | 0.789429 |
50274eb7be343b5c1c93d1ad862663068fe0941f | 1,789 | //
// FetchHistory.swift
// AppleMusicKit
//
// Created by 林 達也 on 2017/07/05.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
public struct GetHeavyRotationContent<
Song: SongDecodable,
Album: AlbumDecodable,
Artist: ArtistDecodable,
MusicVideo: MusicVideoDecodable,
Playlist: PlaylistDecodable,
Curator: CuratorDecodable,
AppleCurator: AppleCuratorDecodable,
Activity: ActivityDecodable,
Station: StationDecodable,
Storefront: StorefrontDecodable,
Genre: GenreDecodable,
Recommendation: RecommendationDecodable
>: PaginatorResourceRequest, InternalPaginatorRequest {
public typealias Resource = AnyResource<NoRelationships>
public var scope: AccessScope { return .user }
public let path: String
public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) }
public internal(set) var limit: Int?
public let offset: Int?
private let _parameters: [String: Any]
public init(language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) {
self.init(path: "/v1/me/history/heavy-rotation",
parameters: ["l": language?.languageTag, "limit": limit, "offset": offset].cleaned)
}
init(path: String, parameters: [String: Any]) {
self.path = path
_parameters = parameters
(limit, offset) = parsePaginatorParameters(parameters)
}
}
extension GetHeavyRotationContent {
public typealias AnyResource<R: Decodable> = AppleMusicKit.AnyResource<
Song,
Album,
Artist,
MusicVideo,
Playlist,
Curator,
AppleCurator,
Activity,
Station,
Storefront,
Genre,
Recommendation,
R>
}
| 28.396825 | 104 | 0.674679 |
6ab6774f2c6ce062122e8c959a6485211f40b86c | 3,127 | //
// SnapKitTableViewController.swift
// SwiftTest
//
// Created by GeWei on 2016/12/25.
// Copyright © 2016年 GeWei. All rights reserved.
//
import UIKit
class SnapKitTableViewController: UITableViewController {
let funcNameArr = ["1. 一个中心view","2. 绿色方块放置橙色方块内部的右下角位置","3. 视图大小相同,绿色方块与橙色视图底部平齐","4. 距离父视图上、左、下、右边距","5. 绿色视图比橙色视图宽度、高度均减50","6. 绿色视图的尺寸设置成橙色视图一半大小"]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "tableviewCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
cell?.textLabel?.text = funcNameArr[indexPath.row]
cell?.textLabel?.font = UIFont.systemFont(ofSize: 12)
cell?.textLabel?.numberOfLines = 0
return cell!
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
extension SnapKitTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let snapVC = SnapKitViewController(function: indexPath.row)
navigationController?.pushViewController(snapVC, animated: true)
}
}
| 32.572917 | 155 | 0.666453 |
7909795755dbabe264c73ba270bb724638cb2fb6 | 1,164 | //
// ExamenRappiUITests.swift
// ExamenRappiUITests
//
// Created by Juan Arcos on 10/19/19.
// Copyright © 2019 Arcos. All rights reserved.
//
import XCTest
class ExamenRappiUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.257143 | 182 | 0.691581 |
7129bc26d582153338badc76176b0bef6e6df3db | 10,199 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
@propertyWrapper
struct Wrapper<T> {
var wrappedValue: T {
didSet {
print(" .. set \(wrappedValue)")
}
}
init(wrappedValue initialValue: T) {
print(" .. init \(initialValue)")
self.wrappedValue = initialValue
}
}
protocol IntInitializable {
init(_: Int)
}
final class Payload : CustomStringConvertible, IntInitializable {
let payload: Int
init(_ p: Int) {
self.payload = p
print(" + payload alloc \(payload)")
}
deinit {
print(" - payload free \(payload)")
}
var description: String {
return "value = \(payload)"
}
}
struct IntStruct {
@Wrapper var wrapped: Int
init() {
wrapped = 42
wrapped = 27
}
init(conditional b: Bool) {
if b {
self._wrapped = Wrapper(wrappedValue: 32)
} else {
wrapped = 42
}
}
init(dynamic b: Bool) {
if b {
wrapped = 42
}
wrapped = 27
}
// Check that we don't crash if the function has unrelated generic parameters.
// SR-11484
mutating func setit<V>(_ v: V) {
wrapped = 5
}
}
final class IntClass {
@Wrapper var wrapped: Int
init() {
wrapped = 42
wrapped = 27
}
init(conditional b: Bool) {
if b {
self._wrapped = Wrapper(wrappedValue: 32)
} else {
wrapped = 42
}
}
init(dynamic b: Bool) {
if b {
wrapped = 42
}
wrapped = 27
}
}
struct RefStruct {
@Wrapper var wrapped: Payload
init() {
wrapped = Payload(42)
wrapped = Payload(27)
}
init(conditional b: Bool) {
if b {
self._wrapped = Wrapper(wrappedValue: Payload(32))
} else {
wrapped = Payload(42)
}
}
init(dynamic b: Bool) {
if b {
wrapped = Payload(42)
}
wrapped = Payload(27)
}
}
final class GenericClass<T : IntInitializable> {
@Wrapper var wrapped: T
init() {
wrapped = T(42)
wrapped = T(27)
}
init(conditional b: Bool) {
if b {
self._wrapped = Wrapper(wrappedValue: T(32))
} else {
wrapped = T(42)
}
}
init(dynamic b: Bool) {
if b {
wrapped = T(42)
}
wrapped = T(27)
}
}
func testIntStruct() {
// CHECK: ## IntStruct
print("\n## IntStruct")
// CHECK-NEXT: .. init 42
// CHECK-NEXT: .. set 27
var t1 = IntStruct()
// CHECK-NEXT: 27
print(t1.wrapped)
// CHECK-NEXT: .. set 5
t1.setit(false)
// CHECK-NEXT: 5
print(t1.wrapped)
// CHECK-NEXT: .. init 42
let t2 = IntStruct(conditional: false)
// CHECK-NEXT: 42
print(t2.wrapped)
// CHECK-NEXT: .. init 32
let t3 = IntStruct(conditional: true)
// CHECK-NEXT: 32
print(t3.wrapped)
// CHECK-NEXT: .. init 27
let t4 = IntStruct(dynamic: false)
// CHECK-NEXT: 27
print(t4.wrapped)
// CHECK-NEXT: .. init 42
// CHECK-NEXT: .. init 27
let t5 = IntStruct(dynamic: true)
// CHECK-NEXT: 27
print(t5.wrapped)
}
func testIntClass() {
// CHECK: ## IntClass
print("\n## IntClass")
// CHECK-NEXT: .. init 42
// CHECK-NEXT: .. set 27
let t1 = IntClass()
// CHECK-NEXT: 27
print(t1.wrapped)
// CHECK-NEXT: .. init 42
let t2 = IntClass(conditional: false)
// CHECK-NEXT: 42
print(t2.wrapped)
// CHECK-NEXT: .. init 32
let t3 = IntClass(conditional: true)
// CHECK-NEXT: 32
print(t3.wrapped)
// CHECK-NEXT: .. init 27
let t4 = IntClass(dynamic: false)
// CHECK-NEXT: 27
print(t4.wrapped)
// CHECK-NEXT: .. init 42
// CHECK-NEXT: .. init 27
let t5 = IntClass(dynamic: true)
// CHECK-NEXT: 27
print(t5.wrapped)
}
func testRefStruct() {
// CHECK: ## RefStruct
print("\n## RefStruct")
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: - payload free 42
// CHECK-NEXT: .. set value = 27
let t1 = RefStruct()
// CHECK-NEXT: value = 27
print(t1.wrapped)
// CHECK-NEXT: - payload free 27
}
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
let t2 = RefStruct(conditional: false)
// CHECK-NEXT: value = 42
print(t2.wrapped)
// CHECK-NEXT: - payload free 42
}
if true {
// CHECK-NEXT: + payload alloc 32
// CHECK-NEXT: .. init value = 32
let t3 = RefStruct(conditional: true)
// CHECK-NEXT: value = 32
print(t3.wrapped)
// CHECK-NEXT: - payload free 32
}
if true {
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: .. init value = 27
let t4 = RefStruct(dynamic: false)
// CHECK-NEXT: value = 27
print(t4.wrapped)
// CHECK-NEXT: - payload free 27
}
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: - payload free 42
// CHECK-NEXT: .. init value = 27
let t5 = RefStruct(dynamic: true)
// CHECK-NEXT: value = 27
print(t5.wrapped)
// CHECK-NEXT: - payload free 27
}
}
func testGenericClass() {
// CHECK: ## GenericClass
print("\n## GenericClass")
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: - payload free 42
// CHECK-NEXT: .. set value = 27
let t1 = GenericClass<Payload>()
// CHECK-NEXT: value = 27
print(t1.wrapped)
// CHECK-NEXT: - payload free 27
}
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
let t2 = GenericClass<Payload>(conditional: false)
// CHECK-NEXT: value = 42
print(t2.wrapped)
// CHECK-NEXT: - payload free 42
}
if true {
// CHECK-NEXT: + payload alloc 32
// CHECK-NEXT: .. init value = 32
let t3 = GenericClass<Payload>(conditional: true)
// CHECK-NEXT: value = 32
print(t3.wrapped)
// CHECK-NEXT: - payload free 32
}
if true {
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: .. init value = 27
let t4 = GenericClass<Payload>(dynamic: false)
// CHECK-NEXT: value = 27
print(t4.wrapped)
// CHECK-NEXT: - payload free 27
}
if true {
// CHECK-NEXT: + payload alloc 42
// CHECK-NEXT: .. init value = 42
// CHECK-NEXT: + payload alloc 27
// CHECK-NEXT: - payload free 42
// CHECK-NEXT: .. init value = 27
let t5 = GenericClass<Payload>(dynamic: true)
// CHECK-NEXT: value = 27
print(t5.wrapped)
// CHECK-NEXT: - payload free 27
}
}
@propertyWrapper
struct WrapperWithDefaultInit<Value> {
private var _value: Value? = nil
init() {
print("default init called on \(Value.self)")
}
var wrappedValue: Value {
get {
return _value!
} set {
print("set value \(newValue)")
_value = newValue
}
}
}
struct UseWrapperWithDefaultInit {
@WrapperWithDefaultInit<Int>
var x: Int
@WrapperWithDefaultInit<String>
var y: String
init(y: String) {
self.y = y
}
}
func testDefaultInit() {
// CHECK: ## DefaultInit
print("\n## DefaultInit")
let use = UseWrapperWithDefaultInit(y: "hello")
// CHECK: default init called on Int
// FIXME: DI should eliminate the following call
// CHECK: default init called on String
// CHECK: set value hello
}
// rdar://problem/51581937: DI crash with a property wrapper of an optional
struct OptIntStruct {
@Wrapper var wrapped: Int?
init() {
wrapped = 42
}
}
func testOptIntStruct() {
// CHECK: ## OptIntStruct
print("\n## OptIntStruct")
let use = OptIntStruct()
// CHECK-NEXT: .. init nil
// CHECK-NEXT: .. set Optional(42)
}
// rdar://problem/53504653
struct DefaultNilOptIntStruct {
@Wrapper var wrapped: Int?
init() {
}
}
func testDefaultNilOptIntStruct() {
// CHECK: ## DefaultNilOptIntStruct
print("\n## DefaultNilOptIntStruct")
let use = DefaultNilOptIntStruct()
// CHECK-NEXT: .. init nil
}
@propertyWrapper
struct Wrapper2<T> {
var wrappedValue: T {
didSet {
print(" .. secondSet \(wrappedValue)")
}
}
init(before: Int = -10, wrappedValue initialValue: T, after: String = "end") {
print(" .. secondInit \(before), \(initialValue), \(after)")
self.wrappedValue = initialValue
}
}
struct HasComposed {
@Wrapper @Wrapper2 var x: Int
init() {
self.x = 17
}
}
func testComposed() {
// CHECK: ## Composed
print("\n## Composed")
_ = HasComposed()
// CHECK-NEXT: .. secondInit -10, 17, end
// CHECK-NEXT: .. init Wrapper2<Int>(wrappedValue: 17)
}
// SR-11477
@propertyWrapper
struct SR_11477_W {
let name: String
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
@propertyWrapper
struct SR_11477_W1 {
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
struct SR_11477_C {
@SR_11477_W var property: Int
@SR_11477_W1 var property1: Int
init() {}
func foo() { print(_property.name) }
func foo1() { print(_property1.name) }
}
func testWrapperInitWithDefaultArg() {
// CHECK: ## InitWithDefaultArg
print("\n## InitWithDefaultArg")
let use = SR_11477_C()
use.foo()
use.foo1()
// CHECK-NEXT: DefaultParamInit
// CHECK-NEXT: Init
}
// rdar://problem/57350503 - DI failure due to an unnecessary cycle breaker
public class Test57350503 {
@Synchronized
public private(set) var anchor: Int
public init(anchor: Int) {
self.anchor = anchor
printMe()
}
private func printMe() { }
}
@propertyWrapper
public final class Synchronized<Value> {
private var value: Value
public var wrappedValue: Value {
get { value }
set { value = newValue }
}
public init(wrappedValue: Value) {
value = wrappedValue
}
}
testIntStruct()
testIntClass()
testRefStruct()
testGenericClass()
testDefaultInit()
testOptIntStruct()
testDefaultNilOptIntStruct()
testComposed()
testWrapperInitWithDefaultArg()
| 19.842412 | 80 | 0.59751 |
1e10ec5180ee717c87c2fb7edd8bb8965c9805ac | 924 | //
// Curve_MainScreenWithWelcomeViewAnimation.swift
// SwiftUIAnimations
//
// Created by Mark Moeykens on 1/26/20.
// Copyright © 2020 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct Curve_MainScreenWithWelcomeViewAnimation: View {
@State private var showMenus = false
private var backgroundGradient = LinearGradient(gradient: Gradient(colors: [Color("Background4"), Color("Secondary4")]), startPoint: .top, endPoint: .bottom)
var body: some View {
ZStack {
backgroundGradient.edgesIgnoringSafeArea(.all)
TitleView()
WelcomeBackView(showMenus: $showMenus)
}
.font(.title)
.foregroundColor(Color("Foreground4"))
}
}
struct Curve_MainScreenWithWelcomeViewAnimation_Previews: PreviewProvider {
static var previews: some View {
Curve_MainScreenWithWelcomeViewAnimation()
}
}
| 28 | 161 | 0.677489 |
4ad3871e31abed0e96cc5bf20b37c8b44cd8962d | 1,354 | //
// ViewController.swift
// BlueToothPeripheral
//
// Created by Olivier Robin on 30/10/2016.
// Copyright © 2016 fr.ormaa. All rights reserved.
//
import UIKit
import CoreBluetooth
import UserNotifications
class MyViewController: UIViewController, BLEPeripheralProtocol {
@IBOutlet weak var logTextView: UITextView!
@IBOutlet weak var switchPeripheral: UISwitch!
var refreshLogs: Timer?
var ble: BLEPeripheralManager?
override func viewDidLoad() {
super.viewDidLoad()
print("MyViewController viewDidLoad")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Activate / disActivate the peripheral
@IBAction func switchPeripheralOnOff(_ sender: AnyObject) {
if self.switchPeripheral.isOn {
print("starting peripheral")
ble = BLEPeripheralManager()
ble?.delegate = self
ble!.startBLEPeripheral()
}
else {
print("stopping Peripheral")
ble!.stopBLEPeripheral()
}
}
func logToScreen(text: String) {
print(text)
var str = logTextView.text + "\n"
str += text
logTextView.text = str
}
}
| 20.830769 | 65 | 0.610783 |
7285c8b4634cbed243c180cde9e67082361794d6 | 312 | //
// ContentView.swift
// FirebaseToDoApp
//
// Created by Mehmet Ateş on 10.10.2021.
//
import SwiftUI
struct ContentView: View {
var body: some View {
HomeView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 11.142857 | 46 | 0.621795 |
9c202d9028d4f5ec383c5dba9c5a54cdf0c91b83 | 5,354 | //
// Bundle+Extension.swift
// Siren
//
// Created by ZhiHui.Li on 2021/4/18. on 3/17/17.
// Copyright (c) 2021 ZhiHui.Li. All rights reserved.
//
import Foundation
// `Bundle` Extension for Siren.
extension Bundle {
/// Constants used in the `Bundle` extension.
enum Constants {
/// Constant for the `.bundle` file extension.
static let bundleExtension = "bundle"
/// Constant for `CFBundleDisplayName`.
static let displayName = "CFBundleDisplayName"
/// Constant for the default US English localization.
static let englishLocalization = "en"
/// Constant for the project file extension.
static let projectExtension = "lproj"
/// Constant for `CFBundleShortVersionString`.
static let shortVersionString = "CFBundleShortVersionString"
/// Constant for the localization table.
static let table = "SirenLocalizable"
}
final class func identifier() -> String? {
Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String
}
/// Fetches the current version of the app.
///
/// - Returns: The current installed version of the app.
final class func version() -> String? {
Bundle.main.object(forInfoDictionaryKey: Constants.shortVersionString) as? String
}
final class func build() -> String? {
Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String
}
/// Returns the localized string for a given default string.
///
/// By default, the English language localization is used.
/// If the device's localization is set to another locale, that local's language is used if it's supported by Siren.
/// If `forcedLanguage` is set to `true`, the chosen language is shown for all devices, irrespective of their device's localization.
///
///
/// - Parameters:
/// - key: The default string used to search the localization table for a specific translation.
/// - forcedLanguage: Returns
/// - Returns: The localized string for a given key.
final class func localizedString(forKey key: String, andForceLocalization forcedLanguage: Localization.Language?) -> String {
guard var path = sirenBundlePath() else {
return key
}
if let deviceLanguage = deviceLanguage(),
let devicePath = sirenForcedBundlePath(forceLanguageLocalization: deviceLanguage)
{
path = devicePath
}
if let forcedLanguage = forcedLanguage,
let forcedPath = sirenForcedBundlePath(forceLanguageLocalization: forcedLanguage)
{
path = forcedPath
}
return Bundle(path: path)?.localizedString(forKey: key, value: key, table: Constants.table) ?? key
}
/// The appropriate name for the app to be displayed in the update alert.
///
/// Siren checks `CFBundleDisplayName` first. It then falls back to
/// to `kCFBundleNameKey` and ultimately to an empty string
/// if the aforementioned values are nil.
///
/// - Returns: The name of the app.
final class func bestMatchingAppName() -> String {
let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: Constants.displayName) as? String
let bundleName = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String
let executableName = Bundle.main.object(forInfoDictionaryKey: kCFBundleExecutableKey as String) as? String
let processInfoName = ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)
return bundleDisplayName ?? bundleName ?? executableName ?? processInfoName ?? ""
}
}
private extension Bundle {
/// The path to Siren's localization `Bundle`.
///
/// - Returns: The bundle's path or `nil`.
final class func sirenBundlePath() -> String? {
#if SWIFT_PACKAGE
return Bundle.module.path(forResource: "\(Siren.self)", ofType: Constants.bundleExtension)
#else
return Bundle(for: Siren.self).path(forResource: "\(Siren.self)", ofType: Constants.bundleExtension)
#endif
}
/// The path for a particular language localizationin Siren's localization `Bundle`.
///
/// - Parameter forceLanguageLocalization: The language localization that should be searched for in Siren's localization `bundle`.
/// - Returns: The path to the forced language localization.
final class func sirenForcedBundlePath(forceLanguageLocalization: Localization.Language) -> String? {
guard let path = sirenBundlePath() else { return nil }
let name = forceLanguageLocalization.rawValue
return Bundle(path: path)?.path(forResource: name, ofType: Constants.projectExtension)
}
/// The user's preferred language based on their device's localization.
///
/// - Returns: The user's preferred language.
final class func deviceLanguage() -> Localization.Language? {
guard let preferredLocalization = Bundle.main.preferredLocalizations.first,
preferredLocalization != Constants.englishLocalization,
let preferredLanguage = Localization.Language(rawValue: preferredLocalization)
else {
return nil
}
return preferredLanguage
}
}
| 41.828125 | 136 | 0.675943 |
4a5e11d624c686114de3124be08905e6e8aecf13 | 1,382 | //
// ImageCacheManager.swift
// FlickrSearch
//
// Created by Gaurav Singh on 21/07/18.
// Copyright © 2018 Gaurav Singh. All rights reserved.
//
import UIKit
class ImageCacheManager {
private let cache = NSCache<NSString, UIImage>()
private let downloadQueue: OperationQueue
static let shared = ImageCacheManager()
private init() {
downloadQueue = OperationQueue()
downloadQueue.qualityOfService = .userInitiated
}
func loadImage(forURL url: URL, completion: @escaping (UIImage?) -> Void) {
let key = url.absoluteString as NSString
if let cacheImage = cache.object(forKey: key) {
completion(cacheImage)
} else {
let downloadOperation = BlockOperation(block: { [weak self] in
guard
let data = try? Data(contentsOf: url),
let image = UIImage(data: data) else {
DispatchQueue.main.async {
completion(nil)
}
return
}
DispatchQueue.main.async {
self?.cache.setObject(image, forKey: key)
completion(image)
}
});
downloadQueue.addOperation(downloadOperation)
}
}
}
| 27.64 | 79 | 0.526773 |
79e90488d3e0d5ae18829868f2ecac7909e3d43e | 264 | //
// main.swift
// leetcode-swift
//
// Created by Chengzhi Jia on 2/21/19.
// Copyright © 2019 com.cj. All rights reserved.
//
import Foundation
print(Q819MostCommonWord().mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
| 22 | 110 | 0.685606 |
4add0388ac4e10e6ea11fb519fef4607c13903c5 | 22,203 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
-----------------------------------------------------------------------------
A very simple rendition of the Xcode project model. There is only sufficient
functionality to allow creation of Xcode projects in a somewhat readable way,
and serialization to .xcodeproj plists. There is no consistency checking to
ensure, for example, that build settings have valid values, dependency cycles
are not created, etc.
Everything here is geared toward supporting project generation. The intended
usage model is for custom logic to build up a project using Xcode terminology
(e.g. "group", "reference", "target", "build phase"), but there is almost no
provision for modifying the model after it has been built up. The intent is
to create it as desired from the start.
Rather than try to represent everything that Xcode's project model supports,
the approach is to start small and to add functionality as needed.
Note that this API represents only the project model — there is no notion of
workspaces, schemes, etc (although schemes are represented individually in a
separate API). The notion of build settings is also somewhat different from
what it is in Xcode: instead of an open-ended mapping of build configuration
names to dictionaries of build settings, here there is a single set of common
build settings plus two overlay sets for debug and release. The generated
project has just the two Debug and Release configurations, created by merging
the common set into the release and debug sets. This allows a more natural
configuration of the settings, since most values are the same between Debug
and Release. Also, the build settings themselves are represented as structs
of named fields, instead of dictionaries with arbitrary name strings as keys.
It is expected that some of these simplifications will need to be lifted over
time, based on need. That should be done carefully, however, to avoid ending
up with an overly complicated model.
Some things that are incomplete in even this first model:
- copy files build phases are incomplete
- shell script build phases are incomplete
- file types in file references are specified using strings; should be enums
so that the client doesn't have to hardcode the mapping to Xcode file type
identifiers
- debug and release settings override common settings; they should be merged
in a way that respects `$(inhertied)` when the same setting is defined in
common and in debug or release
- there is no good way to control the ordering of the `Products` group in the
main group; it needs to be added last in order to appear after the other
references
*/
public struct Xcode {
/// An Xcode project, consisting of a tree of groups and file references,
/// a list of targets, and some additional information. Note that schemes
/// are outside of the project data model.
public class Project {
let mainGroup: Group
var buildSettings: BuildSettingsTable
var productGroup: Group?
var projectDir: String
var targets: [Target]
init() {
self.mainGroup = Group(path: "")
self.buildSettings = BuildSettingsTable()
self.productGroup = nil
self.projectDir = ""
self.targets = []
}
/// Creates and adds a new target (which does not initially have any
/// build phases).
public func addTarget(objectID: String? = nil, productType: Target.ProductType?, name: String) -> Target {
let target = Target(objectID: objectID, productType: productType, name: name)
targets.append(target)
return target
}
}
/// Abstract base class for all items in the group hierarhcy.
public class Reference {
/// Relative path of the reference. It is usually a literal, but may
/// in fact contain build settings.
var path: String
/// Determines the base path for the reference's relative path.
var pathBase: RefPathBase
/// Name of the reference, if different from the last path component
/// (if not set, Xcode will use the last path component as the name).
var name: String?
/// Determines the base path for a reference's relative path (this is
/// what for some reason is called a "source tree" in Xcode).
public enum RefPathBase: String {
/// Indicates that the path is relative to the source root (i.e.
/// the "project directory").
case projectDir = "SOURCE_ROOT"
/// Indicates that the path is relative to the path of the parent
/// group.
case groupDir = "<group>"
/// Indicates that the path is relative to the effective build
/// directory (which varies depending on active scheme, active run
/// destination, or even an overridden build setting.
case buildDir = "BUILT_PRODUCTS_DIR"
}
init(path: String, pathBase: RefPathBase = .groupDir, name: String? = nil) {
self.path = path
self.pathBase = pathBase
self.name = name
}
}
/// A reference to a file system entity (a file, folder, etc).
public class FileReference: Reference {
var objectID: String?
var fileType: String?
init(path: String, pathBase: RefPathBase = .groupDir, name: String? = nil, fileType: String? = nil, objectID: String? = nil) {
super.init(path: path, pathBase: pathBase, name: name)
self.objectID = objectID
self.fileType = fileType
}
}
/// A group that can contain References (FileReferences and other Groups).
/// The resolved path of a group is used as the base path for any child
/// references whose source tree type is GroupRelative.
public class Group: Reference {
var subitems = [Reference]()
/// Creates and appends a new Group to the list of subitems.
/// The new group is returned so that it can be configured.
@discardableResult public func addGroup(
path: String,
pathBase: RefPathBase = .groupDir,
name: String? = nil
) -> Group {
let group = Group(path: path, pathBase: pathBase, name: name)
subitems.append(group)
return group
}
/// Creates and appends a new FileReference to the list of subitems.
@discardableResult public func addFileReference(
path: String,
pathBase: RefPathBase = .groupDir,
name: String? = nil,
fileType: String? = nil,
objectID: String? = nil
) -> FileReference {
let fref = FileReference(path: path, pathBase: pathBase, name: name, fileType: fileType, objectID: objectID)
subitems.append(fref)
return fref
}
}
/// An Xcode target, representing a single entity to build.
public class Target {
var objectID: String?
var name: String
var productName: String
var productType: ProductType?
var buildSettings: BuildSettingsTable
var buildPhases: [BuildPhase]
var productReference: FileReference?
var dependencies: [TargetDependency]
public enum ProductType: String {
case application = "com.apple.product-type.application"
case staticArchive = "com.apple.product-type.library.static"
case dynamicLibrary = "com.apple.product-type.library.dynamic"
case framework = "com.apple.product-type.framework"
case executable = "com.apple.product-type.tool"
case unitTest = "com.apple.product-type.bundle.unit-test"
}
init(objectID: String?, productType: ProductType?, name: String) {
self.objectID = objectID
self.name = name
self.productType = productType
self.productName = name
self.buildSettings = BuildSettingsTable()
self.buildPhases = []
self.dependencies = []
}
// FIXME: There's a lot repetition in these methods; using generics to
// try to avoid that raised other issues in terms of requirements on
// the Reference class, though.
/// Adds a "headers" build phase, i.e. one that copies headers into a
/// directory of the product, after suitable processing.
@discardableResult public func addHeadersBuildPhase() -> HeadersBuildPhase {
let phase = HeadersBuildPhase()
buildPhases.append(phase)
return phase
}
/// Adds a "sources" build phase, i.e. one that compiles sources and
/// provides them to be linked into the executable code of the product.
@discardableResult public func addSourcesBuildPhase() -> SourcesBuildPhase {
let phase = SourcesBuildPhase()
buildPhases.append(phase)
return phase
}
/// Adds a "frameworks" build phase, i.e. one that links compiled code
/// and libraries into the executable of the product.
@discardableResult public func addFrameworksBuildPhase() -> FrameworksBuildPhase {
let phase = FrameworksBuildPhase()
buildPhases.append(phase)
return phase
}
/// Adds a "copy files" build phase, i.e. one that copies files to an
/// arbitrary location relative to the product.
@discardableResult public func addCopyFilesBuildPhase(dstDir: String) -> CopyFilesBuildPhase {
let phase = CopyFilesBuildPhase(dstDir: dstDir)
buildPhases.append(phase)
return phase
}
/// Adds a "shell script" build phase, i.e. one that runs a custom
/// shell script as part of the build.
@discardableResult public func addShellScriptBuildPhase(script: String) -> ShellScriptBuildPhase {
let phase = ShellScriptBuildPhase(script: script)
buildPhases.append(phase)
return phase
}
/// Adds a dependency on another target.
/// FIXME: We do not check for cycles. Should we? This is an extremely
/// minimal API so it's not clear that we should.
public func addDependency(on target: Target) {
dependencies.append(TargetDependency(target: target))
}
/// A simple wrapper to prevent ownership cycles in the `dependencies`
/// property.
struct TargetDependency {
unowned var target: Target
}
}
/// Abstract base class for all build phases in a target.
public class BuildPhase {
var files: [BuildFile] = []
/// Adds a new build file that refers to `fileRef`.
@discardableResult public func addBuildFile(fileRef: FileReference) -> BuildFile {
let buildFile = BuildFile(fileRef: fileRef)
files.append(buildFile)
return buildFile
}
}
/// A "headers" build phase, i.e. one that copies headers into a directory
/// of the product, after suitable processing.
public class HeadersBuildPhase: BuildPhase {
// Nothing extra yet.
}
/// A "sources" build phase, i.e. one that compiles sources and provides
/// them to be linked into the executable code of the product.
public class SourcesBuildPhase: BuildPhase {
// Nothing extra yet.
}
/// A "frameworks" build phase, i.e. one that links compiled code and
/// libraries into the executable of the product.
public class FrameworksBuildPhase: BuildPhase {
// Nothing extra yet.
}
/// A "copy files" build phase, i.e. one that copies files to an arbitrary
/// location relative to the product.
public class CopyFilesBuildPhase: BuildPhase {
var dstDir: String
init(dstDir: String) {
self.dstDir = dstDir
}
}
/// A "shell script" build phase, i.e. one that runs a custom shell script.
public class ShellScriptBuildPhase: BuildPhase {
var script: String
init(script: String) {
self.script = script
}
}
/// A build file, representing the membership of a file reference in a
/// build phase of a target.
public class BuildFile {
weak var fileRef: FileReference?
init(fileRef: FileReference) {
self.fileRef = fileRef
}
var settings = Settings()
/// A set of file settings.
public struct Settings {
var ATTRIBUTES: [String]?
}
}
/// A table of build settings, which for the sake of simplicity consists
/// (in this simplified model) of a set of common settings, and a set of
/// overlay settings for Debug and Release builds. There can also be a
/// file reference to an .xcconfig file on which to base the settings.
public class BuildSettingsTable {
/// Common build settings are in both generated configurations (Debug
/// and Release).
var common = BuildSettings()
/// Debug build settings are overlaid over the common settings in the
/// generated Debug configuration.
var debug = BuildSettings()
/// Release build settings are overlaid over the common settings in the
/// generated Release configuration.
var release = BuildSettings()
/// An optional file reference to an .xcconfig file.
var xcconfigFileRef: FileReference?
/// A set of build settings, which is represented as a struct of optional
/// build settings. This is not optimally efficient, but it is great for
/// code completion and type-checking.
public struct BuildSettings {
// Note: although some of these build settings sound like booleans,
// they are all either strings or arrays of strings, because even
// a boolean may be a macro reference expression.
var CLANG_CXX_LANGUAGE_STANDARD: String?
var CLANG_ENABLE_MODULES: String?
var CLANG_ENABLE_OBJC_ARC: String?
var COMBINE_HIDPI_IMAGES: String?
var COPY_PHASE_STRIP: String?
var DEBUG_INFORMATION_FORMAT: String?
var DEFINES_MODULE: String?
var DYLIB_INSTALL_NAME_BASE: String?
var EMBEDDED_CONTENT_CONTAINS_SWIFT: String?
var ENABLE_NS_ASSERTIONS: String?
var ENABLE_TESTABILITY: String?
var FRAMEWORK_SEARCH_PATHS: [String]?
var GCC_C_LANGUAGE_STANDARD: String?
var GCC_OPTIMIZATION_LEVEL: String?
var GCC_PREPROCESSOR_DEFINITIONS: [String]?
var HEADER_SEARCH_PATHS: [String]?
var INFOPLIST_FILE: String?
var LD_RUNPATH_SEARCH_PATHS: [String]?
var LIBRARY_SEARCH_PATHS: [String]?
var MACOSX_DEPLOYMENT_TARGET: String?
var IPHONEOS_DEPLOYMENT_TARGET: String?
var TVOS_DEPLOYMENT_TARGET: String?
var WATCHOS_DEPLOYMENT_TARGET: String?
var MODULEMAP_FILE: String?
var ONLY_ACTIVE_ARCH: String?
var OTHER_CFLAGS: [String]?
var OTHER_CPLUSPLUSFLAGS: [String]?
var OTHER_LDFLAGS: [String]?
var OTHER_SWIFT_FLAGS: [String]?
var PRODUCT_BUNDLE_IDENTIFIER: String?
var PRODUCT_MODULE_NAME: String?
var PRODUCT_NAME: String?
var PROJECT_NAME: String?
var SDKROOT: String?
var SKIP_INSTALL: String?
var SUPPORTED_PLATFORMS: [String]?
var SWIFT_ACTIVE_COMPILATION_CONDITIONS: [String]?
var SWIFT_FORCE_STATIC_LINK_STDLIB: String?
var SWIFT_FORCE_DYNAMIC_LINK_STDLIB: String?
var SWIFT_OPTIMIZATION_LEVEL: String?
var SWIFT_VERSION: String?
var TARGET_NAME: String?
var USE_HEADERMAP: String?
var LD: String?
init(
CLANG_CXX_LANGUAGE_STANDARD: String? = nil,
CLANG_ENABLE_MODULES: String? = nil,
CLANG_ENABLE_OBJC_ARC: String? = nil,
COMBINE_HIDPI_IMAGES: String? = nil,
COPY_PHASE_STRIP: String? = nil,
DEBUG_INFORMATION_FORMAT: String? = nil,
DEFINES_MODULE: String? = nil,
DYLIB_INSTALL_NAME_BASE: String? = nil,
EMBEDDED_CONTENT_CONTAINS_SWIFT: String? = nil,
ENABLE_NS_ASSERTIONS: String? = nil,
ENABLE_TESTABILITY: String? = nil,
FRAMEWORK_SEARCH_PATHS: [String]? = nil,
GCC_C_LANGUAGE_STANDARD: String? = nil,
GCC_OPTIMIZATION_LEVEL: String? = nil,
GCC_PREPROCESSOR_DEFINITIONS: [String]? = nil,
HEADER_SEARCH_PATHS: [String]? = nil,
INFOPLIST_FILE: String? = nil,
LD_RUNPATH_SEARCH_PATHS: [String]? = nil,
LIBRARY_SEARCH_PATHS: [String]? = nil,
MACOSX_DEPLOYMENT_TARGET: String? = nil,
IPHONEOS_DEPLOYMENT_TARGET: String? = nil,
TVOS_DEPLOYMENT_TARGET: String? = nil,
WATCHOS_DEPLOYMENT_TARGET: String? = nil,
MODULEMAP_FILE: String? = nil,
ONLY_ACTIVE_ARCH: String? = nil,
OTHER_CFLAGS: [String]? = nil,
OTHER_CPLUSPLUSFLAGS: [String]? = nil,
OTHER_LDFLAGS: [String]? = nil,
OTHER_SWIFT_FLAGS: [String]? = nil,
PRODUCT_BUNDLE_IDENTIFIER: String? = nil,
PRODUCT_MODULE_NAME: String? = nil,
PRODUCT_NAME: String? = nil,
PROJECT_NAME: String? = nil,
SDKROOT: String? = nil,
SKIP_INSTALL: String? = nil,
SUPPORTED_PLATFORMS: [String]? = nil,
SWIFT_ACTIVE_COMPILATION_CONDITIONS: [String]? = nil,
SWIFT_FORCE_STATIC_LINK_STDLIB: String? = nil,
SWIFT_FORCE_DYNAMIC_LINK_STDLIB: String? = nil,
SWIFT_OPTIMIZATION_LEVEL: String? = nil,
SWIFT_VERSION: String? = nil,
TARGET_NAME: String? = nil,
USE_HEADERMAP: String? = nil,
LD: String? = nil
) {
self.CLANG_CXX_LANGUAGE_STANDARD = CLANG_CXX_LANGUAGE_STANDARD
self.CLANG_ENABLE_MODULES = CLANG_ENABLE_MODULES
self.CLANG_ENABLE_OBJC_ARC = CLANG_CXX_LANGUAGE_STANDARD
self.COMBINE_HIDPI_IMAGES = COMBINE_HIDPI_IMAGES
self.COPY_PHASE_STRIP = COPY_PHASE_STRIP
self.DEBUG_INFORMATION_FORMAT = DEBUG_INFORMATION_FORMAT
self.DEFINES_MODULE = DEFINES_MODULE
self.DYLIB_INSTALL_NAME_BASE = DYLIB_INSTALL_NAME_BASE
self.EMBEDDED_CONTENT_CONTAINS_SWIFT = EMBEDDED_CONTENT_CONTAINS_SWIFT
self.ENABLE_NS_ASSERTIONS = ENABLE_NS_ASSERTIONS
self.ENABLE_TESTABILITY = ENABLE_TESTABILITY
self.FRAMEWORK_SEARCH_PATHS = FRAMEWORK_SEARCH_PATHS
self.GCC_C_LANGUAGE_STANDARD = GCC_C_LANGUAGE_STANDARD
self.GCC_OPTIMIZATION_LEVEL = GCC_OPTIMIZATION_LEVEL
self.GCC_PREPROCESSOR_DEFINITIONS = GCC_PREPROCESSOR_DEFINITIONS
self.HEADER_SEARCH_PATHS = HEADER_SEARCH_PATHS
self.INFOPLIST_FILE = INFOPLIST_FILE
self.LD_RUNPATH_SEARCH_PATHS = LD_RUNPATH_SEARCH_PATHS
self.LIBRARY_SEARCH_PATHS = LIBRARY_SEARCH_PATHS
self.MACOSX_DEPLOYMENT_TARGET = MACOSX_DEPLOYMENT_TARGET
self.IPHONEOS_DEPLOYMENT_TARGET = IPHONEOS_DEPLOYMENT_TARGET
self.TVOS_DEPLOYMENT_TARGET = TVOS_DEPLOYMENT_TARGET
self.WATCHOS_DEPLOYMENT_TARGET = WATCHOS_DEPLOYMENT_TARGET
self.MODULEMAP_FILE = MODULEMAP_FILE
self.ONLY_ACTIVE_ARCH = ONLY_ACTIVE_ARCH
self.OTHER_CFLAGS = OTHER_CFLAGS
self.OTHER_CPLUSPLUSFLAGS = OTHER_CPLUSPLUSFLAGS
self.OTHER_LDFLAGS = OTHER_LDFLAGS
self.OTHER_SWIFT_FLAGS = OTHER_SWIFT_FLAGS
self.PRODUCT_BUNDLE_IDENTIFIER = PRODUCT_BUNDLE_IDENTIFIER
self.PRODUCT_MODULE_NAME = PRODUCT_MODULE_NAME
self.PRODUCT_NAME = PRODUCT_NAME
self.PROJECT_NAME = PROJECT_NAME
self.SDKROOT = SDKROOT
self.SKIP_INSTALL = SKIP_INSTALL
self.SUPPORTED_PLATFORMS = SUPPORTED_PLATFORMS
self.SWIFT_ACTIVE_COMPILATION_CONDITIONS = SWIFT_ACTIVE_COMPILATION_CONDITIONS
self.SWIFT_FORCE_STATIC_LINK_STDLIB = SWIFT_FORCE_STATIC_LINK_STDLIB
self.SWIFT_FORCE_DYNAMIC_LINK_STDLIB = SWIFT_FORCE_DYNAMIC_LINK_STDLIB
self.SWIFT_OPTIMIZATION_LEVEL = SWIFT_OPTIMIZATION_LEVEL
self.SWIFT_VERSION = SWIFT_VERSION
self.TARGET_NAME = TARGET_NAME
self.USE_HEADERMAP = USE_HEADERMAP
self.LD = LD
}
}
}
}
/// Adds the abililty to append to an option array of strings that hasn't yet
/// been created.
/// FIXME: While we want the end result of being able to say `FLAGS += ["-O"]`
/// it is probably not how we want to implement it, since it changes behavior
/// for all arrays of string. Instead, we should probably have a build setting
/// struct that wraps a string, and then we can write this in terms of just
/// build settings.
public func += (lhs: inout [String]?, rhs: [String]) {
if lhs == nil {
lhs = rhs
} else {
lhs = lhs! + rhs
}
}
| 45.128049 | 134 | 0.634959 |
0ede4aaa8d9f9c3acd010e28cbf8c9f62a0352aa | 2,504 | //
// RealmTranslator.swift
// DAO
//
// Created by Igor Bulyga on 04.02.16.
// Copyright © 2016 RedMadRobot LLC. All rights reserved.
//
import Foundation
import RealmSwift
open class RealmTranslator<Model: Entity, RealmModel: RLMEntry> {
public required init() {}
open func fill(_ entry: RealmModel, fromEntity: Model) {
fatalError("Abstract method")
}
open func fill(_ entity: Model, fromEntry: RealmModel) {
fatalError("Abstract method")
}
/// All properties of entities will be overridden by entries properties.
/// If entry doesn't exist, it'll be created.
///
/// - Parameters:
/// - entries: list of instances of `RealmModel` type.
/// - fromEntities: array of instances of `Model` type.
open func fill(_ entries: List<RealmModel>, fromEntities: [Model]) {
var newEntries = [RealmModel]()
fromEntities
.map { entity -> (RealmModel, Model) in
let entry = entries
.filter { $0.entryId == entity.entityId }
.first
if let entry = entry {
return (entry, entity)
} else {
let entry = RealmModel()
newEntries.append(entry)
return (entry, entity)
}
}
.forEach {
self.fill($0.0, fromEntity: $0.1)
}
if fromEntities.count < entries.count {
let entityIds = fromEntities.map { $0.entityId }
let deletedEntriesIndexes = entries
.filter { !entityIds.contains($0.entryId) }
deletedEntriesIndexes.forEach {
if let index = entries.index(of: $0) {
entries.remove(at: index)
}
}
} else {
entries.append(objectsIn: newEntries)
}
}
/// All properties of entries will be overridden by entities properties.
///
/// - Parameters:
/// - entities: array of instances of `Model` type.
/// - fromEntries: list of instances of `RealmModel` type.
open func fill( _ entities: inout [Model], fromEntries: List<RealmModel>) {
entities.removeAll()
fromEntries.forEach {
let model = Model()
entities.append(model)
self.fill(model, fromEntry: $0)
}
}
}
| 28.454545 | 79 | 0.525958 |
fce25103f8382f980bd11d880edf0dc50ea16a3e | 3,352 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import Foundation
import UIKit
class HashtagsScrollView: UIScrollView, UIScrollViewDelegate {
let hashtagsView: HashtagsView = HashtagsView()
// Helper for animations
var hashtagsCollapsed: Bool = false
init() {
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureHashtagsScrollView() {
self.delegate = self
hashtagsView.backgroundColor = UIColor.clear
// see HashtagsView.swift for detailed configuration
hashtagsView.configureHashtagsView()
hashtagsView.frame.size = CGSize(width: self.frame.width, height: self.hashtagsView.totalVerticalHashtagsHeight + 2 * labelInset)
self.backgroundColor = UIColor.clear
self.contentSize = hashtagsView.frame.size
self.addSubview(hashtagsView)
}
func pagedHashtagsView() {
self.frame.size.height = expandedHashtagsViewH
self.hashtagsView.frame.size = CGSize(width: self.frame.width, height: self.hashtagsView.totalVerticalHashtagsHeight + 2 * labelInset)
self.contentSize = self.hashtagsView.frame.size
self.hashtagsView.verticalHashtagArrangement()
}
func sizeZeroHashtagsView() {
self.frame.size.height = 0.0
self.hashtagsView.frame.size.height = 0.0
self.contentSize = self.hashtagsView.frame.size
}
func linearHashtagsView() {
self.frame.size.height = condensedHashtagsViewH
self.hashtagsView.frame.size = CGSize(width: self.hashtagsView.totalLinearHashtagsWidth + 2 * labelInset, height: condensedHashtagsViewH)
self.contentSize = self.hashtagsView.frame.size
self.hashtagsView.linearHashtagArrangement()
}
var contentPosition: CGPoint = CGPoint(x: 0.0, y: 0.0)
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
for hashtagButton in hashtagsView.hashtagButtons {
hashtagButton.sendActions(for: .touchCancel)
hashtagsView.hashtagNormal(hashtagButton)
}
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let scrollOffset = scrollView.contentOffset
if (scrollOffset.x - contentPosition.x > 0) {
APIConnector.connector().trackMetric("Scrolled Right On Hashtags")
}
if (scrollOffset.y - contentPosition.y > 0) {
APIConnector.connector().trackMetric("Scrolled Down On Hashtags")
}
contentPosition = scrollOffset
}
}
| 37.244444 | 148 | 0.695406 |
5b748910964e434d1908f6696901d18431dedb58 | 1,094 | //
// SignedInCoordinator.swift
// Eber
//
// Created by myung gi son on 24/09/2019.
//
import Pure
import UIKit
import RxSwift
import RxCocoa
final class SignedInCoordinator: ViewCoordinator<NoRoute>, FactoryModule {
struct Dependency {
let vehicleListViewControllerFactory: VehicleListViewController.Factory
let vehicleListViewReactorFactory: VehicleListViewReactor.Factory
}
struct Payload {
var accessToken: AccessToken
}
private var vehicleListViewController: VehicleListViewController!
private let dependency: Dependency
let accessToken: AccessToken
required init(dependency: Dependency, payload: Payload) {
self.dependency = dependency
self.accessToken = payload.accessToken
let vehicleListViewReactor = self.dependency.vehicleListViewReactorFactory.create()
self.vehicleListViewController = self.dependency.vehicleListViewControllerFactory.create(
payload: .init(reactor: vehicleListViewReactor)
)
super.init(rootViewController: self.vehicleListViewController)
}
override func start() {
}
}
| 24.863636 | 93 | 0.764168 |
e8531773a12e7bb750fa708078c8d640b4b73529 | 3,136 | //
// Wikipedia+ArticleSummary.swift
// WikipediaKit
//
// Created by Frank Rausch on 2018-07-30.
// Copyright © 2018 Raureif GmbH / Frank Rausch
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// “Software”), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension Wikipedia {
public func requestArticleSummary(language: WikipediaLanguage,
title: String,
completion: @escaping (WikipediaArticlePreview?, WikipediaError?)->())
-> URLSessionDataTask? {
let title = title.wikipediaURLEncodedString(encodeSlashes: true)
// We use the REST API here because that’s what the Wikipedia website calls for the link hover previews.
// It’s very fast.
let urlString = "https://\(language.code).wikipedia.org/api/rest_v1/page/summary/\(title)"
guard let url = URL(string: urlString)
else {
DispatchQueue.main.async {
completion(nil, .other(nil))
}
return nil
}
let request = URLRequest(url: url)
return WikipediaNetworking.shared.loadJSON(urlRequest: request) { jsonDictionary, error in
guard error == nil else {
// (also occurs when the request was cancelled programmatically)
DispatchQueue.main.async {
completion (nil, error)
}
return
}
guard let jsonDictionary = jsonDictionary else {
DispatchQueue.main.async {
completion (nil, .decodingError)
}
return
}
let articlePreview = WikipediaArticlePreview(jsonDictionary: jsonDictionary, language: language)
DispatchQueue.main.async {
completion(articlePreview, error)
}
}
}
}
| 37.783133 | 116 | 0.61352 |
333087a44ceec007140dc31bb08623d9ba4180f5 | 803 | //
// YHRefreshAutoNormalFooter.swift
// YHKit
//
// Created by nilhy on 2018/5/19.
// Copyright © 2018年 nilhy. All rights reserved.
//
import UIKit
import MJRefresh
class YHRefreshAutoNormalFooter: MJRefreshAutoNormalFooter {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
private func setupUI() {
isAutomaticallyChangeAlpha = true
}
// MJBug fix
override func endRefreshing() {
super.endRefreshing()
state = MJRefreshState.idle
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| 22.305556 | 60 | 0.636364 |
281f94f2139b8644ee939cf43e558b22e7ccd802 | 812 | //
// IONMetricsMessage.swift
// ion-swift
//
// Created by Ivan Manov on 08.03.2020.
// Copyright © 2020 kxpone. All rights reserved.
//
import Foundation
struct IONMetricParameter: Codable, MetricParameter {
/// Created at date string
var createdDate: Date?
/// Source node id. In case of connection info
var sourceId: String?
/// Destination node id. In case of connection info
/// Owner of data node id. In case of device info
var destinationId: String?
// MARK: MetricParameter protocol implementation
/// Parameter type
var type: MetricParameterType
/// Parameter value.
/// Always in range: 0..1. More is better.
var value: Float
}
struct IONMetricsMessage: Codable {
/// Metric parameters array
var parameters: [IONMetricParameter]?
}
| 24.606061 | 55 | 0.684729 |
268bfcb7e17ab076df83c062cf92e151bec5e194 | 11,871 | //
// VirtualTouristGalleryViewController.swift
// Virtual Tourist
//
// Created by nacho on 5/30/15.
// Copyright (c) 2015 Ignacio Moreno. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import CoreData
class VirtualTouristGalleryViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, NSFetchedResultsControllerDelegate, FlickerDelegate, ImageLoadDelegate {
@IBOutlet weak var newCollectionButton: UIBarButtonItem!
@IBOutlet weak var noPhotosLabel: UILabel!
var annotation:MapPinAnnotation!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var collectionView: UICollectionView!
var selectedIndexes = [NSIndexPath]()
var insertedIndexPaths: [NSIndexPath]!
var deletedIndexPaths: [NSIndexPath]!
var updatedIndexPaths: [NSIndexPath]!
var shouldFetch:Bool = false
var activityView:VTActivityViewController?
var recognizer:UILongPressGestureRecognizer!
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
noPhotosLabel.hidden = true
if FlickerPhotoDelegate.sharedInstance().isLoading(annotation.location!) {
self.shouldFetch = true
self.updateToolBar(false)
FlickerPhotoDelegate.sharedInstance().addDelegate(annotation.location!, delegate: self)
self.collectionView.hidden = true
self.activityView = VTActivityViewController()
self.activityView?.show(self, text: "Processing...")
} else {
self.performFetch()
if self.annotation.location!.isDownloading() {
for next in annotation.location!.photos {
if let downloadWorker = PendingPhotoDownloads.sharedInstance().downloadsInProgress[next.description.hashValue] as? PhotoDownloadWorker {
downloadWorker.imageLoadDelegate.append(self)
}
}
} else {
self.updateToolBar(annotation.location!.photos.count > 0)
}
}
if let details = self.annotation.location!.details {
self.navigationItem.title = details.locality
}
self.recognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
self.collectionView.addGestureRecognizer(self.recognizer)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.mapView.removeAnnotations(self.mapView.annotations)
self.mapView.addAnnotation(self.annotation)
self.navigationItem.backBarButtonItem?.title = "Back"
let region:MKCoordinateRegion = MKCoordinateRegion(center: self.annotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 1.0, longitudeDelta: 1.0))
self.mapView.setRegion(region, animated: true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.collectionViewLayout = getCollectionLayout()
}
//MARK: - Controller
func handleLongPress(recognizer:UILongPressGestureRecognizer) {
if (recognizer.state != UIGestureRecognizerState.Ended) {
return
}
let point = recognizer.locationInView(self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(point) {
if let cell = self.collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCell {
let photo = cell.photo
photo.pinLocation = nil
self.sharedContext.deleteObject(photo)
CoreDataStackManager.sharedInstance().saveContext()
}
}
}
func getCollectionLayout() -> UICollectionViewFlowLayout {
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let width = floor(self.collectionView.frame.size.width/3)
layout.itemSize = CGSize(width: width, height: width)
return layout
}
func didSearchLocationImages(success:Bool, location:PinLocation, photos:[Photo]?, errorString:String?) {
for next in annotation.location!.photos {
if let downloadWorker = PendingPhotoDownloads.sharedInstance().downloadsInProgress[next.description.hashValue] as? PhotoDownloadWorker {
downloadWorker.imageLoadDelegate.append(self)
}
}
dispatch_async(dispatch_get_main_queue()) {
let noPhotos = self.annotation.location!.photos.count == 0
self.noPhotosLabel.hidden = !noPhotos
self.activityView?.closeView()
self.activityView = nil
self.collectionView.hidden = false
if (self.shouldFetch) {
self.shouldFetch = false
self.performFetch()
}
self.collectionView.reloadData()
self.collectionView.layoutIfNeeded()
self.view.layoutIfNeeded()
if (photos?.count > 0) {
UIView.animateWithDuration(1.0, animations: {
self.view.layoutIfNeeded()
})
}
}
}
func updateToolBar(enabled:Bool) {
self.newCollectionButton.enabled = enabled
}
@IBAction func newCollection(sender: UIBarButtonItem) {
for photo in self.annotation.location!.photos {
photo.pinLocation = nil
//clean images from disk
photo.image = nil
self.sharedContext.deleteObject(photo)
}
self.searchPhotosForLocation()
CoreDataStackManager.sharedInstance().saveContext()
}
func searchPhotosForLocation() {
FlickerPhotoDelegate.sharedInstance().searchPhotos(self.annotation.location!)
self.collectionView.hidden = true
self.newCollectionButton.enabled = false;
self.view.layoutIfNeeded()
self.updateToolBar(false)
FlickerPhotoDelegate.sharedInstance().addDelegate(annotation.location!, delegate: self)
self.activityView = VTActivityViewController()
self.activityView?.show(self, text: "Processing...")
}
//MARK: - Image Load Delegate
func progress(progress:CGFloat) {
//do nothings
}
func didFinishLoad() {
let downloading = self.annotation.location!.isDownloading()
dispatch_async(dispatch_get_main_queue()) {
self.updateToolBar(!downloading)
}
}
//MARK: - Configure Cell
func configureCell(cell: PhotoCell, atIndexPath indexPath:NSIndexPath) {
let photo = self.fetchedResultsViewController.objectAtIndexPath(indexPath) as! Photo
cell.photo = photo
}
//MARK: - CoreData
lazy var fetchedResultsViewController:NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Photo")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "imagePath", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "pinLocation == %@", self.annotation.location!)
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: "photos")
fetchedResultsController.delegate = self
return fetchedResultsController
}()
lazy var sharedContext:NSManagedObjectContext = {
return CoreDataStackManager.sharedInstance().dataStack.managedObjectContext
}()
private func performFetch() {
var error:NSError?
NSFetchedResultsController.deleteCacheWithName("photos")
do {
try self.fetchedResultsViewController.performFetch()
} catch let error1 as NSError {
error = error1
}
if let _ = error {
print("Error performing initial fetch")
}
let sectionInfo = self.fetchedResultsViewController.sections!.first!
if sectionInfo.numberOfObjects == 0 {
noPhotosLabel.hidden = self.activityView == nil ? false : true
collectionView.hidden = true
} else {
noPhotosLabel.hidden = true
collectionView.hidden = false
}
}
//MARK: - UICollectionView
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.fetchedResultsViewController.sections?.count ?? 0
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsViewController.sections![section]
if let photos = self.annotation!.location?.photos where photos.count == 0 && self.isViewLoaded() && self.view.window != nil && self.newCollectionButton.enabled && !FlickerPhotoDelegate.sharedInstance().isLoading(annotation.location!) {
noPhotosLabel.hidden = false
collectionView.hidden = true
dispatch_async(dispatch_get_main_queue()) {
self.searchPhotosForLocation()
}
}
return sectionInfo.numberOfObjects
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoCell
if let index = selectedIndexes.indexOf(indexPath) {
selectedIndexes.removeAtIndex(index)
} else {
selectedIndexes.append(indexPath)
}
self.configureCell(cell, atIndexPath: indexPath)
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
insertedIndexPaths = [NSIndexPath]()
deletedIndexPaths = [NSIndexPath]()
updatedIndexPaths = [NSIndexPath]()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
self.insertedIndexPaths.append(newIndexPath!)
break
case .Delete:
self.deletedIndexPaths.append(indexPath!)
break
case .Update:
self.updatedIndexPaths.append(indexPath!)
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.collectionView.performBatchUpdates({() -> Void in
if self.insertedIndexPaths.count > 0 {
self.collectionView.insertItemsAtIndexPaths(self.insertedIndexPaths)
}
if self.deletedIndexPaths.count > 0 {
self.collectionView.deleteItemsAtIndexPaths(self.deletedIndexPaths)
}
if self.updatedIndexPaths.count > 0 {
self.collectionView.reloadItemsAtIndexPaths(self.updatedIndexPaths)
}
}, completion: nil)
}
}
| 38.293548 | 243 | 0.646197 |
71c81dafdce6b85713dbefd9871894d5aae57ff9 | 572 | import Combine
import Foundation
extension MercadoLibreClient {
public static let echo = Self(
search: {
Just([.mock($0)])
.setFailureType(to: URLError.self)
.eraseToAnyPublisher()
}
)
}
extension MercadoLibre.Item {
public static func mock(_ value: String) -> Self {
Self(
id: "MCO\(value)",
title: value,
domainId: "MCO-\(value)",
category: "MCO123",
availableQuantity: 1,
acceptsMercadopago: true
)
}
}
| 22 | 54 | 0.517483 |
5bdb6534d27bf3e0027dba89bfb917b88302672b | 15,463 | //
// UserV2API.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import Vapor
#if canImport(AnyCodable)
import AnyCodable
#endif
open class UserV2API {
/**
Get Security
GET /api/v2/user/security
Retrieve information about the current security configuration for the user.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- returns: `EventLoopFuture` of `ClientResponse`
*/
open class func getSecurityRaw(headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<ClientResponse> {
let localVariablePath = "/api/v2/user/security"
let localVariableURLString = FloatplaneAPIClientAPI.basePath + localVariablePath
guard let localVariableApiClient = Configuration.apiClient else {
fatalError("Configuration.apiClient is not set.")
}
return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in
try Configuration.apiWrapper(&localVariableRequest)
try beforeSend(&localVariableRequest)
}
}
public enum GetSecurity {
case http200(value: UserSecurityV2Response, raw: ClientResponse)
case http400(value: ErrorModel, raw: ClientResponse)
case http401(value: ErrorModel, raw: ClientResponse)
case http403(value: ErrorModel, raw: ClientResponse)
case http404(value: ErrorModel, raw: ClientResponse)
case http0(value: ErrorModel, raw: ClientResponse)
}
/**
Get Security
GET /api/v2/user/security
Retrieve information about the current security configuration for the user.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- returns: `EventLoopFuture` of `GetSecurity`
*/
open class func getSecurity(headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<GetSecurity> {
return getSecurityRaw(headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetSecurity in
switch response.status.code {
case 200:
return .http200(value: try response.content.decode(UserSecurityV2Response.self, using: Configuration.contentConfiguration.requireDecoder(for: UserSecurityV2Response.defaultContentType)), raw: response)
case 400:
return .http400(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 401:
return .http401(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 403:
return .http403(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 404:
return .http404(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
default:
return .http0(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
}
}
}
/**
Info
GET /api/v2/user/info
Retrieve more detailed information about one or more users from their identifiers.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter id: (query) The GUID identifer(s) of the user(s) to be retrieved.
- returns: `EventLoopFuture` of `ClientResponse`
*/
open class func getUserInfoRaw(id: [String], headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<ClientResponse> {
let localVariablePath = "/api/v2/user/info"
let localVariableURLString = FloatplaneAPIClientAPI.basePath + localVariablePath
guard let localVariableApiClient = Configuration.apiClient else {
fatalError("Configuration.apiClient is not set.")
}
return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in
try Configuration.apiWrapper(&localVariableRequest)
struct QueryParams: Content {
var id: [String]
enum CodingKeys: String, CodingKey {
case id = "id"
}
}
try localVariableRequest.query.encode(QueryParams(id: id))
try beforeSend(&localVariableRequest)
}
}
public enum GetUserInfo {
case http200(value: UserInfoV2Response, raw: ClientResponse)
case http400(value: ErrorModel, raw: ClientResponse)
case http401(value: ErrorModel, raw: ClientResponse)
case http403(value: ErrorModel, raw: ClientResponse)
case http404(value: ErrorModel, raw: ClientResponse)
case http0(value: ErrorModel, raw: ClientResponse)
}
/**
Info
GET /api/v2/user/info
Retrieve more detailed information about one or more users from their identifiers.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter id: (query) The GUID identifer(s) of the user(s) to be retrieved.
- returns: `EventLoopFuture` of `GetUserInfo`
*/
open class func getUserInfo(id: [String], headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<GetUserInfo> {
return getUserInfoRaw(id: id, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetUserInfo in
switch response.status.code {
case 200:
return .http200(value: try response.content.decode(UserInfoV2Response.self, using: Configuration.contentConfiguration.requireDecoder(for: UserInfoV2Response.defaultContentType)), raw: response)
case 400:
return .http400(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 401:
return .http401(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 403:
return .http403(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 404:
return .http404(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
default:
return .http0(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
}
}
}
/**
Get Info By Name
GET /api/v2/user/named
Retrieve more detailed information about one or more users from their usernames.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter username: (query) The username(s) of the user(s) to be retrieved.
- returns: `EventLoopFuture` of `ClientResponse`
*/
open class func getUserInfoByNameRaw(username: [String], headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<ClientResponse> {
let localVariablePath = "/api/v2/user/named"
let localVariableURLString = FloatplaneAPIClientAPI.basePath + localVariablePath
guard let localVariableApiClient = Configuration.apiClient else {
fatalError("Configuration.apiClient is not set.")
}
return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in
try Configuration.apiWrapper(&localVariableRequest)
struct QueryParams: Content {
var username: [String]
enum CodingKeys: String, CodingKey {
case username = "username"
}
}
try localVariableRequest.query.encode(QueryParams(username: username))
try beforeSend(&localVariableRequest)
}
}
public enum GetUserInfoByName {
case http200(value: UserNamedV2Response, raw: ClientResponse)
case http400(value: ErrorModel, raw: ClientResponse)
case http401(value: ErrorModel, raw: ClientResponse)
case http403(value: ErrorModel, raw: ClientResponse)
case http404(value: ErrorModel, raw: ClientResponse)
case http0(value: ErrorModel, raw: ClientResponse)
}
/**
Get Info By Name
GET /api/v2/user/named
Retrieve more detailed information about one or more users from their usernames.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter username: (query) The username(s) of the user(s) to be retrieved.
- returns: `EventLoopFuture` of `GetUserInfoByName`
*/
open class func getUserInfoByName(username: [String], headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<GetUserInfoByName> {
return getUserInfoByNameRaw(username: username, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetUserInfoByName in
switch response.status.code {
case 200:
return .http200(value: try response.content.decode(UserNamedV2Response.self, using: Configuration.contentConfiguration.requireDecoder(for: UserNamedV2Response.defaultContentType)), raw: response)
case 400:
return .http400(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 401:
return .http401(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 403:
return .http403(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 404:
return .http404(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
default:
return .http0(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
}
}
}
/**
User Creator Ban Status
GET /api/v2/user/ban/status
Determine whether or not the user is banned for a given creator.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter creator: (query) The GUID of the creator being queried.
- returns: `EventLoopFuture` of `ClientResponse`
*/
open class func userCreatorBanStatusRaw(creator: String, headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<ClientResponse> {
let localVariablePath = "/api/v2/user/ban/status"
let localVariableURLString = FloatplaneAPIClientAPI.basePath + localVariablePath
guard let localVariableApiClient = Configuration.apiClient else {
fatalError("Configuration.apiClient is not set.")
}
return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in
try Configuration.apiWrapper(&localVariableRequest)
struct QueryParams: Content {
var creator: String
enum CodingKeys: String, CodingKey {
case creator = "creator"
}
}
try localVariableRequest.query.encode(QueryParams(creator: creator))
try beforeSend(&localVariableRequest)
}
}
public enum UserCreatorBanStatus {
case http200(value: Bool, raw: ClientResponse)
case http400(value: ErrorModel, raw: ClientResponse)
case http401(value: ErrorModel, raw: ClientResponse)
case http403(value: ErrorModel, raw: ClientResponse)
case http404(value: ErrorModel, raw: ClientResponse)
case http0(value: ErrorModel, raw: ClientResponse)
}
/**
User Creator Ban Status
GET /api/v2/user/ban/status
Determine whether or not the user is banned for a given creator.
- API Key:
- type: apiKey sails.sid
- name: CookieAuth
- parameter creator: (query) The GUID of the creator being queried.
- returns: `EventLoopFuture` of `UserCreatorBanStatus`
*/
open class func userCreatorBanStatus(creator: String, headers: HTTPHeaders = FloatplaneAPIClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<UserCreatorBanStatus> {
return userCreatorBanStatusRaw(creator: creator, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UserCreatorBanStatus in
switch response.status.code {
case 200:
return .http200(value: try response.content.decode(Bool.self, using: Configuration.contentConfiguration.requireDecoder(for: Bool.defaultContentType)), raw: response)
case 400:
return .http400(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 401:
return .http401(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 403:
return .http403(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
case 404:
return .http404(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
default:
return .http0(value: try response.content.decode(ErrorModel.self, using: Configuration.contentConfiguration.requireDecoder(for: ErrorModel.defaultContentType)), raw: response)
}
}
}
}
| 51.715719 | 220 | 0.681821 |
9b330e7e1205272aa3ed1e5bed9de52cc32246d7 | 1,686 | //
// SplashViewController.swift
// FreestarNews
//
// Created by Dean Chang on 5/23/18.
// Copyright © 2018 Freestar. All rights reserved.
//
import UIKit
class SplashViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
performSegue(withIdentifier: "showMainViewController", sender: self)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Navigation
@IBAction func unwindToSplashViewControllerFromMain(segue: UIStoryboardSegue) {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showPrivacyViewController", sender: self)
}
}
@IBAction func unwindToSplashViewControllerFromPrivacy(segue: UIStoryboardSegue) {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showMainViewController", sender: self)
}
}
/*
// 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.
}
*/
}
| 30.107143 | 107 | 0.673784 |
23f3da5fbbd0b6a31e66c9b005e67e1ed0847aa5 | 1,070 | //
// GenreCollectionViewCell.swift
// Recipe-CICCC
//
// Created by 北島 志帆美 on 2020-04-17.
// Copyright © 2020 Argus Chen. All rights reserved.
//
import UIKit
class GenreCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var genreLabel: UILabel!
override func awakeFromNib() {
self.genreLabel.textAlignment = .center
contentView.layer.borderColor = UIColor.clear.cgColor
contentView.layer.masksToBounds = true
self.contentView.layer.cornerRadius = 10.0
self.contentView.layer.borderWidth = 3.0
layer.shadowColor = UIColor.lightGray.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2.0)
layer.shadowRadius = 6.0
layer.shadowOpacity = 1.0
layer.masksToBounds = false
layer.backgroundColor = UIColor.clear.cgColor
}
func highlight(active: Bool) {
self.genreLabel.textColor = active ? .white : .orange
self.contentView.backgroundColor = active ? .orange : .white
}
}
| 26.75 | 69 | 0.639252 |
01158570931b48b452299ad5114f43dcddf36364 | 4,277 | //
// GLibType.swift
// GLibObject
//
// Created by Rene Hexel on 17/4/17.
// Copyright © 2017, 2018 Rene Hexel. All rights reserved.
//
import CGLib
import GLib
//
// Unfortunately, the G_TYPE_* macros are not imported into Swift
// Therefore, rewe create them manually here
//
public extension GType {
static let invalid = GType( 0 << TYPE_FUNDAMENTAL_SHIFT)
static let none = GType( 1 << TYPE_FUNDAMENTAL_SHIFT)
static let interface = GType( 2 << TYPE_FUNDAMENTAL_SHIFT)
static let char = GType( 3 << TYPE_FUNDAMENTAL_SHIFT)
static let uchar = GType( 4 << TYPE_FUNDAMENTAL_SHIFT)
static let boolean = GType( 5 << TYPE_FUNDAMENTAL_SHIFT)
static let int = GType( 6 << TYPE_FUNDAMENTAL_SHIFT)
static let uint = GType( 7 << TYPE_FUNDAMENTAL_SHIFT)
static let long = GType( 8 << TYPE_FUNDAMENTAL_SHIFT)
static let ulong = GType( 9 << TYPE_FUNDAMENTAL_SHIFT)
static let int64 = GType(10 << TYPE_FUNDAMENTAL_SHIFT)
static let uint64 = GType(11 << TYPE_FUNDAMENTAL_SHIFT)
static let `enum` = GType(12 << TYPE_FUNDAMENTAL_SHIFT)
static let flags = GType(13 << TYPE_FUNDAMENTAL_SHIFT)
static let float = GType(14 << TYPE_FUNDAMENTAL_SHIFT)
static let double = GType(15 << TYPE_FUNDAMENTAL_SHIFT)
static let string = GType(16 << TYPE_FUNDAMENTAL_SHIFT)
static let pointer = GType(17 << TYPE_FUNDAMENTAL_SHIFT)
static let boxed = GType(18 << TYPE_FUNDAMENTAL_SHIFT)
static let param = GType(19 << TYPE_FUNDAMENTAL_SHIFT)
static let object = GType(20 << TYPE_FUNDAMENTAL_SHIFT)
static let variant = GType(21 << TYPE_FUNDAMENTAL_SHIFT)
static let max = GType(TYPE_FUNDAMENTAL_MAX)
}
public extension GType {
func test(flags: TypeFundamentalFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
func test(flags: TypeFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
/// Return the fundamental type which is the ancestor of `self`.
var fundamental: GType { return g_type_fundamental(self) }
/// Return `true` iff `self` is a fundamental type.
var isFundamental: Bool { return self <= GType.max }
/// Return `true` iff `self` is a derived type.
var isDerived: Bool { return !self.isFundamental }
/// Return `true` iff `self` is an interface type.
var isInterface: Bool { return self.fundamental == .interface }
/// Return `true` iff `self` is a classed type.
var isClassed: Bool { return test(flags: .classed) }
/// Return `true` iff `self` is a derivable type.
var isDerivable: Bool { return test(flags: .derivable) }
/// Return `true` iff `self` is a deep derivable type.
var isDeepDerivable: Bool { return test(flags: .deep_derivable) }
/// Return `true` iff `self` is an instantiatable type.
var isInstantiable: Bool { return test(flags: .instantiatable) }
/// Return `true` iff `self` is an abstract type.
var isAbstract: Bool { return test(flags: .abstract) }
/// Return `true` iff `self` is an abstract value type.
var isAbstractValue: Bool { return test(flags: .value_abstract) }
/// Return `true` iff `self` is a value type.
var isValueType: Bool { return g_type_check_is_value_type(self) != 0 }
/// Return `true` iff `self` has a value table.
var hasValueTable: Bool { return g_type_value_table_peek(self) != nil }
/// Return `true` iff `a` is transformable into `b`
static func transformable(from a: GType, to b: GType) -> Bool {
return g_value_type_transformable(a, b) != 0
}
}
fileprivate struct _GTypeClass { let g_type: GType }
fileprivate struct _GTypeInstance { let g_class: UnsafeMutablePointer<_GTypeClass>? }
/// Convenience extensions for Object types
public extension ObjectProtocol {
/// Underlying type
var type: GType {
let typeInstance = object_ptr.withMemoryRebound(to: _GTypeInstance.self, capacity: 1) { $0 }
guard let cls = typeInstance.pointee.g_class else { return .invalid }
return cls.pointee.g_type
}
/// Name of the underlying type
var typeName: String {
return String(cString: g_type_name(type))
}
}
| 45.021053 | 100 | 0.673369 |
797fb6b699ca803a788770f586f0a8bc013c2caa | 581 | //
// LabelTemplateItem.swift
// IngenicoConnectKit
//
// Created for Ingenico ePayments on 15/12/2016.
// Copyright © 2016 Global Collect Services. All rights reserved.
//
import Foundation
public class LabelTemplateItem: ResponseObjectSerializable {
public var attributeKey: String
public var mask: String?
required public init?(json: [String: Any]) {
guard let attributeKey = json["attributeKey"] as? String else {
return nil
}
self.attributeKey = attributeKey
mask = json["mask"] as? String
}
}
| 22.346154 | 71 | 0.654045 |
4b681e3e5b0d49a04b64ab853749eb522acd93c3 | 13,473 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: sifnode/clp/v1/types.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct Sifnode_Clp_V1_Asset {
// 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 symbol: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Sifnode_Clp_V1_Pool {
// 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 externalAsset: Sifnode_Clp_V1_Asset {
get {return _externalAsset ?? Sifnode_Clp_V1_Asset()}
set {_externalAsset = newValue}
}
/// Returns true if `externalAsset` has been explicitly set.
var hasExternalAsset: Bool {return self._externalAsset != nil}
/// Clears the value of `externalAsset`. Subsequent reads from it will return its default value.
mutating func clearExternalAsset() {self._externalAsset = nil}
var nativeAssetBalance: String = String()
var externalAssetBalance: String = String()
var poolUnits: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _externalAsset: Sifnode_Clp_V1_Asset? = nil
}
struct Sifnode_Clp_V1_LiquidityProvider {
// 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 asset: Sifnode_Clp_V1_Asset {
get {return _asset ?? Sifnode_Clp_V1_Asset()}
set {_asset = newValue}
}
/// Returns true if `asset` has been explicitly set.
var hasAsset: Bool {return self._asset != nil}
/// Clears the value of `asset`. Subsequent reads from it will return its default value.
mutating func clearAsset() {self._asset = nil}
var liquidityProviderUnits: String = String()
var liquidityProviderAddress: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _asset: Sifnode_Clp_V1_Asset? = nil
}
struct Sifnode_Clp_V1_WhiteList {
// 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 validatorList: [String] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Sifnode_Clp_V1_LiquidityProviderData {
// 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 liquidityProvider: Sifnode_Clp_V1_LiquidityProvider {
get {return _liquidityProvider ?? Sifnode_Clp_V1_LiquidityProvider()}
set {_liquidityProvider = newValue}
}
/// Returns true if `liquidityProvider` has been explicitly set.
var hasLiquidityProvider: Bool {return self._liquidityProvider != nil}
/// Clears the value of `liquidityProvider`. Subsequent reads from it will return its default value.
mutating func clearLiquidityProvider() {self._liquidityProvider = nil}
var nativeAssetBalance: String = String()
var externalAssetBalance: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _liquidityProvider: Sifnode_Clp_V1_LiquidityProvider? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "sifnode.clp.v1"
extension Sifnode_Clp_V1_Asset: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Asset"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "symbol"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.symbol) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.symbol.isEmpty {
try visitor.visitSingularStringField(value: self.symbol, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Clp_V1_Asset, rhs: Sifnode_Clp_V1_Asset) -> Bool {
if lhs.symbol != rhs.symbol {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Sifnode_Clp_V1_Pool: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Pool"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "external_asset"),
2: .standard(proto: "native_asset_balance"),
3: .standard(proto: "external_asset_balance"),
4: .standard(proto: "pool_units"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._externalAsset) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.nativeAssetBalance) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.externalAssetBalance) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.poolUnits) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._externalAsset {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if !self.nativeAssetBalance.isEmpty {
try visitor.visitSingularStringField(value: self.nativeAssetBalance, fieldNumber: 2)
}
if !self.externalAssetBalance.isEmpty {
try visitor.visitSingularStringField(value: self.externalAssetBalance, fieldNumber: 3)
}
if !self.poolUnits.isEmpty {
try visitor.visitSingularStringField(value: self.poolUnits, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Clp_V1_Pool, rhs: Sifnode_Clp_V1_Pool) -> Bool {
if lhs._externalAsset != rhs._externalAsset {return false}
if lhs.nativeAssetBalance != rhs.nativeAssetBalance {return false}
if lhs.externalAssetBalance != rhs.externalAssetBalance {return false}
if lhs.poolUnits != rhs.poolUnits {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Sifnode_Clp_V1_LiquidityProvider: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".LiquidityProvider"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "asset"),
2: .standard(proto: "liquidity_provider_units"),
3: .standard(proto: "liquidity_provider_address"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._asset) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.liquidityProviderUnits) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.liquidityProviderAddress) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._asset {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if !self.liquidityProviderUnits.isEmpty {
try visitor.visitSingularStringField(value: self.liquidityProviderUnits, fieldNumber: 2)
}
if !self.liquidityProviderAddress.isEmpty {
try visitor.visitSingularStringField(value: self.liquidityProviderAddress, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Clp_V1_LiquidityProvider, rhs: Sifnode_Clp_V1_LiquidityProvider) -> Bool {
if lhs._asset != rhs._asset {return false}
if lhs.liquidityProviderUnits != rhs.liquidityProviderUnits {return false}
if lhs.liquidityProviderAddress != rhs.liquidityProviderAddress {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Sifnode_Clp_V1_WhiteList: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".WhiteList"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "validator_list"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedStringField(value: &self.validatorList) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.validatorList.isEmpty {
try visitor.visitRepeatedStringField(value: self.validatorList, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Clp_V1_WhiteList, rhs: Sifnode_Clp_V1_WhiteList) -> Bool {
if lhs.validatorList != rhs.validatorList {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Sifnode_Clp_V1_LiquidityProviderData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".LiquidityProviderData"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "liquidity_provider"),
2: .standard(proto: "native_asset_balance"),
3: .standard(proto: "external_asset_balance"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._liquidityProvider) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.nativeAssetBalance) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.externalAssetBalance) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._liquidityProvider {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if !self.nativeAssetBalance.isEmpty {
try visitor.visitSingularStringField(value: self.nativeAssetBalance, fieldNumber: 2)
}
if !self.externalAssetBalance.isEmpty {
try visitor.visitSingularStringField(value: self.externalAssetBalance, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Sifnode_Clp_V1_LiquidityProviderData, rhs: Sifnode_Clp_V1_LiquidityProviderData) -> Bool {
if lhs._liquidityProvider != rhs._liquidityProvider {return false}
if lhs.nativeAssetBalance != rhs.nativeAssetBalance {return false}
if lhs.externalAssetBalance != rhs.externalAssetBalance {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 40.951368 | 148 | 0.741483 |
22b9aa76581440afcc9624aa76bfe7a081e9f8f3 | 4,466 | //
// ContentView.swift
// AlzheimersTest
//
// Created by Amit Gupta on 3/1/21.
//
//
// ContentView.swift
// Copyright © 2020 Pyxeda. All rights reserved.
//
import SwiftUI
import Alamofire
import SwiftyJSON
struct ContentView: View {
@State var animalName = " "
@State private var showingImagePicker = false
@State private var inputImage: UIImage? = UIImage(systemName: "stethoscope")
var body: some View {
HStack {
VStack (alignment: .center,
spacing: 20){
Text("Alzheimer Check")
.font(.system(.largeTitle, design: .rounded))
.fontWeight(.bold)
Text(animalName)
Image(uiImage: inputImage!).resizable()
.aspectRatio(contentMode: .fit)
//Text(animalName)
Button("Check MRI"){
self.buttonPressed()
}
.padding(.all, 14.0)
.foregroundColor(.white)
.background(Color.green)
.cornerRadius(10)
}
.font(.title)
}.sheet(isPresented: $showingImagePicker, onDismiss: processImage) {
ImagePicker(image: self.$inputImage)
}
}
func buttonPressed() {
print("Button pressed")
self.showingImagePicker = true
}
func processImage() {
self.showingImagePicker = false
self.animalName="Checking..."
guard let inputImage = inputImage else {return}
print("Processing image due to Button press")
let imageJPG=inputImage.jpegData(compressionQuality: 0.0034)!
let imageB64 = Data(imageJPG).base64EncodedData()
var uploadURL = "https://3h6ys7t373.execute-api.us-east-1.amazonaws.com/Predict/03378121-5f5b-4e24-8b5b-7a029003f2a4";
uploadURL = "https://q6x4m57367.execute-api.us-east-1.amazonaws.com/Predict/29356b45-0189-461a-ad81-44c240f38ceb"
uploadURL="https://lk5rtu02c1.execute-api.us-east-1.amazonaws.com/Predict/e5e0bce1-53a2-469e-b3b6-e0cf5a32cd26"
AF.upload(imageB64, to: uploadURL).responseJSON { response in
debugPrint(response)
switch response.result {
case .success(let responseJsonStr):
print("\n\n Success value and JSON: \(responseJsonStr)")
let myJson = JSON(responseJsonStr)
var predictedValue = myJson["predicted_label"].string
print("Saw predicted value \(String(describing: predictedValue))")
if(predictedValue=="zero") {
predictedValue="Low"
} else if(predictedValue=="nonzero") {
predictedValue="High"
}
let predictionMessage = "Risk: " + predictedValue!
self.animalName=predictionMessage
case .failure(let error):
print("\n\n Request failed with error: \(error)")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
| 36.016129 | 147 | 0.58867 |
72b4ea7c2e3d4e6c2e55996933201a3c6643721c | 9,856 | //
// ExpandedPlayerView.swift
// Tempo
//
// Created by Logan Allen on 10/26/16.
// Copyright © 2016 CUAppDev. All rights reserved.
//
import UIKit
import MarqueeLabel
class ExpandedPlayerView: ParentPlayerCellView, UIGestureRecognizerDelegate {
let progressIndicatorLength: CGFloat = 12
@IBOutlet weak var postDetailLabel: UILabel!
@IBOutlet weak var songLabel: MarqueeLabel!
@IBOutlet weak var artistLabel: MarqueeLabel!
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var topViewContainer: UIView!
@IBOutlet weak var playToggleButton: UIButton!
@IBOutlet weak var progressView: ProgressView!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var likeButtonImage: UIImageView!
@IBOutlet weak var likeButtonLabel: UILabel!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var addButtonImage: UIImageView!
@IBOutlet weak var addButtonLabel: UILabel!
@IBOutlet weak var openButton: UIButton!
@IBOutlet weak var bottomButtonsView: UIView!
@IBOutlet weak var collapseButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var prevButton: UIButton!
var progressIndicator: UIView!
override var postsLikable: Bool? {
didSet {
likeButton.isUserInteractionEnabled = postsLikable!
}
}
private var wasPlaying = false
var tapGestureRecognizer: UITapGestureRecognizer?
var panGestureRecognizer: UIPanGestureRecognizer?
var initialPanView: UIView?
func setup(parent: PlayerCenter) {
backgroundColor = .tempoOffBlack
bottomButtonsView.backgroundColor = .clear
// Setup gesture recognizers
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(expandedCellTapped(sender:)))
tapGestureRecognizer?.delegate = self
tapGestureRecognizer?.cancelsTouchesInView = false
addGestureRecognizer(tapGestureRecognizer!)
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(progressPanned(gesture:)))
panGestureRecognizer?.delegate = self
panGestureRecognizer?.delaysTouchesBegan = false
bottomButtonsView.addGestureRecognizer(panGestureRecognizer!)
// let cellPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(collapsePan(gesture:)))
// cellPanGestureRecognizer.delaysTouchesBegan = false
// topViewContainer.addGestureRecognizer(cellPanGestureRecognizer)
playerCenter = parent
progressView.playerDelegate = playerCenter
progressView.backgroundColor = .tempoDarkRed
progressIndicator = UIView(frame: CGRect(x: progressView.frame.origin.x - 5, y: progressView.frame.origin.y - 5, width: progressIndicatorLength, height: progressIndicatorLength))
progressIndicator.layer.cornerRadius = progressIndicator.frame.height/2
progressIndicator.clipsToBounds = true
progressIndicator.backgroundColor = .tempoRed
progressIndicator.isUserInteractionEnabled = true
bringSubview(toFront: playToggleButton)
progressView.indicator = progressIndicator
progressView.addSubview(progressIndicator)
setupMarqueeLabel(label: songLabel)
setupMarqueeLabel(label: artistLabel)
if (iPhone5){
addButtonLabel.text = (songStatus == .saved) ? "Saved" : "Save"
let leadingContraints = NSLayoutConstraint(item: addButton, attribute:
.leadingMargin, relatedBy: .equal, toItem: likeButton,
attribute: .leadingMargin, multiplier: 1.0, constant: 72)
let trailingConstraints = NSLayoutConstraint(item: addButton, attribute:
.trailingMargin, relatedBy: .equal, toItem: openButton,
attribute: .leadingMargin, multiplier: 1.0, constant: -30)
let widthContraints = NSLayoutConstraint(item: addButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 60)
NSLayoutConstraint.activate([leadingContraints, trailingConstraints, widthContraints])
} else {
addButtonLabel.text = (songStatus == .saved) ? "Saved to Spotify" : "Save to Spotify"
}
}
override func updateCellInfo(newPost: Post) {
post = newPost
songLabel.text = newPost.song.title
artistLabel.text = newPost.song.artist
albumImage.hnk_setImageFromURL(newPost.song.largeArtworkURL ?? NSURL() as URL)
if delegate is FeedViewController {
postDetailLabel.text = "\(newPost.user.firstName) \(newPost.user.shortenLastName()) posted \(getPostTime(time: newPost.relativeDate())) ago"
} else if delegate is LikedTableViewController {
postDetailLabel.text = "Playing from your Liked Songs"
} else if delegate is PostHistoryTableViewController {
postDetailLabel.text = "Playing from your Post History"
} else if delegate is SearchViewController {
postDetailLabel.text = "Playing from your Search Results"
}
songLabel.holdScrolling = false
artistLabel.holdScrolling = false
updateLikeButton()
updateSavedStatus()
updatePlayingStatus()
updateAddButton()
}
private func getPostTime(time: String) -> String {
let num: String = time.substring(to: time.index(before: time.endIndex))
let unit: String = time.substring(from: time.index(before: time.endIndex))
let convertedUnit: String = {
switch unit {
case "s":
return (Int(num) == 1) ? "second" : "seconds"
case "m":
return (Int(num) == 1) ? "minute" : "minutes"
case "h":
return (Int(num) == 1) ? "hour" : "hours"
case "d":
return (Int(num) == 1) ? "day" : "days"
default:
return (Int(num) == 1) ? "decade" : "decades"
}
}()
return "\(num) \(convertedUnit)"
}
override internal func updateSavedStatus() {
if let selectedPost = post {
if User.currentUser.currentSpotifyUser?.savedTracks[selectedPost.song.spotifyID] != nil {
songStatus = .saved
} else {
songStatus = .notSaved
}
}
}
override func updatePlayingStatus() {
if let selectedPost = post {
let isPlaying = selectedPost.player.isPlaying
songLabel.holdScrolling = !isPlaying
artistLabel.holdScrolling = !isPlaying
}
updatePlayToggleButton()
}
func expandedCellTapped(sender: UITapGestureRecognizer) {
let tapPoint = sender.location(in: self)
let hitView = hitTest(tapPoint, with: nil)
if hitView == playToggleButton {
if let _ = post {
delegate?.didTogglePlaying(animate: true)
}
} else if hitView == addButton {
if let _ = post {
toggleAddButton()
}
} else if hitView == likeButton {
if let post = post, postsLikable! {
post.toggleLike()
delegate?.didToggleLike!()
}
} else if let post = post, hitView == openButton {
guard let appURL = URL(string: "spotify://track/\(post.song.spotifyID)"),
let webURL = URL(string: "https://open.spotify.com/track/\(post.song.spotifyID)") else { return }
if UIApplication.shared.canOpenURL(appURL) {
UIApplication.shared.openURL(appURL)
} else {
UIApplication.shared.openURL(webURL)
}
} else if hitView == nextButton {
delegate?.playNextSong?()
} else if hitView == prevButton {
delegate?.playPrevSong?()
} else {
playerCenter.collapseAccessoryViewController(animated: true)
}
}
dynamic func progressPanned(gesture: UIPanGestureRecognizer) {
if gesture.state != .ended {
if post?.player.isPlaying ?? false {
delegate?.didTogglePlaying(animate: false)
wasPlaying = true
}
} else {
if wasPlaying {
delegate?.didTogglePlaying(animate: false)
}
wasPlaying = false
initialPanView = nil
}
let panPoint = gesture.location(in: self)
let xTranslation = panPoint.x
let progressWidth = progressView.bounds.width
let progress = Double((xTranslation - progressView.frame.origin.x)/progressWidth)
post?.player.progress = progress
delegate?.didChangeProgress?()
progressView.setNeedsDisplay()
}
// func collapsePan(gesture: UIPanGestureRecognizer) {
// let translation = gesture.translation(in: self)
// if gesture.state == .began || gesture.state == .changed {
// let maxCenter = UIScreen.main.bounds.height - expandedPlayerHeight/2.0
//
// if translation.y > 0 || center.y > maxCenter {
// center.y = center.y + translation.y < maxCenter ? maxCenter : center.y + translation.y
// }
// gesture.setTranslation(CGPoint.zero, in: self)
// }
//
// if gesture.state == .ended {
// let velocity = gesture.velocity(in: self)
// playerCenter.animateExpandedCell(isExpanding: velocity.y < 0)
// initialPanView = nil
// }
// setNeedsDisplay()
// }
override func updatePlayToggleButton() {
if let selectedPost = post {
let name = selectedPost.player.isPlaying ? "PlayerPauseButton" : "PlayerPlayButton"
progressView.setUpTimer()
playToggleButton.setImage(UIImage(named: name), for: .normal)
}
}
func updateLikeButton() {
if let selectedPost = post {
let name = (selectedPost.isLiked || selectedPost.postType == .liked) ? "LikedButton" : "PlayerLikeButton"
likeButtonImage.image = UIImage(named: name)
likeButtonLabel.text = (selectedPost.isLiked || selectedPost.postType == .liked) ? "Liked" : "Like"
}
}
override func updateAddButton() {
updateSavedStatus()
addButtonImage.image = (songStatus == .saved) ? #imageLiteral(resourceName: "ExpandedPlayerAddedButton") : #imageLiteral(resourceName: "ExpandedPlayerAddButton")
if (iPhone5){
addButtonLabel.text = (songStatus == .saved) ? "Saved" : "Save"
} else {
addButtonLabel.text = (songStatus == .saved) ? "Saved to Spotify" : "Save to Spotify"
}
}
private func setupMarqueeLabel(label: MarqueeLabel) {
label.speed = .duration(8)
label.trailingBuffer = 10
label.type = .continuous
label.fadeLength = 8
label.tapToScroll = false
label.holdScrolling = true
label.animationDelay = 0
}
override func resetPlayerCell() {
super.resetPlayerCell()
songLabel.text = ""
artistLabel.text = ""
albumImage.hnk_setImageFromURL(NSURL() as URL)
postDetailLabel.text = ""
progressView.setNeedsDisplay()
}
}
| 33.753425 | 180 | 0.725142 |
612ac246368416c45dde338a4149c018e7e5959c | 1,396 | // 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 scale: Scale { .init(name: "scale") }
open class Scale: SPSafeSymbol {
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var _3d: SPSafeSymbol { ext(.start + ".3d") }
}
}
| 43.625 | 81 | 0.744986 |
11d80c82cee411962f8439a533c4cc330f94b291 | 1,792 | //
// LeftViewController.swift
// SlideOutNavigation
//
// Created by James Frost on 03/08/2014.
// Copyright (c) 2014 James Frost. All rights reserved.
//
import UIKit
import CoreLocation
protocol SidePanelViewControllerDelegate: class {
func sortMethodSelected(_ sortBy: SortingMethod)
}
enum SortingMethod {
case byDate
case byLocation
}
final class SortOptionsTableViewController: UITableViewController {
weak var delegate: SidePanelViewControllerDelegate?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
var selectedMethod = SortingMethod.byLocation
if CLLocationManager.authorizationStatus() == .denied ||
CLLocationManager.authorizationStatus() == .restricted {
UIAlertController
.showAlertController(title: "Turn On Location Services to Allow Traffic Watch to Determine Your Location",
message: nil,
viewController: self, approveActionTitle: "Settings",
approveAction: { _ in
// Open settings to allow the user change settings
let settingsURL = URL(string: UIApplicationOpenSettingsURLString)
UIApplication.shared.open(settingsURL!, options: [:], completionHandler: nil)
}, cancelAction: {
_ in
selectedMethod = .byDate
})
}
delegate?.sortMethodSelected(selectedMethod)
default:
delegate?.sortMethodSelected(.byDate)
}
}
}
| 34.461538 | 126 | 0.584821 |
3a9b47edd14c77cc6add27695226faa094276e97 | 439 | //
// ContentView.swift
// ArmorDTest
//
// Created by Derk Norton on 1/12/20.
// Copyright © 2020 Crater Dog Technologies. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, ArmorD!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 18.291667 | 66 | 0.642369 |
e97288aa07f1612c42a6d1bbd91d571d3422e801 | 2,076 | //
// TapAnimateTextView.swift
// AnimateTextExample
//
// Created by jasu on 2022/02/06.
// Copyright (c) 2022 jasu All rights reserved.
//
import SwiftUI
import AnimateText
struct TapAnimateTextView<E: ATTextAnimateEffect>: View {
let type: ATUnitType
let elements: [String]
var userInfo: Any? = nil
@State private var text: String = ""
var body: some View {
GeometryReader { proxy in
VStack(alignment: .leading) {
Spacer()
ZStack(alignment: .leading) {
AnimateText<E>($text, type: type, userInfo: userInfo)
.font(.custom("Helvetica SemiBold", size: 30))
.padding(.vertical)
if text.isEmpty {
VStack(alignment: .leading) {
Text(String(describing: E.self))
.foregroundColor(Color.accentColor)
.font(.custom("Helvetica SemiBold", size: 30))
.transition(.opacity)
Text("Touch the screen.")
.font(.callout)
.opacity(0.3)
.disabled(true)
}
}
}
.padding()
.padding(.bottom, 50)
Spacer()
}
}
.clipped()
.contentShape(Rectangle())
.onTapGesture {
changeText()
}
.onAppear {
text = ""
}
}
private func changeText() {
let newText = self.elements[Int.random(in: (0..<self.elements.count))]
if Bool.random() == true {
text = newText
}else {
text = newText.uppercased()
}
}
}
struct TapAnimateTextView_Previews: PreviewProvider {
static var previews: some View {
TapAnimateTextView<ATTwistEffect>(type: .letters, elements: ["AnimateText"])
}
}
| 29.239437 | 84 | 0.465318 |
72aa89abf86d6e78a8e44ab472a310a39851c3a5 | 2,477 | //
// EventTests.swift
// Vapor
//
// Created by Logan Wright on 4/6/16.
//
//
import XCTest
@testable import Vapor
class ValidationUniqueTests: XCTestCase {
static let allTests = [
("testIntsArray", testIntsArray),
("testStringArray", testStringArray)
]
func testIntsArray() {
let unique = [1, 2, 3, 4, 5, 6, 7, 8]
XCTAssertTrue(unique.passes(Unique))
let notUnique = unique + unique
XCTAssertFalse(notUnique.passes(Unique))
}
func testStringArray() {
let unique = ["a", "b", "c", "d", "e"]
XCTAssertTrue(unique.passes(Unique))
let notUnique = unique + unique
XCTAssertFalse(notUnique.passes(Unique))
}
}
class ValidationInTests: XCTestCase {
static var allTests: [(String, (ValidationInTests) -> () throws -> Void)] {
return [
("testIntsArray", testIntsArray),
("testStringArray", testStringArray)
]
}
func testIntsArray() {
let unique = [1, 2, 3, 4, 5, 6, 7, 8]
XCTAssertTrue(unique.passes(Unique))
let notUnique = unique + unique
XCTAssertFalse(notUnique.passes(Unique))
}
func testStringArray() {
let unique = ["a", "b", "c", "d", "e"]
XCTAssertTrue(unique.passes(Unique))
let notUnique = unique + unique
XCTAssertFalse(notUnique.passes(Unique))
}
func testInArray() {
let array = [0,1,2,3]
XCTAssertTrue(1.passes(In(array)))
XCTAssertFalse(13.passes(In(array)))
}
func testInSet() throws {
let set = Set(["a", "b", "c"])
// Run at least two tests w/ same validator instance that should be true to
// ensure that iteratorFactory is functioning properly
let validator = In(set)
XCTAssertTrue("a".passes(validator))
XCTAssertTrue("b".passes(validator))
XCTAssertFalse("b".passes(!In(set)))
XCTAssertFalse("nope".passes(validator))
}
func testGenerator() {
let array = [0.0, 1.0, 2.0, 3.0]
var idx = 0
let generator = AnyIterator<Double> {
guard idx < array.count else {
XCTFail("Generator should stop when equality found")
return nil
}
let next = array[idx] // will crash if exceeds, we're testing that
idx += 1
return next
}
XCTAssertTrue(3.0.passes(In(generator)))
}
}
| 28.147727 | 84 | 0.570448 |
9b51ef82187ee481c45208c2cd76d13794931e5c | 2,209 | //
// AppDelegate.swift
// Flicks
//
// Created by Arthur on 2017/1/30.
// Copyright © 2017年 Kuan-Ting Wu (Arthur Wu). All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 42.480769 | 285 | 0.744228 |
48e6c32c4f9fb8208bc8050ab53496ed60abfe32 | 2,026 | //
// APIService.swift
// Rates
//
// Created by Michael Henry Pantaleon on 2019/08/28.
// Copyright © 2019 Michael Henry Pantaleon. All rights reserved.
//
import Foundation
class APIService {
static let shared = APIService()
private lazy var requestCaller = RequestCaller()
private let baseUrl:URL = URL(string: "http://apilayer.net")!
private lazy var apiKey:String = {
// I do recommend to set and override the PRODUCTION API KEY
// via CI ENVIRONMENT Variable
// And on Development Environment we provide a default value so that
// the app will continue to work without any additional configuration,
// ONLY if this is in a PRIVATE Repo.
//
// But for DEMO purposes, I will include this API Key
// And there is a chance that this will revoke in the future.
guard let _currencyLayerConfig = Bundle.main
.object(forInfoDictionaryKey: "CurrencyLayer") as? [String: String],
let _apiKey = _currencyLayerConfig["APIKey"] else {
fatalError("No CurrencyLayer.APIKey found")
}
return _apiKey
}()
func fetchCurrencies(completion: @escaping(Result<Currencies, RequestError>) -> Void) {
let endpoint = "api/list"
requestCaller.call(request: request(from: endpoint), completion: completion)
}
func fetchLive(source:String, completion: @escaping(Result<Quotes, RequestError>) -> Void) {
let endpoint = "api/live"
requestCaller.call(
request: request(from: endpoint,
queryParams: ["source": source]),
completion: completion)
}
private func request(from endpoint:String, queryParams:[String:String] = [:]) -> URLRequest {
var components = URLComponents(url: baseUrl.appendingPathComponent(endpoint), resolvingAgainstBaseURL: true)!
var items = [URLQueryItem(name: "access_key", value: apiKey)]
queryParams.forEach {
items.append(URLQueryItem(name: $0.key, value: $0.value))
}
components.queryItems = items
return URLRequest(url: components.url!)
}
}
| 35.54386 | 113 | 0.69151 |
905b579583c468f23d575c299a81bc794ae426df | 3,903 | //
// BookingHistoryViewModel.swift
// Booking Application
//
// Created by student on 28.04.21.
//
import Combine
import SwiftUI
class BookingHistoryViewModel: ObservableObject {
weak var controller: BookingHistoryViewController?
private var cancellables = Set<AnyCancellable>()
private var serverRequest = ServerRequest()
private var canLoadMorePages = true
private var currentPage = 1
@Published var historyOrders = [Order]()
@Published var isLoadingPage = false
// Alert Data
@Published var showAlert = false
@Published var errorMessage = ""
deinit {
for cancellable in cancellables {
cancellable.cancel()
}
}
init() {
self.loadMoreHistoryOrders()
// Register to receive notification in your class
NotificationCenter.default
.publisher(for: .newOrderHistoryNotification)
.sink() { [weak self] _ in
// Handle notification
self?.resetOrdersHistoryData()
self?.loadMoreHistoryOrders()
}
.store(in: &cancellables)
}
// MARK: -> Load Content By Pages
func loadMoreContentIfNeeded(currentItem item: Order?) {
guard let item = item else {
self.loadMoreHistoryOrders()
return
}
let thresholdIndex = historyOrders.index(historyOrders.endIndex, offsetBy: -5)
if historyOrders.firstIndex(where: { $0.id == item.id }) == thresholdIndex {
self.loadMoreHistoryOrders()
}
}
func loadMoreHistoryOrders() {
guard !isLoadingPage && canLoadMorePages else {
return
}
isLoadingPage = true
var url = URLComponents(string: DomainRouter.linkAPIRequests.rawValue + DomainRouter.ordersRoute.rawValue)!
url.queryItems = [
URLQueryItem(name: "history", value: nil),
URLQueryItem(name: "page", value: "\(self.currentPage)")
]
var request = URLRequest(url: url.url!)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer \(UserDefaults.standard.string(forKey: "access_token")!)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTaskPublisher(for: request as URLRequest)
.map(\.data)
.decode(type: Orders.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.handleEvents(receiveOutput: { response in
self.canLoadMorePages = (response.lastPage != response.currentPage)
self.isLoadingPage = false
self.currentPage += 1
})
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("Loading of history orders finished.")
case .failure(let error):
print("Error of load history orders: \(error.localizedDescription)")
self.isLoadingPage = false
self.resetOrdersHistoryData()
self.showAlert = true
self.errorMessage = error.localizedDescription
}
}, receiveValue: { response in
print("Loaded some history orders: \(response.data.count)")
self.historyOrders.append(contentsOf: response.data)
})
.store(in: &cancellables)
}
func resetOrdersHistoryData() {
currentPage = 1
historyOrders.removeAll()
isLoadingPage = false
canLoadMorePages = true
}
}
| 32.798319 | 128 | 0.578529 |
0e5e026cc9cf80cc4d8981985a3a61768fd99a5f | 575 | //
// OnboardingView2.swift
// RouterExample
//
// Created by burt on 2021/03/05.
//
import Foundation
import SwiftUI
import Router
import Defaults
struct OnboardingView2: View {
@EnvironmentObject
var router: Router
@Default(.isFirstLaunch)
var isFirstLaunch: Bool
var body: some View {
VStack {
Text("Onboarding View Page 2")
Button("Finish") {
isFirstLaunch = false
router.route("myapp://content", .replace, animated: false)
}
}
}
}
| 19.166667 | 90 | 0.565217 |
56d9a759cc5da2abefe9232caa8a6ff08f46f4a9 | 1,724 | //
// HabitCreationDayTimePicker.swift
// Agile diary
//
// Created by Илья Харабет on 11/01/2020.
// Copyright © 2020 Mesterra. All rights reserved.
//
import UIKit
import UIComponents
final class HabitCreationDayTimePicker: UIView {
var onSelectDayTime: ((Habit.DayTime) -> Void)?
private let dayTimeSwitcher = Switcher()
@objc private func onDayTimeSwitcherValueChanged() {
guard let dayTime = Habit.DayTime.allCases.item(at: dayTimeSwitcher.selectedItemIndex) else { return }
onSelectDayTime?(dayTime)
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(dayTimeSwitcher)
dayTimeSwitcher.height(28)
dayTimeSwitcher.allEdges().toSuperview()
dayTimeSwitcher.items = Self.makeSwitcherItems()
dayTimeSwitcher.addTarget(self, action: #selector(onDayTimeSwitcherValueChanged), for: .touchUpInside)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setDayTime(_ dayTime: Habit.DayTime) {
dayTimeSwitcher.selectedItemIndex = Habit.DayTime.allCases.index(of: dayTime) ?? 0
}
private static func makeSwitcherItems() -> [SwitcherItem] {
return Habit.DayTime.allCases.map {
switch $0 {
case .morning: return UIImage(imageLiteralResourceName: "day_time_morning")
case .afternoon: return UIImage(imageLiteralResourceName: "day_time_afternoon")
case .evening: return UIImage(imageLiteralResourceName: "day_time_evening")
case .duringTheDay: return $0.localized
}
}
}
}
| 30.785714 | 110 | 0.651392 |
4ac65132ea47747cbadc84d54a057e66b2c10df4 | 8,524 | //
// DetailViewController.swift
// Learn2Tune
//
// Created by gam on 6/9/20.
// Copyright © 2020 gam. All rights reserved.
//
import UIKit
import CoreData
class ImageDetailViewController: UIViewController, NSFetchedResultsControllerDelegate {
var fetchedResultsController: NSFetchedResultsController<Label>!
var photo: Photo!
var dataController: DataController!
var numberOfLabelsHandled = 0
let textFieldDelegate = TextFieldDelegate()
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var predictionLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var fetchPredictionsLabel: UILabel!
@IBOutlet weak var enterLabelTextField: UITextField!
@IBOutlet weak var userPredictionLabel: UILabel!
@IBOutlet weak var activityIndicatorStackView: UIStackView!
@IBAction func retryPrediction(_ sender: Any) {
guard let url = photo.url else {
return
}
activityIndicator.startAnimating()
fetchPredictionsLabel.isHidden = false
activityIndicatorStackView.isHidden = false
enterLabelTextField.isEnabled = false
AzureClient.getPredictionFromAzure(imageLoc: url, completion: AzurePredictionHandler(response:error:))
}
override func viewDidLoad() {
super.viewDidLoad()
if let photo = photo.photo{
imageView.image = UIImage(data: photo)
// Do any additional setup after loading the view.
print("image loaded")
}
enterLabelTextField.delegate = textFieldDelegate
addDoneButtonOnKeyboard()
}
override func viewWillAppear(_ animated: Bool) {
setupFetchedResultsController()
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
// All notification unsubscriptions are here
unsubscribeFromKeyboardNotifications()
}
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
if self.view.frame.origin.y == 0 {
if let activeField = textFieldDelegate.activeField {
var aRect: CGRect = self.view.frame;
aRect.size.height -= getKeyboardHeight(notification);
// activefield is inside a stackview so convert it to global coordinates
if !aRect.contains((activeField.superview?.convert(activeField.frame.origin, to: nil))!) {
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
}
}
}
@objc func keyboardWillHide(_ notification: Notification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
// keyboard hides when return is pressed so fetch the textfield value
fetchLabels()
if !fetchedResultsController.fetchedObjects!.isEmpty {
let userInput = enterLabelTextField.text ?? ""
fetchedResultsController.fetchedObjects?.first?.taggedLabel = userInput
if dataController.viewContext.hasChanges{
try? dataController.viewContext.save()
userPredictionLabel.text = "User Prediction: " + userInput
}
}
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func fetchLabels() {
let fetchRequest:NSFetchRequest<Label> = Label.fetchRequest()
// Many to Many and Many To One have predicates
//let predicateManyToOne = NSPredicate(format: "photo == %@", photo)
let predicateManyToMany = NSPredicate(format: "ANY %K = %@", #keyPath(Label.toPhoto), photo)
fetchRequest.predicate = predicateManyToMany
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataController.viewContext, sectionNameKeyPath: nil, cacheName: "\(photo!)-labels")
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("The fetch could not be performed: \(error.localizedDescription)")
}
}
func setupFetchedResultsController() {
fetchLabels()
fetchedResultsController.delegate = self
numberOfLabelsHandled = fetchedResultsController.fetchedObjects!.count
if numberOfLabelsHandled == 0 {
guard let url = photo.url else {
return
}
activityIndicator.startAnimating()
fetchPredictionsLabel.isHidden = false
activityIndicatorStackView.isHidden = false
AzureClient.getPredictionFromAzure(imageLoc: url, completion: AzurePredictionHandler(response:error:))
} else {
for object in fetchedResultsController.fetchedObjects! {
print("predicted label", object.predictedLabel ?? " ")
var label = object.predictedLabel ?? ""
predictionLabel.text = "Prediction: " + label
label = object.taggedLabel ?? ""
userPredictionLabel.text = "User Prediction " + label
}
}
}
func AzurePredictionHandler(response:
AzurePrediction?, error: Error?) {
activityIndicator.stopAnimating()
activityIndicatorStackView.isHidden = true
fetchPredictionsLabel.isHidden = true
enterLabelTextField.isEnabled = true
guard let response = response else {
showPredictionFailure(message: error?.localizedDescription ?? "Unknown prediction error!" )
return
}
let label = Label(context: dataController.viewContext)
if let date = response.created {
let d = Date(timeIntervalSince1970: date)
label.creationDate = d
} else {
label.creationDate = Date()
}
let text = response.predictedTagName ?? ""
label.predictedLabel = text
photo.addToToLabels(label)
predictionLabel.text = ""
predictionLabel.text = "Prediction: " + label.predictedLabel!
try? dataController.viewContext.save()
print("Labels are fetched!")
}
}
extension ImageDetailViewController{
func showPredictionFailure(message: String) {
let alertVC = UIAlertController(title: "Prediction Failed", message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
// MARK: Use show or present depending on the current viewcontroller (in a navigation or not, tabbar etc.)
present(alertVC, animated: true, completion: nil)
}
func addDoneButtonOnKeyboard()
{
let toolbar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
//create left side empty space so that done button set on right side
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
enterLabelTextField.inputAccessoryView = toolbar
}
@objc
func doneButtonAction()
{
enterLabelTextField.resignFirstResponder()
}
}
| 40.398104 | 195 | 0.65779 |
11dd8cc6a871815b6ff83a3e9e86325123a54b1d | 1,865 | //
// TodayViewController.swift
// widget
//
// Created by Huan Suh on 2020/05/20.
// Copyright © 2020 The Chromium Authors. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet var widgetText: UILabel!
private let kAppGroupName = "group.widgetupdater"
private var sharedContainer : UserDefaults?
var dataDict: [String:Any]?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.reloadInputViews()
self.sharedContainer = UserDefaults(suiteName: kAppGroupName)
//self.widgetText.reloadInputViews()
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
fetchDataFromSharedContainer()
completionHandler(NCUpdateResult.newData)
}
fileprivate func fetchDataFromSharedContainer()
{
print("log:::::")
if let sharedContainer = self.sharedContainer, let dataDict = sharedContainer.dictionary(forKey: "HOME_SCREEN_WIDGET_DATA_KEY")
{
print("log::::::::::::")
self.dataDict = dataDict
let format = DateFormatter()
format.locale = Locale(identifier: "ko_kr")
format.dateFormat = "yyyy-MM-dd hh:mm:ss"
if let data = self.dataDict?["data"] as! String? {
widgetText.text = data
} else {
widgetText.text = format.string(from: Date())
}
}
}
}
| 32.719298 | 135 | 0.629491 |
d5544527aaaaa6b55075885ec7a592b41b0630f2 | 851 | //
// NearEarthObjectsView.swift
// NasaExplorer-iOS
//
// Created by Claudio Miraka on 1/21/22.
//
import SwiftUI
struct NearEarthObjectsView: View {
@ObservedObject var nearEarthObjectsViewModel : NearEarthObjectsViewModel
var body: some View {
if nearEarthObjectsViewModel.isWaiting {
Text("Loading...")
} else{
if let nearObj =
nearEarthObjectsViewModel.nearEarthObjects {
NearEarthObjectsWidget(nearEarthObjects: nearObj)
}else{
Text("Error getting data. Check logs.")
}
}
}
}
struct NearEarthObjectsView_Previews: PreviewProvider {
static var previews: some View {
NearEarthObjectsView(nearEarthObjectsViewModel: NearEarthObjectsViewModel())
}
}
| 23.638889 | 84 | 0.612221 |
8f24c63f3b2e8ea3ed7f0c809819a39defd0d155 | 7,646 | //
// SocketSideEffectTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/11/15.
//
//
import XCTest
@testable import SocketIO
class SocketSideEffectTest: XCTestCase {
func testInitialCurrentAck() {
XCTAssertEqual(socket.currentAck, -1)
}
func testFirstAck() {
socket.emitWithAck("test").timingOut(after: 0) {data in}
XCTAssertEqual(socket.currentAck, 0)
}
func testSecondAck() {
socket.emitWithAck("test").timingOut(after: 0) {data in}
socket.emitWithAck("test").timingOut(after: 0) {data in}
XCTAssertEqual(socket.currentAck, 1)
}
func testHandleAck() {
let expect = expectation(description: "handled ack")
socket.emitWithAck("test").timingOut(after: 0) {data in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
}
socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleAck2() {
let expect = expectation(description: "handled ack2")
socket.emitWithAck("test").timingOut(after: 0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expect.fulfill()
}
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(Data())
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleEvent() {
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleOnceEvent() {
let expect = expectation(description: "handled event")
socket.once("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
XCTAssertEqual(self.socket.testHandlers.count, 0)
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testOffWithEvent() {
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 1)
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 2)
socket.off("test")
XCTAssertEqual(socket.testHandlers.count, 0)
}
func testOffWithId() {
let handler = socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 1)
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 2)
socket.off(id: handler)
XCTAssertEqual(socket.testHandlers.count, 1)
}
func testHandlesErrorPacket() {
let expect = expectation(description: "Handled error")
socket.on("error") {data, ack in
if let error = data[0] as? String, error == "test error" {
expect.fulfill()
}
}
socket.parseSocketMessage("4\"test error\"")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleBinaryEvent() {
let expect = expectation(description: "handled binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData {
XCTAssertEqual(data as Data, self.data)
expect.fulfill()
}
}
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
socket.parseBinaryData(data)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleMultipleBinaryEvent() {
let expect = expectation(description: "handled multiple binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData,
let data2 = dict["test2"] as? NSData {
XCTAssertEqual(data as Data, self.data)
XCTAssertEqual(data2 as Data, self.data2)
expect.fulfill()
}
}
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
socket.parseBinaryData(data)
socket.parseBinaryData(data2)
waitForExpectations(timeout: 3, handler: nil)
}
func testSocketManager() {
let manager = SocketClientManager.sharedManager
manager["test"] = socket
XCTAssert(manager["test"] === socket, "failed to get socket")
manager["test"] = nil
XCTAssert(manager["test"] == nil, "socket not removed")
}
func testChangingStatusCallsStatusChangeHandler() {
let expect = expectation(description: "The client should announce when the status changes")
let statusChange = SocketIOClientStatus.connecting
socket.on("statusChange") {data, ack in
guard let status = data[0] as? SocketIOClientStatus else {
XCTFail("Status should be one of the defined statuses")
return
}
XCTAssertEqual(status, statusChange, "The status changed should be the one set")
expect.fulfill()
}
socket.setTestStatus(statusChange)
waitForExpectations(timeout: 0.2)
}
func testOnClientEvent() {
let expect = expectation(description: "The client should call client event handlers")
let event = SocketClientEvent.disconnect
let closeReason = "testing"
socket.on(clientEvent: event) {data, ack in
guard let reason = data[0] as? String else {
XCTFail("Client should pass data for client events")
return
}
XCTAssertEqual(closeReason, reason, "The data should be what was sent to handleClientEvent")
expect.fulfill()
}
socket.handleClientEvent(event, data: [closeReason])
waitForExpectations(timeout: 0.2)
}
func testClientEventsAreBackwardsCompatible() {
let expect = expectation(description: "The client should call old style client event handlers")
let event = SocketClientEvent.disconnect
let closeReason = "testing"
socket.on("disconnect") {data, ack in
guard let reason = data[0] as? String else {
XCTFail("Client should pass data for client events")
return
}
XCTAssertEqual(closeReason, reason, "The data should be what was sent to handleClientEvent")
expect.fulfill()
}
socket.handleClientEvent(event, data: [closeReason])
waitForExpectations(timeout: 0.2)
}
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
private var socket: SocketIOClient!
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
socket.setTestable()
}
}
| 32.675214 | 139 | 0.603322 |
619ffd6254aa286b1da891c4c0d545f82389cb65 | 1,369 | import Parsing
import XCTest
final class IntTests: XCTestCase {
func testBasics() {
let parser = Int.parser(of: Substring.UTF8View.self)
var input = "123 Hello"[...].utf8
XCTAssertEqual(123, parser.parse(&input))
XCTAssertEqual(" Hello", String(input))
input = "-123 Hello"[...].utf8
XCTAssertEqual(-123, parser.parse(&input))
XCTAssertEqual(" Hello", String(input))
input = "+123 Hello"[...].utf8
XCTAssertEqual(123, parser.parse(&input))
XCTAssertEqual(" Hello", String(input))
input = "\(Int.max) Hello"[...].utf8
XCTAssertEqual(Int.max, parser.parse(&input))
XCTAssertEqual(" Hello", String(input))
input = "\(Int.min) Hello"[...].utf8
XCTAssertEqual(Int.min, parser.parse(&input))
XCTAssertEqual(" Hello", String(input))
input = "Hello"[...].utf8
XCTAssertEqual(nil, parser.parse(&input))
XCTAssertEqual("Hello", String(input))
input = "- Hello"[...].utf8
XCTAssertEqual(nil, parser.parse(&input))
XCTAssertEqual("- Hello", String(input))
input = "+ Hello"[...].utf8
XCTAssertEqual(nil, parser.parse(&input))
XCTAssertEqual("+ Hello", String(input))
}
func testOverflow() {
var input = "1234 Hello"[...].utf8
XCTAssertEqual(nil, UInt8.parser(of: Substring.UTF8View.self).parse(&input))
XCTAssertEqual("1234 Hello", String(input))
}
}
| 29.12766 | 80 | 0.647188 |
61e8e65cd7241e270ffb42197ebd504d6206de5c | 124 | import XCTest
import PersistenceTests
var tests = [XCTestCaseEntry]()
tests += PersistenceTests.allTests()
XCTMain(tests)
| 15.5 | 36 | 0.790323 |
d952eb08230b99f38456256e4d90edf4bc5a3031 | 1,263 | //
// Section_2_21UITests.swift
// Section 2-21UITests
//
// Created by Ilias Alexopoulos on 08/09/2016.
// Copyright © 2016 WorkAngel. All rights reserved.
//
import XCTest
class Section_2_21UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.135135 | 182 | 0.666667 |
3af28252ee87e24a3c2339bd71b8e742c2f99d61 | 2,072 | //
// Siri.swift
//
// Copyright (c) 2015-2017 Damien (http://delba.io)
//
// 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.
//
#if PERMISSION_SIRI
import Intents
extension Permission {
var statusSiri: PermissionStatus {
guard #available(iOS 10.0, *) else { fatalError() }
let status = INPreferences.siriAuthorizationStatus()
switch status {
case .authorized: return .authorized
case .restricted, .denied: return .denied
case .notDetermined: return .notDetermined
@unknown default: return .notDetermined
}
}
func requestSiri(_ callback: @escaping Callback) {
guard #available(iOS 10.0, *) else { fatalError() }
guard let _ = Bundle.main.object(forInfoDictionaryKey: .siriUsageDescription) else {
print("WARNING: \(String.siriUsageDescription) not found in Info.plist")
return
}
INPreferences.requestSiriAuthorization { _ in
callback(self.statusSiri)
}
}
}
#endif
| 37 | 92 | 0.696429 |
8ffdab41a25373870e34bf558bc87e0f718d07e1 | 1,760 | import UIKit
final class TabItemView: UIView {
private(set) var titleLabel: UILabel = UILabel()
public var font: UIFont = UIFont.boldSystemFont(ofSize: 14)
public var selectedFont: UIFont = UIFont.boldSystemFont(ofSize: 14)
public var textColor: UIColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0)
public var selectedTextColor: UIColor = .white
public var isSelected: Bool = false {
didSet {
if isSelected {
titleLabel.textColor = selectedTextColor
} else {
titleLabel.textColor = textColor
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func layoutSubviews() {
super.layoutSubviews()
}
private func setupLabel() {
titleLabel = UILabel(frame: bounds)
titleLabel.textAlignment = .center
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
titleLabel.textColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0)
titleLabel.backgroundColor = UIColor.clear
addSubview(titleLabel)
layoutLabel()
}
private func layoutLabel() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: self.topAnchor),
titleLabel.widthAnchor.constraint(equalTo: self.widthAnchor),
titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
| 30.877193 | 100 | 0.644318 |
f820dc98eee705d30f65ba38ffdd8c36c3ed9306 | 4,767 | //
// NetFlowSummaryTotalDataView.swift
// Alamofire
//
// Created by 王来 on 2020/10/19.
//
class NetFlowSummaryTotalDataItemView: UIView {
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.regular(10)
titleLabel.textColor = UIColor.assistant_black_2()
titleLabel.textAlignment = .center
return titleLabel
}()
private lazy var valueLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.regular(22)
titleLabel.textColor = UIColor.assistant_black_1()
titleLabel.textAlignment = .center
return titleLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpUI() {
addSubview(valueLabel)
valueLabel.snp.makeConstraints {
$0.top.right.left.equalToSuperview().offset(0)
}
addSubview(titleLabel)
titleLabel.snp.makeConstraints {
$0.right.left.equalToSuperview().offset(0)
$0.top.equalTo(valueLabel.snp.bottom).offset(10.fitSizeFrom750)
}
}
func renderUIWithTitle(_ title: String, value: String) {
titleLabel.text = title
valueLabel.text = value
}
}
class NetFlowSummaryTotalDataView: UIView {
/// 抓包时间
private lazy var timeView: NetFlowSummaryTotalDataItemView = {
let timeView = NetFlowSummaryTotalDataItemView()
return timeView
}()
/// 抓包数量
private lazy var numView: NetFlowSummaryTotalDataItemView = {
let timeView = NetFlowSummaryTotalDataItemView()
return timeView
}()
/// 数据上传
private lazy var upLoadView: NetFlowSummaryTotalDataItemView = {
let timeView = NetFlowSummaryTotalDataItemView()
return timeView
}()
/// 数据下载
private lazy var downLoadView: NetFlowSummaryTotalDataItemView = {
let timeView = NetFlowSummaryTotalDataItemView()
return timeView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpUI() {
self.layer.cornerRadius = 5
self.backgroundColor = UIColor.white
addSubview(timeView)
timeView.snp.makeConstraints {
$0.top.equalToSuperview().offset(20.fitSizeFrom750)
$0.centerX.equalToSuperview().offset(0)
$0.height.equalTo(60.fitSizeFrom750)
}
addSubview(numView)
numView.snp.makeConstraints {
$0.left.bottom.equalToSuperview().offset(0)
$0.width.equalToSuperview().multipliedBy(1.0 / 3.0)
$0.height.equalTo(timeView.snp.height)
}
addSubview(upLoadView)
upLoadView.snp.makeConstraints {
$0.bottom.equalToSuperview().offset(0)
$0.centerX.equalToSuperview().offset(0)
$0.width.equalTo(numView.snp.width)
$0.height.equalTo(timeView.snp.height)
}
addSubview(downLoadView)
downLoadView.snp.makeConstraints {
$0.right.bottom.equalToSuperview().offset(0)
$0.width.equalTo(numView.snp.width)
$0.height.equalTo(timeView.snp.height)
}
// 抓包时间
var time = ""
if let startInterceptDate = NetFlowManager.shared.startInterceptDate {
let nowDate = Date()
let cha = nowDate.timeIntervalSince(startInterceptDate as Date)
time = String(format: "%.2f%@", cha, "秒")
} else {
time = "暂未开启网络监控"
}
timeView.renderUIWithTitle("总计已为您抓包", value: time)
// 抓包数量
let httpModelArray: [NetFlowHttpModel] = NetFlowDataSource.shared.httpModelArray
let num = "\(httpModelArray.count)"
var totalUploadFlow = 0
var totalDownFlow = 0
for index in 0..<httpModelArray.count {
let httpModel = httpModelArray[index]
let uploadFlow = NSString(string: httpModel.uploadFlow ?? "").intValue
let downFlow = NSString(string: httpModel.downFlow ?? "").intValue
totalUploadFlow += Int(uploadFlow)
totalDownFlow += Int(downFlow)
}
numView.renderUIWithTitle("抓包数量", value: num)
// 数据上传
let upLoad = AssistantUtil.formatByte(Float(totalUploadFlow))
upLoadView.renderUIWithTitle("数据上传", value: upLoad)
// 数据下载
let downLoad = AssistantUtil.formatByte(Float(totalDownFlow))
downLoadView.renderUIWithTitle("数据下载", value: downLoad)
}
}
| 29.245399 | 88 | 0.618418 |
eb5198e48129d1919d6816ff7c0ae244c83125e0 | 1,842 | //
// AddGoalNamePresenterTests.swift
// Odysseia
//
// Created by lcr on 27/10/2020.
// Copyright © 2020 lcr. All rights reserved.
//
@testable import Odysseia
import XCTest
class AddGoalNamePresenterTest: XCTestCase {
var view: MockAddGoalNameView!
var router: MockAddGoalNameRouter!
var presenter: AddGoalNamePresenter!
override func setUp() {
super.setUp()
view = MockAddGoalNameView()
router = MockAddGoalNameRouter()
presenter = AddGoalNamePresenter(view: view, router: router)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testValidationErrorTitle() {
let testCases = [
(title: "", errorMessage: L10n.Localizable.goalTitleNilMsg, callCount: 1),
(title: createString(length: 50), errorMessage: "", callCount: 0),
(title: createString(length: 51), errorMessage: L10n.Localizable.goalTitleMaxLengthMsg, callCount: 1)
]
for testCase in testCases {
// setup
self.setUp()
presenter.updateDedline(year: 2020)
// execute
presenter.nextButtonTouched(title: testCase.title)
// verify
XCTxContext("titleが空のときエラーが返ること") {
XCTAssertEqual(view.callCountValidationError, testCase.callCount)
XCTAssertEqual(view.validationErrorMsg, testCase.errorMessage)
}
// tearDown
self.tearDown()
}
}
private func createString(length: Int) -> String {
let allowedChars = "a"
var randomString = ""
for _ in 0..<length {
randomString += allowedChars
}
return randomString
}
}
| 28.78125 | 113 | 0.614549 |
f9117e8b727cfa76ac1b572a1297e06f642f365b | 4,830 | @testable import FinnhubSwift
import XCTest
final class MarketNewsTests: XCTestCase {
func testsThatItCreatesMarketNewsEntries() {
let notJsonString = Data("Hello".utf8)
let wrong = Data("""
[
"AAPL",
"EMC",
"HPQ",
"DELL",
"WDC",
"HPE",
"NTAP",
"CPQ",
"SNDK",
"SEG"
]
""".utf8)
let partial = Data("""
[
{
"category": "technology",
"datetime": 1596589501,
"image": "https://image.cnbcfm.com/api/v1/image/105569283-1542050972462rts25mct.jpg?v=1542051069",
}
]
""".utf8)
let one = Data("""
[
{
"category": "technology",
"datetime": 1596589501,
"headline": "Square surges after reporting 64% jump in revenue, more customers using Cash App",
"id": 5085164,
"image": "https://image.cnbcfm.com/api/v1/image/105569283-1542050972462rts25mct.jpg?v=1542051069",
"related": "",
"source": "CNBC",
"url": "https://www.cnbc.com/2020/08/04/square-sq-earnings-q2-2020.html"
}
]
""".utf8)
let many = Data("""
[
{
"category": "technology",
"datetime": 1596589501,
"headline": "Square surges after reporting 64% jump in revenue, more customers using Cash App",
"id": 5085164,
"image": "https://image.cnbcfm.com/api/v1/image/105569283-1542050972462rts25mct.jpg?v=1542051069",
"related": "",
"source": "CNBC",
"url": "https://www.cnbc.com/2020/08/04/square-sq-earnings-q2-2020.html"
},
{
"category": "business",
"datetime": 1596588232,
"headline": "B&G Foods CEO expects pantry demand to hold up post-pandemic",
"id": 5085113,
"image": "https://image.cnbcfm.com/api/v1/image/106629991-1595532157669-gettyimages-1221952946-362857076_1-5.jpeg?v=1595532242",
"related": "",
"source": "CNBC",
"url": "https://www.cnbc.com/2020/08/04/bg-foods-ceo-expects-pantry-demand-to-hold-up-post-pandemic.html"
},
]
""".utf8)
let data: [CodableTester] = [
CodableTester(payload: many, expect: true),
CodableTester(payload: one, expect: true),
CodableTester(payload: partial, expect: false),
CodableTester(payload: wrong, expect: false),
CodableTester(payload: notJsonString, expect: false),
]
for datum in data {
testsThatItCreatesMarketNews(data: datum)
}
}
func testsThatItCreatesMarketNews(data: CodableTester) {
let country = try? JSONDecoder().decode([MarketNews].self, from: data.payload)
if data.expect {
print(data)
XCTAssertNotNil(country)
} else {
XCTAssertNil(country)
}
}
func testThatEquatable() {
let fixture1 = MarketNews(category: "technology", datetime: 156_934_523_432, headline: "B&G Foods", id: 5_085_113, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
let fixture2 = MarketNews(category: "technology", datetime: 156_934_523_432, headline: "B&G Foods", id: 5_085_113, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
XCTAssertEqual(fixture1, fixture2)
}
func testThatEquatableById() {
let fixture1 = MarketNews(category: "technology", datetime: 156_934_523_432, headline: "B&G Foods", id: 5_085_113, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
let fixture2 = MarketNews(category: "news", datetime: 2, headline: "", id: 5_085_113, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
XCTAssertEqual(fixture1, fixture2)
}
func testThatHashable() {
let fixture1 = MarketNews(category: "technology", datetime: 156_934_523_432, headline: "B&G Foods", id: 5_085_113, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
let fixture2 = MarketNews(category: "news", datetime: 2, headline: "", id: 5_085_111, image: "https://image.com", related: "", source: "CNBC", url: "https://cnbc.com")
let fixtures: Set<MarketNews> = [fixture1, fixture2]
XCTAssertTrue(fixtures.contains(fixture1))
XCTAssertTrue(fixtures.contains(fixture2))
}
}
| 42.368421 | 204 | 0.544099 |
ddde0373653ca1fc743a46a5e7a5c6f7dd1c9726 | 8,769 | import Foundation
import NIO
extension MQTTPacket {
struct Publish: MQTTPacketDuplexType {
// MARK: - Vars
var message: MQTTMessage {
return data.message
}
var packetId: UInt16? {
return data.packetId
}
var isDuplicate: Bool {
return data.isDuplicate
}
var topicAlias: Int? {
return data.topicAlias
}
private let data: Data
// MARK: - Init
init(
message: MQTTMessage,
packetId: UInt16?,
isDuplicate: Bool = false,
topicAlias: Int? = nil
) {
data = Data(
message: message,
packetId: packetId,
isDuplicate: isDuplicate,
topicAlias: topicAlias
)
}
// MARK: - MQTTPacketDuplexType
static func parse(
from packet: inout MQTTPacket,
version: MQTTProtocolVersion
) throws -> Self {
let flags = Flags(rawValue: packet.fixedHeaderData)
let topic = try packet.data.readMQTTString("Topic")
let packetId: UInt16?
if flags.qos != .atMostOnce {
packetId = packet.data.readInteger(as: UInt16.self)
guard packetId != nil else {
throw MQTTProtocolError("Missing packet identifier")
}
} else {
packetId = nil
}
let properties: MQTTProperties
if version >= .version5 {
properties = try MQTTProperties.parse(from: &packet.data, using: propertiesParser)
} else {
properties = MQTTProperties()
}
let payload: MQTTPayload
if packet.data.readableBytes > 0 {
if properties.payloadFormatIsUTF8 {
guard let string = packet.data.readString(length: packet.data.readableBytes) else {
throw MQTTProtocolError("Invalid string payload")
}
payload = .string(string, contentType: properties.contentType)
} else {
payload = .bytes(packet.data.slice())
}
} else {
payload = .empty
}
return Publish(
message: MQTTMessage(
topic: topic,
payload: payload,
qos: flags.qos,
retain: flags.contains(.retain),
properties: messageProperties(for: properties)
),
packetId: packetId,
isDuplicate: flags.contains(.dup),
topicAlias: properties.topicAlias
)
}
func serialize(version: MQTTProtocolVersion) throws -> MQTTPacket {
let flags = generateFlags()
var buffer = Allocator.shared.buffer(capacity: 0)
try buffer.writeMQTTString(message.topic, "Topic")
if flags.qos != .atMostOnce {
guard let packetId = packetId else {
throw MQTTProtocolError("Missing packet identifier")
}
buffer.writeInteger(packetId)
}
if version >= .version5 {
try properties.serialize(to: &buffer)
}
switch message.payload {
case .empty:
break
case .bytes(var bytes):
buffer.writeBuffer(&bytes)
case .string(let string, _):
buffer.writeString(string)
}
return MQTTPacket(kind: .publish, fixedHeaderData: flags.rawValue, data: buffer)
}
// MARK: - Utils
func size(version: MQTTProtocolVersion) -> Int {
var dataSize = 0
dataSize += ByteBuffer.sizeForMQTTString(message.topic)
if message.qos != .atMostOnce {
dataSize += MemoryLayout<UInt16>.size
}
if version >= .version5 {
dataSize += properties.size()
}
switch message.payload {
case .empty:
break
case .bytes(let bytes):
dataSize += bytes.readableBytes
case .string(let string, _):
dataSize += string.utf8.count
}
return MQTTPacketEncoder.size(forPacketWithDataSize: dataSize)
}
private func generateFlags() -> Flags {
var flags: Flags = []
if message.retain {
flags.insert(.retain)
}
switch message.qos {
case .atMostOnce:
break
case .atLeastOnce:
flags.insert(.qos1)
case .exactlyOnce:
flags.insert(.qos2)
}
if isDuplicate {
flags.insert(.dup)
}
return flags
}
@MQTTPropertiesParserBuilder
private static var propertiesParser: MQTTPropertiesParser {
\.$payloadFormatIsUTF8
\.$messageExpiryInterval
\.$topicAlias
\.$responseTopic
\.$correlationData
\.$userProperties
\.$subscriptionIdentifiers
\.$contentType
}
private var properties: MQTTProperties {
var properties = MQTTProperties()
switch message.payload {
case .empty, .bytes:
properties.payloadFormatIsUTF8 = false
case .string(_, let contentType):
properties.payloadFormatIsUTF8 = true
properties.contentType = contentType
}
properties.messageExpiryInterval = message.properties.expiryInterval
properties.topicAlias = topicAlias
properties.userProperties = message.properties.userProperties
properties.responseTopic = message.properties.responseTopic
properties.correlationData = message.properties.correlationData?.byteBuffer
return properties
}
private static func messageProperties(for properties: MQTTProperties) -> MQTTMessage.Properties {
return MQTTMessage.Properties(
expiryInterval: properties.messageExpiryInterval,
responseTopic: properties.responseTopic,
correlationData: properties.correlationData.map {
Foundation.Data($0.readableBytesView)
},
userProperties: properties.userProperties,
subscriptionIdentifiers: properties.subscriptionIdentifiers
)
}
}
}
extension MQTTPacket.Publish {
// Wrapper to avoid heap allocations when added to NIOAny
fileprivate class Data {
let message: MQTTMessage
let packetId: UInt16?
let isDuplicate: Bool
let topicAlias: Int?
init(
message: MQTTMessage,
packetId: UInt16?,
isDuplicate: Bool,
topicAlias: Int?
) {
self.message = message
self.packetId = packetId
self.isDuplicate = isDuplicate
self.topicAlias = topicAlias
}
}
private struct Flags: OptionSet {
let rawValue: UInt8
static let retain = Flags(rawValue: 1 << 0)
static let qos1 = Flags(rawValue: 1 << 1)
static let qos2 = Flags(rawValue: 1 << 2)
static let dup = Flags(rawValue: 1 << 3)
init(rawValue: UInt8) {
self.rawValue = rawValue
}
var qos: MQTTQoS {
if contains(.qos2) {
return .exactlyOnce
}
if contains(.qos1) {
return .atLeastOnce
}
return .atMostOnce
}
var description: String {
return [
"retain": contains(.retain),
"qos1": contains(.qos1),
"qos2": contains(.qos2),
"dup": contains(.dup),
].description
}
}
}
| 30.985866 | 105 | 0.482381 |
01e5417b1c6e889ac491d0102f93fbdd2da0848a | 3,213 | //
// DanceCard.swift
// Dance Caller Cards
//
// Created by Sarah Trop on 1/5/22.
//
import SwiftUI
fileprivate struct DancePart: View {
@EnvironmentObject var settings: UserSettings
var figures: [Figure]
var body: some View {
HStack(alignment: .top) {
if settings.showPartNames {
Text(figures[0].part!)
.font(.subheadline)
.fontWeight(.bold)
.frame(width: 30)
.padding(.leading, 7)
.padding(.bottom, 3)
.font(.system(size: 16))
}
HStack {
VStack(alignment: .leading) {
ForEach(figures) { figure in
Text(figure.beatsString(settings.beatsNotation))
.fontWeight(.light)
.padding(.bottom, 0.2)
}
}
.frame(width: 30)
VStack(alignment: .leading) {
ForEach(figures) { figure in
Text(figure.figure!)
.padding(.bottom, 0.2)
}
}
}
.font(.system(size: 14))
.padding(.bottom, 3)
Spacer()
}
}
}
fileprivate struct DanceContents: View {
@EnvironmentObject var settings: UserSettings
var dance: Dance
var body: some View {
VStack {
DancePart(figures: dance.figures.filter({$0.part == "A1"}).sorted())
.environmentObject(settings)
DancePart(figures: dance.figures.filter({$0.part == "A2"}).sorted())
.environmentObject(settings)
DancePart(figures: dance.figures.filter({$0.part == "B1"}).sorted())
.environmentObject(settings)
DancePart(figures: dance.figures.filter({$0.part == "B2"}).sorted())
.environmentObject(settings)
}
}
}
struct DanceCard: View {
@EnvironmentObject var settings: UserSettings
var dance: Dance
var isExpanded: Bool = false
var body: some View {
VStack {
// set the title, author, tags at the top
DancePreview(dance: dance)
if isExpanded {
Divider()
// include the figures of the dance, divided into the parts of the song (a, b)
DanceContents(dance: dance)
// if there are caller notes, display them
if !dance.notes!.isEmpty {
VStack {
Divider()
HStack {
Text(dance.notes!)
.font(.system(size: 14))
.padding(.all, 7)
Spacer()
}
}
}
}
}
}
}
//struct DanceCard_Previews: PreviewProvider {
// static let settings = UserSettings()
//
// static var previews: some View {
// DanceCard(dance: ModelData().dances[0])
// .environmentObject(settings)
// }
//}
| 30.028037 | 94 | 0.461251 |
897f4c2aaa92527c1e4af508f3918c271be7b3c3 | 877 | //
// Copyright © 2015 Big Nerd Ranch
//
import XCTest
@testable import TouchTracker
class TouchTrackerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.575758 | 111 | 0.628278 |
d6629258924f3b6280cd341bb58cfae3ce2906a6 | 190 | import UIKit
// Arrays are Structs
var toys = ["Woody"]
print(toys.count)
toys.append("Buzz")
print(toys)
toys.firstIndex(of: "Buzz")
print(toys.sorted())
toys.remove(at: 0)
print(toys)
| 12.666667 | 27 | 0.7 |
f75f8b8d0bccdf0a74c3024f1688c31828affcbd | 432 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import class Datadog.HTTPHeadersWriter
@objcMembers
public class DDHTTPHeadersWriter: NSObject {
let swiftHTTPHeadersWriter = HTTPHeadersWriter()
override public init() {}
}
| 28.8 | 117 | 0.768519 |
16d16aa2cb9185f29b4890dd5961b362d0b5807a | 10,312 | // RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil %s | %FileCheck %s
// We want to check two things here:
// - Correctness
// - That certain "is" checks are eliminated based on static analysis at compile-time
//
// In ideal world, all those testNN functions should be simplified down to a single basic block
// which returns either true or false, i.e. all type checks should folded statically.
// REQUIRES: objc_interop
import Foundation
class ObjCX : NSObject {}
struct CX: _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> ObjCX {
return ObjCX()
}
static func _forceBridgeFromObjectiveC(_ source: ObjCX, result: inout CX?) {}
static func _conditionallyBridgeFromObjectiveC(_ source: ObjCX, result: inout CX?) -> Bool {
return false
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ObjCX?)
-> CX {
var result: CX?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
// Check casts to types which are _ObjectiveCBridgeable
func cast0(_ o: AnyObject) -> Bool {
return o is CX
}
// CHECK-LABEL: sil hidden [noinline] @_T017cast_folding_objc5test0SbyF
// CHECK: bb0
// Check that cast is not eliminated even though cast0 is a conversion
// from a class to struct, because it casts to a struct implementing
// the _BridgedToObjectiveC protocol
// CHECK: checked_cast
// CHECK: return
@inline(never)
func test0() -> Bool {
return cast0(NSNumber(value:1))
}
// Check that this cast does not get eliminated, because
// the compiler does not statically know if this object
// is NSNumber can be converted into Int.
// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc35testMayBeBridgedCastFromObjCtoSwiftySiyXlF
// CHECK: unconditional_checked_cast_addr
// CHECK: return
@inline(never)
public func testMayBeBridgedCastFromObjCtoSwift(_ o: AnyObject) -> Int {
return o as! Int
}
// Check that this cast does not get eliminated, because
// the compiler does not statically know if this object
// is NSString can be converted into String.
// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc41testConditionalBridgedCastFromObjCtoSwiftySSSgyXlF
// CHECK: unconditional_checked_cast_addr
// CHECK: return
@inline(never)
public func testConditionalBridgedCastFromObjCtoSwift(_ o: AnyObject) -> String? {
return o as? String
}
public func castObjCToSwift<T>(_ t: T) -> Int {
return t as! Int
}
// Check that compiler understands that this cast always fails
// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromObjCtoSwiftySiSo8NSStringCF
// CHECK: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func testFailingBridgedCastFromObjCtoSwift(_ ns: NSString) -> Int {
return castObjCToSwift(ns)
}
// Check that compiler understands that this cast always fails
// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromSwiftToObjCySiSSF
// CHECK: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func testFailingBridgedCastFromSwiftToObjC(_ s: String) -> NSInteger {
return s as! NSInteger
}
@inline(never)
public func testCastNSObjectToAnyClass(_ o: NSObject) -> AnyClass {
return o as! AnyClass
}
@inline(never)
public func testCastNSObjectToClassObject(_ o: NSObject) -> NSObject.Type {
return o as! NSObject.Type
}
@inline(never)
public func testCastNSObjectToAnyType(_ o: NSObject) -> Any.Type {
return o as! Any.Type
}
@inline(never)
public func testCastNSObjectToEveryType<T>(_ o: NSObject) -> T.Type {
return o as! T.Type
}
@inline(never)
public func testCastNSObjectToNonClassType(_ o: NSObject) -> Int.Type {
return o as! Int.Type
}
@inline(never)
public func testCastAnyObjectToAnyClass(_ o: AnyObject) -> AnyClass {
return o as! AnyClass
}
@inline(never)
public func testCastAnyObjectToClassObject(_ o: AnyObject) -> AnyObject.Type {
return o as! AnyObject.Type
}
@inline(never)
public func testCastAnyObjectToAnyType(_ o: AnyObject) -> Any.Type {
return o as! Any.Type
}
@inline(never)
public func testCastAnyObjectToEveryType<T>(_ o: AnyObject) -> T.Type {
return o as! T.Type
}
@inline(never)
public func testCastAnyObjectToNonClassType(_ o: AnyObject) -> Int.Type {
return o as! Int.Type
}
@inline(never)
public func testCastAnyToAny2Class(_ o: Any) -> AnyClass {
return o as! AnyClass
}
@inline(never)
public func testCastAnyToClassObject(_ o: Any) -> AnyObject.Type {
return o as! AnyObject.Type
}
@inline(never)
public func testCastAnyToAny2Type(_ o: Any) -> Any.Type {
return o as! Any.Type
}
@inline(never)
public func testCastAnyToEveryType<T>(_ o: Any) -> T.Type {
return o as! T.Type
}
@inline(never)
public func testCastAnyToNonClassType(_ o: Any) -> Int.Type {
return o as! Int.Type
}
@inline(never)
public func testCastEveryToAnyClass<T>(_ o: T) -> AnyClass {
return o as! AnyClass
}
@inline(never)
public func testCastEveryToClassObject<T>(_ o: T) -> AnyObject.Type {
return o as! AnyObject.Type
}
@inline(never)
public func testCastEveryToAnyType<T>(_ o: T) -> Any.Type {
return o as! Any.Type
}
@inline(never)
public func testCastEveryToEvery2Type<T, U>(_ o: U) -> T.Type {
return o as! T.Type
}
@inline(never)
public func testCastEveryToNonClassType<T>(_ o: T) -> Int.Type {
return o as! Int.Type
}
func cast<U, V>(_ u: U.Type) -> V? {
return u as? V
}
public protocol P {
}
// Any casts from P.Protocol to P.Type should fail.
@inline(never)
public func testCastPProtocolToPType() -> ObjCP.Type? {
return cast(ObjCP.self)
}
@objc
public protocol ObjCP {
}
@inline(never)
public func testCastObjCPProtocolToObjCPType() -> ObjCP.Type? {
return cast(ObjCP.self)
}
@inline(never)
public func testCastProtocolCompositionProtocolToProtocolCompositionType() -> (P & ObjCP).Type? {
return cast((P & ObjCP).self)
}
@inline(never)
public func testCastProtocolCompositionProtocolToProtocolType () -> P.Type? {
return (P & ObjCP).self as? P.Type
}
print("test0=\(test0())")
// CHECK-LABEL: sil [noinline] @{{.*}}testCastNSObjectToEveryType{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastNSObjectToNonClassType
// CHECK: builtin "int_trap"
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyObjectToEveryType{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyObjectToNonClassType
// CHECK-NOT: builtin "int_trap"
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyToAny2Class{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyToClassObject{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyToAny2Type{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyToEveryType{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyToNonClassType
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastEveryToAnyClass{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastEveryToClassObject{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastEveryToAnyType{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastEveryToEvery2Type{{.*}}
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastEveryToNonClassType
// CHECK: unconditional_checked_cast_addr
// CHECK-LABEL: sil [noinline] @{{.*}}testCastPProtocolToPType
// CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt
// CHECK-NEXT: return %0
// CHECK-LABEL: sil [noinline] @{{.*}}testCastObjCPProtocolTo{{.*}}PType
// CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt
// CHECK-NEXT: return %0
// CHECK-LABEL: sil [noinline] @{{.*}}testCastProtocolComposition{{.*}}Type
// CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt
// CHECK-NEXT: return %0
// Check that compiler understands that this cast always succeeds.
// Since it is can be statically proven that NSString is bridgeable to String,
// _forceBridgeFromObjectiveC from String should be invoked instead of
// a more general, but less effective swift_bridgeNonVerbatimFromObjectiveC, which
// also performs conformance checks at runtime.
@inline(never)
public func testBridgedCastFromObjCtoSwift(_ ns: NSString) -> String {
return ns as String
}
// Check that compiler understands that this cast always succeeds
// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc30testBridgedCastFromSwiftToObjCySo8NSStringCSSF
// CHECK-NOT: {{ cast}}
// CHECK: function_ref @_T0SS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
@inline(never)
public func testBridgedCastFromSwiftToObjC(_ s: String) -> NSString {
return s as NSString
}
public class MyString: NSString {}
// Check that the cast-optimizer bails out on a conditional downcast to a subclass of a
// bridged ObjC class.
// CHECK-LABEL: sil [noinline] @{{.*}}testConditionalBridgedCastFromSwiftToNSObjectDerivedClass{{.*}}
// CHECK: function_ref @_T0SS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK-NOT: apply
// CHECK-NOT: unconditional_checked_cast
// CHECK: checked_cast_br
// CHECK-NOT: apply
// CHECK-NOT: unconditional
// CHECK: return
@inline(never)
public func testConditionalBridgedCastFromSwiftToNSObjectDerivedClass(_ s: String) -> MyString? {
return s as? MyString
}
// Check that the cast-optimizer does not bail out on an unconditional downcast to a subclass of a
// bridged ObjC class.
// CHECK-LABEL: sil [noinline] @{{.*}}testForcedBridgedCastFromSwiftToNSObjectDerivedClass{{.*}}
// CHECK: function_ref @_T0SS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK-NOT: apply
// CHECK-NOT: checked_cast_br
// CHECK: unconditional_checked_cast
// CHECK-NOT: apply
// CHECK-NOT: unconditional
// CHECK-NOT: checked_cast
// CHECK: return
@inline(never)
public func testForcedBridgedCastFromSwiftToNSObjectDerivedClass(_ s: String) -> MyString {
return s as! MyString
}
| 29.976744 | 121 | 0.733223 |
0ab1a087454a90ed11d2d5e5ca10d04e9c8b5cb9 | 2,944 | //
// ContentView.swift
// Shared
//
// Created by RGH on 2022/02/16.
//
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
} label: {
Text(item.timestamp!, formatter: itemFormatter)
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
#if os(iOS)
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
#endif
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
| 32.351648 | 199 | 0.5625 |
566de4a606329aba54e5e3f2149e9bb8c428433a | 584 | import Foundation
protocol Configuration {
var shouldUseImage: Bool { get set }
var filledImage: UIImage? { get set }
var emptyImage: UIImage? { get set }
var halfImage: UIImage? { get set }
var borderColor: UIColor? { get set }
var emptyStarColor: UIColor { get set }
var borderWidth: CGFloat { get set }
var spacing: CGFloat { get set }
var minimumValue: UInt { get set }
var maximumValue: UInt { get set }
var currentValue: Float { get set }
var allowHalfMode: Bool { get set }
var accurateHalfMode: Bool { get set }
var continuous: Bool { get set }
}
| 30.736842 | 41 | 0.690068 |
6a1170c0eaf576330ebc57149cd3ca460e858911 | 1,416 | //
// AppDelegate.swift
// TestMapView
//
// Created by user167484 on 4/13/20.
// Copyright © 2020 Allen Savio. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.263158 | 179 | 0.747881 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.