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
|
---|---|---|---|---|---|
f87472f27f065ee81a55b0f448062856c9dfc412 | 1,706 | //
// EntryOverviewView.swift
// JournalingApp
//
// Created by Philipp Baldauf on 17.12.19.
// Copyright © 2019 Philipp Baldauf. All rights reserved.
//
import SwiftUI
struct EntryOverviewView: View {
@State private var showCreateScreen = false
@ObservedObject var entryModel: EntryModel
private let network = RequestEntries()
var body: some View {
NavigationView {
List(entryModel.entries, id: \.id) { entry in
NavigationLink(destination: EntryDetailView(entry: entry)) {
EntryRow(entry: entry)
}
}
.navigationBarTitle("Entries")
.navigationBarItems(trailing: Button(action: {
self.showCreateScreen.toggle()
}, label: {
Image(systemName: "plus")
}))
.sheet(isPresented: $showCreateScreen) {
NavigationView {
CreateEntryView(entryModel: self.entryModel)
}
}
}
}
init(entryModel: EntryModel) {
self.entryModel = entryModel
refresh()
}
private func refresh() {
entryModel.entries.removeAll()
network.requestAllEntries { result in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let entries):
self.entryModel.entries.append(contentsOf: entries)
}
}
}
}
struct EntryOverviewView_Previews: PreviewProvider {
static var previews: some View {
EntryOverviewView(entryModel: EntryModel(entries: sampleEntries))
}
}
| 27.079365 | 76 | 0.566823 |
d9b1c5f988d0b470b82db0ce7f055d0da2392560 | 2,279 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
/// HubChannel represents the channels on which Amplify category messages will be dispatched. Apps can define their own
/// channels for intra-app communication. Internally, Amplify uses the Hub for dispatching notifications about events
/// associated with different categories.
public enum HubChannel {
case analytics
case api
case auth
case dataStore
case hub
case logging
case predictions
case storage
case custom(String)
/// Convenience property to return an array of all non-`custom` channels
static var amplifyChannels: [HubChannel] = {
let categoryChannels = CategoryType
.allCases
.sorted { $0.displayName < $1.displayName }
.map { HubChannel(from: $0) }
.compactMap { $0 }
return categoryChannels
}()
}
extension HubChannel: Equatable {
public static func == (lhs: HubChannel, rhs: HubChannel) -> Bool {
switch (lhs, rhs) {
case (.analytics, .analytics):
return true
case (.api, .api):
return true
case (.auth, .auth):
return true
case (.dataStore, .dataStore):
return true
case (.hub, .hub):
return true
case (.logging, .logging):
return true
case (.predictions, .predictions):
return true
case (.storage, .storage):
return true
case (.custom(let lhsValue), .custom(let rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
}
extension HubChannel {
public init(from categoryType: CategoryType) {
switch categoryType {
case .analytics:
self = .analytics
case .api:
self = .api
case .auth:
self = .auth
case .dataStore:
self = .dataStore
case .hub:
self = .hub
case .logging:
self = .logging
case .predictions:
self = .predictions
case .storage:
self = .storage
}
}
}
extension HubChannel: Hashable { }
| 24.244681 | 119 | 0.568232 |
79c8f1fbf8e9613a53f9ca6614eb9de50c47b344 | 3,328 | //
// SuccessViewController.swift
// PayDay
//
// Created by Oleksandr Burla on 3/17/16.
// Copyright © 2016 Oleksandr Burla. All rights reserved.
//
import UIKit
class SuccessViewController: UIViewController {
var JSONFromClock = [String: AnyObject]()
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var ampmLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
var name = ""
var statusSuccess = ""
var date = ""
var time = ""
var ampmText = ""
var location = ""
var isSuperUser = 0
override func viewDidLoad() {
super.viewDidLoad()
print(JSONFromClock)
updateDataFrom(JSONFromClock)
self.nameLabel.text = "Hi, \(name)"
self.dateLabel.text = date
self.timeLabel.text = time
var statusText = "NO STATUS"
if statusSuccess == "CLOCK IN" {
statusText = "CLOCKED IN"
self.statusLabel.textColor = UIColor(red:0.00, green:0.62, blue:0.23, alpha:1.0)
} else if statusSuccess == "CLOCK OUT" {
statusText = "CLOCKED OUT"
self.statusLabel.textColor = UIColor(red:0.78, green:0.14, blue:0.14, alpha:1.0)
} else if statusSuccess == "START BREAK" {
statusText = "BREAKED IN"
self.statusLabel.textColor = UIColor(red:0.98, green:0.75, blue:0.00, alpha:1.0)
} else if statusSuccess == "STOP BREAK" {
statusText = "BREAKED OUT"
self.statusLabel.textColor = UIColor(red:0.78, green:0.14, blue:0.14, alpha:1.0)
} else if statusSuccess == "DUTY IN" {
statusText = "DUTY IN"
self.statusLabel.textColor = UIColor(red:0.00, green:0.62, blue:0.23, alpha:1.0)
} else if statusSuccess == "DUTY OUT" {
statusText = "DUTY OUT"
self.statusLabel.textColor = UIColor(red:0.78, green:0.14, blue:0.14, alpha:1.0)
}
self.statusLabel.text = statusText
self.locationLabel.text = location
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateDataFrom(json: [String : AnyObject]) {
self.location = (json["location"] as? String)!
let timeText = (json["time"] as? NSString)!
self.ampmText = timeText.substringFromIndex(timeText.length - 2)
self.time = timeText.substringToIndex(timeText.length - 2)
self.date = (json["date"] as? String)!
}
@IBAction func backButtonPressed(sender: UIBarButtonItem) {
backAction()
}
@IBAction func okButtonPressed(sender: UIButton) {
backAction()
}
func backAction() {
print("SUPERUSER \(isSuperUser)")
if isSuperUser == 1 {
self.performSegueWithIdentifier("unwindToKeypadID", sender: nil)
} else {
self.performSegueWithIdentifier("unwindToLoginID", sender: nil)
}
}
}
| 28.444444 | 92 | 0.573017 |
0ed781a63af6b5f98e5f76f65b2a075a877f30f0 | 6,476 | // RUN: %empty-directory(%t)
// Resilient protocol definition
// RUN: %target-swift-frontend -emit-ir -enable-resilience -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s
// Resilient protocol usage
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -assume-parsing-unqualified-ownership-sil %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE
// ----------------------------------------------------------------------------
// Resilient protocol definition
// ----------------------------------------------------------------------------
// CHECK: @"default assoc type x" = linkonce_odr hidden constant
// CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0
// CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" =
// Protocol descriptor
// CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( protected)?}} constant
// CHECK-DEFINITION-SAME: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN"
// Associated type default + flags
// CHECK-DEFINITION-SAME: [[INT]] add
// CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP"
// CHECK-DEFINITION-SAME: [[INT]] 1
// Protocol requirements base descriptor
// CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1)
// Associated type and conformance
// CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias
// CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias
// Default associated conformance witnesses
// CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN"
import resilient_protocol
// ----------------------------------------------------------------------------
// Resilient witness tables
// ----------------------------------------------------------------------------
// CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" =
// CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl
// CHECK-USAGE-SAME: @"symbolic x"
public struct ConformsToProtocolWithRequirements<Element>
: ProtocolWithRequirements {
public typealias T = Element
public func first() { }
public func second() { }
}
public protocol P { }
public struct ConditionallyConforms<Element> { }
public struct Y { }
// CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" =
// CHECK-USAGE-SAME: i32 131072,
// CHECK-USAGE-SAME: i16 1,
// CHECK-USAGE-SAME: i16 0
extension Y: OtherResilientProtocol { }
// CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" =
// CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn
// CHECK-USAGE-SAME: $s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0PWT
public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults {
}
// CHECK-USAGE: @"$sx1T18resilient_protocol24ProtocolWithRequirementsP_MXA" =
// CHECK-USAGE-SAME: i32 0
// CHECK-USAGE-SAME: @"{{got.|__imp_}}$s18resilient_protocol24ProtocolWithRequirementsMp"
// CHECK-USAGE-SAME: @"$sx1T18resilient_protocol24ProtocolWithRequirementsP_MXA"
// CHECK-USAGE-SAME: %swift.protocol_requirement** @"{{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl"
// CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc"
extension ConditionallyConforms: ProtocolWithRequirements
where Element: ProtocolWithRequirements, Element.T == Y {
public typealias T = Element.T
public func first() { }
public func second() { }
}
// ----------------------------------------------------------------------------
// Resilient protocol usage
// ----------------------------------------------------------------------------
// CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type*, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]])
public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type {
// CHECK-USAGE: call %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl")
return PWR.T.self
}
func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { }
// CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF"
public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) {
// CHECK-USAGE: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.ProtocolWithAssocTypeDefaults, [[INT]] udiv ([[INT]] sub ([[INT]] ptrtoint (%swift.protocol_requirement* @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" to [[INT]]), [[INT]] ptrtoint (%swift.protocol_requirement* @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsTL" to [[INT]])), [[INT]] 8)
// CHECK-USAGE: load i8*, i8** [[WITNESS_ADDR]]
useOtherResilientProtocol(T.T2.self)
}
| 62.873786 | 444 | 0.738882 |
f9ef9f4610b7a18b1bd1f15420ef5065dc1badbd | 1,425 | //
// AppDelegate.swift
// VKHackathonDonations
//
// Created by Artem Belkov on 11.09.2020.
// Copyright © 2020 Tech Birds. 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.
}
}
| 41.911765 | 179 | 0.751579 |
1cdb15367f99afbfe12b10d8916ce9217ce8f07c | 319 | //
// UIImageExtension.swift
// MealDB
//
// Created by Владислав Галкин on 16.07.2021.
//
import UIKit
extension UIImage {
func imageResized(to size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
}
| 18.764706 | 63 | 0.62069 |
3a472e6ecb5c90be9620b6e18116a2496a48a6ef | 763 | import UIKit
import XCTest
import ThirdPod
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.433333 | 111 | 0.606815 |
9b72b03d3f240d703d7b25a749798cd1be15ffab | 591 | //
// SendCustomRequest.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.8.0-fa8feefe
// https://github.com/tdlib/td/tree/fa8feefe
//
import Foundation
/// Sends a custom request; for bots only
public struct SendCustomRequest: Codable, Equatable {
/// The method name
public let method: String?
/// JSON-serialized method parameters
public let parameters: String?
public init(
method: String?,
parameters: String?
) {
self.method = method
self.parameters = parameters
}
}
| 18.46875 | 54 | 0.65313 |
33b208d6a0dc5ce811628b5919510da34cacbbb9 | 1,083 | //
// EntertainmentViewModel.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/8/7.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
class EntertainmentViewModel: BaseViewModel {
var data: [TagModel] = []
func loadDataWithHandler(handler: (loadState: LoadState) -> ()) {
let url = URL.getHotRoom + String.getNowTimeString()
NetworkTool.GET(url, successHandler: {[weak self] (result) in
if let resultJSON = result {
if let data = Mapper<TagModel>().map(resultJSON)?.data {
self?.data = data
handler(loadState: .success)
}
else {
handler(loadState: LoadState.failure(errorMessage: "数据解析错误"))
}
}
else {
handler(loadState: .failure(errorMessage: "服务器返回的错误"))
}
}) { (error) in
handler(loadState: .failure(errorMessage: "网络错误"))
}
}
}
| 26.414634 | 81 | 0.499538 |
236b53e5f78fdf0e60f3b7f4ea246613623f9765 | 4,714 | //
// ArgumentBuilder.swift
// commitPrefix
//
// MIT License
//
// Copyright (c) 2019 STEPHEN L. MARTINEZ
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import TerminalController
struct ArgumentBuilder {
let usage: String = """
[<PrefixValue1>,<PrefixValue2>,<PrefixValue3>...] [-o | --output] [-d | --delete]
[-n | -normal] [ -b | --branchParse <ValidatorValue> ] [-v | --version]
"""
let overview: String = """
The CommitPrefix stores a desired set of prefixes for your commit messages. It
stores it within the .git folder of the current repository. A commit-msg hook is
also generated and stored within the .git folder which is used to prefix the
commit message.
Modes:
CommitPrefix has two modes, normal and branch parse.
- NORMAL
example: commitPrefix <PrefixValue1>,<PrefixValue2>,<PrefixValue3>...
You can add normal prefixes by entering comma seperated values. These values will
be parsed as prefixes and prepended to future commit messages.
- BRANCH_PARSE
example commitPrefix -b <ValidatorValue>
Branch parse mode checks the current branch for an issue number validated by the
value passed in as an argument. For example if you passed in a validator value of
"eng" and your current branch was named ENG-342-SomeFeatureBranchLinkedToENG-101,
commitPrefix will pickup [ENG-342] and [ENG-101] as branch prefixes to be
prepended to you next commit along with any other normal prefixes you might have.
You can change back to NORMAL mode by entering:
example: commitPrefix -n
To view the current state of prefixes and mode, enter:
example: commitPrefix
"""
func buildParser() -> ArgumentParser {
ArgumentParser(usage: usage, overview: overview)
}
func buildVersionArgument(parser: ArgumentParser) -> OptionArgument<Bool> {
return parser.add(
option: "--version",
shortName: "-v",
kind: Bool.self,
usage: "Outputs the current version information",
completion: nil
)
}
func buildOutputArgument(parser: ArgumentParser) -> OptionArgument<Bool> {
return parser.add(
option: "--output",
shortName: "-o",
kind: Bool.self,
usage: "Outputs the full, formated prefix to standard output",
completion: nil
)
}
func buildDeleteArgument(parser: ArgumentParser) -> OptionArgument<Bool> {
return parser.add(
option: "--delete",
shortName: "-d",
kind: Bool.self,
usage: "Deletes the stored prefixes",
completion: nil
)
}
func buildNormalArgument(parser: ArgumentParser) -> OptionArgument<Bool> {
return parser.add(
option: "--normal",
shortName: "-n",
kind: Bool.self,
usage: "Sets the mode to NORMAL",
completion: nil
)
}
func buildBranchParseArgument(parser: ArgumentParser) -> OptionArgument<Bool> {
return parser.add(
option: "--branchParse",
shortName: "-b",
kind: Bool.self,
usage: "Sets the mode to BRANCH_PARSE. Requires a validator argument",
completion: nil
)
}
func buildUserEntryArgument(parser: ArgumentParser) -> PositionalArgument<[String]> {
return parser.add(
positional: "UserEntry",
kind: [String].self,
optional: true,
usage: nil,
completion: nil
)
}
}
| 35.179104 | 89 | 0.646797 |
fed606b90675aa6566aa9f6f4c182ef8913ccbc2 | 4,493 | //
// Storyboard.swift
// StoryKit
//
// Created by John Clayton on 8/22/18.
// Copyright © 2018 Impossible Flight, LLC. All rights reserved.
//
import UIKit
import Bridge
public enum Scope {
case transient
case container
}
extension SceneDescriptor {
var scopeKey: SceneIdentifier {
return self.identifier
}
var storyboardIdentifier: String {
return self.name
}
}
public class Storyboard<S: SceneDescriptor> {
enum Error: Swift.Error, CustomStringConvertible {
case usedSnapshotAsDescriptor(SceneDescriptor)
case underlyingStoryboardError(Storyboard, UIStoryboard.Error)
var description: String {
switch self {
case .usedSnapshotAsDescriptor(let descriptor):
let controller = try? descriptor.sceneController()
return "Could not infer a descriptor for controller in storyboard: \(String(describing: controller)). Did you forget to register the storyboard descriptor with StoryKit, add a case for the referenced controller, or add its restoration identifier to the descriptor?"
case .underlyingStoryboardError(let storyboard, let underlyingError):
return "\(storyboard) -> \(underlyingError)"
}
}
}
var descriptorType: S.Type
var bundle: Bundle?
public static func described<T: SceneDescriptor>(by descriptor: T, bundle: Bundle? = nil) throws -> Storyboard<T> {
guard !(descriptor is _InternalDescriptor) else {
throw Error.usedSnapshotAsDescriptor(descriptor)
}
let cacheKey = descriptor.typeIdentifier
if let s = storyboardCache[cacheKey] as? Storyboard<T> {
return s
}
let s = try Storyboard<T>(descriptorType: T.self)
storyboardCache[cacheKey] = s
return s
}
private init(descriptorType: S.Type, bundle: Bundle? = nil) throws {
self.descriptorType = S.self
self.bundle = bundle
let name = String(describing: descriptorType)
_storyboard = try ObjC.throwingReturn { UIStoryboard(name: name, bundle: bundle) }
}
public func viewController<V: UIViewController>(forScene descriptor: S, scope: Scope = .transient, initializer: ((V) -> Void)? = nil) throws -> V {
if scope == .container, let controller = containerScope[descriptor.scopeKey] as? V {
return controller
}
let controller: V
do {
controller = try _storyboard.instantiateViewController(withIdentifier: descriptor.storyboardIdentifier)
} catch let error as UIStoryboard.Error {
throw Error.underlyingStoryboardError(self, error)
}
controller.freeze(descriptor: descriptor)
if scope == .container {
containerScope[descriptor.scopeKey] = controller
try addChildrenInContainerScope(node: controller)
}
if let initializer = initializer {
initializer(controller)
}
return controller
}
public func register<V: UIViewController>(viewController: V, forScene descriptor: S) throws {
viewController.freeze(descriptor: descriptor)
containerScope[descriptor.scopeKey] = viewController
try addChildrenInContainerScope(node: viewController)
}
//MARK: Private
private func addChildrenInContainerScope(node: UIViewController) throws {
for child in node.children {
let childDescriptor = child.sceneDescriptor
let bundle: Bundle = Bundle(for: type(of: child))
try childDescriptor.registerInBoard(viewController: child, bundle: bundle)
}
}
fileprivate var containerScope = Dictionary<String,UIViewController>()
fileprivate var _storyboard: UIStoryboard
}
fileprivate var storyboardCache = Dictionary<String,Any>()
extension SceneDescriptor {
// This inversion (over just creating the storyboard using the value of controller.sceneDescriptor) is necessary because we cannot get the concrete type of controller.sceneDescriptor statically (as it is a constrained to a protocol at runtime), and so cannot create a storyboard constrained to that type. Using Self here opens the existential and the compiler can replace with the current concrete type.
func registerInBoard<V: UIViewController>(viewController: V, bundle: Bundle? = nil) throws {
let board = try Storyboard<Self>.described(by: self)
try board.register(viewController: viewController, forScene: self)
}
}
extension FrozenDescriptor {
func registerInBoard<V: UIViewController>(viewController: V, bundle: Bundle? = nil) throws {
let board = try Storyboard<DescriptorType>.described(by: self.descriptor)
try board.register(viewController: viewController, forScene: self.descriptor)
}
}
extension Storyboard: CustomStringConvertible {
public var description: String {
return "Storyboard<\(descriptorType)>"
}
}
| 34.29771 | 404 | 0.762965 |
dbb9005c5fdd6c5a8c30f7b5b7443fbf94602bc2 | 10,007 | import AsyncKit
import NIO
public final class QueryBuilder<Model>
where Model: FluentKit.Model
{
public var query: DatabaseQuery
public let database: Database
internal var includeDeleted: Bool
internal var shouldForceDelete: Bool
internal var models: [Schema.Type]
public var eagerLoaders: [AnyEagerLoader]
public convenience init(database: Database) {
self.init(
query: .init(schema: Model.schema),
database: database,
models: [Model.self]
)
}
private init(
query: DatabaseQuery,
database: Database,
models: [Schema.Type] = [],
eagerLoaders: [AnyEagerLoader] = [],
includeDeleted: Bool = false,
shouldForceDelete: Bool = false
) {
self.query = query
self.database = database
self.models = models
self.eagerLoaders = eagerLoaders
self.includeDeleted = includeDeleted
self.shouldForceDelete = shouldForceDelete
// Pass through custom ID key for database if used.
let idKey = Model()._$id.key
switch idKey {
case .id: break
default:
self.query.customIDKey = idKey
}
}
public func copy() -> QueryBuilder<Model> {
.init(
query: self.query,
database: self.database,
models: self.models,
eagerLoaders: self.eagerLoaders,
includeDeleted: self.includeDeleted,
shouldForceDelete: self.shouldForceDelete
)
}
// MARK: Fields
@discardableResult
public func fields<Joined>(for model: Joined.Type) -> Self
where Joined: Schema & Fields
{
self.addFields(for: Joined.self, to: &self.query)
return self
}
internal func addFields(for model: (Schema & Fields).Type, to query: inout DatabaseQuery) {
query.fields += model.keys.map { path in
.path([path], schema: model.schemaOrAlias)
}
}
@discardableResult
public func field<Field>(_ field: KeyPath<Model, Field>) -> Self
where Field: QueryableProperty, Field.Model == Model
{
self.field(Model.self, field)
}
@discardableResult
public func field<Joined, Field>(_ joined: Joined.Type, _ field: KeyPath<Joined, Field>) -> Self
where Joined: Schema, Field: QueryableProperty, Field.Model == Joined
{
self.query.fields.append(.path(Joined.path(for: field), schema: Joined.schema))
return self
}
@discardableResult
public func field(_ field: DatabaseQuery.Field) -> Self {
self.query.fields.append(field)
return self
}
// MARK: Soft Delete
@discardableResult
public func withDeleted() -> Self {
self.includeDeleted = true
return self
}
// MARK: Actions
public func create() -> EventLoopFuture<Void> {
self.query.action = .create
return self.run()
}
public func update() -> EventLoopFuture<Void> {
self.query.action = .update
return self.run()
}
public func delete(force: Bool = false) -> EventLoopFuture<Void> {
self.includeDeleted = force
self.shouldForceDelete = force
self.query.action = .delete
return self.run()
}
// MARK: Limit
@discardableResult
public func limit(_ count: Int) -> Self {
self.query.limits.append(.count(count))
return self
}
// MARK: Offset
@discardableResult
public func offset(_ count: Int) -> Self {
self.query.offsets.append(.count(count))
return self
}
// MARK: Unqiue
@discardableResult
public func unique() -> Self {
self.query.isUnique = true
return self
}
// MARK: Fetch
public func chunk(max: Int, closure: @escaping ([Result<Model, Error>]) -> ()) -> EventLoopFuture<Void> {
var partial: [Result<Model, Error>] = []
partial.reserveCapacity(max)
return self.all { row in
partial.append(row)
if partial.count >= max {
closure(partial)
partial = []
}
}.flatMapThrowing {
// any stragglers
if !partial.isEmpty {
closure(partial)
partial = []
}
}
}
public func first() -> EventLoopFuture<Model?> {
return self.limit(1)
.all()
.map { $0.first }
}
public func all<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<[Field.Value]>
where
Field: QueryableProperty,
Field.Model == Model
{
let copy = self.copy()
copy.query.fields = [.path(Model.path(for: key), schema: Model.schema)]
return copy.all().map {
$0.map {
$0[keyPath: key].value!
}
}
}
public func all<Joined, Field>(
_ joined: Joined.Type,
_ field: KeyPath<Joined, Field>
) -> EventLoopFuture<[Field.Value]>
where
Joined: Schema,
Field: QueryableProperty,
Field.Model == Joined
{
let copy = self.copy()
copy.query.fields = [.path(Joined.path(for: field), schema: Joined.schemaOrAlias)]
return copy.all().flatMapThrowing {
try $0.map {
try $0.joined(Joined.self)[keyPath: field].value!
}
}
}
public func all() -> EventLoopFuture<[Model]> {
var models: [Result<Model, Error>] = []
return self.all { model in
models.append(model)
}.flatMapThrowing {
return try models
.map { try $0.get() }
}
}
public func run() -> EventLoopFuture<Void> {
return self.run { _ in }
}
public func all(_ onOutput: @escaping (Result<Model, Error>) -> ()) -> EventLoopFuture<Void> {
var all: [Model] = []
let done = self.run { output in
onOutput(.init(catching: {
let model = Model()
try model.output(from: output.schema(Model.schema))
all.append(model)
return model
}))
}
// if eager loads exist, run them, and update models
if !self.eagerLoaders.isEmpty {
return done.flatMap {
// don't run eager loads if result set was empty
guard !all.isEmpty else {
return self.database.eventLoop.makeSucceededFuture(())
}
// run eager loads
return EventLoopFutureQueue(eventLoop: self.database.eventLoop).append(each: self.eagerLoaders) { loader in
return loader.anyRun(models: all, on: self.database)
}.flatMapErrorThrowing { error in
if case .previousError(let error) = error as? EventLoopFutureQueue.ContinueError {
throw error
} else {
throw error
}
}
}
} else {
return done
}
}
@discardableResult
internal func action(_ action: DatabaseQuery.Action) -> Self {
self.query.action = action
return self
}
public func run(_ onOutput: @escaping (DatabaseOutput) -> ()) -> EventLoopFuture<Void> {
// make a copy of this query before mutating it
// so that run can be called multiple times
var query = self.query
// If fields are not being manually selected,
// add fields from all models being queried.
if query.fields.isEmpty {
for model in self.models {
self.addFields(for: model, to: &query)
}
}
// If deleted models aren't included, add filters
// to exclude them for each model being queried.
if !self.includeDeleted {
for model in self.models {
model.excludeDeleted(from: &query)
}
}
// TODO: combine this logic with model+crud timestamps
let forceDelete = Model.init().deletedTimestamp == nil
? true : self.shouldForceDelete
switch query.action {
case .delete:
if !forceDelete {
query.action = .update
query.input = [.dictionary([:])]
self.addTimestamps(triggers: [.update, .delete], to: &query)
}
case .create:
self.addTimestamps(triggers: [.create, .update], to: &query)
case .update:
self.addTimestamps(triggers: [.update], to: &query)
default:
break
}
self.database.logger.debug("\(self.query)")
self.database.history?.add(self.query)
let done = self.database.execute(query: query) { output in
assert(
self.database.eventLoop.inEventLoop,
"database driver output was not on eventloop"
)
onOutput(output)
}
done.whenComplete { _ in
assert(
self.database.eventLoop.inEventLoop,
"database driver output was not on eventloop"
)
}
return done
}
private func addTimestamps(
triggers: [TimestampTrigger],
to query: inout DatabaseQuery
) {
var data: [DatabaseQuery.Value] = []
for case .dictionary(var nested) in query.input {
let timestamps = Model().timestamps.filter { triggers.contains($0.trigger) }
for timestamp in timestamps {
// Only add timestamps if they weren't already set
if nested[timestamp.key] == nil {
nested[timestamp.key] = timestamp.currentTimestampInput
}
}
data.append(.dictionary(nested))
}
query.input = data
}
}
| 29.871642 | 123 | 0.549216 |
29ede6491145e2cade64c4ee79444d3f3a8bd1be | 535 | //
// SettingsViewController.swift
// PictoBoard
//
// Created by Zehna van den Berg on 19/04/2019.
// Copyright © 2019 Zehnzen. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
navigationController?.navigationBar.isHidden = false
}
@IBAction func pressedRewindButton(_ sender: Any) {
RewindController.shared.rewindLastAction()
}
}
| 24.318182 | 71 | 0.695327 |
ab55d7e4152c6fbb0f96083893d633e066017bad | 510 | //
// ViewController.swift
// MovieViewer
//
// Created by Lucas Andrade on 1/24/16.
// Copyright © 2016 LucasRibeiro. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.615385 | 80 | 0.672549 |
23dd65aefa008f95b823f2519b1148f0878d153e | 1,625 | //
// RoundButton.swift
// SmarcHome
//
// Created by Ibrahim Saqr on 4/30/18.
// Copyright © 2018 Ibrahim Saqr. All rights reserved.
//
import Foundation
@IBDesignable class RoundButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 15 {
didSet {
refreshCorners(value: cornerRadius)
}
}
// @IBInspectable var backgroundImageColor: UIColor = UIColor.init(red: 0, green: 122/255.0, blue: 255/255.0, alpha: 1) {
// didSet {
// refreshColors(color: backgroundImageColor)
// }
// }
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
override func prepareForInterfaceBuilder() {
sharedInit()
}
func sharedInit() {
// Common logic goes here
refreshCorners(value: cornerRadius)
// refreshColors(color: backgroundImageColor)
}
func refreshCorners(value: CGFloat) {
layer.cornerRadius = value
}
// func refreshColors(color: UIColor) {
// let image = createImage(color: color)
// setBackgroundImage(image, for: UIControlState.normal)
// clipsToBounds = true
// }
//
// func createImage(color: UIColor) -> UIImage {
// UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), true, 0.0)
// color.setFill()
// UIRectFill(CGRect(x: 0, y: 0, width: 1, height: 1))
// let image = UIGraphicsGetImageFromCurrentImageContext()!
// return image
// }
}
| 25.793651 | 124 | 0.609846 |
8f626d6a52f9e5e71a0047292a12330caf249a78 | 3,513 | //
// SettingsFlow.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import RxFlow
final class SettingsFlow: Flow {
// MARK: - Assets
var root: Presentable {
rootViewController
}
private lazy var rootViewController: UINavigationController = {
let navigationController = Factory.NavigationController.make(fromType: .standard)
navigationController.tabBarItem.image = R.image.tabbar_settings_ios11()
navigationController.tabBarItem.title = R.string.localizable.tab_settings()
return navigationController
}()
// MARK: - Initialization
init() {}
deinit {
printDebugMessage(domain: String(describing: self), message: "was deinitialized")
}
// MARK: - Functions
func navigate(to step: Step) -> FlowContributors {
guard let step = step as? SettingsStep else {
return .none
}
switch step {
case .settings:
return summonSettingsController()
case .about:
return summonAboutController()
case .apiKeyEdit:
return summonApiKeyEditController()
case .manageLocations:
return summonManageLocationsController()
case .addLocation:
return summonAddLocationController()
case let .webBrowser(url):
return summonWebBrowser(url: url)
}
}
}
private extension SettingsFlow {
static func preferredTableViewStyle() -> UITableView.Style {
if #available(iOS 13, *) {
return .insetGrouped
}
return .grouped
}
func summonSettingsController() -> FlowContributors {
let settingsViewController = SettingsTableViewController(style: SettingsFlow.preferredTableViewStyle())
rootViewController.setViewControllers([settingsViewController], animated: false)
return .one(flowContributor: .contribute(withNext: settingsViewController))
}
func summonAboutController() -> FlowContributors {
let aboutController = AboutAppTableViewController(style: SettingsFlow.preferredTableViewStyle())
rootViewController.pushViewController(aboutController, animated: true)
return .one(flowContributor: .contribute(withNext: aboutController))
}
func summonApiKeyEditController() -> FlowContributors {
let apiKeyEditController = SettingsInputTableViewController(style: SettingsFlow.preferredTableViewStyle())
rootViewController.pushViewController(apiKeyEditController, animated: true)
return .one(flowContributor: .contribute(withNext: apiKeyEditController))
}
func summonManageLocationsController() -> FlowContributors {
guard !WeatherDataService.shared.bookmarkedLocations.isEmpty else {
return .none
}
let locationManagementController = WeatherLocationManagementTableViewController(style: SettingsFlow.preferredTableViewStyle())
rootViewController.pushViewController(locationManagementController, animated: true)
return .one(flowContributor: .contribute(withNext: locationManagementController))
}
func summonAddLocationController() -> FlowContributors {
let addLocationController = WeatherLocationSelectionTableViewController(style: SettingsFlow.preferredTableViewStyle())
rootViewController.pushViewController(addLocationController, animated: true)
return .one(flowContributor: .contribute(withNext: addLocationController))
}
func summonWebBrowser(url: URL) -> FlowContributors {
rootViewController.presentSafariViewController(for: url)
return .none
}
}
| 33.141509 | 130 | 0.75064 |
deea1195258bf44d845b650758e666d62250a637 | 610 | //
// NetworkConfig.swift
// Abstract
//
// Created by Egi Wibowo on 18/10/21.
//
import Foundation
public protocol NetworkConfigurable {
var baseURL: URL { get }
var apiKey: String { get }
var headers: [String: String] { get }
}
public struct ApiDataNetworkConfig: NetworkConfigurable {
public let baseURL: URL
public var apiKey: String
public let headers: [String: String]
public init(baseURL: URL,
apiKey: String,
headers: [String: String] = [:]) {
self.baseURL = baseURL
self.apiKey = apiKey
self.headers = headers
}
}
| 21.034483 | 57 | 0.62623 |
ebf87478742e991a45b3c756491043770f4bcd67 | 3,365 | //
// CountryTableViewCell.swift
// Countries
//
// Created by Ali Arda İsenkul on 15.01.2022.
//
import UIKit
import CoreData
class CountryTableViewCell: UITableViewCell {
// MARK: - I CHOSE UI IMAGEVIEW FOR STAR ICON AND CHANGE ITS OPACITY FOR FAVORITE/UNFAVORITE
@IBOutlet weak var countryView: UIView!
@IBOutlet weak var countryLabel: UILabel!
@IBOutlet weak var countryFavImage: UIImageView!
var page : String = "Main"
var currentTableView : UITableView!
var listViewModel : CountryListViewModel!
var countryCode = ""
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(addToFavorite(tapGestureRecognizer:)))
countryFavImage.isUserInteractionEnabled = true
countryFavImage.addGestureRecognizer(tapGestureRecognizer)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@objc func addToFavorite(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
if tappedImage.alpha < 1 {
tappedImage.alpha = 1.0
} else{
tappedImage.alpha = 0.2
}
self.changeFavoriteStatus(code:countryCode)
}
}
// MARK: - Change Country Favorite Status
extension CountryTableViewCell {
func changeFavoriteStatus(code:String){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SavedCountries")
fetchRequest.predicate = NSPredicate(format: "countryCode = %@", code)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try context.fetch(fetchRequest)
if results.count > 0 {
for result in results as! [NSManagedObject] {
context.delete(result)
if page == "Saved" {
self.listViewModel.removeItem(code: countryCode)
}
}
}else{
let newCountryCode = NSEntityDescription.insertNewObject(forEntityName: "SavedCountries", into: context)
newCountryCode.setValue(code, forKey: "countryCode")
}
do {
try context.save()
print("coredata successfully saved")
}
catch {
print("error while coredata saving for favorite process")
}
} catch{
print("core data fetching favorited object")
}
}
}
// MARK: - TRYING TO ADD AN EXTENSION TO TRIGGER VIEWCONTROLLER FROM CUSTOM CELL INSTANTLY BUT I DID NOT HAVE ENOUGH TIME AND LACK OF KNOWLEDGE
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
| 33.989899 | 143 | 0.625854 |
6174411891bef5b13428c1b06b34d081f4514049 | 902 | //
// ExampleTests.swift
// ExampleTests
//
// Created by Guilherme Moura on 8/17/15.
// Copyright (c) 2015 Reefactor, Inc. All rights reserved.
//
import UIKit
import XCTest
class ExampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 24.378378 | 111 | 0.613082 |
fe8c6fffe5fda18f223835d0f39aae7c411d81d9 | 2,923 | //
// ValidateableTests.swift
// SwiftValidation
//
// Created by Jon on 01/06/2016.
// Copyright © 2016 joncotton. All rights reserved.
//
import XCTest
@testable import SwiftValidation
class ValidateableTests: XCTestCase {
enum MockValidationError: ErrorType {
case failed
}
struct MockValidator: Validator {
var shouldPass = true
func isValid(value: MockValidateable) throws -> Bool {
guard shouldPass else {
throw MockValidationError.failed
}
return true
}
}
class MockValidateable: Validateable {
typealias ValidatorType = MockValidator
}
func test_validateable_valid_value_returns_itself_when_the_validator_passes() {
let mockValidateable = MockValidateable()
var mockValidator = MockValidator()
mockValidator.shouldPass = true
guard let validValue = try? mockValidateable.validValue(mockValidator) else {
XCTFail("Expected Validateable to return itself from validValue")
return
}
XCTAssert(validValue === mockValidateable)
}
func test_validateable_valid_value_throws_an_error_when_the_validator_fails() {
let mockValidateable = MockValidateable()
var mockValidator = MockValidator()
mockValidator.shouldPass = false
XCTAssertThrowsError(try mockValidateable.validValue(mockValidator))
}
func test_validateable_valid_value_throws_a_nil_error_if_testing_a_nil_optional() {
let mockValidateable: MockValidateable? = nil
var mockValidator = MockValidator()
mockValidator.shouldPass = true
do {
try mockValidateable.validValue(mockValidator)
} catch let errors as AggregateError {
guard let firstError = errors[0] as? ValidationError else {
XCTFail("Validateable validValue threw aggregate error containing unexpected when testing nil optional")
return
}
XCTAssertEqual(firstError, ValidationError.valueIsNil)
} catch {
XCTFail("Validateable validValue threw unexpected error when testing nil optional")
}
XCTAssertThrowsError(try mockValidateable.validValue(mockValidator))
}
func test_validateable_valid_value_returns_unwrapped_value_when_testing_non_nil_optional() {
let mockValidateable: MockValidateable? = MockValidateable()
var mockValidator = MockValidator()
mockValidator.shouldPass = true
guard let validValue = try? mockValidateable.validValue(mockValidator) else {
XCTFail("Expected Validateable to return unwrapped self from validValue")
return
}
XCTAssert(validValue === mockValidateable)
}
}
| 33.215909 | 120 | 0.655491 |
1c4b9707a6bb7e9c2aa10c98753cf77becebd4e1 | 941 | /// A type (usually an enum) whose static members have a strict ordering.
public protocol CaseIterable: Hashable {
/// An ordered traversal of the cases in the type.
associatedtype List: Sequence = AnySequence<Self>
/// A getter for the ordered cases of this type.
static var all: Self.List { get }
associatedtype Count: SignedInteger = Int
/// The number of elements in `all`.
static var count: Count { get }
}
extension CaseIterable where List: Collection, Count == List.IndexDistance {
public static var count: List.IndexDistance {
return all.count
}
}
extension CaseIterable where Self: RawRepresentable, Self.RawValue: Strideable {
public func distance(to other: Self) -> RawValue.Stride {
return rawValue.distance(to: other.rawValue)
}
public func advanced(by n: RawValue.Stride) -> Self {
return Self(rawValue: rawValue.advanced(by: n))!
}
}
| 26.138889 | 80 | 0.683316 |
0e9b4f062a2fce8c857fc5cbc1a7d26eb2e483c8 | 1,961 | ///// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 CoreData
@objc(Reminder)
public class Reminder: NSManagedObject {
}
| 50.282051 | 83 | 0.758287 |
f9e3bf6a7d9702a207d6388b6aef05d953f787f4 | 25,158 | /*
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
*/
import Basics
import PackageLoading
import PackageModel
import SPMTestSupport
import TSCBasic
import TSCUtility
import XCTest
class PackageDescription5_0LoadingTests: PackageDescriptionLoadingTests {
override var toolsVersion: ToolsVersion {
.v5
}
func testBasics() throws {
let content = """
import PackageDescription
let package = Package(
name: "Trivial",
products: [
.executable(name: "tool", targets: ["tool"]),
.library(name: "Foo", targets: ["foo"]),
],
dependencies: [
.package(url: "/foo1", from: "1.0.0"),
],
targets: [
.target(
name: "foo",
dependencies: ["dep1", .product(name: "product"), .target(name: "target")]),
.target(
name: "tool"),
.testTarget(
name: "bar",
dependencies: ["foo"]),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.displayName, "Trivial")
// Check targets.
let foo = manifest.targetMap["foo"]!
XCTAssertEqual(foo.name, "foo")
XCTAssertFalse(foo.isTest)
XCTAssertEqual(foo.dependencies, ["dep1", .product(name: "product"), .target(name: "target")])
let bar = manifest.targetMap["bar"]!
XCTAssertEqual(bar.name, "bar")
XCTAssertTrue(bar.isTest)
XCTAssertEqual(bar.dependencies, ["foo"])
// Check dependencies.
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })
XCTAssertEqual(deps["foo1"], .localSourceControl(path: .init("/foo1"), requirement: .upToNextMajor(from: "1.0.0")))
// Check products.
let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })
let tool = products["tool"]!
XCTAssertEqual(tool.name, "tool")
XCTAssertEqual(tool.targets, ["tool"])
XCTAssertEqual(tool.type, .executable)
let fooProduct = products["Foo"]!
XCTAssertEqual(fooProduct.name, "Foo")
XCTAssertEqual(fooProduct.type, .library(.automatic))
XCTAssertEqual(fooProduct.targets, ["foo"])
}
func testSwiftLanguageVersion() throws {
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [.v4, .v4_2, .v5]
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.swiftLanguageVersions, [.v4, .v4_2, .v5])
}
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [.v3]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.invalidManifestFormat(let message, _) = error {
XCTAssertMatch(message, .contains("'v3' is unavailable"))
XCTAssertMatch(message, .contains("'v3' was obsoleted in PackageDescription 5"))
} else {
XCTFail("unexpected error: \(error)")
}
}
}
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
swiftLanguageVersions: [.version("")]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.runtimeManifestErrors(let messages) = error {
XCTAssertEqual(messages, ["invalid Swift language version: "])
} else {
XCTFail("unexpected error: \(error)")
}
}
}
}
func testPlatformOptions() throws {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS("10.13.option1.option2"), .iOS("12.2.option2"),
.tvOS("12.3.4.option5.option7.option9")
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.platforms, [
PlatformDescription(name: "macos", version: "10.13", options: ["option1", "option2"]),
PlatformDescription(name: "ios", version: "12.2", options: ["option2"]),
PlatformDescription(name: "tvos", version: "12.3.4", options: ["option5", "option7", "option9"]),
])
}
func testPlatforms() throws {
// Sanity check.
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS(.v10_13), .iOS("12.2"),
.tvOS(.v12), .watchOS(.v3),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.platforms, [
PlatformDescription(name: "macos", version: "10.13"),
PlatformDescription(name: "ios", version: "12.2"),
PlatformDescription(name: "tvos", version: "12.0"),
PlatformDescription(name: "watchos", version: "3.0"),
])
}
// Test invalid custom versions.
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS("-11.2"), .iOS("12.x.2"), .tvOS("10..2"), .watchOS("1.0"),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.runtimeManifestErrors(let errors) = error {
XCTAssertEqual(errors, [
"invalid macOS version -11.2; -11 should be a positive integer",
"invalid iOS version 12.x.2; x should be a positive integer",
"invalid tvOS version 10..2; found an empty component",
"invalid watchOS version 1.0; the minimum major version should be 2",
])
} else {
XCTFail("unexpected error: \(error)")
}
}
}
// Duplicates.
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS(.v10_10), .macOS(.v10_12),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.runtimeManifestErrors(let errors) = error {
XCTAssertEqual(errors, ["found multiple declaration for the platform: macos"])
} else {
XCTFail("unexpected error: \(error)")
}
}
}
// Empty.
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: []
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.runtimeManifestErrors(let errors) = error {
XCTAssertEqual(errors, ["supported platforms can't be empty"])
} else {
XCTFail("unexpected error: \(error)")
}
}
}
// Newer OS version.
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS(.v11), .iOS(.v14),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.invalidManifestFormat(let message, _) = error {
XCTAssertMatch(message, .contains("error: 'v11' is unavailable"))
XCTAssertMatch(message, .contains("note: 'v11' was introduced in PackageDescription 5.3"))
XCTAssertMatch(message, .contains("note: 'v14' was introduced in PackageDescription 5.3"))
} else {
XCTFail("unexpected error: \(error)")
}
}
}
// Newer OS version alias (now marked as unavailable).
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
platforms: [
.macOS(.v10_16), .iOS(.v14),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.invalidManifestFormat(let message, _) = error {
XCTAssertMatch(message, .contains("error: 'v10_16' has been renamed to 'v11'"))
XCTAssertMatch(message, .contains("note: 'v10_16' has been explicitly marked unavailable here"))
XCTAssertMatch(message, .contains("note: 'v14' was introduced in PackageDescription 5.3"))
} else {
XCTFail("unexpected error: \(error)")
}
}
}
}
func testBuildSettings() throws {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
cSettings: [
.headerSearchPath("path/to/foo"),
.define("C", .when(platforms: [.linux])),
.define("CC", to: "4", .when(platforms: [.linux], configuration: .release)),
],
cxxSettings: [
.headerSearchPath("path/to/bar"),
.define("CXX"),
],
swiftSettings: [
.define("SWIFT", .when(configuration: .release)),
.define("SWIFT_DEBUG", .when(platforms: [.watchOS], configuration: .debug)),
],
linkerSettings: [
.linkedLibrary("libz"),
.linkedFramework("CoreData", .when(platforms: [.macOS, .tvOS])),
]
),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
let settings = manifest.targets[0].settings
XCTAssertEqual(settings[0], .init(tool: .c, name: .headerSearchPath, value: ["path/to/foo"]))
XCTAssertEqual(settings[1], .init(tool: .c, name: .define, value: ["C"], condition: .init(platformNames: ["linux"])))
XCTAssertEqual(settings[2], .init(tool: .c, name: .define, value: ["CC=4"], condition: .init(platformNames: ["linux"], config: "release")))
XCTAssertEqual(settings[3], .init(tool: .cxx, name: .headerSearchPath, value: ["path/to/bar"]))
XCTAssertEqual(settings[4], .init(tool: .cxx, name: .define, value: ["CXX"]))
XCTAssertEqual(settings[5], .init(tool: .swift, name: .define, value: ["SWIFT"], condition: .init(config: "release")))
XCTAssertEqual(settings[6], .init(tool: .swift, name: .define, value: ["SWIFT_DEBUG"], condition: .init(platformNames: ["watchos"], config: "debug")))
XCTAssertEqual(settings[7], .init(tool: .linker, name: .linkedLibrary, value: ["libz"]))
XCTAssertEqual(settings[8], .init(tool: .linker, name: .linkedFramework, value: ["CoreData"], condition: .init(platformNames: ["macos", "tvos"])))
}
func testSerializedDiagnostics() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let manifestPath = path.appending(components: "pkg", "Package.swift")
let loader = ManifestLoader(
toolchain: ToolchainConfiguration.default,
serializedDiagnostics: true,
cacheDir: path)
do {
let observability = ObservabilitySystem.makeForTesting()
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
)
"""
}
do {
_ = try loader.load(
at: manifestPath.parentDirectory,
packageKind: .fileSystem(manifestPath.parentDirectory),
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
} catch ManifestParseError.invalidManifestFormat(let error, let diagnosticFile) {
XCTAssertMatch(error, .contains("expected expression in container literal"))
let contents = try localFileSystem.readFileContents(diagnosticFile!)
XCTAssertNotNil(contents)
}
}
do {
let observability = ObservabilitySystem.makeForTesting()
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
import PackageDescription
func foo() {
let a = 5
}
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
}
_ = try loader.load(
at: manifestPath.parentDirectory,
packageKind: .fileSystem(manifestPath.parentDirectory),
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
testDiagnostics(observability.diagnostics) { result in
let diagnostic = result.check(diagnostic: .contains("initialization of immutable value"), severity: .warning)
let contents = try diagnostic?.metadata?.manifestLoadingDiagnosticFile.map { try localFileSystem.readFileContents($0) }
XCTAssertNotNil(contents)
}
}
}
}
func testInvalidBuildSettings() throws {
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
cSettings: [
.headerSearchPath("$(BYE)/path/to/foo/$(SRCROOT)/$(HELLO)"),
]
),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.runtimeManifestErrors(let errors) = error {
XCTAssertEqual(errors, ["the build setting 'headerSearchPath' contains invalid component(s): $(BYE) $(SRCROOT) $(HELLO)"])
} else {
XCTFail("unexpected error: \(error)")
}
}
}
do {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
cSettings: []
),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
_ = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
func testWindowsPlatform() throws {
let content = """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "foo",
cSettings: [
.define("LLVM_ON_WIN32", .when(platforms: [.windows])),
]
),
]
)
"""
do {
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.invalidManifestFormat(let message, _) = error {
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5.2"))
} else {
XCTFail("unexpected error: \(error)")
}
}
}
do {
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, toolsVersion: .v5_2, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.displayName, "Foo")
// Check targets.
let foo = manifest.targetMap["foo"]!
XCTAssertEqual(foo.name, "foo")
XCTAssertFalse(foo.isTest)
XCTAssertEqual(foo.dependencies, [])
let settings = foo.settings
XCTAssertEqual(settings[0], .init(tool: .c, name: .define, value: ["LLVM_ON_WIN32"], condition: .init(platformNames: ["windows"])))
}
}
func testPackageNameUnavailable() throws {
let content = """
import PackageDescription
let package = Package(
name: "Trivial",
products: [],
dependencies: [
.package(name: "Foo", url: "/foo1", from: "1.0.0"),
],
targets: [
.target(
name: "foo",
dependencies: [.product(name: "product", package: "Foo")]),
]
)
"""
let observability = ObservabilitySystem.makeForTesting()
XCTAssertThrowsError(try loadManifest(content, observabilityScope: observability.topScope), "expected error") { error in
if case ManifestParseError.invalidManifestFormat(let message, _) = error {
XCTAssertMatch(message, .contains("is unavailable"))
XCTAssertMatch(message, .contains("was introduced in PackageDescription 5.2"))
} else {
XCTFail("unexpected error: \(error)")
}
}
}
func testManifestWithPrintStatements() throws {
let content = """
import PackageDescription
print(String(repeating: "Hello manifest... ", count: 65536))
let package = Package(
name: "PackageWithChattyManifest"
)
"""
let observability = ObservabilitySystem.makeForTesting()
let manifest = try loadManifest(content, observabilityScope: observability.topScope)
XCTAssertFalse(observability.diagnostics.hasErrors)
XCTAssertEqual(manifest.displayName, "PackageWithChattyManifest")
XCTAssertEqual(manifest.toolsVersion, .v5)
XCTAssertEqual(manifest.targets, [])
XCTAssertEqual(manifest.dependencies, [])
}
func testManifestLoaderEnvironment() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let packagePath = path.appending(component: "pkg")
let manifestPath = packagePath.appending(component: "Package.swift")
try fs.writeFileContents(manifestPath) { stream in
stream <<< """
// swift-tools-version:5
import PackageDescription
let package = Package(
name: "Trivial",
targets: [
.target(
name: "foo",
dependencies: []),
]
)
"""
}
let moduleTraceFilePath = path.appending(component: "swift-module-trace")
var toolchain = ToolchainConfiguration.default
toolchain.swiftCompilerEnvironment["SWIFT_LOADED_MODULE_TRACE_FILE"] = moduleTraceFilePath.pathString
let manifestLoader = ManifestLoader(
toolchain: toolchain,
serializedDiagnostics: true,
isManifestSandboxEnabled: false,
cacheDir: nil)
let observability = ObservabilitySystem.makeForTesting()
let manifest = try manifestLoader.load(
at: manifestPath.parentDirectory,
packageKind: .fileSystem(manifestPath.parentDirectory),
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(manifest.displayName, "Trivial")
let moduleTraceJSON = try XCTUnwrap(try localFileSystem.readFileContents(moduleTraceFilePath).validDescription)
XCTAssertMatch(moduleTraceJSON, .contains("PackageDescription"))
}
}
}
| 40.188498 | 158 | 0.514787 |
8fba69d590bc6e85db60567beb4c8597e1ebd777 | 2,891 | //===----------------------------------------------------------------------===//
//
// This source file is part of the KafkaNIO open source project
//
// Copyright © 2020 Thomas Bartelmess.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// This file is auto generated from the Kafka Protocol definition. DO NOT EDIT.
import NIO
struct LeaveGroupRequest: KafkaRequest {
struct MemberIdentity: KafkaRequestStruct {
/// The member ID to remove from the group.
let memberID: String?
/// The group instance ID to remove from the group.
let groupInstanceID: String?
let taggedFields: [TaggedField] = []
func write(into buffer: inout ByteBuffer, apiVersion: APIVersion) throws {
let lengthEncoding: IntegerEncoding = (apiVersion >= 4) ? .varint : .bigEndian
if apiVersion >= 3 {
guard let memberID = self.memberID else {
throw KafkaError.missingValue
}
buffer.write(memberID, lengthEncoding: lengthEncoding)
}
if apiVersion >= 3 {
buffer.write(groupInstanceID, lengthEncoding: lengthEncoding)
}
if apiVersion >= 4 {
buffer.write(taggedFields)
}
}
init(memberID: String?, groupInstanceID: String?) {
self.memberID = memberID
self.groupInstanceID = groupInstanceID
}
}
let apiKey: APIKey = .leaveGroup
let apiVersion: APIVersion
let clientID: String?
let correlationID: Int32
let taggedFields: [TaggedField] = []
/// The ID of the group to leave.
let groupID: String
/// The member ID to remove from the group.
let memberID: String?
/// List of leaving member identities.
let members: [MemberIdentity]?
func write(into buffer: inout ByteBuffer) throws {
let lengthEncoding: IntegerEncoding = (apiVersion >= 4) ? .varint : .bigEndian
writeHeader(into: &buffer, version: apiKey.requestHeaderVersion(for: apiVersion))
buffer.write(groupID, lengthEncoding: lengthEncoding)
if apiVersion <= 2 {
guard let memberID = self.memberID else {
throw KafkaError.missingValue
}
buffer.write(memberID, lengthEncoding: lengthEncoding)
}
if apiVersion >= 3 {
guard let members = self.members else {
throw KafkaError.missingValue
}
try buffer.write(members, apiVersion: apiVersion, lengthEncoding: lengthEncoding)
}
if apiVersion >= 4 {
buffer.write(taggedFields)
}
}
}
| 32.852273 | 93 | 0.567278 |
768d03bc11cd431311cd94d075e91fa3603e00ee | 205 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
""[1
class
var d{{class
case c,case
| 22.777778 | 87 | 0.756098 |
086b741e9e3b3c527b2afe5f8fd724a30f30ce0b | 3,126 | //
// DetalhesFilmes.swift
// Filmes
//
// Created by Jaqueline Bittencourt Santos on 30/03/21.
import Foundation
// MARK: - DetalhesFilmes
struct DetalhesFilmes: Codable {
let adult: Bool
let backdropPath: String
let belongsToCollection: JSONNull?
let budget: Int
let genres: [Genre]
let homepage: String
let id: Int
let imdbID, originalLanguage, originalTitle, overview: String
let popularity: Double
let posterPath: String
let productionCompanies: [ProductionCompany]
let productionCountries: [ProductionCountry]
let releaseDate: String
let revenue, runtime: Int
let spokenLanguages: [SpokenLanguage]
let status, tagline, title: String
let video: Bool
let voteAverage: Double
let voteCount: Int
enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case belongsToCollection = "belongs_to_collection"
case budget, genres, homepage, id
case imdbID = "imdb_id"
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview, popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case revenue, runtime
case spokenLanguages = "spoken_languages"
case status, tagline, title, video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
}
// MARK: - Genre
struct Genre: Codable {
let id: Int
let name: String
}
// MARK: - ProductionCompany
struct ProductionCompany: Codable {
let id: Int
let logoPath: String?
let name, originCountry: String
enum CodingKeys: String, CodingKey {
case id
case logoPath = "logo_path"
case name
case originCountry = "origin_country"
}
}
// MARK: - ProductionCountry
struct ProductionCountry: Codable {
let iso3166_1, name: String
enum CodingKeys: String, CodingKey {
case iso3166_1 = "iso_3166_1"
case name
}
}
// MARK: - SpokenLanguage
struct SpokenLanguage: Codable {
let englishName, iso639_1, name: String
enum CodingKeys: String, CodingKey {
case englishName = "english_name"
case iso639_1 = "iso_639_1"
case name
}
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
| 26.268908 | 159 | 0.664427 |
3aeb40c9376e105505a3c664a1ff221548f5b23e | 12,960 | //
// FZMTextMessageCell.swift
// Chat33
//
// Created by 吴文拼 on 2018/9/27.
// Copyright © 2018年 吴文拼. All rights reserved.
//
import UIKit
import YYText
class FZMTextMessageCell: FZMBaseMessageCell {
let rewardTap = UITapGestureRecognizer.init()
let admireTap = UITapGestureRecognizer.init()
lazy var messageLab: YYLabel = {
let lbl = YYLabel()
lbl.numberOfLines = 0
lbl.isUserInteractionEnabled = true
lbl.preferredMaxLayoutWidth = ScreenWidth - 160
lbl.setContentHuggingPriority(.defaultHigh, for: .horizontal)
lbl.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
return lbl
}()
lazy var bgImageView: UIImageView = {
let v = UIImageView()
v.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
v.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
let inset = UIEdgeInsets.init(top: 30, left: 30, bottom: 30, right: 30)
var image = GetBundleImage("message_text")
image = image?.resizableImage(withCapInsets: inset, resizingMode: .stretch)
v.image = image
v.isUserInteractionEnabled = true
return v
}()
lazy var flodImageView: UIImageView = {
let v = UIImageView()
var image = GetBundleImage("text_unfold")
v.image = image
v.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(flodImageViewTap))
v.addGestureRecognizer(tap)
v.enlargeClickEdge(10, 10, 10, 10)
return v
}()
lazy var flodLab: YYLabel = {
let lbl = YYLabel()
lbl.numberOfLines = 2
lbl.isUserInteractionEnabled = true
lbl.isHidden = true
lbl.preferredMaxLayoutWidth = ScreenWidth - 190
return lbl
}()
@objc func flodImageViewTap() {
self.vm.isNeedFold = !self.vm.isNeedFold
if let tableView = self.superview as? UITableView, let indexPath = tableView.indexPath(for: self) {
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func initView() {
super.initView()
self.contentView.addSubview(bgImageView)
self.contentView.addSubview(messageLab)
messageLab.numberOfLines = 0
messageLab.snp.makeConstraints { (m) in
m.top.equalTo(self.userNameLbl.snp.bottom).offset(12)
m.bottom.equalToSuperview().offset(-25)
m.left.equalTo(headerImageView.snp.right).offset(30)
m.right.lessThanOrEqualToSuperview().offset(-80)
m.height.greaterThanOrEqualTo(20)
}
bgImageView.snp.makeConstraints { (m) in
m.centerX.equalTo(messageLab)
m.centerY.equalTo(messageLab).offset(3)
m.width.equalTo(messageLab).offset(50)
m.height.equalTo(messageLab).offset(40)
}
sendingView.snp.makeConstraints { (m) in
m.centerY.equalTo(bgImageView)
m.left.equalTo(bgImageView.snp.right).offset(5)
m.size.equalTo(CGSize(width: 15, height: 15))
}
self.contentView.addSubview(self.lockView)
self.lockView.snp.makeConstraints { (m) in
m.top.equalTo(self.userNameLbl.snp.bottom).offset(-5)
m.left.equalToSuperview().offset(55)
m.size.equalTo(CGSize(width: 120, height: 65))
}
self.bgImageView.addSubview(self.countDownTimeView)
self.countDownTimeView.snp.makeConstraints { (m) in
m.top.equalToSuperview().offset(10)
m.centerX.equalTo(self.bgImageView.snp.right).offset(-10)
m.size.equalTo(CGSize(width: 0, height: 0))
}
self.contentView.addSubview(flodImageView)
flodImageView.snp.makeConstraints { (m) in
m.bottom.equalTo(self.bgImageView.snp.bottom).offset(-30)
m.right.equalTo(self.bgImageView).offset(-23)
m.size.equalTo(CGSize(width: 10, height: 6))
}
flodLab.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
self.contentView.addSubview(flodLab)
flodLab.snp.makeConstraints { (m) in
m.top.left.bottom.equalTo(messageLab)
m.right.equalTo(messageLab).offset(-20)
}
self.admireView.snp.makeConstraints { (m) in
m.bottom.equalTo(bgImageView.snp.bottom).offset(-15)
m.left.equalTo(bgImageView.snp.right).offset(-5)
}
let longPress = UILongPressGestureRecognizer()
longPress.rx.event.subscribe {[weak self] (event) in
guard case .next(let press) = event else { return }
guard let strongSelf = self else { return }
if press.state == .began {
self?.showMenu(in: strongSelf.bgImageView)
}
}.disposed(by: disposeBag)
messageLab.addGestureRecognizer(longPress)
let longPress2 = UILongPressGestureRecognizer()
longPress2.rx.event.subscribe {[weak self] (event) in
guard case .next(let press) = event else { return }
guard let strongSelf = self else { return }
if press.state == .began {
self?.showMenu(in: strongSelf.bgImageView)
}
}.disposed(by: disposeBag)
flodLab.addGestureRecognizer(longPress2)
admireTap.rx.event.subscribe(onNext: {[weak self] (_) in
guard let strongSelf = self else { return }
strongSelf.actionDelegate?.textTapAdmire(msgId: strongSelf.vm.msgId)
}).disposed(by: disposeBag)
self.messageLab.addGestureRecognizer(admireTap)
rewardTap.numberOfTapsRequired = 2
rewardTap.rx.event.subscribe(onNext: {[weak self] (_) in
guard let strongSelf = self else { return }
strongSelf.actionDelegate?.textTapReward(msgId: strongSelf.vm.msgId)
strongSelf.messageLab.isUserInteractionEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
strongSelf.messageLab.isUserInteractionEnabled = true
}
}).disposed(by: disposeBag)
self.messageLab.addGestureRecognizer(rewardTap)
admireTap.require(toFail: rewardTap)
}
override func configure(with data: FZMMessageBaseVM) {
super.configure(with: data)
messageLab.numberOfLines = 0
messageLab.isHidden = false
messageLab.text = nil
messageLab.attributedText = nil
flodLab.text = nil
flodLab.attributedText = nil
flodImageView.isHidden = true
flodLab.isHidden = true
guard data.direction == .receive, let data = data as? FZMTextMessageVM else { return }
if data.snap == .burn {
lockView.isHidden = false
messageLab.isHidden = true
bgImageView.isHidden = true
}else {
lockView.isHidden = true
messageLab.isHidden = false
bgImageView.isHidden = false
self.showContentText(with: data.content)
}
}
fileprivate func showContentText(with str: String) {
let attStr = self.makeString(with: str, normalColor: FZM_BlackWordColor, linkColor: FZM_TitleColor)
messageLab.attributedText = attStr
if str.isURL() && str.count > 50 {
messageLab.isHidden = true
flodImageView.isHidden = false
flodLab.isHidden = false
flodLab.attributedText = attStr
if self.vm.isNeedFold {
messageLab.numberOfLines = 2
flodLab.numberOfLines = 2
flodImageView.image = GetBundleImage("text_unfold")
} else {
messageLab.numberOfLines = 0
flodLab.numberOfLines = 0
flodImageView.image = GetBundleImage("text_fold")
}
}else if self.vm.isTextNeedFold && messageLab.getLineCount(text: str)>3{
messageLab.isHidden = true
flodImageView.isHidden = false
flodLab.isHidden = false
flodLab.attributedText = attStr
if self.vm.isNeedFold {
messageLab.numberOfLines = 3
flodLab.numberOfLines = 3
flodImageView.image = GetBundleImage("text_unfold")
} else {
messageLab.numberOfLines = 0
flodLab.numberOfLines = 0
flodImageView.image = GetBundleImage("text_fold")
}
}
}
fileprivate func makeString(with str: String, normalColor: UIColor, linkColor: UIColor) -> NSMutableAttributedString?{
let regularStr = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
let reg = try? NSRegularExpression.init(pattern: regularStr, options: .caseInsensitive)
guard let regex = reg else { return nil }
let arrayOfAllMatches = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
var arr = [String]()
var rangeArr = [NSRange]()
arrayOfAllMatches.forEach { (match) in
let substringForMatch = str.substring(with: match.range)
arr.append(substringForMatch)
}
let subStr = str
arr.forEach { (useStr) in
rangeArr.append(str.nsRange(from: useStr))
}
let mutStr = NSMutableAttributedString(string: subStr)
mutStr.yy_font = UIFont.regularFont(16)
mutStr.yy_color = normalColor
mutStr.yy_alignment = .left
rangeArr.forEach { (range) in
let index = rangeArr.index(of: range)!
mutStr.yy_setTextHighlight(range, color: linkColor, backgroundColor: UIColor.gray, userInfo: nil, tapAction: { (containerView, text, clickrang, rect) in
let url = arr[index]
FZMUIMediator.shared().openUrl(with: url)
}, longPressAction: nil)
}
self.admireTap.isEnabled = rangeArr.isEmpty
self.rewardTap.isEnabled = rangeArr.isEmpty
return mutStr
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class FZMMineTextMessageCell: FZMTextMessageCell {
override func initView() {
super.initView()
self.changeMineConstraints()
self.contentView.addSubview(sourceLab)
sourceLab.snp.makeConstraints { (m) in
m.right.equalTo(headerImageView.snp.left).offset(-20)
m.left.greaterThanOrEqualToSuperview().offset(80)
m.bottom.equalToSuperview().offset(-10)
m.height.lessThanOrEqualTo(35)
}
messageLab.snp.remakeConstraints { (m) in
m.top.equalTo(self.userNameLbl.snp.bottom).offset(12)
m.bottom.equalTo(self.sourceLab.snp.top).offset(-12)
m.right.equalTo(headerImageView.snp.left).offset(-30)
m.left.greaterThanOrEqualToSuperview().offset(80)
m.height.greaterThanOrEqualTo(20)
}
lockView.removeFromSuperview()
countDownTimeView.removeFromSuperview()
self.bgImageView.addSubview(lockImg)
lockImg.snp.makeConstraints { (m) in
m.top.equalToSuperview().offset(8)
m.left.equalToSuperview()
m.size.equalTo(CGSize(width: 20, height: 20))
}
let inset = UIEdgeInsets.init(top: 30, left: 30, bottom: 30, right: 30)
var image = GetBundleImage("message_text_mine")
image = image?.resizableImage(withCapInsets: inset, resizingMode: .stretch)
bgImageView.image = image
sendingView.snp.remakeConstraints { (m) in
m.centerY.equalTo(bgImageView)
m.right.equalTo(bgImageView.snp.left).offset(-5)
m.size.equalTo(CGSize(width: 15, height: 15))
}
self.admireView.snp.remakeConstraints { (m) in
m.bottom.equalTo(bgImageView.snp.bottom).offset(-15)
m.right.equalTo(bgImageView.snp.left).offset(5)
}
}
override func configure(with data: FZMMessageBaseVM) {
super.configure(with: data)
guard data.direction == .send, let data = data as? FZMTextMessageVM else { return }
self.showContentText(with: data.content)
self.lockImg.isHidden = data.snap == .none
sourceLab.text = data.forwardType == .detail ? data.forwardDescriptionText : nil
}
}
| 40.248447 | 223 | 0.610957 |
1a41ee9a00b5e69045552e9cd64b0c5e9853a4ac | 990 | //
// ShareViewPreview.swift
// JuiceUI
//
// Created by Matthew Wyskiel on 8/6/19.
import SwiftUI
import JuiceUI
struct ShareSheetPreview: View {
@State private var showShareSheet = false
@State private var status = ""
let url = "https://github.com/mattwyskiel"
var body: some View {
VStack {
Text(url)
Text(status)
Button("Share") {
self.showShareSheet = true
}
}.sheet(isPresented: $showShareSheet) {
ShareSheet(items: [URL(string: self.url)!])
.onComplete { (activityType, completed, returnedItems, activityError) in
if completed {
self.status = "completed!"
} else {
self.status = "incomplete!"
}
}
}
}
}
#if DEBUG
struct ShareViewPreview_Previews: PreviewProvider {
static var previews: some View {
ShareSheetPreview()
}
}
#endif
| 24.146341 | 84 | 0.546465 |
160f80608090a92137de3eac3df791c53da9a0bc | 4,843 | //
// PhotoEditor+Controls.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
// MARK: - Control
public enum control: String {
case crop
case sticker
case draw
case text
case save
case share
case clear
public func string() -> String {
return self.rawValue
}
}
extension PhotoEditorViewController {
//MARK: Top Toolbar
@IBAction func cancelButtonTapped(_ sender: Any) {
photoEditorDelegate?.canceledEditing()
self.dismiss(animated: true, completion: nil)
}
@IBAction func cropButtonTapped(_ sender: UIButton) {
let controller = CropViewController()
controller.delegate = self
controller.image = image
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true, completion: nil)
}
@IBAction func stickersButtonTapped(_ sender: Any) {
addStickersViewController()
}
@IBAction func drawButtonTapped(_ sender: Any) {
isDrawing = true
canvasImageView.isUserInteractionEnabled = false
doneButton.isHidden = false
colorPickerView.isHidden = false
hideToolbar(hide: true)
}
@IBAction func textButtonTapped(_ sender: Any) {
isTyping = true
let textView = UITextView(frame: CGRect(x: 0, y: canvasImageView.center.y,
width: UIScreen.main.bounds.width, height: 30))
textView.textAlignment = .center
textView.font = UIFont(name: "Helvetica", size: 30)
textView.textColor = textColor
textView.layer.shadowColor = UIColor.black.cgColor
textView.layer.shadowOffset = CGSize(width: 1.0, height: 0.0)
textView.layer.shadowOpacity = 0.2
textView.layer.shadowRadius = 1.0
textView.layer.backgroundColor = UIColor.clear.cgColor
textView.autocorrectionType = .no
textView.isScrollEnabled = false
textView.delegate = self
self.canvasImageView.addSubview(textView)
addGestures(view: textView)
textView.becomeFirstResponder()
}
@IBAction func doneButtonTapped(_ sender: Any) {
view.endEditing(true)
doneButton.isHidden = true
colorPickerView.isHidden = true
canvasImageView.isUserInteractionEnabled = true
hideToolbar(hide: false)
isDrawing = false
}
//MARK: Bottom Toolbar
@IBAction func saveButtonTapped(_ sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(canvasView.toImage(),self, #selector(PhotoEditorViewController.image(_:withPotentialError:contextInfo:)), nil)
}
@IBAction func shareButtonTapped(_ sender: UIButton) {
let activity = UIActivityViewController(activityItems: [canvasView.toImage()], applicationActivities: nil)
if let popoverController = activity.popoverPresentationController {
popoverController.barButtonItem = UIBarButtonItem(customView: sender)
}
present(activity, animated: true, completion: nil)
}
@IBAction func clearButtonTapped(_ sender: AnyObject) {
//clear drawing
canvasImageView.image = nil
//clear stickers and textviews
for subview in canvasImageView.subviews {
subview.removeFromSuperview()
}
}
@IBAction func continueButtonPressed(_ sender: Any) {
let image = self.canvasView.toImage()
photoEditorDelegate?.doneEditing(image: image)
self.dismiss(animated: true, completion: nil)
}
//MAKR: helper methods
@objc func image(_ image: UIImage, withPotentialError error: NSErrorPointer, contextInfo: UnsafeRawPointer) {
let alert = UIAlertController(title: "已保存", message: "图片已保存到相册", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "完成", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func hideControls() {
var controls = hiddenControls
for control in controls {
if (control == "clear") {
clearButton.isHidden = true
} else if (control == "crop") {
cropButton.isHidden = true
} else if (control == "draw") {
drawButton.isHidden = true
} else if (control == "save") {
saveButton.isHidden = true
} else if (control == "share") {
shareButton.isHidden = true
} else if (control == "sticker") {
stickerButton.isHidden = true
} else if (control == "text") {
textButton.isHidden = true
}
}
}
}
| 32.945578 | 149 | 0.628949 |
dbb66142f41aa2ded173a8cc4eccc6d217a9049d | 582 | //
// ImageInfo.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 1/4/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import CZUtils
import ReactiveListViewKit
/// Model of image info
class ImageInfo: ReactiveListDiffable {
let url: String
let width: Int
let height: Int
// MARK: - CZListDiffable
func isEqual(toDiffableObj object: AnyObject) -> Bool {
return isEqual(toCodable: object)
}
// MARK: - NSCopying
func copy(with zone: NSZone? = nil) -> Any {
return codableCopy(with: zone)
}
}
| 20.785714 | 59 | 0.646048 |
088381ff55523a9b42ae63465cc7a7393c1463a8 | 1,161 | //
// AlertViewButtonStyle.swift
// EatList
//
// Created by Christian Alvarez on 12/30/20.
//
import UIKit
enum AlertViewButtonStyle {
case primary
case secondary
}
extension AlertViewButtonStyle {
var contentEdgeInsets: UIEdgeInsets {
return UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
}
var titleColor: UIColor {
switch self {
case .primary:
return .white
case .secondary:
return .black
}
}
var font: UIFont {
switch self {
case .primary: return .systemFont(ofSize: 12, weight: .semibold)
case .secondary: return .systemFont(ofSize: 12, weight: .medium)
}
}
var backgroundColor: UIColor? {
switch self {
case .primary: return .black
case .secondary: return nil
}
}
var borderColor: UIColor {
switch self {
case .primary,
.secondary:
return .clear
}
}
var borderWidth: CGFloat {
switch self {
case .primary,
.secondary:
return 0
}
}
}
| 19.677966 | 72 | 0.538329 |
39b743860e122547dda114c62fbae7b90db76e86 | 608 | //
// MovieCell.swift
// Flicks
//
// Created by tianhe_wang on 8/4/16.
// Copyright © 2016 tianhe_wang. All rights reserved.
//
import UIKit
class MovieCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.714286 | 63 | 0.675987 |
7232e9176780ef8fbf80d6c582637576cba0a8e5 | 3,359 | public struct Vec2<T: IntExpressibleAlgebraicField>: Addable, Subtractable, Multipliable, Divisible, Negatable, Hashable, CustomStringConvertible {
public var x: T
public var y: T
public var asTuple: (x: T, y: T) { (x: x, y: y) }
public var asNDArray: NDArray<T> { NDArray([x, y]) }
public var xInverted: Vec2<T> { Vec2(x: -x, y: y) }
public var yInverted: Vec2<T> { Vec2(x: x, y: -y) }
public var description: String { "(\(x), \(y))" }
public init(x: T = 0, y: T = 0) {
self.x = x
self.y = y
}
public init(both value: T) {
x = value
y = value
}
public func map(_ f: (T) throws -> T) rethrows -> Vec2<T> { try Vec2(x: f(x), y: f(y)) }
public func mapBoth(_ fx: (T) throws -> T, _ fy: (T) throws -> T) rethrows -> Vec2<T> { try Vec2(x: fx(x), y: fy(y)) }
public static func zero() -> Vec2<T> { Vec2(x: 0, y: 0) }
public static func +(lhs: Vec2<T>, rhs: Vec2<T>) -> Vec2<T> { Vec2(x: lhs.x + rhs.x, y: lhs.y + rhs.y) }
public static func -(lhs: Vec2<T>, rhs: Vec2<T>) -> Vec2<T> { Vec2(x: lhs.x - rhs.x, y: lhs.y - rhs.y) }
public static func *(lhs: Vec2<T>, rhs: Vec2<T>) -> Vec2<T> { Vec2(x: lhs.x * rhs.x, y: lhs.y * rhs.y) }
public static func /(lhs: Vec2<T>, rhs: Vec2<T>) -> Vec2<T> { Vec2(x: lhs.x / rhs.x, y: lhs.y / rhs.y) }
public static func *(lhs: Vec2<T>, rhs: T) -> Vec2<T> { Vec2(x: lhs.x * rhs, y: lhs.y * rhs) }
public static func /(lhs: Vec2<T>, rhs: T) -> Vec2<T> { Vec2(x: lhs.x / rhs, y: lhs.y / rhs) }
public prefix static func -(operand: Vec2<T>) -> Vec2<T> { Vec2(x: -operand.x, y: -operand.y) }
public static func +=(lhs: inout Vec2<T>, rhs: Vec2<T>) {
lhs.x += rhs.x
lhs.y += rhs.y
}
public static func -=(lhs: inout Vec2<T>, rhs: Vec2<T>) {
lhs.x -= rhs.x
lhs.y -= rhs.y
}
public static func *=(lhs: inout Vec2<T>, rhs: Vec2<T>) {
lhs.x *= rhs.x
lhs.y *= rhs.y
}
public static func /=(lhs: inout Vec2<T>, rhs: Vec2<T>) {
lhs.x /= rhs.x
lhs.y /= rhs.y
}
public mutating func negate() {
x.negate()
y.negate()
}
public func dot(_ other: Vec2<T>) -> T {
(x * other.x) + (y * other.y)
}
public func cross(_ other: Vec2<T>) -> T {
(x * other.y) - (y * other.x)
}
public func map<R: IntExpressibleAlgebraicField>(mapper: (T) -> R) -> Vec2<R> {
Vec2<R>(x: mapper(x), y: mapper(y))
}
public func with(x newX: T) -> Vec2<T> {
Vec2(x: newX, y: y)
}
public func with(y newY: T) -> Vec2<T> {
Vec2(x: x, y: newY)
}
}
extension Vec2 where T: BinaryFloatingPoint {
public var squaredMagnitude: T { ((x * x) + (y * y)) }
public var magnitude: T { squaredMagnitude.squareRoot() }
public var normalized: Vec2<T> { self / magnitude }
public var floored: Vec2<Int> { Vec2<Int>(x: Int(x.rounded(.down)), y: Int(y.rounded(.down))) }
}
extension Vec2 where T: BinaryInteger {
public var squaredMagnitude: Double { Double((x * x) + (y * y)) }
public var magnitude: Double { squaredMagnitude.squareRoot() }
public var asDouble: Vec2<Double> { map { Double($0) } }
}
extension NDArray {
public var asVec2: Vec2<T>? {
shape == [2] ? Vec2(x: values[0], y: values[1]) : nil
}
}
| 31.990476 | 147 | 0.542721 |
e512a382c86d3197e44496a20fbeb9a13b780fc3 | 16,685 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/// Service object for interacting with AWS ManagedBlockchain service.
///
/// Amazon Managed Blockchain is a fully managed service for creating and managing blockchain networks using open-source frameworks. Blockchain allows you to build applications where multiple parties can securely and transparently run transactions and share data without the need for a trusted, central authority. Managed Blockchain supports the Hyperledger Fabric and Ethereum open-source frameworks. Ethereum on Managed Blockchain is in preview release and is subject to change. Because of fundamental differences between the frameworks, some API actions or data types may only apply in the context of one framework and not the other. For example, actions related to Hyperledger Fabric network members such as CreateMember and DeleteMember do not apply to Ethereum. The description for each action indicates the framework or frameworks to which it applies. Data types and properties that apply only in the context of a particular framework are similarly indicated.
public struct ManagedBlockchain: AWSService {
// MARK: Member variables
/// Client used for communication with AWS
public let client: AWSClient
/// Service configuration
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the ManagedBlockchain client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "managedblockchain",
serviceProtocol: .restjson,
apiVersion: "2018-09-24",
endpoint: endpoint,
errorType: ManagedBlockchainErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Creates a member within a Managed Blockchain network. Applies only to Hyperledger Fabric.
public func createMember(_ input: CreateMemberInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateMemberOutput> {
return self.client.execute(operation: "CreateMember", path: "/networks/{networkId}/members", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new blockchain network using Amazon Managed Blockchain. Applies only to Hyperledger Fabric.
public func createNetwork(_ input: CreateNetworkInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateNetworkOutput> {
return self.client.execute(operation: "CreateNetwork", path: "/networks", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a node on the specified blockchain network. Applies to Hyperledger Fabric and Ethereum. Ethereum on Managed Blockchain is in preview release and is subject to change.
public func createNode(_ input: CreateNodeInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateNodeOutput> {
return self.client.execute(operation: "CreateNode", path: "/networks/{networkId}/nodes", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a proposal for a change to the network that other members of the network can vote on, for example, a proposal to add a new member to the network. Any member can create a proposal. Applies only to Hyperledger Fabric.
public func createProposal(_ input: CreateProposalInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateProposalOutput> {
return self.client.execute(operation: "CreateProposal", path: "/networks/{networkId}/proposals", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a member. Deleting a member removes the member and all associated resources from the network. DeleteMember can only be called for a specified MemberId if the principal performing the action is associated with the AWS account that owns the member. In all other cases, the DeleteMember action is carried out as the result of an approved proposal to remove a member. If MemberId is the last member in a network specified by the last AWS account, the network is deleted also. Applies only to Hyperledger Fabric.
public func deleteMember(_ input: DeleteMemberInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteMemberOutput> {
return self.client.execute(operation: "DeleteMember", path: "/networks/{networkId}/members/{memberId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a node that your AWS account owns. All data on the node is lost and cannot be recovered. Applies to Hyperledger Fabric and Ethereum.
public func deleteNode(_ input: DeleteNodeInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteNodeOutput> {
return self.client.execute(operation: "DeleteNode", path: "/networks/{networkId}/nodes/{nodeId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns detailed information about a member. Applies only to Hyperledger Fabric.
public func getMember(_ input: GetMemberInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMemberOutput> {
return self.client.execute(operation: "GetMember", path: "/networks/{networkId}/members/{memberId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns detailed information about a network. Applies to Hyperledger Fabric and Ethereum.
public func getNetwork(_ input: GetNetworkInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetNetworkOutput> {
return self.client.execute(operation: "GetNetwork", path: "/networks/{networkId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns detailed information about a node. Applies to Hyperledger Fabric and Ethereum.
public func getNode(_ input: GetNodeInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetNodeOutput> {
return self.client.execute(operation: "GetNode", path: "/networks/{networkId}/nodes/{nodeId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns detailed information about a proposal. Applies only to Hyperledger Fabric.
public func getProposal(_ input: GetProposalInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetProposalOutput> {
return self.client.execute(operation: "GetProposal", path: "/networks/{networkId}/proposals/{proposalId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of all invitations for the current AWS account. Applies only to Hyperledger Fabric.
public func listInvitations(_ input: ListInvitationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListInvitationsOutput> {
return self.client.execute(operation: "ListInvitations", path: "/invitations", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of the members in a network and properties of their configurations. Applies only to Hyperledger Fabric.
public func listMembers(_ input: ListMembersInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListMembersOutput> {
return self.client.execute(operation: "ListMembers", path: "/networks/{networkId}/members", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about the networks in which the current AWS account participates. Applies to Hyperledger Fabric and Ethereum.
public func listNetworks(_ input: ListNetworksInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListNetworksOutput> {
return self.client.execute(operation: "ListNetworks", path: "/networks", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about the nodes within a network. Applies to Hyperledger Fabric and Ethereum.
public func listNodes(_ input: ListNodesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListNodesOutput> {
return self.client.execute(operation: "ListNodes", path: "/networks/{networkId}/nodes", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the list of votes for a specified proposal, including the value of each vote and the unique identifier of the member that cast the vote. Applies only to Hyperledger Fabric.
public func listProposalVotes(_ input: ListProposalVotesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListProposalVotesOutput> {
return self.client.execute(operation: "ListProposalVotes", path: "/networks/{networkId}/proposals/{proposalId}/votes", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of proposals for the network. Applies only to Hyperledger Fabric.
public func listProposals(_ input: ListProposalsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListProposalsOutput> {
return self.client.execute(operation: "ListProposals", path: "/networks/{networkId}/proposals", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of tags for the specified resource. Each tag consists of a key and optional value. For more information about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> {
return self.client.execute(operation: "ListTagsForResource", path: "/tags/{resourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Rejects an invitation to join a network. This action can be called by a principal in an AWS account that has received an invitation to create a member and join a network. Applies only to Hyperledger Fabric.
public func rejectInvitation(_ input: RejectInvitationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RejectInvitationOutput> {
return self.client.execute(operation: "RejectInvitation", path: "/invitations/{invitationId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds or overwrites the specified tags for the specified Amazon Managed Blockchain resource. Each tag consists of a key and optional value. When you specify a tag key that already exists, the tag value is overwritten with the new value. Use UntagResource to remove tag keys. A resource can have up to 50 tags. If you try to create more than 50 tags for a resource, your request fails and returns an error. For more information about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide.
public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> {
return self.client.execute(operation: "TagResource", path: "/tags/{resourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes the specified tags from the Amazon Managed Blockchain resource. For more information about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide.
public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> {
return self.client.execute(operation: "UntagResource", path: "/tags/{resourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a member configuration with new parameters. Applies only to Hyperledger Fabric.
public func updateMember(_ input: UpdateMemberInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateMemberOutput> {
return self.client.execute(operation: "UpdateMember", path: "/networks/{networkId}/members/{memberId}", httpMethod: .PATCH, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a node configuration with new parameters. Applies only to Hyperledger Fabric.
public func updateNode(_ input: UpdateNodeInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateNodeOutput> {
return self.client.execute(operation: "UpdateNode", path: "/networks/{networkId}/nodes/{nodeId}", httpMethod: .PATCH, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Casts a vote for a specified ProposalId on behalf of a member. The member to vote as, specified by VoterMemberId, must be in the same AWS account as the principal that calls the action. Applies only to Hyperledger Fabric.
public func voteOnProposal(_ input: VoteOnProposalInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<VoteOnProposalOutput> {
return self.client.execute(operation: "VoteOnProposal", path: "/networks/{networkId}/proposals/{proposalId}/votes", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension ManagedBlockchain {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: ManagedBlockchain, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| 88.280423 | 967 | 0.743422 |
462262f364886b56c0bc4ec7b775b845cd606cbf | 475 | //
// UserRouterTests.swift
// iOSPruebaCeibaTests
//
// Created by Hector Satizabal on 28/08/21.
//
import XCTest
@testable import iOSPruebaCeiba
class UserRouterTests: XCTestCase {
var router = UserRouter()
func testUserRouter_ShouldReturnNotNil() throws {
XCTAssertNotNil(router.viewController)
}
func testUserRouter_ShouldPushScreenUserPostsReturnNotNil() throws {
router.pushToUserPostsScreen(id: 0, name: "Pedro")
}
}
| 21.590909 | 72 | 0.713684 |
1e361193f65756300b989699088818841151549c | 583 | #if os(iOS)
import SwiftPrelude
import WebKit
public protocol WKWebViewProtocol: UIViewProtocol {
var scrollView: UIScrollView { get }
}
extension WKWebView: WKWebViewProtocol {}
public extension LensHolder where Object: WKWebViewProtocol {
public var scrollView: Lens<Object, UIScrollView> {
return Lens(
view: { $0.scrollView },
set: { $1 }
)
}
}
extension Lens where Whole: WKWebViewProtocol, Part == UIScrollView {
public var delaysContentTouches: Lens<Whole, Bool> {
return Whole.lens.scrollView..Part.lens.delaysContentTouches
}
}
#endif
| 21.592593 | 69 | 0.727273 |
725d098d61a9d2997b8b0a58b0d27cf9eff7601c | 30,119 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
func _NSIndexPathCreateFromIndexes(_ idx1: Int, _ idx2: Int) -> NSObject {
var indexes = (idx1, idx2)
return withUnsafeBytes(of: &indexes) { (ptr) -> NSIndexPath in
return NSIndexPath.init(indexes: ptr.baseAddress!.assumingMemoryBound(to: Int.self), length: 2)
}
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
#endif
/**
`IndexPath` represents the path to a specific node in a tree of nested array collections.
Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node.
*/
public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableCollection, RandomAccessCollection, Comparable, ExpressibleByArrayLiteral {
public typealias ReferenceType = NSIndexPath
public typealias Element = Int
public typealias Index = Array<Int>.Index
public typealias Indices = DefaultIndices<IndexPath>
fileprivate enum Storage : ExpressibleByArrayLiteral {
typealias Element = Int
case empty
case single(Int)
case pair(Int, Int)
case array([Int])
init(arrayLiteral elements: Int...) {
self.init(elements)
}
init(_ elements: [Int]) {
switch elements.count {
case 0:
self = .empty
break
case 1:
self = .single(elements[0])
break
case 2:
self = .pair(elements[0], elements[1])
break
default:
self = .array(elements)
break
}
}
func dropLast() -> Storage {
switch self {
case .empty:
return .empty
case .single:
return .empty
case .pair(let first, _):
return .single(first)
case .array(let indexes):
switch indexes.count {
case 3:
return .pair(indexes[0], indexes[1])
default:
return .array(Array<Int>(indexes.dropLast()))
}
}
}
mutating func append(_ other: Int) {
switch self {
case .empty:
self = .single(other)
break
case .single(let first):
self = .pair(first, other)
break
case .pair(let first, let second):
self = .array([first, second, other])
break
case .array(let indexes):
self = .array(indexes + [other])
break
}
}
mutating func append(contentsOf other: Storage) {
switch self {
case .empty:
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .single(rhsIndex)
break
case .pair(let rhsFirst, let rhsSecond):
self = .pair(rhsFirst, rhsSecond)
break
case .array(let rhsIndexes):
self = .array(rhsIndexes)
break
}
break
case .single(let lhsIndex):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .pair(lhsIndex, rhsIndex)
break
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsIndex, rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array([lhsIndex] + rhsIndexes)
break
}
break
case .pair(let lhsFirst, let lhsSecond):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array([lhsFirst, lhsSecond, rhsIndex])
break
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsFirst, lhsSecond, rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array([lhsFirst, lhsSecond] + rhsIndexes)
break
}
break
case .array(let lhsIndexes):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array(lhsIndexes + [rhsIndex])
break
case .pair(let rhsFirst, let rhsSecond):
self = .array(lhsIndexes + [rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array(lhsIndexes + rhsIndexes)
break
}
break
}
}
mutating func append(contentsOf other: [Int]) {
switch self {
case .empty:
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .single(other[0])
break
case 2:
self = .pair(other[0], other[1])
break
default:
self = .array(other)
break
}
break
case .single(let first):
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .pair(first, other[0])
break
default:
self = .array([first] + other)
break
}
break
case .pair(let first, let second):
switch other.count {
case 0:
// DO NOTHING
break
default:
self = .array([first, second] + other)
break
}
break
case .array(let indexes):
self = .array(indexes + other)
break
}
}
subscript(_ index: Int) -> Int {
get {
switch self {
case .empty:
fatalError("index \(index) out of bounds of count 0")
break
case .single(let first):
precondition(index == 0, "index \(index) out of bounds of count 1")
return first
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "index \(index) out of bounds of count 2")
return index == 0 ? first : second
case .array(let indexes):
return indexes[index]
}
}
set {
switch self {
case .empty:
fatalError("index \(index) out of bounds of count 0")
break
case .single:
precondition(index == 0, "index \(index) out of bounds of count 1")
self = .single(newValue)
break
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "index \(index) out of bounds of count 2")
if index == 0 {
self = .pair(newValue, second)
} else {
self = .pair(first, newValue)
}
break
case .array(let indexes_):
var indexes = indexes_
indexes[index] = newValue
self = .array(indexes)
break
}
}
}
subscript(range: Range<Index>) -> Storage {
get {
switch self {
case .empty:
switch (range.lowerBound, range.upperBound) {
case (0, 0):
return .empty
default:
fatalError("range \(range) is out of bounds of count 0")
}
case .single(let index):
switch (range.lowerBound, range.upperBound) {
case (0, 0): fallthrough
case (1, 1):
return .empty
case (0, 1):
return .single(index)
default:
fatalError("range \(range) is out of bounds of count 1")
}
return self
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
fallthrough
case (1, 1):
fallthrough
case (2, 2):
return .empty
case (0, 1):
return .single(first)
case (1, 2):
return .single(second)
case (0, 2):
return self
default:
fatalError("range \(range) is out of bounds of count 2")
}
case .array(let indexes):
let slice = indexes[range]
switch slice.count {
case 0:
return .empty
case 1:
return .single(slice[0])
case 2:
return .pair(slice[0], slice[1])
default:
return .array(Array<Int>(slice))
}
}
}
set {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "range \(range) is out of bounds of count 0")
self = newValue
break
case .single(let index):
switch (range.lowerBound, range.upperBound, newValue) {
case (0, 0, .empty):
fallthrough
case (1, 1, .empty):
break
case (0, 0, .single(let other)):
self = .pair(other, index)
break
case (0, 0, .pair(let first, let second)):
self = .array([first, second, index])
break
case (0, 0, .array(let other)):
self = .array(other + [index])
break
case (0, 1, .empty):
fallthrough
case (0, 1, .single):
fallthrough
case (0, 1, .pair):
fallthrough
case (0, 1, .array):
self = newValue
case (1, 1, .single(let other)):
self = .pair(index, other)
break
case (1, 1, .pair(let first, let second)):
self = .array([index, first, second])
break
case (1, 1, .array(let other)):
self = .array([index] + other)
break
default:
fatalError("range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([other, first, second])
break
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, first, second])
break
case .array(let other):
self = .array(other + [first, second])
break
}
break
case (0, 1):
switch newValue {
case .empty:
self = .single(second)
break
case .single(let other):
self = .pair(other, second)
break
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, second])
break
case .array(let other):
self = .array(other + [second])
break
}
break
case (0, 2):
self = newValue
break
case (1, 2):
switch newValue {
case .empty:
self = .single(first)
break
case .single(let other):
self = .pair(first, other)
break
case .pair(let otherFirst, let otherSecond):
self = .array([first, otherFirst, otherSecond])
break
case .array(let other):
self = .array([first] + other)
}
break
case (2, 2):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([first, second, other])
break
case .pair(let otherFirst, let otherSecond):
self = .array([first, second, otherFirst, otherSecond])
break
case .array(let other):
self = .array([first, second] + other)
}
break
default:
fatalError("range \(range) is out of bounds of count 2")
}
case .array(let indexes):
var newIndexes = indexes
newIndexes.removeSubrange(range)
switch newValue {
case .empty:
break
case .single(let index):
newIndexes.insert(index, at: range.lowerBound)
break
case .pair(let first, let second):
newIndexes.insert(first, at: range.lowerBound)
newIndexes.insert(second, at: range.lowerBound + 1)
break
case .array(let other):
newIndexes.insert(contentsOf: other, at: range.lowerBound)
break
}
self = Storage(newIndexes)
break
}
}
}
var count: Int {
switch self {
case .empty:
return 0
case .single:
return 1
case .pair:
return 2
case .array(let indexes):
return indexes.count
}
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return count
}
var allValues: [Int] {
switch self {
case .empty: return []
case .single(let index): return [index]
case .pair(let first, let second): return [first, second]
case .array(let indexes): return indexes
}
}
func index(before i: Int) -> Int {
return i - 1
}
func index(after i: Int) -> Int {
return i + 1
}
var description: String {
switch self {
case .empty:
return "[]"
case .single(let index):
return "[\(index)]"
case .pair(let first, let second):
return "[\(first), \(second)]"
case .array(let indexes):
return indexes.description
}
}
func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Int>) throws -> R) rethrows -> R {
switch self {
case .empty:
return try body(UnsafeBufferPointer<Int>(start: nil, count: 0))
case .single(let index_):
var index = index_
return try withUnsafePointer(to: &index) { (start) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: start, count: 1))
}
case .pair(let first, let second):
var pair = (first, second)
return try withUnsafeBytes(of: &pair) { (rawBuffer: UnsafeRawBufferPointer) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: rawBuffer.baseAddress?.assumingMemoryBound(to: Int.self), count: 2))
}
case .array(let indexes):
return try indexes.withUnsafeBufferPointer(body)
}
}
var debugDescription: String { return description }
static func +(_ lhs: Storage, _ rhs: Storage) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func +(_ lhs: Storage, _ rhs: [Int]) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func ==(_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.empty, .empty):
return true
case (.single(let lhsIndex), .single(let rhsIndex)):
return lhsIndex == rhsIndex
case (.pair(let lhsFirst, let lhsSecond), .pair(let rhsFirst, let rhsSecond)):
return lhsFirst == rhsFirst && lhsSecond == rhsSecond
case (.array(let lhsIndexes), .array(let rhsIndexes)):
return lhsIndexes == rhsIndexes
default:
return false
}
}
}
fileprivate var _indexes : Storage
/// Initialize an empty index path.
public init() {
_indexes = []
}
/// Initialize with a sequence of integers.
public init<ElementSequence : Sequence>(indexes: ElementSequence)
where ElementSequence.Iterator.Element == Element {
_indexes = Storage(indexes.map { $0 })
}
/// Initialize with an array literal.
public init(arrayLiteral indexes: Element...) {
_indexes = Storage(indexes)
}
/// Initialize with an array of elements.
public init(indexes: Array<Element>) {
_indexes = Storage(indexes)
}
fileprivate init(storage: Storage) {
_indexes = storage
}
/// Initialize with a single element.
public init(index: Element) {
_indexes = [index]
}
/// Return a new `IndexPath` containing all but the last element.
public func dropLast() -> IndexPath {
return IndexPath(storage: _indexes.dropLast())
}
/// Append an `IndexPath` to `self`.
public mutating func append(_ other: IndexPath) {
_indexes.append(contentsOf: other._indexes)
}
/// Append a single element to `self`.
public mutating func append(_ other: Element) {
_indexes.append(other)
}
/// Append an array of elements to `self`.
public mutating func append(_ other: Array<Element>) {
_indexes.append(contentsOf: other)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Element) -> IndexPath {
var result = _indexes
result.append(other)
return IndexPath(storage: result)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: IndexPath) -> IndexPath {
return IndexPath(storage: _indexes + other._indexes)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Array<Element>) -> IndexPath {
return IndexPath(storage: _indexes + other)
}
public subscript(index: Index) -> Element {
get {
return _indexes[index]
}
set {
_indexes[index] = newValue
}
}
public subscript(range: Range<Index>) -> IndexPath {
get {
return IndexPath(storage: _indexes[range])
}
set {
_indexes[range] = newValue._indexes
}
}
public func makeIterator() -> IndexingIterator<IndexPath> {
return IndexingIterator(_elements: self)
}
public var count: Int {
return _indexes.count
}
public var startIndex: Index {
return _indexes.startIndex
}
public var endIndex: Index {
return _indexes.endIndex
}
public func index(before i: Index) -> Index {
return _indexes.index(before: i)
}
public func index(after i: Index) -> Index {
return _indexes.index(after: i)
}
/// Sorting an array of `IndexPath` using this comparison results in an array representing nodes in depth-first traversal order.
public func compare(_ other: IndexPath) -> ComparisonResult {
let thisLength = count
let otherLength = other.count
let length = Swift.min(thisLength, otherLength)
for idx in 0..<length {
let otherValue = other[idx]
let value = self[idx]
if value < otherValue {
return .orderedAscending
} else if value > otherValue {
return .orderedDescending
}
}
if thisLength > otherLength {
return .orderedDescending
} else if thisLength < otherLength {
return .orderedAscending
}
return .orderedSame
}
public func hash(into hasher: inout Hasher) {
// Note: We compare all indices in ==, so for proper hashing, we must
// also feed them all to the hasher.
//
// To ensure we have unique hash encodings in nested hashing contexts,
// we combine the count of indices as well as the indices themselves.
// (This matches what Array does.)
switch _indexes {
case .empty:
hasher.combine(0)
case let .single(index):
hasher.combine(1)
hasher.combine(index)
case let .pair(first, second):
hasher.combine(2)
hasher.combine(first)
hasher.combine(second)
case let .array(indexes):
hasher.combine(indexes.count)
for index in indexes {
hasher.combine(index)
}
}
}
// MARK: - Bridging Helpers
fileprivate init(nsIndexPath: ReferenceType) {
let count = nsIndexPath.length
if count == 0 {
_indexes = []
} else if count == 1 {
_indexes = .single(nsIndexPath.index(atPosition: 0))
} else if count == 2 {
_indexes = .pair(nsIndexPath.index(atPosition: 0), nsIndexPath.index(atPosition: 1))
} else {
var indexes = Array<Int>(repeating: 0, count: count)
indexes.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int>) -> Void in
nsIndexPath.getIndexes(buffer.baseAddress!, range: NSRange(location: 0, length: count))
}
_indexes = .array(indexes)
}
}
fileprivate func makeReference() -> ReferenceType {
switch _indexes {
case .empty:
return ReferenceType()
case .single(let index):
return ReferenceType(index: index)
case .pair(let first, let second):
return _NSIndexPathCreateFromIndexes(first, second) as! ReferenceType
default:
return _indexes.withUnsafeBufferPointer {
return ReferenceType(indexes: $0.baseAddress, length: $0.count)
}
}
}
public static func ==(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs._indexes == rhs._indexes
}
public static func +(lhs: IndexPath, rhs: IndexPath) -> IndexPath {
return lhs.appending(rhs)
}
public static func +=(lhs: inout IndexPath, rhs: IndexPath) {
lhs.append(rhs)
}
public static func <(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
public static func <=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == .orderedAscending || order == .orderedSame
}
public static func >(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == .orderedDescending
}
public static func >=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == .orderedDescending || order == .orderedSame
}
}
extension IndexPath : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return _indexes.description
}
public var debugDescription: String {
return _indexes.debugDescription
}
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
extension IndexPath : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSIndexPath.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexPath {
return makeReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) {
result = IndexPath(nsIndexPath: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) -> Bool {
result = IndexPath(nsIndexPath: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexPath?) -> IndexPath {
guard let src = source else { return IndexPath() }
return IndexPath(nsIndexPath: src)
}
}
extension NSIndexPath : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(IndexPath(nsIndexPath: self))
}
}
extension IndexPath : Codable {
private enum CodingKeys : Int, CodingKey {
case indexes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var indexesContainer = try container.nestedUnkeyedContainer(forKey: .indexes)
var indexes = [Int]()
if let count = indexesContainer.count {
indexes.reserveCapacity(count)
}
while !indexesContainer.isAtEnd {
let index = try indexesContainer.decode(Int.self)
indexes.append(index)
}
self.init(indexes: indexes)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var indexesContainer = container.nestedUnkeyedContainer(forKey: .indexes)
switch self._indexes {
case .empty:
break
case .single(let index):
try indexesContainer.encode(index)
case .pair(let first, let second):
try indexesContainer.encode(first)
try indexesContainer.encode(second)
case .array(let indexes):
try indexesContainer.encode(contentsOf: indexes)
}
}
}
| 35.26815 | 151 | 0.467047 |
e4b6567dc3632f57134a59aa6c3536e94b320dc2 | 2,371 | //
// SearchResultsPageWrapper.swift
// Movie DB
//
// Created by Jonas Frey on 01.08.20.
// Copyright © 2020 Jonas Frey. All rights reserved.
//
import Foundation
/// Deocdes a search result as either a `TMDBMovieSearchResult` or a `TMDBShowSearchResult`.
struct SearchResultsPageWrapper: PageWrapperProtocol {
private struct Empty: Decodable {}
var results: [TMDBSearchResult]
var totalPages: Int
/// Initializes the interal results array from the given decoder
/// - Parameter decoder: The decoder
init(from decoder: Decoder) throws {
self.results = []
// Contains the page and results
let container = try decoder.container(keyedBy: CodingKeys.self)
// Contains the TMDBSearchResults array
// Create two identical containers, so we can extract the same value twice
var arrayContainer = try container.nestedUnkeyedContainer(forKey: .results)
var arrayContainer2 = try container.nestedUnkeyedContainer(forKey: .results)
assert(arrayContainer.count == arrayContainer2.count)
while (!arrayContainer.isAtEnd) {
// Decode the media object as a GenericMedia to read the type
let mediaTypeContainer = try arrayContainer.nestedContainer(keyedBy: GenericMedia.CodingKeys.self)
let mediaType = try mediaTypeContainer.decode(String.self, forKey: .mediaType)
// Decide based on the media type which type to use for decoding
switch mediaType {
case MediaType.movie.rawValue:
self.results.append(try arrayContainer2.decode(TMDBMovieSearchResult.self))
case MediaType.show.rawValue:
self.results.append(try arrayContainer2.decode(TMDBShowSearchResult.self))
default:
// Skip the entry (probably type person)
_ = try? arrayContainer2.decode(Empty.self)
}
}
self.totalPages = try container.decode(Int.self, forKey: .totalPages)
}
enum CodingKeys: String, CodingKey {
case results
case totalPages = "total_pages"
}
private struct GenericMedia: Codable {
var mediaType: String
enum CodingKeys: String, CodingKey {
case mediaType = "media_type"
}
}
}
| 37.634921 | 110 | 0.646141 |
48a726a4ec77aecf66501d57909cab3c54c9698d | 643 | //
// ShowAppliedUniTableViewCell.swift
// CYU
//
// Created by Ankit Mishra on 28/09/17.
// Copyright © 2017 Ankit Mishra. All rights reserved.
//
import UIKit
class ShowAppliedUniTableViewCell: UITableViewCell {
@IBOutlet weak var uniName: UILabel!
@IBOutlet weak var courseName: UILabel!
@IBOutlet weak var imagePreview: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.964286 | 65 | 0.688958 |
ef16d9454568b2bac603c89a4deab80fc70d9cd8 | 2,867 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// 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 Transition
/**
* This is our animation: a single animation layer that, based on the direction of the operation (present/dismiss)
* will set the appropriate transform on the top view.
*/
class SimpleAnimation : TransitionAnimation {
private weak var topView: UIView?
private var targetTransform: CGAffineTransform = .identity
func setup(in operationContext: TransitionOperationContext) {
let context = operationContext.context
let isPresenting = operationContext.operation.isPresenting
// We have to add the toView to the transitionContext, at the appropriate index:
if isPresenting {
context.containerView.addSubview(context.toView)
} else if context.toView.superview == nil {
context.containerView.insertSubview(context.toView, belowSubview: context.fromView)
}
context.toView.frame = context.finalFrame(for: context.toViewController)
// We only animate the view that will be on top:
topView = isPresenting ? context.toView : context.fromView
let hiddenTransform = CGAffineTransform(translationX: 0, y: -context.containerView.bounds.height)
topView?.transform = isPresenting ? hiddenTransform : .identity
targetTransform = isPresenting ? .identity : hiddenTransform
}
var layers: [AnimationLayer] {
return [AnimationLayer(timingParameters: AnimationTimingParameters(animationCurve: .easeOut), animation: animate)]
}
func animate() {
topView?.transform = targetTransform
}
func completion(position: UIViewAnimatingPosition) {}
}
| 42.161765 | 122 | 0.705616 |
698c34a0040781c69c1909b862d1757889649a75 | 5,143 | @testable @_spi(Experimental) import MapboxMaps
@_implementationOnly import MapboxCoreMaps_Private
import CoreLocation
final class MockMapboxMap: MapboxMapProtocol {
var size: CGSize = .zero
var cameraBounds = MapboxMaps.CameraBounds(
bounds: CoordinateBounds(
southwest: CLLocationCoordinate2D(
latitude: -90,
longitude: -180),
northeast: CLLocationCoordinate2D(
latitude: 90,
longitude: 180)),
maxZoom: 20,
minZoom: 0,
maxPitch: 50,
minPitch: 0)
var cameraState = CameraState(
center: CLLocationCoordinate2D(
latitude: 0,
longitude: 0),
padding: UIEdgeInsets(
top: 0,
left: 0,
bottom: 0,
right: 0),
zoom: 0,
bearing: 0,
pitch: 0)
var anchor = CGPoint.zero
let setCameraStub = Stub<MapboxMaps.CameraOptions, Void>()
func setCamera(to cameraOptions: MapboxMaps.CameraOptions) {
setCameraStub.call(with: cameraOptions)
}
let dragStartStub = Stub<CGPoint, Void>()
func dragStart(for point: CGPoint) {
dragStartStub.call(with: point)
}
struct DragCameraOptionsParams: Equatable {
var from: CGPoint
var to: CGPoint
}
let dragCameraOptionsStub = Stub<DragCameraOptionsParams, MapboxMaps.CameraOptions>(defaultReturnValue: CameraOptions())
func dragCameraOptions(from: CGPoint, to: CGPoint) -> MapboxMaps.CameraOptions {
dragCameraOptionsStub.call(with: DragCameraOptionsParams(from: from, to: to))
}
let dragEndStub = Stub<Void, Void>()
func dragEnd() {
dragEndStub.call()
}
struct OnEveryParams {
var eventType: MapEvents.EventKind
var handler: (Event) -> Void
}
let onEveryStub = Stub<OnEveryParams, Cancelable>(defaultReturnValue: MockCancelable())
@discardableResult
func onEvery(_ eventType: MapEvents.EventKind, handler: @escaping (Event) -> Void) -> Cancelable {
onEveryStub.call(with: OnEveryParams(eventType: eventType, handler: handler))
}
let beginAnimationStub = Stub<Void, Void>()
func beginAnimation() {
beginAnimationStub.call()
}
let endAnimationStub = Stub<Void, Void>()
func endAnimation() {
endAnimationStub.call()
}
let beginGestureStub = Stub<Void, Void>()
func beginGesture() {
beginGestureStub.call()
}
let endGestureStub = Stub<Void, Void>()
func endGesture() {
endGestureStub.call()
}
let setViewAnnotationPositionsUpdateListenerStub = Stub<ViewAnnotationPositionsUpdateListener?, Void>()
func setViewAnnotationPositionsUpdateListener(_ listener: ViewAnnotationPositionsUpdateListener?) {
setViewAnnotationPositionsUpdateListenerStub.call(with: listener)
}
struct ViewAnnotationModificationOptions: Equatable {
var id: String
var options: MapboxMaps.ViewAnnotationOptions
}
let addViewAnnotationStub = Stub<ViewAnnotationModificationOptions, Void>()
func addViewAnnotation(withId id: String, options: MapboxMaps.ViewAnnotationOptions) throws {
addViewAnnotationStub.call(with: ViewAnnotationModificationOptions(id: id, options: options))
}
let updateViewAnnotationStub = Stub<ViewAnnotationModificationOptions, Void>()
func updateViewAnnotation(withId id: String, options: MapboxMaps.ViewAnnotationOptions) throws {
updateViewAnnotationStub.call(with: ViewAnnotationModificationOptions(id: id, options: options))
}
let removeViewAnnotationStub = Stub<String, Void>()
func removeViewAnnotation(withId id: String) throws {
removeViewAnnotationStub.call(with: id)
}
let optionsForViewAnnotationWithIdStub = Stub<String, MapboxMaps.ViewAnnotationOptions>(defaultReturnValue: ViewAnnotationOptions())
func options(forViewAnnotationWithId id: String) throws -> MapboxMaps.ViewAnnotationOptions {
return optionsForViewAnnotationWithIdStub.call(with: id)
}
let pointIsAboveHorizonStub = Stub<CGPoint, Bool>(defaultReturnValue: .random())
func pointIsAboveHorizon(_ point: CGPoint) -> Bool {
pointIsAboveHorizonStub.call(with: point)
}
struct CameraForGeometryParams {
var geometry: Geometry
var padding: UIEdgeInsets
var bearing: CGFloat?
var pitch: CGFloat?
}
let cameraForGeometryStub = Stub<CameraForGeometryParams, MapboxMaps.CameraOptions>(defaultReturnValue: .random())
func camera(for geometry: Geometry,
padding: UIEdgeInsets,
bearing: CGFloat?,
pitch: CGFloat?) -> MapboxMaps.CameraOptions {
cameraForGeometryStub.call(with: .init(
geometry: geometry,
padding: padding,
bearing: bearing,
pitch: pitch))
}
let pointStub = Stub<CLLocationCoordinate2D, CGPoint>(defaultReturnValue: .random())
func point(for coordinate: CLLocationCoordinate2D) -> CGPoint {
pointStub.call(with: coordinate)
}
}
| 34.516779 | 136 | 0.676648 |
7197ae1c2b3299513d269bab4bb76b89b4e8f63e | 5,236 | //
// StopsForRoute.swift
// OBAKit
//
// Copyright © Open Transit Software Foundation
// This source code is licensed under the Apache 2.0 license found in the
// LICENSE file in the root directory of this source tree.
//
import Foundation
import MapKit
// swiftlint:disable nesting
/// Retrieve the set of stops serving a particular route, including groups by direction of travel.
///
/// The stops-for-route method first and foremost provides a method for retrieving the set of stops
/// that serve a particular route. In addition to the full set of stops, we provide various
/// “stop groupings” that are used to group the stops into useful collections. Currently, the main
/// grouping provided organizes the set of stops by direction of travel for the route. Finally,
/// this method also returns a set of polylines that can be used to draw the path traveled by the route.
public class StopsForRoute: NSObject, Identifiable, Decodable, HasReferences {
public var id: String {
return routeID
}
let routeID: String
public private(set) var route: Route!
public let rawPolylines: [String]
public lazy var polylines: [MKPolyline] = rawPolylines.compactMap { Polyline(encodedPolyline: $0).mkPolyline }
public lazy var mapRect: MKMapRect = {
var bounds = MKMapRect.null
for p in polylines {
bounds = bounds.union(p.boundingMapRect)
}
return bounds
}()
let stopIDs: [String]
public private(set) var stops: [Stop]!
public private(set) var regionIdentifier: Int?
public let stopGroupings: [StopGrouping]
private enum CodingKeys: String, CodingKey {
case routeID = "routeId"
case rawPolylines = "polylines"
case stopIDs = "stopIds"
case stopGroupings
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
routeID = try container.decode(String.self, forKey: .routeID)
rawPolylines = try container.decode([PolylineEntity].self, forKey: .rawPolylines).compactMap { $0.points }
stopIDs = try container.decode([String].self, forKey: .stopIDs)
stopGroupings = try container.decode([StopGrouping].self, forKey: .stopGroupings)
}
// MARK: - HasReferences
public func loadReferences(_ references: References, regionIdentifier: Int?) {
route = references.routeWithID(routeID)!
stops = references.stopsWithIDs(stopIDs)
stopGroupings.loadReferences(references, regionIdentifier: regionIdentifier)
self.regionIdentifier = regionIdentifier
}
// MARK: - Nested Types
// MARK: - StopGrouping
public class StopGrouping: NSObject, Decodable, HasReferences {
public let ordered: Bool
public let groupingType: String
public let stopGroups: [StopGroup]
public private(set) var regionIdentifier: Int?
private enum CodingKeys: String, CodingKey {
case ordered
case groupingType = "type"
case stopGroups
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
ordered = try container.decode(Bool.self, forKey: .ordered)
groupingType = try container.decode(String.self, forKey: .groupingType)
stopGroups = try container.decode([StopGroup].self, forKey: .stopGroups)
}
public func loadReferences(_ references: References, regionIdentifier: Int?) {
stopGroups.loadReferences(references, regionIdentifier: regionIdentifier)
self.regionIdentifier = regionIdentifier
}
}
// MARK: - StopGroup
public class StopGroup: NSObject, Decodable, HasReferences {
public let id: String
public let name: String
public let groupingType: String
public let polylines: [String]
let stopIDs: [String]
public private(set) var stops = [Stop]()
public private(set) var regionIdentifier: Int?
private enum CodingKeys: String, CodingKey {
case id
case name
case groupingType = "type"
case polylines
case stopIDs = "stopIds"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
let nameContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .name)
name = try nameContainer.decode(String.self, forKey: .name)
groupingType = try nameContainer.decode(String.self, forKey: .groupingType)
let polylineEntities = try container.decode([PolylineEntity].self, forKey: .polylines)
polylines = polylineEntities.compactMap { $0.points }
stopIDs = try container.decode([String].self, forKey: .stopIDs)
}
public func loadReferences(_ references: References, regionIdentifier: Int?) {
stops = references.stopsWithIDs(stopIDs)
self.regionIdentifier = regionIdentifier
}
}
}
| 36.110345 | 114 | 0.668831 |
46845b2812c1e797d361b083d0d6b1808801af44 | 2,102 | //
// AttributedPassword.swift
// Guru
//
// Created by 堅書真太郎 on 2021/08/14.
//
import UIKit
func attributedPassword(_ password: String) -> NSAttributedString {
let charactersInPassword = Array(password)
let attributedText = NSMutableAttributedString(string: password)
for i in 0..<charactersInPassword.count {
let char: Character = charactersInPassword[i]
let range: NSRange = NSRange(location: i, length: 1)
switch true {
case char.isUppercase:
let font: UIFont = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont(name: "Menlo", size: 16.0)!)
let color: UIColor = .systemIndigo
attributedText.addAttribute(NSAttributedString.Key.font, value: font, range: range)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
case char.isLowercase:
let font: UIFont = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont(name: "Menlo", size: 16.0)!)
let color: UIColor = .systemBlue
attributedText.addAttribute(NSAttributedString.Key.font, value: font, range: range)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
case char.isNumber:
let font: UIFont = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont(name: "Menlo", size: 16.0)!)
let color: UIColor = .systemRed
attributedText.addAttribute(NSAttributedString.Key.font, value: font, range: range)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
default:
let font: UIFont = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont(name: "Menlo", size: 16.0)!)
let color: UIColor = .systemOrange
attributedText.addAttribute(NSAttributedString.Key.font, value: font, range: range)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
}
return attributedText
}
| 47.772727 | 117 | 0.678402 |
d6b009bfc664eb917bda28b17d6f128f049ac070 | 3,017 | //
// UnionFind.swift
// Sedgewick
//
// Created by Todd Olsen on 3/11/16.
// Copyright © 2016 Todd Olsen. All rights reserved.
//
private func getPairs(filename: String) -> (count: Int, pairs: [(Int, Int)]) {
let bundle = NSBundle(identifier: "proxpero.Sedgewick")!
let url = bundle.URLForResource(filename, withExtension: "txt")!
let text = try! String(contentsOfURL: url, encoding: NSUTF8StringEncoding)
let entries = text.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let count = Int(entries[0])!
let pairs = entries[1..<entries.endIndex].map { $0.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }.map { (Int($0[0])!, (Int($0[1]))!) }
return (count, pairs)
}
public struct UnionFind {
private var parent: Array<Int>
private var size: Array<Int> = []
public private(set) var count: Int = 0
// public init(n: Int) {
// self.parent = Array<Int>(0..<n)
// self.size = Array<Int>(count: n, repeatedValue: 1)
// self.count = n
// }
public init(filename: String) {
let result = getPairs(filename)
self.parent = Array<Int>(0..<result.count)
self.size = Array<Int>(count: result.count, repeatedValue: 1)
self.count = result.count
read(result.pairs)
}
public init(n: Int, _ pairs: [(Int, Int)] = []) {
self.parent = Array<Int>(0..<n)
self.size = Array<Int>(count: n, repeatedValue: 1)
self.count = n
read(pairs)
}
mutating public func read(pairs: [(Int, Int)]) {
for (p, q) in pairs {
union(p, q)
}
}
mutating public func union(p: Int, _ q: Int) {
let i = root(p)
let j = root(q)
if i == j { return }
if size[i] < size[j] {
parent[i] = j
var sizej = size[j]
sizej += size[i]
size[j] += size[i]
assert(size[j] == sizej)
} else {
parent[j] = i
size[i] += size[j]
var sizei = size[i]
sizei += size[j]
size[i] += size[j]
assert(size[i] == sizei)
}
count -= 1
}
mutating public func connected(p: Int, _ q: Int) -> Bool {
return root(p) == root(q)
}
mutating func root(i: Int) -> Int {
var root = i
while root != parent[root] {
parent[root] = parent[parent[root]]
root = parent[root]
}
return root
}
// mutating func find(p: Int) -> Int {
// var root = p
// while root != parent[root] {
// root = parent[root]
// }
//
// var pp = p
// while pp != root {
// let newp = parent[pp]
// parent[pp] = root
// pp = newp
// }
// return root
// }
}
| 27.18018 | 173 | 0.49884 |
3801c4701e5f605bec7788b3790f48d972c3b32b | 826 | //
// TweetTableViewCell.swift
// twitter
//
// Created by Daniel Margulis on 2/21/16.
// Copyright © 2016 Daniel Margulis. All rights reserved.
//
import UIKit
class TweetTableViewCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.736842 | 63 | 0.673123 |
284022beee73a1e878625e843be4fdf4af5c9618 | 4,147 | //
// Request.swift
// web3swift
//
// Created by Dmitry on 14/12/2018.
// Copyright © 2018 Bankex Foundation. All rights reserved.
//
import Foundation
import PromiseKit
enum JsonRpcError: Error {
case syntaxError(code: Int, message: String)
case responseError(code: Int, message: String)
var localizedDescription: String {
switch self {
case let .syntaxError(code: code, message: message):
return "Json rpc syntax error: \(message) (\(code))"
case let .responseError(code: code, message: message):
return "Request failed: \(message) (\(code))"
}
}
}
/// Work in progress. Will be released in 2.2
open class Request {
public var id = Counter.increment()
public var method: String
public var promise: Promise<AnyReader>
public var resolver: Resolver<AnyReader>
public init(method: String) {
self.method = method
(promise,resolver) = Promise.pending()
}
open func response(data: AnyReader) throws {
}
open func failed(error: Error) {
}
open func request() -> [Any] {
return []
}
open func requestBody() -> Any {
var dictionary = [String: Any]()
dictionary["jsonrpc"] = "2.0"
dictionary["method"] = method
dictionary["id"] = id
dictionary["params"] = request()
return dictionary
}
open func request(url: URL) throws -> URLRequest {
var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let body = requestBody()
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
return urlRequest
}
open func checkJsonRpcSyntax(data: AnyReader) throws {
try data.at("jsonrpc").string().starts(with: "2.")
if let error = try? data.at("error") {
let code = try error.at("code").int()
let message = try error.at("message").string()
if data.contains("id") {
throw JsonRpcError.responseError(code: code, message: message)
} else {
throw JsonRpcError.syntaxError(code: code, message: message)
}
} else {
try data.at("id").int()
}
}
open func _response(data: AnyReader) throws {
try checkJsonRpcSyntax(data: data)
let result = try data.at("result")
try response(data: result)
resolver.fulfill(result)
}
open func _failed(error: Error) {
failed(error: error)
resolver.reject(error)
}
}
/// Work in progress. Will be released in 2.2
open class CustomRequest: Request {
public var parameters: [Any]
public init(method: String, parameters: [Any]) {
self.parameters = parameters
super.init(method: method)
}
open override func request() -> [Any] {
return parameters
}
}
/// Work in progress. Will be released in 2.2
open class RequestBatch: Request {
private(set) var requests = [Request]()
public init() {
super.init(method: "")
}
open func append(_ request: Request) {
if let batch = request as? RequestBatch {
requests.append(contentsOf: batch.requests)
} else {
requests.append(request)
}
}
open override func response(data: AnyReader) throws {
try data.array {
let id = try $0.at("id").int()
guard let request = requests.first(where: {$0.id == id}) else { return }
do {
try request._response(data: $0)
} catch {
request._failed(error: error)
}
}
}
open override func _response(data: AnyReader) throws {
try response(data: data)
resolver.fulfill(data)
}
open override func requestBody() -> Any {
return requests.map { $0.requestBody() }
}
}
| 30.492647 | 91 | 0.588859 |
169c4af1f2d46245bcdeddc02b2d0219c48845c5 | 29,076 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Task -------------------------------------------------------------------
/// An asynchronous task (just "Task" hereafter) is the analogue of a thread for
/// asynchronous functions. All asynchronous functions run as part of some task.
///
/// An instance of `Task` always represents a top-level task. The instance
/// can be used to await its completion, cancel the task, etc., The task will
/// run to completion even if there are no other instances of the `Task`.
///
/// `Task` also provides appropriate context-sensitive static functions which
/// operate on the "current" task, which might either be a detached task or
/// a child task. Because all such functions are `async` they can only
/// be invoked as part of an existing task, and therefore are guaranteed to be
/// effective.
///
/// A task's execution can be seen as a series of periods where the task was
/// running. Each such period ends at a suspension point or -- finally -- the
/// completion of the task.
///
/// These partial periods towards the task's completion are
/// individually schedulable as jobs. Jobs are generally not interacted
/// with by end-users directly, unless implementing a scheduler.
@available(SwiftStdlib 5.5, *)
public struct Task<Success, Failure: Error>: Sendable {
internal let _task: Builtin.NativeObject
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
}
@available(SwiftStdlib 5.5, *)
extension Task {
/// Wait for the task to complete, returning (or throwing) its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
public var value: Success {
get async throws {
return try await _taskFutureGetThrowing(_task)
}
}
/// Wait for the task to complete, returning (or throwing) its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
/// Wait for the task to complete, returning its `Result`.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
public var result: Result<Success, Failure> {
get async {
do {
return .success(try await value)
} catch {
return .failure(error as! Failure) // as!-safe, guaranteed to be Failure
}
}
}
/// Attempt to cancel the task.
///
/// Whether this function has any effect is task-dependent.
///
/// For a task to respect cancellation it must cooperatively check for it
/// while running. Many tasks will check for cancellation before beginning
/// their "actual work", however this is not a requirement nor is it guaranteed
/// how and when tasks check for cancellation in general.
public func cancel() {
Builtin.cancelAsyncTask(_task)
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Wait for the task to complete, returning its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// The task this refers to may check for cancellation, however
/// since it is not-throwing it would have to handle it using some other
/// way than throwing a `CancellationError`, e.g. it could provide a neutral
/// value of the `Success` type, or encode that cancellation has occurred in
/// that type itself.
public var value: Success {
get async {
return await _taskFutureGet(_task)
}
}
}
@available(SwiftStdlib 5.5, *)
extension Task: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.5, *)
extension Task: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Task Priority ----------------------------------------------------------
/// Task priority may inform decisions an `Executor` makes about how and when
/// to schedule tasks submitted to it.
///
/// ### Priority scheduling
/// An executor MAY utilize priority information to attempt running higher
/// priority tasks first, and then continuing to serve lower priority tasks.
///
/// The exact semantics of how priority is treated are left up to each
/// platform and `Executor` implementation.
///
/// ### Priority inheritance
/// Child tasks automatically inherit their parent task's priority.
///
/// Detached tasks (created by `Task.detached`) DO NOT inherit task priority,
/// as they are "detached" from their parent tasks after all.
///
/// ### Priority elevation
/// In some situations the priority of a task must be elevated (or "escalated", "raised"):
///
/// - if a `Task` running on behalf of an actor, and a new higher-priority
/// task is enqueued to the actor, its current task must be temporarily
/// elevated to the priority of the enqueued task, in order to allow the new
/// task to be processed at--effectively-- the priority it was enqueued with.
/// - this DOES NOT affect `Task.currentPriority()`.
/// - if a task is created with a `Task.Handle`, and a higher-priority task
/// calls the `await handle.get()` function the priority of this task must be
/// permanently increased until the task completes.
/// - this DOES affect `Task.currentPriority()`.
///
/// TODO: Define the details of task priority; It is likely to be a concept
/// similar to Darwin Dispatch's QoS; bearing in mind that priority is not as
/// much of a thing on other platforms (i.e. server side Linux systems).
@available(SwiftStdlib 5.5, *)
public struct TaskPriority: RawRepresentable, Sendable {
public typealias RawValue = UInt8
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static let high: TaskPriority = .init(rawValue: 0x19)
public static let userInitiated: TaskPriority = high
public static let `default`: TaskPriority = .init(rawValue: 0x15)
public static let low: TaskPriority = .init(rawValue: 0x11)
public static let utility: TaskPriority = low
public static let background: TaskPriority = .init(rawValue: 0x09)
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Equatable {
public static func == (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue == rhs.rawValue
}
public static func != (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue != rhs.rawValue
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Comparable {
public static func < (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue <= rhs.rawValue
}
public static func > (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue > rhs.rawValue
}
public static func >= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue >= rhs.rawValue
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Codable { }
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
/// Returns the `current` task's priority.
///
/// If no current `Task` is available, queries the system to determine the
/// priority at which the current function is running. If the system cannot
/// provide an appropriate priority, returns `Priority.default`.
///
/// - SeeAlso: `TaskPriority`
public static var currentPriority: TaskPriority {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let task = task {
return task.priority
}
// Otherwise, query the system.
return TaskPriority(rawValue: UInt8(0))
}
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority {
/// Downgrade user-interactive to user-initiated.
var _downgradeUserInteractive: TaskPriority {
return self
}
}
// ==== Job Flags --------------------------------------------------------------
/// Flags for schedulable jobs.
///
/// This is a port of the C++ FlagSet.
@available(SwiftStdlib 5.5, *)
struct JobFlags {
/// Kinds of schedulable jobs.
enum Kind: Int32 {
case task = 0
}
/// The actual bit representation of these flags.
var bits: Int32 = 0
/// The kind of job described by these flags.
var kind: Kind {
get {
Kind(rawValue: bits & 0xFF)!
}
set {
bits = (bits & ~0xFF) | newValue.rawValue
}
}
/// Whether this is an asynchronous task.
var isAsyncTask: Bool { kind == .task }
/// The priority given to the job.
var priority: TaskPriority? {
get {
let value = (Int(bits) & 0xFF00) >> 8
if value == 0 {
return nil
}
return TaskPriority(rawValue: UInt8(value))
}
set {
bits = (bits & ~0xFF00) | Int32((Int(newValue?.rawValue ?? 0) << 8))
}
}
/// Whether this is a child task.
var isChildTask: Bool {
get {
(bits & (1 << 24)) != 0
}
set {
if newValue {
bits = bits | 1 << 24
} else {
bits = (bits & ~(1 << 24))
}
}
}
/// Whether this is a future.
var isFuture: Bool {
get {
(bits & (1 << 25)) != 0
}
set {
if newValue {
bits = bits | 1 << 25
} else {
bits = (bits & ~(1 << 25))
}
}
}
/// Whether this is a group child.
var isGroupChildTask: Bool {
get {
(bits & (1 << 26)) != 0
}
set {
if newValue {
bits = bits | 1 << 26
} else {
bits = (bits & ~(1 << 26))
}
}
}
/// Whether this is a task created by the 'async' operation, which
/// conceptually continues the work of the synchronous code that invokes
/// it.
var isContinuingAsyncTask: Bool {
get {
(bits & (1 << 27)) != 0
}
set {
if newValue {
bits = bits | 1 << 27
} else {
bits = (bits & ~(1 << 27))
}
}
}
}
// ==== Task Creation ----------------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Run given `operation` as asynchronously in its own top-level task.
///
/// The `async` function should be used when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached`, the async function creates a separate, top-level
/// task.
///
/// Unlike `Task.detached`, the task creating by the `Task` initializer
/// inherits the priority and actor context of the caller, so the `operation`
/// is treated more like an asynchronous extension to the synchronous
/// operation.
///
/// - Parameters:
/// - priority: priority of the task. If nil, the priority will come from
/// Task.currentPriority.
/// - operation: the operation to execute
@discardableResult
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> Success
) {
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority ?? Task<Never, Never>.currentPriority._downgradeUserInteractive
flags.isFuture = true
flags.isContinuingAsyncTask = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(Int(flags.bits), /*options*/nil, operation)
// Copy all task locals to the newly created task.
// We must copy them rather than point to the current task since the new task
// is not structured and may out-live the current task.
//
// WARNING: This MUST be done BEFORE we enqueue the task,
// because it acts as-if it was running inside the task and thus does not
// take any extra steps to synchronize the task-local operations.
_taskLocalsCopy(to: task)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
self._task = task
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Error {
/// Run given `operation` as asynchronously in its own top-level task.
///
/// This initializer creates asynchronous work on behalf of the synchronous function that calls it.
/// Like `Task.detached`, this initializer creates a separate, top-level task.
/// Unlike `Task.detached`, the task created inherits the priority and
/// actor context of the caller, so the `operation` is treated more like an
/// asynchronous extension to the synchronous operation.
///
/// - Parameters:
/// - priority: priority of the task. If nil, the priority will come from
/// Task.currentPriority.
/// - operation: the operation to execute
@discardableResult
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> Success
) {
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority ?? Task<Never, Never>.currentPriority._downgradeUserInteractive
flags.isFuture = true
flags.isContinuingAsyncTask = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(Int(flags.bits), /*options*/nil, operation)
// Copy all task locals to the newly created task.
// We must copy them rather than point to the current task since the new task
// is not structured and may out-live the current task.
//
// WARNING: This MUST be done BEFORE we enqueue the task,
// because it acts as-if it was running inside the task and thus does not
// take any extra steps to synchronize the task-local operations.
_taskLocalsCopy(to: task)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
self._task = task
}
}
// ==== Detached Tasks ---------------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Run given throwing `operation` as part of a new top-level task.
///
/// Creating detached tasks should, generally, be avoided in favor of using
/// `async` functions, `async let` declarations and `await` expressions - as
/// those benefit from structured, bounded concurrency which is easier to reason
/// about, as well as automatically inheriting the parent tasks priority,
/// task-local storage, deadlines, as well as being cancelled automatically
/// when their parent task is cancelled. Detached tasks do not get any of those
/// benefits, and thus should only be used when an operation is impossible to
/// be modelled with child tasks.
///
/// ### Cancellation
/// A detached task always runs to completion unless it is explicitly cancelled.
/// Specifically, dropping a detached tasks `Task` does _not_ automatically
/// cancel given task.
///
/// Cancelling a task must be performed explicitly via `cancel()`.
///
/// - Note: it is generally preferable to use child tasks rather than detached
/// tasks. Child tasks automatically carry priorities, task-local state,
/// deadlines and have other benefits resulting from the structured
/// concurrency concepts that they model. Consider using detached tasks only
/// when strictly necessary and impossible to model operations otherwise.
///
/// - Parameters:
/// - priority: priority of the task
/// - operation: the operation to execute
/// - Returns: handle to the task, allowing to `await get()` on the
/// tasks result or `cancel` it. If the operation fails the handle will
/// throw the error the operation has thrown when awaited on.
@discardableResult
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> Success
) -> Task<Success, Failure> {
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority ?? .unspecified
flags.isFuture = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(Int(flags.bits), /*options*/nil, operation)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
return Task(task)
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Error {
/// Run given throwing `operation` as part of a new top-level task.
///
/// Creating detached tasks should, generally, be avoided in favor of using
/// `async` functions, `async let` declarations and `await` expressions - as
/// those benefit from structured, bounded concurrency which is easier to reason
/// about, as well as automatically inheriting the parent tasks priority,
/// task-local storage, deadlines, as well as being cancelled automatically
/// when their parent task is cancelled. Detached tasks do not get any of those
/// benefits, and thus should only be used when an operation is impossible to
/// be modelled with child tasks.
///
/// ### Cancellation
/// A detached task always runs to completion unless it is explicitly cancelled.
/// Specifically, dropping a detached tasks `Task.Handle` does _not_ automatically
/// cancel given task.
///
/// Cancelling a task must be performed explicitly via `handle.cancel()`.
///
/// - Note: it is generally preferable to use child tasks rather than detached
/// tasks. Child tasks automatically carry priorities, task-local state,
/// deadlines and have other benefits resulting from the structured
/// concurrency concepts that they model. Consider using detached tasks only
/// when strictly necessary and impossible to model operations otherwise.
///
/// - Parameters:
/// - priority: priority of the task
/// - executor: the executor on which the detached closure should start
/// executing on.
/// - operation: the operation to execute
/// - Returns: handle to the task, allowing to `await handle.get()` on the
/// tasks result or `cancel` it. If the operation fails the handle will
/// throw the error the operation has thrown when awaited on.
@discardableResult
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority ?? .unspecified
flags.isFuture = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(Int(flags.bits), /*options*/nil, operation)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
return Task(task)
}
}
// ==== Async Sleep ------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
/// Suspends the current task for _at least_ the given duration
/// in nanoseconds.
///
/// This function does _not_ block the underlying thread.
public static func sleep(_ duration: UInt64) async {
let currentTask = Builtin.getCurrentAsyncTask()
let priority = getJobFlags(currentTask).priority ?? Task.currentPriority._downgradeUserInteractive
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(priority: Int(priority.rawValue), continuation: continuation)
_enqueueJobGlobalWithDelay(duration, job)
}
}
}
// ==== Voluntary Suspension -----------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
/// Explicitly suspend the current task, potentially giving up execution actor
/// of current actor/task, allowing other tasks to execute.
///
/// This is not a perfect cure for starvation;
/// if the task is the highest-priority task in the system, it might go
/// immediately back to executing.
public static func yield() async {
let currentTask = Builtin.getCurrentAsyncTask()
let priority = getJobFlags(currentTask).priority ?? Task.currentPriority._downgradeUserInteractive
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(priority: Int(priority.rawValue), continuation: continuation)
_enqueueJobGlobal(job)
}
}
}
// ==== UnsafeCurrentTask ------------------------------------------------------
/// Calls the given closure with the with the "current" task in which this
/// function was invoked.
///
/// If invoked from an asynchronous function the task will always be non-nil,
/// as an asynchronous function is always running within some task.
/// However if invoked from a synchronous function the task may be nil,
/// meaning that the function is not executing within a task, i.e. there is no
/// asynchronous context available in the call stack.
///
/// It is generally not safe to escape/store the `UnsafeCurrentTask` for future
/// use, as some operations on it may only be performed from the same task
/// that it is representing.
///
/// It is possible to obtain a `Task` fom the `UnsafeCurrentTask` which is safe
/// to access from other tasks or even store for future reference e.g. equality
/// checks.
@available(SwiftStdlib 5.5, *)
public func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T {
guard let _task = _getCurrentAsyncTask() else {
return try body(nil)
}
// FIXME: This retain seems pretty wrong, however if we don't we WILL crash
// with "destroying a task that never completed" in the task's destroy.
// How do we solve this properly?
Builtin.retain(_task)
return try body(UnsafeCurrentTask(_task))
}
/// An *unsafe* 'current' task handle.
///
/// An `UnsafeCurrentTask` should not be stored for "later" access.
///
/// Storing an `UnsafeCurrentTask` has no implication on the task's actual lifecycle.
///
/// The sub-set of APIs of `UnsafeCurrentTask` which also exist on `Task` are
/// generally safe to be invoked from any task/thread.
///
/// All other APIs must not, be called 'from' any other task than the one
/// represented by this handle itself. Doing so may result in undefined behavior,
/// and most certainly will break invariants in other places of the program
/// actively running on this task.
@available(SwiftStdlib 5.5, *)
public struct UnsafeCurrentTask {
internal let _task: Builtin.NativeObject
// May only be created by the standard library.
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
/// Returns `true` if the task is cancelled, and should stop executing.
///
/// - SeeAlso: `checkCancellation()`
public var isCancelled: Bool {
_taskIsCancelled(_task)
}
/// Returns the `current` task's priority.
///
/// - SeeAlso: `TaskPriority`
/// - SeeAlso: `Task.currentPriority`
public var priority: TaskPriority {
getJobFlags(_task).priority ?? .unspecified
}
}
@available(SwiftStdlib 5.5, *)
extension UnsafeCurrentTask: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.5, *)
extension UnsafeCurrentTask: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Internal ---------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getCurrent")
func _getCurrentAsyncTask() -> Builtin.NativeObject?
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getJobFlags")
func getJobFlags(_ task: Builtin.NativeObject) -> JobFlags
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_enqueueGlobal")
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_enqueueGlobalWithDelay")
@usableFromInline
func _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_asyncMainDrainQueue")
public func _asyncMainDrainQueue() -> Never
@available(SwiftStdlib 5.5, *)
public func _runAsyncMain(_ asyncFun: @escaping () async throws -> ()) {
Task.detached {
do {
#if !os(Windows)
Builtin.hopToActor(MainActor.shared)
#endif
try await asyncFun()
exit(0)
} catch {
_errorInMain(error)
}
}
_asyncMainDrainQueue()
}
// FIXME: both of these ought to take their arguments _owned so that
// we can do a move out of the future in the common case where it's
// unreferenced
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_future_wait")
public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_future_wait_throwing")
public func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_cancel")
func _taskCancel(_ task: Builtin.NativeObject)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_isCancelled")
func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_createNullaryContinuationJob")
func _taskCreateNullaryContinuationJob(priority: Int, continuation: Builtin.RawUnsafeContinuation) -> Builtin.Job
@available(SwiftStdlib 5.5, *)
@usableFromInline
@_silgen_name("swift_task_isCurrentExecutor")
func _taskIsCurrentExecutor(_ executor: Builtin.Executor) -> Bool
@available(SwiftStdlib 5.5, *)
@usableFromInline
@_silgen_name("swift_task_reportUnexpectedExecutor")
func _reportUnexpectedExecutor(_ _filenameStart: Builtin.RawPointer,
_ _filenameLength: Builtin.Word,
_ _filenameIsASCII: Builtin.Int1,
_ _line: Builtin.Word,
_ _executor: Builtin.Executor)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getCurrentThreadPriority")
func _getCurrentThreadPriority() -> Int
#if _runtime(_ObjC)
/// Intrinsic used by SILGen to launch a task for bridging a Swift async method
/// which was called through its ObjC-exported completion-handler-based API.
@available(SwiftStdlib 5.5, *)
@_alwaysEmitIntoClient
@usableFromInline
internal func _runTaskForBridgedAsyncMethod(@_inheritActorContext _ body: __owned @Sendable @escaping () async -> Void) {
Task(operation: body)
}
#endif
| 36.119255 | 121 | 0.677672 |
14c119ed7a05c672f472b158e4e7824a91e4eb58 | 30,233 | //
// GXExposureAlertsManager.swift
//
import Foundation
import ExposureNotification
import BackgroundTasks
@available(iOS 12.5, *)
class GXExposureAlertsManager {
static let shared = GXExposureAlertsManager()
internal static let isDeviceSupported: Bool = UIDevice.current.model == "iPhone"
internal static let isENManagerAvailable: Bool = NSClassFromString("ENManager") != nil
private let enManager: ENManager!
private var activationError: Error? = nil {
didSet {
if let error = activationError {
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure Notification manager activation failed with error: \(error)", for: .general, with: .error, logToConsole: true)
}
}
}
}
private var waitingForActivationOp: BlockOperation? = nil
init() {
if #available(iOS 13.5, *) {
Self.registerDetectionBackgroundTask()
}
guard Self.isENManagerAvailable, Self.isDeviceSupported else {
enManager = nil
activationError = NSError.defaultGXError(withDeveloperDescription: "Exposure Notification API is not available on this device.")
return
}
enManager = ENManager()
let waitingForActivationOp_ = BlockOperation()
waitingForActivationOp = waitingForActivationOp_
if #available(iOS 13.0, *) { }
else { // iOS 12.5
registerDetectionLaunchActivityHandler() // Before activation
}
enManager.activate { error in
self.waitingForActivationOp = nil
self.activationError = error
gx_dispatch_on_main_queue {
if !waitingForActivationOp_.executionBlocks.isEmpty {
waitingForActivationOp_.start()
DispatchQueue.global(qos: .background).async {
waitingForActivationOp_.waitUntilFinished() // retain op until finised
}
}
if #available(iOS 13.5, *) {
Self.scheduleBackgroundTaskIfNeeded()
}
}
}
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(self.onExposureDetectionMinIntervalDidChange),
name: GXExposureAlertsLocalStorage.Notifications.exposureDetectionMinIntervalDidChange,
object: GXExposureAlertsLocalStorage.shared)
}
deinit {
guard Self.isDeviceSupported else {
return
}
enManager.invalidate()
NotificationCenter.default.removeObserver(self)
}
public func isEnabled(_ completion: @escaping (Result<Bool, Error>) -> Void) {
executeAfterSuccessfulActivation(failureCompletion: completion) {
var enabled = self.enManager.exposureNotificationEnabled
if enabled && GXExposureAlertsLocalStorage.shared.lastStartedExposureConfiguration == nil {
// Re-enable is required.
enabled = false
self.stop { (_) in }
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure Notification manager was enabled but has no configuration. Re-enable is required, disable.", for: .general, with: .debug, logToConsole: true)
}
}
completion(.success(enabled))
}
}
public func isBluetoothEnabled(_ completion: @escaping (Result<Bool, Error>) -> Void) {
executeAfterSuccessfulActivation(failureCompletion: completion) {
completion(.success(self.enManager.exposureNotificationStatus != .bluetoothOff))
}
}
public func start(config: ENExposureConfiguration, completion: @escaping ENErrorHandler) {
self.setEnabled(true) { (error) in
if error == nil {
GXExposureAlertsLocalStorage.shared.lastStartedExposureConfiguration = .init(enConfig: config)
if #available(iOS 13.5, *) {
Self.scheduleBackgroundTaskIfNeeded()
}
}
completion(error)
}
}
public func stop(completion: @escaping ENErrorHandler) {
self.setEnabled(false) { (error) in
if error == nil {
GXExposureAlertsLocalStorage.shared.lastStartedExposureConfiguration = nil
if #available(iOS 13.5, *) {
Self.cancelPendingBackgroundTask()
}
}
completion(error)
}
}
public func getDiagnosisKeysWithCompletionHandler(completion: @escaping (Result<[ENTemporaryExposureKey], Error>) -> Void) {
executeAfterSuccessfulActivation(failureCompletion: completion) {
self.enManager.getDiagnosisKeys { (keys, error) in
if let error = error {
completion(.failure(error))
}
else {
completion(.success(keys!))
}
}
}
}
// MARK - Notification Observers
@objc private func onExposureDetectionMinIntervalDidChange() {
if #available(iOS 13.5, *) {
Self.scheduleBackgroundTaskIfNeeded()
}
}
// MARK - Private Helpers
private func executeAfterActivation(_ handler: @escaping () -> Void) {
if waitingForActivationOp != nil {
gx_dispatch_on_main_queue {
if let op = self.waitingForActivationOp {
op.addExecutionBlock(handler)
}
else {
handler()
}
}
}
else {
handler()
}
}
private func executeAfterSuccessfulActivation<T>(failureCompletion: @escaping (Result<T, Error>) -> Void, successfulHandler: @escaping () -> Void) {
executeAfterActivation {
if let error = self.activationError {
failureCompletion(.failure(error))
}
else {
successfulHandler()
}
}
}
private func executeAfterSuccessfulActivation(errorCompletion: @escaping (Error?) -> Void, successfulHandler: @escaping () -> Void) {
executeAfterActivation {
if let error = self.activationError {
errorCompletion(error)
}
else {
successfulHandler()
}
}
}
private func setEnabled(_ enabled: Bool, completion: @escaping ENErrorHandler) {
executeAfterSuccessfulActivation(errorCompletion: completion) {
let willRequestAuthorization = enabled && ENManager.authorizationStatus == .unknown
self.enManager.setExposureNotificationEnabled(enabled) { (error) in
guard let enError = error as? ENError else {
completion(error)
return
}
let completionError: Error
let userCanceledPermissionRequest = willRequestAuthorization && enError.code == ENError.notAuthorized
if userCanceledPermissionRequest {
completionError = NSError.userCancelledError()
}
else if ENManager.authorizationStatus == .notAuthorized {
completionError = NSError.permissionDeniedErrorWithGoToSettingsRecoveryAttempter()
}
else {
completionError = enError
}
completion(completionError)
}
}
}
private var detectingExposures = false
private var keysDownloaderURLSession: URLSession? = nil {
didSet {
if let oldSession = oldValue, oldValue != keysDownloaderURLSession {
oldSession.invalidateAndCancel()
}
}
}
@discardableResult
internal func detectExposures(completionHandler: ((Bool) -> Void)? = nil) -> Progress {
let progress = Progress()
executeAfterActivation {
guard self.activationError == nil else {
completionHandler?(false)
return
}
self.activatedDetectExposures(progress: progress, completionHandler: completionHandler)
}
return progress
}
private func activatedDetectExposures(progress: Progress, completionHandler: ((Bool) -> Void)? = nil) {
// Disallow concurrent exposure detection, because if allowed we might try to detect the same diagnosis keys more than once
guard !detectingExposures, !progress.isCancelled, ENManager.authorizationStatus == .authorized,
let configuration = GXExposureAlertsLocalStorage.shared.lastStartedExposureConfiguration else {
completionHandler?(false)
return
}
detectingExposures = true
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure detection session START", for: .general, with: .debug, logToConsole: true)
}
let tmpLocalKeysDirectoryURL = FileManager.default.temporaryDirectory.appendingPathComponent("GXExposureNotificationSession", isDirectory: true)
func finish(_ result: Result<GXExposureAlertsLocalStorage.ExposureDetectionSessionResult, Error>) {
try? FileManager.default.removeItem(at: tmpLocalKeysDirectoryURL) // Clean-up
let success: Bool
if progress.isCancelled {
if #available(iOS 13.5, *) {
GXExposureAlertsManager.scheduleBackgroundTaskIfNeeded(earliestBeginDate: nil, verifyPendingTasks: false)
}
success = false
} else {
switch result {
case let .success(sessionResult):
GXExposureAlertsLocalStorage.shared.lastExposureDetectionResult = sessionResult
if #available(iOS 13.5, *) {
GXExposureAlertsManager.scheduleBackgroundTaskIfNeeded(earliestBeginDate: nil, verifyPendingTasks: false)
}
if logService.isLogEnabled {
logService.logMessage("Exposure detection session ended: \(sessionResult.sessionTimeStamp) with matches: \(sessionResult.matchedKeyCount)", for: .general, with: .debug, logToConsole: true)
}
success = true
case let .failure(error):
var retryTimeInterval: TimeInterval? = nil
let nsError = error as NSError
if nsError.isNetworkPossibleError() {
retryTimeInterval = 10 * 60
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure detection session failed with network error: \(error)", for: .network, with: .debug, logToConsole: true)
}
}
else {
let logService = GXLog.loggerService()
if logService.isLogEnabled, !nsError.isUserCancelledError() {
logService.logMessage("Exposure detection session failed with error: \(error)", for: .general, with: .error, logToConsole: true)
}
if let enError = error as? ENError {
switch enError.code {
case .restricted:
break
case .insufficientStorage, .insufficientMemory:
retryTimeInterval = 6 * 60 * 60
default:
retryTimeInterval = 12 * 60 * 60
}
}
else {
retryTimeInterval = 12 * 60 * 60
}
}
if let retryTimeInterval = retryTimeInterval {
if #available(iOS 13.5, *) {
GXExposureAlertsManager.scheduleBackgroundTaskIfNeeded(earliestBeginDate: Date(timeIntervalSinceNow: retryTimeInterval), verifyPendingTasks: false)
}
}
success = false
}
}
detectingExposures = false
if logService.isLogEnabled {
logService.logMessage("Exposure detection session END (Success: \(success))", for: .general, with: .debug, logToConsole: true)
}
if success, let sessionResult = GXExposureAlertsLocalStorage.shared.lastExposureDetectionResult, sessionResult.matchedKeyCount > 0 {
gx_dispatch_on_main_queue { // Fire Event on main queue
let eventName = GXEOExposureNotification.externalObjectName.appending(".OnExposureDetected")
if let completionHandler = completionHandler, GXExecutionEnvironmentHelper.applicationState == .background {
let completionDispatchGroup = DispatchGroup()
completionDispatchGroup.enter()
GXActionExObjEventsHelper.dispatchExternalObjectEvent(eventName,
withParameters: nil,
outParametersIndexes: nil,
serialHandling: false,
concurrencyMode: .default)
{ (_) in
completionDispatchGroup.leave()
}
DispatchQueue.global(qos: .utility).async {
_ = completionDispatchGroup.wait(timeout: .now() + .seconds(3))
completionHandler(true)
}
}
else {
GXActionExObjEventsHelper.dispatchExternalObjectEvent(eventName)
completionHandler?(true)
}
}
}
else {
completionHandler?(success)
}
}
downloadDiagnosisKeyFileURLs { result in
switch result {
case let .failure(error):
finish(.failure(error))
return
case let .success(remoteURLs):
guard !remoteURLs.isEmpty else {
finish(.success(.newSessionResultWithoutMatches()))
return
}
try? FileManager.default.removeItem(at: tmpLocalKeysDirectoryURL) // Clean-up previous session
do { try FileManager.default.createDirectory(at: tmpLocalKeysDirectoryURL, withIntermediateDirectories: true, attributes: nil) }
catch {
finish(.failure(error))
return
}
if logService.isLogEnabled {
logService.logMessage("Exposure detection session keys download START (Count: \(remoteURLs.count))", for: .general, with: .debug, logToConsole: true)
}
let dispatchGroup = DispatchGroup()
var localURLResults = [Result<URL, Error>]()
let urlSession = self.keysDownloaderURLSession ?? URLSession(configuration: .default)
self.keysDownloaderURLSession = urlSession
for remoteURL in remoteURLs {
dispatchGroup.enter()
let downloadTask = urlSession.downloadTask(with: remoteURL) { [weak urlSession] (downloadedURL, _, downloadError) in
defer {
dispatchGroup.leave()
}
guard !progress.isCancelled else { return }
let result: Result<URL, Error>
if let downloadError = downloadError {
result = .failure(downloadError)
}
else {
let tmpLocalKeyURL = tmpLocalKeysDirectoryURL.appendingPathComponent(remoteURL.lastPathComponent, isDirectory: false)
do {
try FileManager.default.moveItem(at: downloadedURL!, to: tmpLocalKeyURL)
result = .success(tmpLocalKeyURL)
}
catch {
result = .failure(error)
}
}
localURLResults.append(result)
if case .failure(_) = result {
if self.keysDownloaderURLSession == urlSession {
self.keysDownloaderURLSession = nil // calls invalidateAndCancel()
}
}
}
downloadTask.resume()
}
dispatchGroup.notify(queue: .global(qos: .utility)) {
if logService.isLogEnabled {
logService.logMessage("Exposure detection session keys download END", for: .general, with: .debug, logToConsole: true)
}
guard !progress.isCancelled else {
finish(.failure(NSError.userCancelledError()))
return
}
var diagnosisKeyURLs: [(bin: URL, sig: URL)] = [] // .bin and .sig file name must match and be unique
do {
let localZipsURLs = try localURLResults.map({ (result) -> URL in
switch result {
case let .success(localURL):
return localURL
case let .failure(error):
throw error
}
})
for localZipURL in localZipsURLs {
let keyName = localZipURL.deletingPathExtension().lastPathComponent
let unzippedURL = localZipURL.deletingLastPathComponent().appendingPathComponent("\(keyName)_unzipped", isDirectory: true)
let zipArchive = ZipArchive()
var unzipSuccess = zipArchive.unzipOpenFile(localZipURL.path)
if unzipSuccess {
unzipSuccess = zipArchive.unzipFile(to: unzippedURL.path, overWrite: true)
unzipSuccess = zipArchive.unzipCloseFile() && unzipSuccess
}
guard unzipSuccess else {
throw NSError.defaultGXError(withDeveloperDescription: "Could not unzip key file: \(localZipURL.path)")
}
let exportBinURL = unzippedURL.appendingPathComponent("export.bin", isDirectory: false)
let exportSigURL = unzippedURL.appendingPathComponent("export.sig", isDirectory: false)
let renamedBinURL = unzippedURL.appendingPathComponent("\(keyName).bin", isDirectory: false)
let renamedSigURL = unzippedURL.appendingPathComponent("\(keyName).sig", isDirectory: false)
try FileManager.default.moveItem(at: exportBinURL, to: renamedBinURL)
try FileManager.default.moveItem(at: exportSigURL, to: renamedSigURL)
diagnosisKeyURLs.append((bin: renamedBinURL, sig: renamedSigURL))
}
}
catch {
finish(.failure(error))
return
}
if logService.isLogEnabled {
logService.logMessage("Exposure detection session ENManager.detectExposures START", for: .general, with: .debug, logToConsole: true)
}
let enConfig = configuration.createENExposureConfiguration()
let minimumRiskScore = enConfig.minimumRiskScore
self.enManager.detectExposures(configuration: enConfig,
diagnosisKeyURLs: diagnosisKeyURLs.flatMap { [$0.bin, $0.sig] })
{ optionalSummary, optionalError in
if logService.isLogEnabled {
logService.logMessage("Exposure detection session ENManager.detectExposures END", for: .general, with: .debug, logToConsole: true)
}
if let error = optionalError {
finish(.failure(error))
return
}
guard !progress.isCancelled else {
finish(.failure(NSError.userCancelledError()))
return
}
let summary = optionalSummary!
let hasMatches = summary.matchedKeyCount > 0
guard hasMatches else {
finish(.success(.newSessionResultWithoutMatches()))
return
}
func finishWithSuccess(withExposureDetails exposureDetails: [ENExposureInfo]?) {
let secondsSinceLastExposure = TimeInterval(summary.daysSinceLastExposure * 24 * 60 * 60)
let lastExposureDate = Date.gxDateByRemovingTimePart(from: Date(timeIntervalSinceNow: -secondsSinceLastExposure))
let exposureDetailsResult: [GXExposureAlertsLocalStorage.ExposureInfo]
exposureDetailsResult = exposureDetails?.map { exposureInfo in
let totalRiskScore: UInt16
if summary.maximumRiskScore == ENRiskScore.max,
let totalRiskScoreNum = GXUtilities.unsignedIntegerNumber(fromValue: summary.metadata?["totalRiskScoreFullRange"]) {
totalRiskScore = totalRiskScoreNum.uint16Value
}
else {
totalRiskScore = UInt16(exposureInfo.totalRiskScore)
}
return .init(date: Date.gxDateByRemovingDatePart(from: exposureInfo.date),
duration: exposureInfo.duration,
transmissionRiskLevel: exposureInfo.transmissionRiskLevel,
totalRiskScore: totalRiskScore,
attenuationValue: exposureInfo.attenuationValue,
attenuationDurations: exposureInfo.attenuationDurations.map { $0.doubleValue })
} ?? []
let sessionResult: GXExposureAlertsLocalStorage.ExposureDetectionSessionResult
let maximumRiskScore: UInt16
if summary.maximumRiskScore == ENRiskScore.max,
let maximumRiskScoreNum = GXUtilities.unsignedIntegerNumber(fromValue: summary.metadata?["maximumRiskScoreFullRange"]) {
maximumRiskScore = maximumRiskScoreNum.uint16Value
}
else {
maximumRiskScore = UInt16(summary.maximumRiskScore)
}
sessionResult = .init(id: UUID(),
sessionTimeStamp: Date(),
lastExposureDate: lastExposureDate,
matchedKeyCount: UInt(summary.matchedKeyCount),
maximumRiskScore: maximumRiskScore,
attenuationDurations: summary.attenuationDurations.map { $0.doubleValue },
exposuresDetails: exposureDetailsResult)
finish(.success(sessionResult))
}
// iOS 12.5 does not support getExposureInfo(summary:) API
guard #available(iOS 13.5, *), summary.maximumRiskScore >= minimumRiskScore,
let userExplanation = GXExposureAlertsLocalStorage.shared.exposureInformationUserExplanation else {
finishWithSuccess(withExposureDetails: nil)
return
}
if logService.isLogEnabled {
logService.logMessage("Exposure detection session ENManager.getExposureInfo START", for: .general, with: .debug, logToConsole: true)
}
self.enManager.getExposureInfo(summary: summary, userExplanation: userExplanation) { exposures, error in
if logService.isLogEnabled {
logService.logMessage("Exposure detection session ENManager.getExposureInfo END", for: .general, with: .debug, logToConsole: true)
}
if let error = error {
finish(.failure(error))
}
else {
guard !progress.isCancelled else {
finish(.failure(NSError.userCancelledError()))
return
}
finishWithSuccess(withExposureDetails: exposures!)
}
}
}
}
}
}
}
@discardableResult
private func downloadDiagnosisKeyFileURLs(allowWaitingForAppModel: Bool = true, completion: @escaping (Result<[URL], Error>) -> Void) -> GXCancelableOperation? {
guard let appModel = GXApplicationModel.current() else {
if allowWaitingForAppModel {
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Waiting for GXModel to load while downloading DiagnosisKeyDataProviderResult.", for: .general, with: .debug, logToConsole: true)
}
var observerObj: NSObjectProtocol? = nil
func removeObserverIfNeeded() {
if let observerObj_ = observerObj {
observerObj = nil
NotificationCenter.default.removeObserver(observerObj_)
}
}
var innerCancelableOp: GXCancelableOperation? = nil
let cancelableOp = GXCancelableOperationWithBlock.init {
innerCancelableOp?.cancel()
completion(.failure(NSError.userCancelledError()))
}
observerObj = NotificationCenter.default.addObserver(forName: .GXModelDidChangeCurrentModel, object: GXModel.self, queue: .main, using: { [weak self] _ in
if !cancelableOp.isCancelled {
innerCancelableOp = self?.downloadDiagnosisKeyFileURLs(allowWaitingForAppModel: false, completion: completion)
}
removeObserverIfNeeded()
})
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(10)) { // Timeout after 10 seconds
cancelableOp.cancel()
removeObserverIfNeeded()
}
return cancelableOp
}
else {
completion(.failure(NSError.defaultGXError(withDeveloperDescription: "GXModel not loaded while downloading DiagnosisKeyDataProviderResult.")))
return nil
}
}
let diagnosisKeysDPPropKey = GXExposureAlertsApplicationModelLoaderExtension.appEntryPointPropertyDiagnosisKeysProviderKey
guard let diagnosisKeysDPName = appModel.appEntryPoint?.value(forAppEntryPointProperty: diagnosisKeysDPPropKey) as? String else {
let error = GXUtilities.tryHandleFatalError("GXModel Exposure Notification Diagnosis Keys Provider property not found while downloading DiagnosisKeyDataProviderResult.")
completion(.failure(error))
return nil
}
let executionOptions = GXProcedureExecutionOptions()
executionOptions.shouldRetryOnSecurityCheckFailure = false
executionOptions.shouldProcessMessagesOutput = false
let helperOptions = GXProcedureHelperExecutionOptions()
helperOptions.executionOptions = executionOptions
return GXProcedureHelper.execute(diagnosisKeysDPName, params: [NSNull()], options: helperOptions) { (result) in
DispatchQueue.global(qos: .utility).async {
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let outParams):
var remoteURLs: [URL] = []
var parseURLSuccess = false
let dpResult = GXSDTData.fromStructureDataTypeName("ExposureAlerts.DiagnosisKeyDataProviderResult",
value: outParams.first,
fieldIsCollection: false)
if let keysCollection = dpResult.valueForFieldSpecifier("Keys") as? GXSDTDataCollectionProtocol {
parseURLSuccess = true
for keysCollectionItem in keysCollection.sdtDataCollectionItems {
guard let remoteURLString = keysCollectionItem as? String,
let remoteURL = URL(string: remoteURLString) else {
parseURLSuccess = false
break
}
remoteURLs.append(remoteURL)
}
}
guard parseURLSuccess else {
completion(.failure(NSError.defaultGXError(withDeveloperDescription: "DiagnosisKeyDataProviderResult invalid format.")))
return
}
completion(.success(remoteURLs))
}
}
}
}
// MARK - Background Task
@available(iOS 13.5, *)
private static let backgroundTaskIdentifier = Bundle.main.bundleIdentifier! + ".exposure-notification"
@available(iOS 13.5, *)
private static func registerDetectionBackgroundTask() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: .main) { task in
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure detection session BGTask: \(task.identifier)", for: .general, with: .debug, logToConsole: true)
}
let progress = shared.detectExposures { success in
task.setTaskCompleted(success: success)
}
// Handle running out of time
task.expirationHandler = {
progress.cancel()
if logService.isLogEnabled {
logService.logMessage("Background exposure detection session ran out of background time.", for: .general, with: .warning, logToConsole: false)
}
}
}
}
@available(iOS, introduced: 12.5, obsoleted: 13.0, message: "Use registerDetectionBackgroundTask instead")
private func registerDetectionLaunchActivityHandler() {
if #available(iOS 13.0, *) {
fatalError("Use registerDetectionBackgroundTask instead in iOS >= 13.5")
}
else { // iOS 12.5
enManager.setLaunchActivityHandler { activityFlags in
if activityFlags.contains(.periodicRun) {
// Your app now has 3.5 minutes to perform download and detection.
let logService = GXLog.loggerService()
if logService.isLogEnabled {
logService.logMessage("Exposure detection session LaunchActivityHandler", for: .general, with: .debug, logToConsole: true)
}
Self.shared.detectExposures()
}
}
}
}
@available(iOS 13.5, *)
private static func scheduleBackgroundTaskIfNeeded(earliestBeginDate: Date? = nil, verifyPendingTasks: Bool = true, completion: (() -> Void)? = nil) {
guard ENManager.authorizationStatus == .authorized,
GXExposureAlertsLocalStorage.shared.lastStartedExposureConfiguration != nil else {
completion?()
return
}
var minEarliestBeginDate = earliestBeginDate
let minInterval = GXExposureAlertsLocalStorage.shared.exposureDetectionMinInterval
if minInterval > 0, let lastSession = GXExposureAlertsLocalStorage.shared.lastExposureDetectionResult?.sessionTimeStamp {
let candidateEarliestBeginDate = lastSession.addingTimeInterval(TimeInterval(minInterval * 60))
if minEarliestBeginDate == nil || minEarliestBeginDate!.after(candidateEarliestBeginDate) {
minEarliestBeginDate = candidateEarliestBeginDate
}
}
if minEarliestBeginDate?.before(Date()) ?? false {
minEarliestBeginDate = nil
}
func addTask() {
let taskRequest = BGProcessingTaskRequest(identifier: backgroundTaskIdentifier)
taskRequest.requiresNetworkConnectivity = true
taskRequest.earliestBeginDate = minEarliestBeginDate
let logService = GXLog.loggerService()
do {
try BGTaskScheduler.shared.submit(taskRequest)
if logService.isLogEnabled {
logService.logMessage("Exposure detection background task scheduled for \(minEarliestBeginDate != nil ? minEarliestBeginDate! as Any : "as soon as possible")", for: .general, with: .debug, logToConsole: true)
}
} catch {
if logService.isLogEnabled {
logService.logMessage("Unable to schedule background task: \(error)", for: .general, with: .error, logToConsole: true)
}
}
}
if verifyPendingTasks {
BGTaskScheduler.shared.getPendingTaskRequests { (tasks) in
if let pendingTask = tasks.first(where: { $0.identifier == backgroundTaskIdentifier }) {
if let pTaskEarliestBeginDate = pendingTask.earliestBeginDate,
minEarliestBeginDate == nil || minEarliestBeginDate!.before(pTaskEarliestBeginDate)
{
addTask()
}
}
else {
addTask()
}
completion?()
}
}
else {
addTask()
completion?()
}
}
@available(iOS 13.5, *)
private static func cancelPendingBackgroundTask() {
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: backgroundTaskIdentifier)
}
}
@available(iOS 12.5, *)
extension GXExposureAlertsLocalStorage.ExposureConfiguration {
public init(enConfig: ENExposureConfiguration) {
self.init(minimumRiskScore: UInt16(enConfig.minimumRiskScore),
attenuationLevelValues: enConfig.attenuationLevelValues.map { $0.uint8Value },
attenuationWeight: enConfig.attenuationWeight,
daysSinceLastExposureLevelValues: enConfig.daysSinceLastExposureLevelValues.map { $0.uint8Value },
daysSinceLastExposureWeight: enConfig.daysSinceLastExposureWeight,
durationLevelValues: enConfig.durationLevelValues.map { $0.uint8Value },
durationWeight: enConfig.durationWeight,
transmissionRiskLevelValues: enConfig.transmissionRiskLevelValues.map { $0.uint8Value },
transmissionRiskWeight: enConfig.transmissionRiskWeight)
}
public func createENExposureConfiguration() -> ENExposureConfiguration {
let enConfig = ENExposureConfiguration()
enConfig.minimumRiskScore = ENRiskScore(min(minimumRiskScore, UInt16(ENRiskScore.max)))
enConfig.attenuationLevelValues = attenuationLevelValues.map { NSNumber(value: $0) }
enConfig.attenuationWeight = attenuationWeight
enConfig.daysSinceLastExposureLevelValues = daysSinceLastExposureLevelValues.map { NSNumber(value: $0) }
enConfig.daysSinceLastExposureWeight = daysSinceLastExposureWeight
enConfig.durationLevelValues = durationLevelValues.map { NSNumber(value: $0) }
enConfig.durationWeight = durationWeight
enConfig.transmissionRiskLevelValues = transmissionRiskLevelValues.map { NSNumber(value: $0) }
enConfig.transmissionRiskWeight = transmissionRiskWeight
return enConfig
}
}
// MARK - iOS 12.5 BGTaskScheduler alternative: https://developer.apple.com/documentation/exposurenotification/supporting_exposure_notifications_in_ios_12_5
@available(iOS, introduced: 12.5, obsoleted: 13.0, message: "Use BGTaskScheduler instead")
fileprivate struct ENActivityFlags: OptionSet {
let rawValue: UInt32
/// The app launched to perform periodic operations.
static let periodicRun = ENActivityFlags(rawValue: 1 << 2)
}
@available(iOS, introduced: 12.5, obsoleted: 13.0, message: "Use BGTaskScheduler instead")
fileprivate typealias ENActivityHandler = (ENActivityFlags) -> Void
@available(iOS 12.5, *)
fileprivate extension ENManager {
@available(iOS, introduced: 12.5, deprecated: 13.0, message: "Use BGTaskScheduler instead")
func setLaunchActivityHandler(activityHandler: @escaping ENActivityHandler) {
let proxyActivityHandler: @convention(block) (UInt32) -> Void = {integerFlag in
activityHandler(ENActivityFlags(rawValue: integerFlag))
}
setValue(proxyActivityHandler, forKey: "activityHandler")
}
}
| 38.415502 | 213 | 0.719016 |
56c63affdf47385180be07e1b4fb5648104c957e | 1,466 | // MIT license. Copyright (c) 2018 Ashish Bhandari. All rights reserved.
import Foundation
public enum ABNetworkResponse {
case error(_: Error?, _: HTTPURLResponse?)
case file(location: URL?, _: HTTPURLResponse?)
case json(_: Any?, _: HTTPURLResponse?)
init(_ response: (httpResponse: HTTPURLResponse?, data: Any?, error: Error?), for request: ABRequestProtocol) {
guard response.httpResponse?.statusCode == 200, response.error == nil else {
var error = response.error
if let errorData = response.data,
let statusCode = response.httpResponse?.statusCode {
error = NSError(domain: "", code: statusCode, userInfo: [ABNetworkFailingURLResponseDataErrorKey : errorData])
}
self = .error(error, response.httpResponse)
return
}
switch request.responseType {
case .file(_):
self = .file(location: .none, response.httpResponse)
case .json:
do {
if let data = response.data as? Data {
self = try .json(JSONSerialization.jsonObject(with: data, options: .mutableContainers), response.httpResponse)
} else {
self = .json(response.data, response.httpResponse)
}
} catch (let exception) {
self = .error(exception, response.httpResponse)
}
}
}
}
| 37.589744 | 131 | 0.581173 |
28a30c33166702292502690a4f4a1e57f62ae733 | 1,027 | //
// ANTextStylesFormatters.swift
// ANLIB
//
// Created by Paolo Prodossimo Lopes on 28/02/22.
//
import Foundation
open class ANTextStylesFormatters {
public static func makeTwoDiferentStyleInText(partOne: String, partTwo: String) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString(
string: partOne, attributes: [.font: UIFont.systemFont(ofSize: 17),
.foregroundColor: UIColor.black]
)
attributedText.append(NSAttributedString(
string: partTwo, attributes: [.font: UIFont.boldSystemFont(ofSize: 17),
.foregroundColor: UIColor.red]
))
return attributedText
}
public static func underlinePropertieGetter(_ text: String) -> NSAttributedString {
return NSMutableAttributedString(
string: text,
attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue]
)
}
}
| 31.121212 | 114 | 0.614411 |
bbb544f8307a95db7a7b2204ccb8d51a944dc17d | 211 | //
// GithubAccess.swift
// clangParser
//
// Created by Patrick Kladek on 26.04.17.
// Copyright © 2017 Patrick Kladek. All rights reserved.
//
import Cocoa
struct GithubAccess {
let token: String
}
| 14.066667 | 57 | 0.682464 |
e523863bb447f22761af33b83084c0632c701d9e | 241 | //
// PokemonSpeciesModel.swift
// PokedexTests
//
// Created by Tomosuke Okada on 2021/02/21.
//
import DataStore
@testable import Domain
extension PokemonSpeciesModel {
static var stub: Self {
return .init(.stub)
}
}
| 14.176471 | 44 | 0.672199 |
14e417b5d1440a7503e85ea0e97b34cfab477e91 | 234 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A{
struct A{
}
func c
protocol c:b
protocol b:b
class A<T:a | 21.272727 | 87 | 0.75641 |
efd368aaf10cd0fb260ee2bff057e2b4be2dab69 | 8,491 | //
// ViewControllerDetail.swift
// Napalm
//
// Created by Mattia Picariello on 07/04/2017.
// Copyright © 2017 NewppyTeam. All rights reserved.
//
import UIKit
import MapKit
class ViewControllerDetail: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIScrollViewDelegate, MKMapViewDelegate, CLLocationManagerDelegate{
var employee = Employee()
var currentPlacemark : CLPlacemark?
var currentRoute: MKRoute?
let manager = CLLocationManager()
@IBOutlet var addressMap: MKMapView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var surnameLabe: UILabel!
@IBOutlet var idNumberLabel: UILabel!
@IBOutlet var addImageButton: UIButton!
@IBOutlet var imageEmployeeView: UIImageView!
@IBOutlet var roleIconImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
addressMap.delegate = self
addressMap.showsScale = true
addressMap.showsCompass = true
addAPin()
functions.setBorderRadiusImageView(imageView: self.imageEmployeeView)
}
@IBAction func goButtonDidPressed(_ sender: Any) {
addressToCoordinatesConverter(address: "Via Alcide De Gasperi, 50, 80046")
}
func addressToCoordinatesConverter(address: String) {
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else {
// handle no location found
return
}
// Use your location
self.openMapForPlace(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, name: address)
}
}
func openMapForPlace(latitude: CLLocationDegrees, longitude: CLLocationDegrees, name: String) {
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = name
mapItem.openInMaps(launchOptions: options)
}
func addAPin() {
let addressToPin = CLGeocoder()
addressToPin.geocodeAddressString("Via Alcide De Gasperi, 50, San Giorgio a Cremano") { (placemarks, error) in
if (error != nil){
print ("there was an error")
}
if let placemarks = placemarks {
let myPlc = placemarks[0]
let annotationToAdd = MKPointAnnotation()
annotationToAdd.title = "Via Alcide De Gasperi"
annotationToAdd.subtitle = "My Place Subtitle!"
annotationToAdd.coordinate = (myPlc.location?.coordinate)!
self.addressMap.showAnnotations([annotationToAdd], animated: true)
}
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: MKUserLocation.self) {
return nil
}
var AnnotationView : MKPinAnnotationView? = self.addressMap.dequeueReusableAnnotationView(withIdentifier: "myPin") as? MKPinAnnotationView
if AnnotationView == nil {
AnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
AnnotationView?.canShowCallout = true
AnnotationView?.rightCalloutAccessoryView = UIButton(type:
UIButtonType.detailDisclosure)
AnnotationView?.pinTintColor = UIColor.blue
}
let leftImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 53, height: 53))
leftImage.image = UIImage(named: "street")
AnnotationView?.leftCalloutAccessoryView = leftImage
return AnnotationView
}
func imagePressed()
{
//do Your action here whatever you want
let secondViewController = self.storyboard!.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
secondViewController.setImage = employee.getImage()
secondViewController.name = employee.getName()
secondViewController.navigationItem.title = employee.getName() + " " + employee.getSurname()
self.navigationController!.pushViewController(secondViewController, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
self.imageEmployeeView.image = employee.getImage()
self.roleIconImage.image = employee.getRoleIcon()
self.nameLabel.text = employee.getName()
self.surnameLabe.text = employee.getSurname()
self.idNumberLabel.text = employee.getID()
self.navigationItem.title = employee.getName() + " " + employee.getSurname()
let tapGesture = UITapGestureRecognizer(target:self, action:#selector(ViewControllerDetail.imagePressed))
self.imageEmployeeView.isUserInteractionEnabled = true // this line is important
self.imageEmployeeView.addGestureRecognizer(tapGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addImageButtonDidPressed(_ sender: Any) {
selectPhoto()
}
func selectPhoto() {
let picker = UIImagePickerController()
picker.delegate = self
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
action in
picker.sourceType = .camera
picker.allowsEditing = true
self.present(picker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
action in
picker.sourceType = .photoLibrary
picker.allowsEditing = true
self.present(picker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
// resizeImage(image!, newWidth: 200)
let postRequest = NetworkRequestsTests(functions.resizeImage(image: image, newWidth: 1000))
postRequest.postData(completion: { (message) in
DispatchQueue.main.async {
print("OK It work!")
}
})
imageEmployeeView.image = functions.resizeImage(image: image, newWidth: imageEmployeeView.bounds.size.width)
}
else
{
//Error message
}
picker.dismiss(animated: true, completion: nil)
//self.tabBarController?.selectedIndex = 0
// let svc = self.storyboard!.instantiateViewController(withIdentifier: "profileID")
// self.present(svc, animated: false, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 35.676471 | 178 | 0.621364 |
1a995bcee55f20257e113f0506cb3123ca63fe84 | 1,023 | //
// ProductCatalogFilterOptions.swift
// i2app
//
// Created by Arcus Team on 2/7/18.
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
import Foundation
import Cornea
/**
Filter options for the product catalog.
*/
enum ProductCatalogFilterOptions: Int {
/**
All the products available.
*/
case allProducts
/**
Products that require a hub.
*/
case hubRequired
/**
Products that do not require a hub.
*/
case noHubRequired
}
| 21.765957 | 75 | 0.701857 |
228466d120686e73c5e0410eca60b3929cf73c7f | 771 | //
// UIImage+Extensions.swift
// FaceDex
//
// Created by Benjamin Emdon on 2017-02-04.
// Copyright © 2017 Benjamin Emdon. All rights reserved.
//
import UIKit
extension UIImage {
func resizeWith(percentage: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
}
| 32.125 | 139 | 0.753567 |
b9a4f5da76a34a8c85c00e0d15d794f9f687c9f4 | 3,583 | //
// ArrayUtils.swift
// configen
//
// Created by Suyash Srijan on 13/01/2020.
// Copyright © 2020 Kin + Carta. All rights reserved.
//
import Foundation
final class ArrayUtils {
enum Error: Swift.Error {
case invalidArrayType
}
/// Check if this is a valid Array type by checking if the brackets are balanced
static func isValidArrayType(_ rawType: String) -> Result<String, Error> {
var stack: [Character] = []
var elementNameChars: [Character] = []
// A quick and simple check to see if this could *potentially* be an
// Array type.
guard rawType.first == .lSquare && rawType.last == .rSquare else {
return .failure(.invalidArrayType)
}
// Okay, let's properly check if the brackets are balanced
for character in rawType {
if case .lSquare = character {
stack.append(character)
continue
}
if case .rSquare = character {
guard stack.last == .lSquare else {
return .failure(.invalidArrayType)
}
_ = stack.popLast()
continue
}
// We're looking at something that is not a bracket. This is likely
// the name of the array's element type (the innermost name if this is
// a nested array). It can only be alphanumeric (i.e. String, UInt8, etc).
if character.isLetter || character.isNumber {
elementNameChars.append(character)
}
}
// If we extracted the name of the element type and the brackets were
// balanced, then this is a valid type.
if !elementNameChars.isEmpty && stack.isEmpty {
return .success(String(elementNameChars))
}
// Otherwise, either we're looking at a different type or the user
// has made a mistake when writing the type name.
return .failure(.invalidArrayType)
}
/// Format a raw value of NSArray type to a String representation
static func transformArrayToString(_ arrayElementType: String, rawValue: Any) -> String {
precondition(rawValue is NSArray, "Expected an 'NSArray', got '\(type(of: rawValue))'")
let rawValueToConvert = castArray(rawValue as! NSArray, arrayElementType: arrayElementType)
var rawValueString = "\(rawValueToConvert)".trimmingCharacters(in: .whitespacesAndNewlines)
// Special case: If we have an array of URLs, then we need to drop all
// double quotes.
if arrayElementType == "URL" {
rawValueString = rawValueString.filter { $0 != "\"" }
}
return rawValueString
}
/// Transform an NSArray to Swift Array by explicitly bridging each element.
private static func castArray(_ array: NSArray, arrayElementType: String) -> Any {
var temp: [Any] = []
for index in 0..<array.count {
if let item = array[index] as? NSArray {
temp.append(castArray(item, arrayElementType: arrayElementType))
} else {
temp.append(castArrayElement(array[index], arrayElementType: arrayElementType))
}
}
return temp
}
/// Cast a value to the given array element type
private static func castArrayElement(_ value: Any, arrayElementType: String) -> Any {
func emitFailedCastError() -> Never {
fatalError("Cast from element of type '\(type(of: value))' to " +
"type '\(arrayElementType)' is unsupported")
}
switch arrayElementType {
case "String":
return value as! String
case "Bool":
return value as! Bool
case "Int":
return value as! Int
case "Double":
return value as! Double
case "URL":
guard let str = value as? String, let _ = URL(string: str) else {
emitFailedCastError()
}
return "URL(string: \(str))!"
case "Any":
return value
default:
// TODO: Handle Data, Date, etc types
emitFailedCastError()
}
}
}
| 30.887931 | 93 | 0.68825 |
fbde3b92bcf8c12d54a7091fd2cbc1d16cdf6a0a | 1,752 | //
// SQLTableReference.swift
// RxSQL
//
// Created by Hammad, Abdelrahman on 4/21/19.
//
import Foundation
import SQLite3
public class SQLTable: SQLStatement {
public var statement: String
internal init(statement: String, tableName: String) {
self.statement = "\(statement) \(tableName)"
}
fileprivate init(statement: String) {
self.statement = statement
}
}
extension SQLTable {
public func innerJoin(_ val: String) -> SQLUnconditionalJoinedTable {
let newStatement = "\(statement) JOIN \(val)"
return SQLUnconditionalJoinedTable(statement: newStatement)
}
public func crossJoin(_ val: String) -> SQLTable {
let newStatement = "\(statement) CROSS JOIN \(val)"
return SQLTable(statement: newStatement)
}
public func outerJoin(_ val: String) -> SQLUnconditionalJoinedTable {
let newStatement = "\(statement) LEFT OUTER JOIN \(val)"
return SQLUnconditionalJoinedTable(statement: newStatement)
}
public func `where`(_ val: String) -> SQLTable {
let newStatement = "\(statement) WHERE \(val)"
return SQLTable(statement: newStatement)
}
}
public class SQLUnconditionalJoinedTable: SQLStatement {
public var statement: String
fileprivate init(statement: String) {
self.statement = statement
}
func on(_ val: String) -> SQLTable {
let newStatement = "\(statement) ON \(val)"
return SQLTable(statement: newStatement)
}
func using(_ val: String) -> SQLTable {
let newStatement = "\(statement) USING \(val)"
return SQLTable(statement: newStatement)
}
}
public enum OuterJoinType {
case left
case right
}
| 25.764706 | 73 | 0.646689 |
64ddcaa204cb473397aa9bd2823111d06ab07b3b | 1,613 | //
// Product.swift
// ecommerce-ios
//
// Created by Su T. Nguyen on 14/05/2021.
//
import Foundation
struct Product: Identifiable {
let id: String
let name: String
let imageName: String
let price: Price
var formattedPrice: String { price.formattedPrice }
}
// MARK: - Product dummy
extension Product {
private enum CubeType: String, CaseIterable {
case gray, pink, indigo, honey, gray1, pink1, indigo1, honey1
var value: String {
switch self {
case .gray, .gray1: return "gray"
case .pink, .pink1: return "pink"
case .indigo, .indigo1: return "indigo"
case .honey, .honey1: return "honey"
}
}
var name: String {
"\(value) cube"
}
var imageName: String {
"dummy-tshirt/tshirt-cube-\(value)"
}
}
static var suggestedProduct: Product {
Product(
id: "suggested_product",
name: "Poly Cube 2021",
imageName: "",
price: Price(id: "price1", amount: 8_000, currency: "฿")
)
}
static var products: [Product] {
var items: [Product] = []
for (index, item) in CubeType.allCases.enumerated() {
items.append(
Product(
id: "\(index)",
name: item.name,
imageName: item.imageName,
price: Price(id: "\(index)", amount: Double(index + 1) * 1_000.0, currency: "฿")
)
)
}
return items
}
}
| 23.042857 | 100 | 0.50465 |
ffafb65ddb309c8ad9189773ed2b13e5e04db864 | 432 | func IsHappy (n:Int)-> Int {
var sumNum:Int = 0
let nn = String(n)
for c in nn.characters {
let cc = Int(String(c))
sumNum = sumNum + cc! * cc!
}
//print(sumNum)
if sumNum == 1{
print("It is happy number")
return sumNum
} else if sumNum >= 10 {
return IsHappy(sumNum)
}else {
print("It is not happy number")
return sumNum
}
}
IsHappy(19)
| 19.636364 | 39 | 0.520833 |
de5fd323fe96a0c33574dfb0a29123a901dbef05 | 1,290 | //
// BLEDataTests.swift
// BLECombineKitTests
//
// Created by Henry Javier Serrano Echeverria on 30/5/20.
// Copyright © 2020 Henry Serrano. All rights reserved.
//
import XCTest
@testable import BLECombineKit
class BLEDataTests: XCTestCase {
var mockupPeripheral: MockBLEPeripheral!
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
mockupPeripheral = MockBLEPeripheral()
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
mockupPeripheral = nil
}
func testGenericDataConversionToFloat() throws {
var float32 = Float32(12.99)
var float32Data = Data()
withUnsafePointer(to:&float32, { (ptr: UnsafePointer<Float32>) -> Void in
float32Data = Data( buffer: UnsafeBufferPointer(start: ptr, count: 1))
})
let data = BLEData(value: float32Data, peripheral: mockupPeripheral)
if let result = data.to(type: Float32.self) {
XCTAssertEqual(float32, result, accuracy: 0.000001)
} else {
XCTFail()
}
}
}
| 29.318182 | 111 | 0.645736 |
89707250915175399cfd6d420a0f38a354ae0564 | 1,035 | //
// Breadcrumb.swift
//
// Created by Nicholas Cromwell on 12/12/20.
//
import Foundation
public struct Breadcrumb: Codable {
public init(deviceId: String, position: LatLng, recordedAt: Date, acceptedAt: Date? = nil, externalUserId: String? = "", accuracy: Int? = 0, metadata: [KeyValuePair]? = []) throws {
if (deviceId.isEmpty) {
throw BreadcrumbErrors.deviceIdRequired
}
self.deviceId = deviceId
self.position = position
self.recordedAt = recordedAt
self.acceptedAt = acceptedAt
self.externalUserId = externalUserId
self.accuracy = accuracy
self.metadata = metadata
}
public let deviceId: String
public let position: LatLng
public let recordedAt: Date
public private(set) var acceptedAt: Date?
public private(set) var externalUserId: String?
public private(set) var accuracy: Int?
public private(set) var metadata: [KeyValuePair]?
}
public enum BreadcrumbErrors: Error {
case deviceIdRequired
}
| 29.571429 | 185 | 0.671498 |
33a1a529ac36cbd1326a0342398948df231965b2 | 1,010 | import Foundation
enum Corner: CustomStringConvertible {
case topLeft
case topRight
case bottomRight
case bottomLeft
var description: String {
switch self {
case .topLeft:
return "1️⃣"
case .topRight:
return "2️⃣"
case .bottomRight:
return "3️⃣"
case .bottomLeft:
return "4️⃣"
}
}
static func corner(for position: CGPoint, in size: CGSize) -> Self {
switch (position.x / size.width, position.y / size.height) {
case let (x, y) where x < 0.5 && y < 0.5:
return .topLeft
case let (x, y) where x >= 0.5 && y < 0.5:
return .topRight
case let (x, y) where x >= 0.5 && y >= 0.5:
return .bottomRight
case let (x, y) where x < 0.5 && y >= 0.5:
return .bottomLeft
default:
return .bottomRight
}
}
}
| 26.578947 | 72 | 0.463366 |
1c7ba8d59e0fd8269b131e6ea9966e878a5ecc69 | 2,550 | //
// CameraMethods.swift
// Pods
//
// Created by Nagy istván on 2020. 09. 04..
//
import Foundation
import Mapbox
extension MapboxMapController {
func setPosition(forTracker tracker: Tracker, withZoomLevel zoomLevel: Double = 16) {
mapView.setCenter(CLLocationCoordinate2D(latitude: tracker.latlong.lat, longitude: tracker.latlong.long), animated: false)
mapView.setZoomLevel(zoomLevel, animated: false)
}
func showAllAnnotations(withMyTrackers trackers: [Tracker]){
mapView.setVisibleCoordinateBounds(generateCoordinatesBounds(withMyTrackers: trackers), animated: true)
}
func generateCoordinatesBounds(withMyTrackers trackers: [Tracker]) -> MGLCoordinateBounds {
var maxN = CLLocationDegrees(), maxS = CLLocationDegrees() , maxE = CLLocationDegrees() , maxW = CLLocationDegrees()
for coordinates in trackers {
if Double(coordinates.latlong.lat) >= maxN || maxN == 0 { maxN = coordinates.latlong.lat }
if Double(coordinates.latlong.lat) <= maxS || maxS == 0 { maxS = coordinates.latlong.lat }
if Double(coordinates.latlong.long) >= maxE || maxE == 0 { maxE = coordinates.latlong.long }
if Double(coordinates.latlong.long) <= maxW || maxW == 0{ maxW = coordinates.latlong.long }
}
let offset = 0.01
let maxNE = CLLocationCoordinate2D(latitude: maxN + offset, longitude: maxE + offset)
let maxSW = CLLocationCoordinate2D(latitude: maxS - offset, longitude: maxW - offset)
return MGLCoordinateBounds(sw: maxSW, ne: maxNE)
}
func getCurrentLocation(){
// self.locationManager.requestAlwaysAuthorization()
// self.locationManager.requestWhenInUseAuthorization()
// if CLLocationManager.locationServicesEnabled() {
// locationManager.delegate = self
// locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
// locationManager.startUpdatingLocation()
// let camera = MGLMapCamera()
// camera.centerCoordinate.latitude = locationManager.location?.coordinate.latitude ?? 47.5
// camera.centerCoordinate.longitude = locationManager.location?.coordinate.longitude ?? 19.5
// mapView?.setCamera(camera, animated: false)
// mapView?.setCenter(CLLocationCoordinate2D(latitude: locationManager.location?.coordinate.latitude ?? 47.5, longitude: locationManager.location?.coordinate.longitude ?? 19.5), zoomLevel: 16, animated: false)
// }
}
}
| 50 | 220 | 0.686667 |
5b5f83e0786083e795b6e7e8d2154e31ba20897c | 745 | //
// IssueInteractor.swift
// IssueTracker
//
// Created by 홍경표 on 2020/11/02.
//
import Foundation
import NetworkService
protocol IssueBusinessLogic {
func request<T: Codable>(endPoint: IssueEndPoint, completionHandler: @escaping (T?) -> Void)
}
class IssueInteractor: IssueBusinessLogic {
func request<T>(endPoint: IssueEndPoint, completionHandler: @escaping (T?) -> Void) where T : Decodable, T : Encodable {
NetworkManager.shared.request(endPoint: endPoint) { (data: T?, response: NetworkManager.Response?) in
guard response == nil else {
debugPrint(response)
completionHandler(nil)
return
}
completionHandler(data)
}
}
}
| 27.592593 | 124 | 0.640268 |
bfcea048d9ec2764cddf3900fe94990c9997aefb | 1,744 | import Foundation
public class IdbQuery {
private var _select = ""
private var _from = [String]()
private var _whereTests = [String]()
private var _groupBy = ""
private var _columnNames = [String]()
internal func setup(select: IdbQuerySelectMaker,
from: [String],
wheres: [IdbQueryWhereTest],
groupBy: IdbQueryGroupByMaker) {
_select = select.queryString
_columnNames = select.columnNames
_from = from
_whereTests = wheres.map{ $0.queryCompatibleString() }
_groupBy = groupBy.queryString
}
public var queryString: String {
var whereClause = ""
var intoClause = ""
let groupByClause = _groupBy.count > 0 ? _groupBy : ""
var orderByClause = ""
var limitClause = ""
var offsetClause = ""
var slimitClause = ""
var soffsetClause = ""
let fromString = _from.map{ "\"\($0)\"" }.joined(separator: ",")
if _whereTests.count > 0 {
let whereTestString = _whereTests.joined(separator: " and ")
whereClause = " where \(whereTestString)"
}
let queryString = "select \(_select)\(intoClause) from \(fromString)\(whereClause)\(groupByClause)\(orderByClause)\(limitClause)\(offsetClause)\(slimitClause)\(soffsetClause)"
print("Q: \(queryString)")
return queryString
}
public var columnNames: [String] {
return _columnNames
}
}
extension InfluxDb {
public static func makeQuery(closure: ((IdbQueryMaker) -> ())) -> IdbQuery {
let maker = IdbQueryMaker()
closure(maker)
return maker.build()
}
}
| 31.709091 | 183 | 0.580275 |
9047f05e479079c5d2fb2b8657b4a74dbf293ef0 | 2,027 | //
// PlanView.swift
// Meal
//
// Created by Inpyo Hong on 2021/08/05.
//
import SwiftUI
struct PlanView: View {
let index: Int
let plan: Plan
@Environment(\.verticalSizeClass) var
verticalSizeClass: UserInterfaceSizeClass?
@Environment(\.horizontalSizeClass) var
horizontalSizeClass: UserInterfaceSizeClass?
var isIPad: Bool {
horizontalSizeClass == .regular &&
verticalSizeClass == .regular
}
var body: some View {
VStack(alignment: .leading, spacing: -4) {
HStack(alignment: .center, spacing: -4) {
MealIconView()
VStack(alignment: .leading, spacing: -6) {
HStack {
MealTitleLabel(size: 40,
textColor: Color(UIColor.label))
Text("\(PlanStore().convertDateToStr(date: PlanStore().dateFormatter.date(from: plan.day)!))")
.font(.footnote)
.foregroundColor(Color(.gray))
.bold()
}
Text(PlanStore().getMealPlanStr(plan: plan))
.foregroundColor(Color(UIColor.label))
.font(.custom("NanumMyeongjoOTFBold", size: 16))
//.bold()
}
.padding(.horizontal)
.foregroundColor(Color(UIColor.systemGray))
}
if let planData = PlanStore().getPlanData(plan: plan) {
Text(PlanStore().getBibleSummary(verses: planData.verses))
.font(.custom("NanumMyeongjoOTF", size: 12))
.lineLimit(3)
//.font(.footnote)
.foregroundColor(Color(UIColor.label))
.padding([.top, .bottom], 20)
.padding([.leading, .trailing], 10)
}
}
.padding(10)
.frame(width: isIPad ? 644 : nil)
.background(Color.itemBkgd)
.cornerRadius(15)
.shadow(color: Color.black.opacity(0.1), radius: 10)
}
}
//struct PlanView_Previews: PreviewProvider {
// static var previews: some View {
// PlanView(index: 0, plan: Plan())
// .previewLayout(.sizeThatFits)
// .colorScheme(.dark)
// }
//}
| 27.767123 | 106 | 0.588061 |
2668a9f857089f5e5b6d8768c4818a677c88c213 | 223 | while !isOnGem {
moveForward ()
if isOnClosedSwitch && isBlocked {
toggleSwitch ()
turnLeft ()
} else if isOnClosedSwitch {
turnRight ()
toggleSwitch ()
}
}
collectGem ()
| 17.153846 | 38 | 0.55157 |
21455b3863347245b4c8710c1202f8468a2a8043 | 472 | import Cocoa
import FlutterMacOS
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController.init()
let windowFrame = self.frame
self.contentViewController = flutterViewController
//self.setFrame(windowFrame, display: true)
self.setFrame(NSRect(x:0, y:0, width: 1200, height: 900), display: true)
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
}
| 27.764706 | 76 | 0.754237 |
1aa4516bb615e3f22e788bef79cf177c2eb7c20a | 6,208 | //
// FiltersViewController.swift
// Yelp
//
// Created by Jerry on 2/9/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol FiltersViewControllerDelegate {
optional func filtersViewController(filtersViewController: FiltersViewController, didUpdateField filters: [String: AnyObject])
}
class FiltersViewController: UIViewController , UITableViewDataSource, UITableViewDelegate, SwitchTableViewCellDelegate, DealSwitchTableViewCellDelegate, SortTableViewCellDelegate, DistanceTableViewCellDelegate {
@IBOutlet weak var tableView: UITableView!
weak var delegate: FiltersViewControllerDelegate?
var categories:[[String:String]]?
var catSwitchStates = [Int:Bool]()
var sortBy = 0
var distance = 0
var deals = false
let sections = ["", "Sort By", "Distance", "Category"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor(red: 255/255, green: 126/255, blue: 126/255, alpha: 1)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.categories = self.getCategories()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = indexPath.section
switch section {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("dealCell") as! DealSwitchTableViewCell
cell.delegate = self
cell.dealLabel.text = "Offering a Deal"
cell.dealSwitch.on = self.deals
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("sortCell") as! SortTableViewCell
cell.delegate = self
cell.sortSegmentedControl.selectedSegmentIndex = self.sortBy
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("distanceCell") as! DistanceTableViewCell
cell.delegate = self
cell.distanceSegmentedControl.selectedSegmentIndex = self.distance
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
case 3:
let cell = tableView.dequeueReusableCellWithIdentifier("switchCell") as! SwitchTableViewCell
cell.delegate = self
cell.switchLabel.text = self.categories![indexPath.row]["name"]
cell.onSwitch.on = self.catSwitchStates[indexPath.row] ?? false
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("switchCell") as! SwitchTableViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1
case 2:
return 1
case 3:
return (self.categories?.count)!
default:
return 0
}
}
func switchTableViewCell(switchCell: SwitchTableViewCell, didChangeValue value: Bool) {
let indexPath = self.tableView.indexPathForCell(switchCell)
self.catSwitchStates[indexPath!.row] = value
}
func dealSwitchTableViewCell(dealCell: DealSwitchTableViewCell, didChangeValue value: Bool) {
self.deals = value
}
func sortTableViewCell(sortCell: SortTableViewCell, didSelectValue value: Int) {
self.sortBy = value
}
func distanceTableViewCell(distanceCell: DistanceTableViewCell, didSelectValue value: Int) {
var distanceValue = 0
switch value {
case 0:
distanceValue = 0
case 1:
distanceValue = 480
case 2:
distanceValue = 1600
case 3:
distanceValue = 8000
case 4:
distanceValue = 32000
default:
distanceValue = 0
}
self.distance = distanceValue
}
@IBAction func onCancelPressed(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true) { () -> Void in
//
}
}
@IBAction func onSearchPressed(sender: UIBarButtonItem) {
var filters = [String:AnyObject]()
var selectedCategories = [String]()
for (row, isSelected) in catSwitchStates {
if isSelected {
selectedCategories.append(self.categories![row]["code"]!)
}
}
if selectedCategories.count > 0 {
filters["categories"] = selectedCategories
}
filters["deals"] = self.deals
filters["sort"] = self.sortBy
filters["distance"] = self.distance
self.delegate?.filtersViewController!(self, didUpdateField: filters)
self.dismissViewControllerAnimated(true, completion: nil)
}
func getCategories() -> [[String: String]] {
return [
["name" : "Burgers", "code": "burgers"],
["name" : "Chinese", "code": "chinese"],
["name" : "Hong Kong Style Cafe", "code": "hkcafe"],
["name" : "Steakhouses", "code": "steak"],
["name" : "Sushi Bars", "code": "sushi"]]
}
}
| 35.073446 | 212 | 0.63096 |
fed75d233873e2016e54071303da906d2f51213b | 4,063 | //
// BYLightView.swift
// Common_iOS
//
// Created by CardiorayT1 on 2019/1/9.
// Copyright © 2019 houboye. All rights reserved.
//
import UIKit
fileprivate let kLight_View_Count = 16
class BYLightView: UIView {
let lightBackView = UIView()
let centerLightIV = UIImageView()
var lightViewArr = Array<UIView>()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
self.frame = CGRect(x: UIScreen.main.bounds.size.width * 0.5, y: UIScreen.main.bounds.size.height * 0.5, width: 155, height: 155)
layer.cornerRadius = 10
let titleLabel = UILabel(frame: CGRect(x: 0, y: 5, width: self.bounds.size.width, height: 30))
titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
titleLabel.textColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1.00)
titleLabel.textAlignment = .center
titleLabel.text = "亮度"
addSubview(titleLabel)
centerLightIV.frame = CGRect(x: 0, y: 0, width: 79, height: 76)
centerLightIV.image = UIImage(named: "BYPlayer.bundle/play_new_brightness_day")
centerLightIV.center = CGPoint(x: 155 * 0.5, y: 155 * 0.5)
addSubview(centerLightIV)
lightBackView.frame = CGRect(x: 13, y: 132, width: self.bounds.size.width - 26, height: 7)
lightBackView.backgroundColor = UIColor(red: 65/255, green: 67/255, blue: 70/255, alpha: 1)
addSubview(lightBackView)
let view_width: CGFloat = (lightBackView.bounds.size.width - 17) / 16
let view_height: CGFloat = 5
let view_y: CGFloat = 1
for i in 0..<kLight_View_Count {
let view_x: CGFloat = CGFloat(i) * (view_width + 1) + 1
let view = UIView(frame: CGRect(x: view_x, y: view_y, width: view_width, height: view_height))
view.backgroundColor = UIColor.white
lightViewArr.append(view)
lightBackView.addSubview(view)
}
updateLongView(UIScreen.main.brightness)
// 通知
NotificationCenter.default.addObserver(self, selector: #selector(onOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
UIScreen.main.addObserver(self, forKeyPath: "brightness", options: NSKeyValueObservingOptions.new, context: nil)
alpha = 0.0
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let sound = change?[NSKeyValueChangeKey.newKey] as! Float
if alpha == 0.0 {
alpha = 1.0
let deadline = DispatchTime.now() + 1.0
DispatchQueue.main.asyncAfter(deadline: deadline) {
self.hideLightView()
}
}
updateLongView(CGFloat(sound))
}
private func hideLightView() {
if alpha == 1.0 {
UIView.animate(withDuration: 0.8, animations: {
self.alpha = 0.0
}) { (isFinished) in
}
}
}
@objc func onOrientationDidChange(_ notify: Notification) {
alpha = 0.0
}
// MARK: - update view
private func updateLongView(_ sound: CGFloat) {
let stage: CGFloat = 1.0 / 15.0
let level: Int = Int(sound/stage)
for i in 0..<lightViewArr.count {
let aView = lightViewArr[i]
if i <= level {
aView.isHidden = false
} else {
aView.isHidden = true
}
}
setNeedsLayout()
superview?.bringSubviewToFront(self)
}
override func layoutSubviews() {
super.layoutSubviews()
}
deinit {
UIScreen.main.removeObserver(self, forKeyPath: "brightness")
NotificationCenter.default.removeObserver(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 34.726496 | 163 | 0.59808 |
50f4721fbf32bb9a6f147fa00efb373a023b8fab | 2,077 | import Foundation
/// A Transfer on Tink represents the tentative action of requesting a payment initiation.
/// By consequence, its success does not represent that money has been successfully transferred from one account to another because the payment initiation relays the responsibility of properly executing the monetary reallocation to the financial institution.
/// The source account must belong to the authenticated user. Source and destination accounts are sent in a special URI format.
struct RESTTransferRequest: Codable {
/// The amount that will be transferred. Should be positive.
var amount: Double
/// The id of the Credentials used to make the transfer. For PIS with AIS it will be the credentials of which the source account belongs to. For PIS without AIS it is not linked to source account.
var credentialsId: String?
/// The currency of the amount to be transferred. Should match the SourceUri's currency.
var currency: String
/// The message to the recipient. Optional for bank transfers but required for payments. If the payment recipient requires a structured (specially formatted) message, it should be set in this field.
var destinationMessage: String
/// The unique identifier of the transfer.
var id: String?
/// The transaction description on the source account for the transfer.
var sourceMessage: String?
/// The date when the payment or bank transfer should be executed. If no dueDate is given, it will be executed immediately.
var dueDate: Date?
/// Transfe's message type, only required for BE and SEPA-EUR schemes. STRUCTURED is for PAYMENT type transfers and FREE_TEXT is for BANK_TRANSFER type transfers.
var messageType: String?
/// The destination account or recipient of the transfer, in the form of a uri. With possible scheme: `sepa-eur`, `se-bg`, `se-pg`
var destinationUri: String
/// The source account of the transfer, in the form of a uri. With possible scheme: `sepa-eur`, `se-bg`, `se-pg`
var sourceUri: String
var redirectUri: String?
}
| 69.233333 | 258 | 0.753491 |
f48a1ee6115169401811b50742eb59a50888233b | 2,184 | //
// AppDelegate.swift
// PreneticsTestCocoa
//
// Created by rocooshiang on 06/08/2017.
// Copyright (c) 2017 rocooshiang. 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.468085 | 285 | 0.755952 |
fe4c45504beb19ca9b524e23d9fc5157fe3a6361 | 1,201 | //
// UIColor+Ext.swift
// Outcubator
//
// Created by doquanghuy on 18/05/2021.
//
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: alpha
)
}
convenience init(hex: String) {
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
let a, r, g, b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
| 30.794872 | 114 | 0.488759 |
e55eda0aee658678d2b446111040a4c9f0f0cf23 | 102,771 | //
// ArrayTests.swift
// StubsCodeGeneratorTests
//
// Created by Patrick Remy on 28.01.18.
//
import XCTest
import Antlr4
@testable import StubsAST
import StubsTypeChecker
class ArrayTests: XCTestCase {
override func setUp() {
continueAfterFailure = false
}
// MARK: - Declaration
// MARK: Global
func testGlobalIntegerArray() {
let ast = ObjectDecNode(
"ArrayGlobalIntegerTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
],
statements: [
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayGlobalIntegerTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayGlobalIntegerTest")
XCTAssertEqual(output, "1\n2\n3\n")
}
// MARK: Local
func testLocalIntegerArray() {
let ast = ObjectDecNode(
"ArrayLocalIntegerTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
statements: [
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayLocalIntegerTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayLocalIntegerTest")
XCTAssertEqual(output, "1\n2\n3\n")
}
// MARK: Parameter
func testPrintIntegerParameter() {
let ast = ObjectDecNode(
"ArrayPrintIntegerParameterTest",
variables: [],
functions: [
FuncDecNode(
"foo",
parameters: [
("bar", .array(of: .integer))
],
returnType: nil,
declarations: [],
statements: [
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"bar",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
),
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayPrintIntegerParameterTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayPrintIntegerParameterTest")
XCTAssertEqual(output, "2\n")
}
func testPrintStringParameter() {
let ast = ObjectDecNode(
"ArrayPrintStringParameterTest",
variables: [],
functions: [
FuncDecNode(
"sayHello",
parameters: [
("message", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"message",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
),
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
FuncCallNode(
IdentifierNode(
"sayHello",
references: CommonToken(0)
),
parameters: [
ArrayNode(
[
PrimitiveNode(
"Hello",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"World",
ofType: .string,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayPrintStringParameterTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayPrintStringParameterTest")
XCTAssertEqual(output, "World\n")
}
// MARK: Double conversion
func testDoubleConversion() {
let ast = ObjectDecNode(
"ArrayDoubleConversionTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"42.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
statements: [
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayDoubleConversionTest"))
let output: String! = try! TestSuite.runProgram(url, className: "ArrayDoubleConversionTest")
XCTAssertNotNil(output)
let outputNumber: Double! = Double(output.trimmingCharacters(in: .whitespacesAndNewlines))
XCTAssertNotNil(outputNumber)
XCTAssertEqual((outputNumber * 10).rounded() / 10, 42.0)
}
// MARK: - Assignment
// MARK: Global
func testAssignToGlobalIntegerArray() {
let ast = ObjectDecNode(
"ArrayAssignToGlobalIntegerArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToGlobalIntegerArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToGlobalIntegerArrayTest")
XCTAssertEqual(output, "1\n3\n")
}
func testAssignToGlobalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignToGlobalDoubleArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3.0",
ofType: .double,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToGlobalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToGlobalDoubleArrayTest")
XCTAssertEqual(output, "1.0\n3.0\n")
}
func testAssignIntegerToGlobalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignIntegerToGlobalDoubleArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignIntegerToGlobalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignIntegerToGlobalDoubleArrayTest")
XCTAssertEqual(output, "1.0\n3.0\n")
}
func testAssignToGlobalStringArray() {
let ast = ObjectDecNode(
"ArrayAssignToGlobalStringArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .string),
assign: ArrayNode(
[
PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"bar",
ofType: .string,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToGlobalStringArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToGlobalStringArrayTest")
XCTAssertEqual(output, "foo\nfoo\n")
}
func testAssignToGlobalBooleanArray() {
let ast = ObjectDecNode(
"ArrayAssignToGlobalBooleanArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .boolean),
assign: ArrayNode(
[
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToGlobalBooleanArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToGlobalBooleanArrayTest")
XCTAssertEqual(output, "true\ntrue\n")
}
// MARK: Local
func testAssignToLocalIntegerArray() {
let ast = ObjectDecNode(
"ArrayAssignToLocalIntegerArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToLocalIntegerArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToLocalIntegerArrayTest")
XCTAssertEqual(output, "1\n3\n")
}
func testAssignToLocalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignToLocalDoubleArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3.0",
ofType: .double,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToLocalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToLocalDoubleArrayTest")
XCTAssertEqual(output, "1.0\n3.0\n")
}
func testAssignIntegerToLocalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignIntegerToLocalDoubleArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"3",
ofType: .integer,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignIntegerToLocalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignIntegerToLocalDoubleArrayTest")
XCTAssertEqual(output, "1.0\n3.0\n")
}
func testAssignToLocalStringArray() {
let ast = ObjectDecNode(
"ArrayAssignToLocalStringArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .string),
assign: ArrayNode(
[
PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"bar",
ofType: .string,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToLocalStringArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToLocalStringArrayTest")
XCTAssertEqual(output, "foo\nfoo\n")
}
func testAssignToLocalBooleanArray() {
let ast = ObjectDecNode(
"ArrayAssignToLocalBooleanArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .boolean),
assign: ArrayNode(
[
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
index: PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
assign: PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignToLocalBooleanArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignToLocalBooleanArrayTest")
XCTAssertEqual(output, "true\ntrue\n")
}
// MARK: - New array assignment
// MARK: Global
func testAssignNewArrayToGlobalBooleanArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToGlobalBooleanArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .boolean),
assign: ArrayNode(
[
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalBooleanArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalBooleanArrayTest")
XCTAssertEqual(output, "false\ntrue\n")
}
func testAssignNewArrayToGlobalIntegerArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToGlobalIntegerArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"4",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalIntegerArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalIntegerArrayTest")
XCTAssertEqual(output, "4\n2\n")
}
func testAssignNewArrayToGlobalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToGlobalDoubleArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"4.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalDoubleArrayTest")
XCTAssertEqual(output, "4.0\n2.0\n")
}
func testAssignNewArrayToGlobalStringArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToGlobalStringArrayTest",
variables: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .string),
assign: ArrayNode(
[
PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"bar",
ofType: .string,
references: CommonToken(0)
)
]
)
)
],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"Hello",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"World",
ofType: .string,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalStringArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToGlobalStringArrayTest")
XCTAssertEqual(output, "Hello\nWorld\n")
}
// MARK: Local
func testAssignNewArrayToLocalBooleanArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToLocalBooleanArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .boolean),
assign: ArrayNode(
[
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"false",
ofType: .boolean,
references: CommonToken(0)
),
PrimitiveNode(
"true",
ofType: .boolean,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalBooleanArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalBooleanArrayTest")
XCTAssertEqual(output, "false\ntrue\n")
}
func testAssignNewArrayToLocalIntegerArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToLocalIntegerArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .integer),
assign: ArrayNode(
[
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"4",
ofType: .integer,
references: CommonToken(0)
),
PrimitiveNode(
"2",
ofType: .integer,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalIntegerArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalIntegerArrayTest")
XCTAssertEqual(output, "4\n2\n")
}
func testAssignNewArrayToLocalDoubleArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToLocalDoubleArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .double),
assign: ArrayNode(
[
PrimitiveNode(
"1.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"4.0",
ofType: .double,
references: CommonToken(0)
),
PrimitiveNode(
"2.0",
ofType: .double,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalDoubleArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalDoubleArrayTest")
XCTAssertEqual(output, "4.0\n2.0\n")
}
func testAssignNewArrayToLocalStringArray() {
let ast = ObjectDecNode(
"ArrayAssignNewArrayToLocalStringArrayTest",
variables: [],
functions: [
FuncDecNode(
"main",
parameters: [
("args", .array(of: .string))
],
returnType: nil,
declarations: [
VarDecNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
datatype: .array(of: .string),
assign: ArrayNode(
[
PrimitiveNode(
"foo",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"bar",
ofType: .string,
references: CommonToken(0)
)
]
)
)
],
statements: [
VarAssignNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
assign: ArrayNode(
[
PrimitiveNode(
"Hello",
ofType: .string,
references: CommonToken(0)
),
PrimitiveNode(
"World",
ofType: .string,
references: CommonToken(0)
)
]
)
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"0",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
),
FuncCallNode(
IdentifierNode(
"println",
references: CommonToken(0)
),
parameters: [
FuncCallNode(
IdentifierNode(
"foo",
references: CommonToken(0)
),
parameters: [
PrimitiveNode(
"1",
ofType: .integer,
references: CommonToken(0)
)
]
)
]
)
]
)
]
)
XCTAssertNoThrow(try TypeChecker.validate(ast))
XCTAssertNoThrow(try TestSuite.generateClassFile(ast))
let url = try! TestSuite.generateClassFile(ast)
XCTAssertNoThrow(try TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalStringArrayTest"))
let output = try! TestSuite.runProgram(url, className: "ArrayAssignNewArrayToLocalStringArrayTest")
XCTAssertEqual(output, "Hello\nWorld\n")
}
}
| 41.913132 | 113 | 0.266855 |
d58d1a0560a4b4c6b21cdae97a609eb7c7204206 | 460 | //
// AlienEntity.swift
// Marvel Heroes
//
// Created by Thiago Vaz on 06/06/20.
// Copyright © 2020 Thiago Santos. All rights reserved.
//
import Foundation
class AlienEntity {
var name: String = ""
var alterEgo: String = ""
var imagePath: String = ""
var biography: String = ""
var abilities: AbilitiesEntity = AbilitiesEntity()
var movies: [String] = []
var caracteristics: CaracteristicsEntity = CaracteristicsEntity()
}
| 23 | 69 | 0.669565 |
69c67973a5b34966270955ddb63533989bec8605 | 16,821 | @testable import App
import Fluent
import Vapor
import XCTest
class IngestorTests: AppTestCase {
func test_ingest_basic() throws {
// setup
let urls = ["https://github.com/finestructure/Gala",
"https://github.com/finestructure/Rester",
"https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server"]
Current.fetchMetadata = { _, pkg in self.future(.mock(for: pkg)) }
let packages = try savePackages(on: app.db, urls.asURLs, processingStage: .reconciliation)
let lastUpdate = Date()
// MUT
try ingest(client: app.client, database: app.db, logger: app.logger, limit: 10).wait()
// validate
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.map(\.$package.id), packages.map(\.id))
repos.forEach {
XCTAssertNotNil($0.id)
XCTAssertNotNil($0.$package.id)
XCTAssertNotNil($0.createdAt)
XCTAssertNotNil($0.updatedAt)
XCTAssertNotNil($0.description)
XCTAssertEqual($0.defaultBranch, "main")
XCTAssert($0.forks != nil && $0.forks! > 0)
XCTAssert($0.stars != nil && $0.stars! > 0)
}
// assert packages have been updated
(try Package.query(on: app.db).all().wait()).forEach {
XCTAssert($0.updatedAt != nil && $0.updatedAt! > lastUpdate)
XCTAssertEqual($0.status, .new)
XCTAssertEqual($0.processingStage, .ingestion)
}
}
func test_fetchMetadata() throws {
// setup
let packages = try savePackages(on: app.db, ["https://github.com/foo/1",
"https://github.com/foo/2"])
Current.fetchMetadata = { _, pkg in
if pkg.url == "https://github.com/foo/1" {
return self.future(error: AppError.metadataRequestFailed(nil, .badRequest, URI("1")))
}
return self.future(.mock(for: pkg))
}
Current.fetchLicense = { _, _ in self.future(Github.License(htmlUrl: "license")) }
// MUT
let res = try fetchMetadata(client: app.client, packages: packages).wait()
// validate
XCTAssertEqual(res.map(\.isSuccess), [false, true])
let license = try XCTUnwrap(res.last?.get().2)
XCTAssertEqual(license, .init(htmlUrl: "license"))
}
func test_insertOrUpdateRepository() throws {
let pkg = try savePackage(on: app.db, "https://github.com/foo/bar")
do { // test insert
try insertOrUpdateRepository(on: app.db,
for: pkg,
metadata: .mock(for: pkg),
licenseInfo: .init(htmlUrl: ""),
readmeInfo: .init(downloadUrl: "", htmlUrl: "")).wait()
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.map(\.summary), [.some("This is package https://github.com/foo/bar")])
}
do { // test update - run the same package again, with different metadata
var md = Github.Metadata.mock(for: pkg)
md.repository?.description = "New description"
try insertOrUpdateRepository(on: app.db,
for: pkg,
metadata: md,
licenseInfo: .init(htmlUrl: ""),
readmeInfo: .init(downloadUrl: "", htmlUrl: "")).wait()
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.map(\.summary), [.some("New description")])
}
}
func test_updateRepositories() throws {
// setup
let pkg = try savePackage(on: app.db, "2")
let metadata: [Result<(Package, Github.Metadata, Github.License?, Github.Readme?),
Error>] = [
.failure(AppError.metadataRequestFailed(nil, .badRequest, "1")),
.success((pkg,
.init(defaultBranch: "main",
forks: 1,
issuesClosedAtDates: [
Date(timeIntervalSince1970: 0),
Date(timeIntervalSince1970: 2),
Date(timeIntervalSince1970: 1),
],
license: .mit,
openIssues: 1,
openPullRequests: 2,
owner: "foo",
pullRequestsClosedAtDates: [
Date(timeIntervalSince1970: 1),
Date(timeIntervalSince1970: 3),
Date(timeIntervalSince1970: 2),
],
releases: [
.init(description: "a release",
descriptionHTML: "<p>a release</p>",
isDraft: false,
publishedAt: Date(timeIntervalSince1970: 5),
tagName: "1.2.3",
url: "https://example.com/1.2.3")
],
name: "bar",
stars: 2,
summary: "package desc",
isInOrganization: true),
licenseInfo: .init(htmlUrl: "license url"),
readmeInfo: .init(downloadUrl: "readme url", htmlUrl: "readme html url")))
]
// MUT
let res = try updateRepositories(on: app.db, metadata: metadata).wait()
// validate
XCTAssertEqual(res.map(\.isSuccess), [false, true])
let repo = try XCTUnwrap(
Repository.query(on: app.db)
.filter(\.$package.$id == pkg.requireID())
.first().wait()
)
XCTAssertEqual(repo.defaultBranch, "main")
XCTAssertEqual(repo.forks, 1)
XCTAssertEqual(repo.lastIssueClosedAt, Date(timeIntervalSince1970: 2))
XCTAssertEqual(repo.lastPullRequestClosedAt, Date(timeIntervalSince1970: 3))
XCTAssertEqual(repo.license, .mit)
XCTAssertEqual(repo.licenseUrl, "license url")
XCTAssertEqual(repo.openIssues, 1)
XCTAssertEqual(repo.openPullRequests, 2)
XCTAssertEqual(repo.owner, "foo")
XCTAssertEqual(repo.ownerName, "foo")
XCTAssertEqual(repo.ownerAvatarUrl, "https://avatars.githubusercontent.com/u/61124617?s=200&v=4")
XCTAssertEqual(repo.readmeUrl, "readme url")
XCTAssertEqual(repo.readmeHtmlUrl, "readme html url")
XCTAssertEqual(repo.releases, [
.init(description: "a release",
descriptionHTML: "<p>a release</p>",
isDraft: false,
publishedAt: Date(timeIntervalSince1970: 5),
tagName: "1.2.3",
url: "https://example.com/1.2.3")
])
XCTAssertEqual(repo.name, "bar")
XCTAssertEqual(repo.stars, 2)
XCTAssertEqual(repo.isInOrganization, true)
XCTAssertEqual(repo.summary, "package desc")
}
func test_updatePackage() throws {
// setup
let pkgs = try savePackages(on: app.db, ["https://github.com/foo/1",
"https://github.com/foo/2"])
let results: [Result<Package, Error>] = [
.failure(AppError.metadataRequestFailed(try pkgs[0].requireID(), .badRequest, "1")),
.success(pkgs[1])
]
// MUT
try updatePackages(client: app.client,
database: app.db,
logger: app.logger,
results: results,
stage: .ingestion).wait()
// validate
do {
let pkgs = try Package.query(on: app.db).sort(\.$url).all().wait()
XCTAssertEqual(pkgs.map(\.status), [.metadataRequestFailed, .new])
XCTAssertEqual(pkgs.map(\.processingStage), [.ingestion, .ingestion])
}
}
func test_updatePackages_new() throws {
// Ensure newly ingested packages are passed on with status = new to fast-track
// them into analysis
let pkgs = [
Package(id: UUID(), url: "https://github.com/foo/1", status: .ok, processingStage: .reconciliation),
Package(id: UUID(), url: "https://github.com/foo/2", status: .new, processingStage: .reconciliation)
]
try pkgs.save(on: app.db).wait()
let results: [Result<Package, Error>] = [ .success(pkgs[0]), .success(pkgs[1])]
// MUT
try updatePackages(client: app.client,
database: app.db,
logger: app.logger,
results: results,
stage: .ingestion).wait()
// validate
do {
let pkgs = try Package.query(on: app.db).sort(\.$url).all().wait()
XCTAssertEqual(pkgs.map(\.status), [.ok, .new])
XCTAssertEqual(pkgs.map(\.processingStage), [.ingestion, .ingestion])
}
}
func test_partial_save_issue() throws {
// Test to ensure futures are properly waited for and get flushed to the db in full
// setup
Current.fetchMetadata = { _, pkg in self.future(.mock(for: pkg)) }
let packages = try savePackages(on: app.db, testUrls, processingStage: .reconciliation)
// MUT
try ingest(client: app.client, database: app.db, logger: app.logger, limit: testUrls.count).wait()
// validate
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.count, testUrls.count)
XCTAssertEqual(repos.map(\.$package.id), packages.map(\.id))
}
func test_insertOrUpdateRepository_bulk() throws {
// test flattening of many updates
// Mainly a debug test for the issue described here:
// https://discordapp.com/channels/431917998102675485/444249946808647699/704335749637472327
let packages = try savePackages(on: app.db, testUrls100)
let req = packages
.map { ($0, Github.Metadata.mock(for: $0)) }
.map { insertOrUpdateRepository(on: self.app.db,
for: $0.0,
metadata: $0.1,
licenseInfo: .init(htmlUrl: ""),
readmeInfo: .init(downloadUrl: "", htmlUrl: "")) }
.flatten(on: app.db.eventLoop)
try req.wait()
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.count, testUrls100.count)
XCTAssertEqual(repos.map(\.$package.id.uuidString).sorted(),
packages.map(\.id).compactMap { $0?.uuidString }.sorted())
}
func test_ingest_badMetadata() throws {
// setup
let urls = ["https://github.com/foo/1",
"https://github.com/foo/2",
"https://github.com/foo/3"]
let packages = try savePackages(on: app.db, urls.asURLs, processingStage: .reconciliation)
Current.fetchMetadata = { _, pkg in
if pkg.url == "https://github.com/foo/2" {
return self.future(error: AppError.metadataRequestFailed(packages[1].id, .badRequest, URI("2")))
}
return self.future(.mock(for: pkg))
}
let lastUpdate = Date()
// MUT
try ingest(client: app.client, database: app.db, logger: app.logger, limit: 10).wait()
// validate
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.count, 2)
XCTAssertEqual(repos.map(\.summary),
[.some("This is package https://github.com/foo/1"), .some("This is package https://github.com/foo/3")])
(try Package.query(on: app.db).all().wait()).forEach {
if $0.url == "https://github.com/foo/2" {
XCTAssertEqual($0.status, .metadataRequestFailed)
} else {
XCTAssertEqual($0.status, .new)
}
XCTAssert($0.updatedAt! > lastUpdate)
}
}
func test_ingest_unique_owner_name_violation() throws {
// Test error behaviour when two packages resolving to the same owner/name are ingested:
// - don't update package
// - don't create repository records
// - report critical error up to Rollbar
// setup
let urls = ["https://github.com/foo/1", "https://github.com/foo/2"]
let packages = try savePackages(on: app.db, urls.asURLs, processingStage: .reconciliation)
// Return identical metadata for both packages, same as a for instance a redirected
// package would after a rename / ownership change
Current.fetchMetadata = { _, _ in self.future(Github.Metadata.init(
defaultBranch: "main",
forks: 0,
issuesClosedAtDates: [],
license: .mit,
openIssues: 0,
openPullRequests: 0,
owner: "owner",
pullRequestsClosedAtDates: [],
name: "name",
stars: 0,
summary: "desc",
isInOrganization: false))
}
var reportedLevel: AppError.Level? = nil
var reportedError: String? = nil
Current.reportError = { _, level, error in
// Errors seen here go to Rollbar
reportedLevel = level
reportedError = error.localizedDescription
return self.future(())
}
let lastUpdate = Date()
// MUT
try ingest(client: app.client, database: app.db, logger: app.logger, limit: 10).wait()
// validate repositories (single element pointing to first package)
let repos = try Repository.query(on: app.db).all().wait()
XCTAssertEqual(repos.map(\.$package.id), [packages[0].id].compactMap{ $0 })
// validate packages
let pkgs = try Package.query(on: app.db).sort(\.$url).all().wait()
// the first package gets the update ...
XCTAssertEqual(pkgs[0].status, .new)
XCTAssertEqual(pkgs[0].processingStage, .ingestion)
XCTAssert(pkgs[0].updatedAt! > lastUpdate)
// ... the second package remains unchanged ...
XCTAssertEqual(pkgs[1].status, .new)
XCTAssertEqual(pkgs[1].processingStage, .reconciliation)
XCTAssert(pkgs[1].updatedAt! < lastUpdate)
// ... and an error report has been triggered
XCTAssertEqual(reportedLevel, .critical)
XCTAssert(reportedError?.contains("duplicate key value violates unique constraint") ?? false)
}
func test_issue_761_no_license() throws {
// https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/761
// setup
let packages = try savePackages(on: app.db, ["https://github.com/foo/1"])
// use mock for metadata request which we're not interested in ...
Current.fetchMetadata = { _, _ in self.future(Github.Metadata()) }
// and live fetch request for fetchLicense, whose behaviour we want to test ...
Current.fetchLicense = Github.fetchLicense(client:package:)
// and simulate its underlying request returning a 404 (by making all requests
// return a 404, but it's the only one we're sending)
let client = MockClient { _, resp in resp.status = .notFound }
// MUT
let res = try fetchMetadata(client: client, packages: packages).wait()
// validate
XCTAssertEqual(res.map(\.isSuccess), [true], "future must be in success state")
let license = try XCTUnwrap(res.first?.get()).2
XCTAssertEqual(license, nil)
}
}
| 46.595568 | 126 | 0.519886 |
f8f894253056024a561437238aba4cc66ade7f0a | 1,935 | // Copyright 2021 David Sansome
//
// 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
class AppStoreScreenshots: XCTestCase {
var app: XCUIApplication!
override func setUp() {
continueAfterFailure = false
app = XCUIApplication()
setupSnapshot(app, waitForAnimations: false)
app.launch()
}
override func tearDown() {
// Stop the app, then run it again and tell it to clear its settings.
app.terminate()
app.launchArguments.append("ResetUserDefaults")
app.launch()
}
func testAppStoreScreenshots() {
Thread.sleep(forTimeInterval: 1.0) // Wait for the profile photo to be downloaded.
// Snapshot the home screen
snapshot("01_home_screen")
// Snapshot a search results page
app.tables.buttons["Search"].tap()
let search = app.searchFields["Search"]
search.typeText("sake\n")
Thread.sleep(forTimeInterval: 0.5)
snapshot("04_search")
search.buttons["Clear text"].tap()
// Select a subject and snapshot the subject details
search.typeText("person")
app.tables["Search results"].staticTexts["私自身"].tap()
snapshot("02_subject_details")
app.buttons["Back"].tap()
// Catalogue view
app.tables.staticTexts["Show all"].tap()
snapshot("05_catalogue")
app.navigationBars["Level 24"].buttons["Back"].tap()
// Reviews view
app.tables.staticTexts["Reviews"].tap()
snapshot("02_lesson")
}
}
| 29.769231 | 86 | 0.700258 |
116c193d1cc50dd6bbf08234c46d97af0546439f | 1,536 | // Copyright © 2020 Niklas Buelow. All rights reserved.
import Foundation
import AVFoundation
/// The AudioManager is solely responsible for any audio in the game.
/// In our case the only audio is the background music.
class AudioManager {
/// Singleton instance of the audio manager
static let shared: AudioManager = .init()
private let backgroundFilePath = Audio.backgroundMusic
private var audioPlayer: AVAudioPlayer?
/// Set this property to enable or disable the background music
var isBackgroundMusicEnabled: Bool = true {
didSet {
if isBackgroundMusicEnabled {
startBackgroundMusic()
} else {
stopBackgroundMusic()
}
}
}
private init() { /* This class should only be instantiated once */ }
private func startBackgroundMusic() {
guard !(audioPlayer?.isPlaying ?? false) else { return }
guard let url = Bundle.main.url(forResource: backgroundFilePath, withExtension: FileTypes.mp3.rawValue) else { return }
guard let avPlayer = try? AVAudioPlayer(contentsOf: url) else { return }
audioPlayer = avPlayer
// This will cause the music to repeat forever until stopped.
audioPlayer?.numberOfLoops = -1
audioPlayer?.play()
isBackgroundMusicEnabled = true
}
private func stopBackgroundMusic() {
guard audioPlayer?.isPlaying ?? false else { return }
audioPlayer?.stop()
isBackgroundMusicEnabled = false
}
}
| 31.346939 | 127 | 0.660156 |
1a7c76f7d66cbb2647b7d1dba7c543f57d659242 | 17,303 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreBluetooth
/**
The central's delegate is called when asynchronous events occur.
*/
public protocol BKCentralDelegate: class {
/**
Called when a remote peripheral disconnects or is disconnected.
- parameter central: The central from which it disconnected.
- parameter remotePeripheral: The remote peripheral that disconnected.
*/
func central(_ central: BKCentral, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral)
}
/**
The class used to take the Bluetooth LE central role. The central discovers remote peripherals by scanning
and connects to them. When a connection is established the central can receive data from the remote peripheral.
*/
public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoolDelegate, BKAvailabilityObservable {
// MARK: Type Aliases
public typealias ScanProgressHandler = ((_ newDiscoveries: [BKDiscovery]) -> Void)
public typealias ScanCompletionHandler = ((_ result: [BKDiscovery]?, _ error: BKError?) -> Void)
public typealias ContinuousScanChangeHandler = ((_ changes: [BKDiscoveriesChange], _ discoveries: [BKDiscovery]) -> Void)
public typealias ContinuousScanStateHandler = ((_ newState: ContinuousScanState) -> Void)
public typealias ContinuousScanErrorHandler = ((_ error: BKError) -> Void)
public typealias ConnectCompletionHandler = ((_ remotePeripheral: BKRemotePeripheral, _ error: BKError?) -> Void)
// MARK: Enums
/**
Possible states returned by the ContinuousScanStateHandler.
- Stopped: The scan has come to a complete stop and won't start again by triggered manually.
- Scanning: The scan is currently active.
- Waiting: The scan is on hold due while waiting for the in-between delay to expire, after which it will start again.
*/
public enum ContinuousScanState {
case stopped
case scanning
case waiting
}
// MARK: Properties
/// Bluetooth LE availability, derived from the underlying CBCentralManager.
public var availability: BKAvailability? {
guard let centralManager = _centralManager else {
return nil
}
#if os(iOS) || os(tvOS)
if #available(tvOS 10.0, iOS 10.0, *) {
return BKAvailability(managerState: centralManager.state)
} else {
return BKAvailability(centralManagerState: centralManager.centralManagerState)
}
#else
return BKAvailability(centralManagerState: centralManager.state)
#endif
}
/// All currently connected remote peripherals.
public var connectedRemotePeripherals: [BKRemotePeripheral] {
return connectionPool.connectedRemotePeripherals
}
override public var configuration: BKConfiguration? {
return _configuration
}
/// The delegate of the BKCentral object.
public weak var delegate: BKCentralDelegate?
/// Current availability observers.
public var availabilityObservers = [BKWeakAvailabilityObserver]()
internal override var connectedRemotePeers: [BKRemotePeer] {
get {
return connectedRemotePeripherals
}
set {
connectionPool.connectedRemotePeripherals = newValue.flatMap({
guard let remotePeripheral = $0 as? BKRemotePeripheral else {
return nil
}
return remotePeripheral
})
}
}
private var centralManager: CBCentralManager? {
return _centralManager
}
private let scanner = BKScanner()
private let connectionPool = BKConnectionPool()
private var _configuration: BKConfiguration?
private var continuousScanner: BKContinousScanner!
private var centralManagerDelegate: BKCBCentralManagerDelegateProxy!
private var stateMachine: BKCentralStateMachine!
private var _centralManager: CBCentralManager!
// MARK: Initialization
public override init() {
super.init()
centralManagerDelegate = BKCBCentralManagerDelegateProxy(stateDelegate: self, discoveryDelegate: scanner, connectionDelegate: connectionPool)
stateMachine = BKCentralStateMachine()
connectionPool.delegate = self
continuousScanner = BKContinousScanner(scanner: scanner)
}
// MARK: Public Functions
/**
Start the BKCentral object with a configuration.
- parameter configuration: The configuration defining which UUIDs to use when discovering peripherals.
- throws: Throws an InternalError if the BKCentral object is already started.
*/
public func startWithConfiguration(_ configuration: BKConfiguration) throws {
do {
try stateMachine.handleEvent(.start)
_configuration = configuration
_centralManager = CBCentralManager(delegate: centralManagerDelegate, queue: nil, options: nil)
scanner.configuration = configuration
scanner.centralManager = centralManager
connectionPool.centralManager = centralManager
} catch let error {
throw BKError.internalError(underlyingError: error)
}
}
/**
Scan for peripherals for a limited duration of time.
- parameter duration: The number of seconds to scan for (defaults to 3). A duration of 0 means endless
- parameter updateDuplicates: normally, discoveries for the same peripheral are coalesced by IOS. Setting this to true advises the OS to generate new discoveries anyway. This allows you to react to RSSI changes (defaults to false).
- parameter progressHandler: A progress handler allowing you to react immediately when a peripheral is discovered during a scan.
- parameter completionHandler: A completion handler allowing you to react on the full result of discovered peripherals or an error if one occured.
*/
public func scanWithDuration(_ duration: TimeInterval = 3, updateDuplicates: Bool = false, progressHandler: ScanProgressHandler?, completionHandler: ScanCompletionHandler?) {
do {
try stateMachine.handleEvent(.scan)
try scanner.scanWithDuration(duration, updateDuplicates: updateDuplicates, progressHandler: progressHandler) { result, error in
var returnError: BKError?
if error == nil {
_ = try? self.stateMachine.handleEvent(.setAvailable)
} else {
returnError = .internalError(underlyingError: error)
}
completionHandler?(result, returnError)
}
} catch let error {
completionHandler?(nil, .internalError(underlyingError: error))
return
}
}
/**
Scan for peripherals for a limited duration of time continuously with an in-between delay.
- parameter changeHandler: A change handler allowing you to react to changes in "maintained" discovered peripherals.
- parameter stateHandler: A state handler allowing you to react when the scanner is started, waiting and stopped.
- parameter duration: The number of seconds to scan for (defaults to 3). A duration of 0 means endless and inBetweenDelay is pointless
- parameter inBetweenDelay: The number of seconds to wait for, in-between scans (defaults to 3).
- parameter updateDuplicates: normally, discoveries for the same peripheral are coalesced by IOS. Setting this to true advises the OS to generate new discoveries anyway. This allows you to react to RSSI changes (defaults to false).
- parameter errorHandler: An error handler allowing you to react when an error occurs. For now this is also called when the scan is manually interrupted.
*/
public func scanContinuouslyWithChangeHandler(_ changeHandler: @escaping ContinuousScanChangeHandler, stateHandler: ContinuousScanStateHandler?, duration: TimeInterval = 3, inBetweenDelay: TimeInterval = 3, updateDuplicates: Bool = false, errorHandler: ContinuousScanErrorHandler?) {
do {
try stateMachine.handleEvent(.scan)
continuousScanner.scanContinuouslyWithChangeHandler(changeHandler, stateHandler: { newState in
if newState == .stopped && self.availability == .available {
_ = try? self.stateMachine.handleEvent(.setAvailable)
}
stateHandler?(newState)
}, duration: duration, inBetweenDelay: inBetweenDelay, updateDuplicates: updateDuplicates, errorHandler: { error in
errorHandler?(.internalError(underlyingError: error))
})
} catch let error {
errorHandler?(.internalError(underlyingError: error))
}
}
/**
Interrupts the active scan session if present.
*/
public func interruptScan() {
continuousScanner.interruptScan()
scanner.interruptScan()
}
/**
Connect to a remote peripheral.
- parameter timeout: The number of seconds the connection attempt should continue for before failing.
- parameter remotePeripheral: The remote peripheral to connect to.
- parameter completionHandler: A completion handler allowing you to react when the connection attempt succeeded or failed.
*/
public func connect(_ timeout: TimeInterval = 3, remotePeripheral: BKRemotePeripheral, completionHandler: @escaping ConnectCompletionHandler) {
do {
try stateMachine.handleEvent(.connect)
try connectionPool.connectWithTimeout(timeout, remotePeripheral: remotePeripheral) { remotePeripheral, error in
var returnError: BKError?
if error == nil {
_ = try? self.stateMachine.handleEvent(.setAvailable)
} else {
returnError = .internalError(underlyingError: error)
}
completionHandler(remotePeripheral, returnError)
}
} catch let error {
completionHandler(remotePeripheral, .internalError(underlyingError: error))
return
}
}
/**
Disconnects a connected peripheral.
- parameter remotePeripheral: The peripheral to disconnect.
- throws: Throws an InternalError if the remote peripheral is not currently connected.
*/
public func disconnectRemotePeripheral(_ remotePeripheral: BKRemotePeripheral) throws {
do {
try connectionPool.disconnectRemotePeripheral(remotePeripheral)
} catch let error {
throw BKError.internalError(underlyingError: error)
}
}
/**
Stops the BKCentral object.
- throws: Throws an InternalError if the BKCentral object isn't already started.
*/
public func stop() throws {
do {
try stateMachine.handleEvent(.stop)
interruptScan()
connectionPool.reset()
_configuration = nil
_centralManager = nil
} catch let error {
throw BKError.internalError(underlyingError: error)
}
}
/**
Retrieves a previously-scanned peripheral for direct connection.
- parameter remoteUUID: The UUID of the remote peripheral to look for
- return: optional remote peripheral if found
*/
public func retrieveRemotePeripheralWithUUID (remoteUUID: UUID) -> BKRemotePeripheral? {
guard let peripherals = retrieveRemotePeripheralsWithUUIDs(remoteUUIDs: [remoteUUID]) else {
return nil
}
guard peripherals.count > 0 else {
return nil
}
return peripherals[0]
}
/**
Retrieves an array of previously-scanned peripherals for direct connection.
- parameter remoteUUIDs: An array of UUIDs of remote peripherals to look for
- return: optional array of found remote peripherals
*/
public func retrieveRemotePeripheralsWithUUIDs (remoteUUIDs: [UUID]) -> [BKRemotePeripheral]? {
if let centralManager = _centralManager {
let peripherals = centralManager.retrievePeripherals(withIdentifiers: remoteUUIDs)
guard peripherals.count > 0 else {
return nil
}
var remotePeripherals: [BKRemotePeripheral] = []
for peripheral in peripherals {
let remotePeripheral = BKRemotePeripheral(identifier: peripheral.identifier, peripheral: peripheral)
remotePeripheral.configuration = configuration
remotePeripherals.append(remotePeripheral)
}
return remotePeripherals
}
return nil
}
// MARK: Internal Functions
internal func setUnavailable(_ cause: BKUnavailabilityCause, oldCause: BKUnavailabilityCause?) {
scanner.interruptScan()
connectionPool.reset()
if oldCause == nil {
for availabilityObserver in availabilityObservers {
availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .unavailable(cause: cause))
}
} else if oldCause != nil && oldCause != cause {
for availabilityObserver in availabilityObservers {
availabilityObserver.availabilityObserver?.availabilityObserver(self, unavailabilityCauseDidChange: cause)
}
}
}
internal override func sendData(_ data: Data, toRemotePeer remotePeer: BKRemotePeer) -> Bool {
guard let remotePeripheral = remotePeer as? BKRemotePeripheral,
let peripheral = remotePeripheral.peripheral,
let characteristic = remotePeripheral.characteristicData else {
return false
}
peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
return true
}
// MARK: BKCBCentralManagerStateDelegate
internal func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown, .resetting:
break
case .unsupported, .unauthorized, .poweredOff:
let newCause: BKUnavailabilityCause
#if os(iOS) || os(tvOS)
if #available(iOS 10.0, tvOS 10.0, *) {
newCause = BKUnavailabilityCause(managerState: central.state)
} else {
newCause = BKUnavailabilityCause(centralManagerState: central.centralManagerState)
}
#else
newCause = BKUnavailabilityCause(centralManagerState: central.state)
#endif
switch stateMachine.state {
case let .unavailable(cause):
let oldCause = cause
_ = try? stateMachine.handleEvent(.setUnavailable(cause: newCause))
setUnavailable(oldCause, oldCause: newCause)
default:
_ = try? stateMachine.handleEvent(.setUnavailable(cause: newCause))
setUnavailable(newCause, oldCause: nil)
}
case .poweredOn:
let state = stateMachine.state
_ = try? stateMachine.handleEvent(.setAvailable)
switch state {
case .starting, .unavailable:
for availabilityObserver in availabilityObservers {
availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .available)
}
default:
break
}
}
}
// MARK: BKConnectionPoolDelegate
internal func connectionPool(_ connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) {
delegate?.central(self, remotePeripheralDidDisconnect: remotePeripheral)
}
}
| 44.710594 | 287 | 0.663584 |
761da4d03f815a05b099a78ac2b273bc65c59098 | 856 | //
// DAppLifeCycleManager.swift
// DemirciyFramework
//
// Created by Yusuf Demirci on 10.12.2019.
// Copyright © 2019 Yusuf Demirci. All rights reserved.
//
public class DAppLifeCycleManager {
// MARK: - Properties
public static let shared: DAppLifeCycleManager = DAppLifeCycleManager()
// AppDelegate
public var applicationDidBecomeActive: (() -> Void)?
public var applicationWillResignActive: (() -> Void)?
public var applicationWillEnterForeground: (() -> Void)?
public var applicationDidEnterBackground: (() -> Void)?
// SceneDelegate
public var sceneDidDisconnect: (() -> Void)?
public var sceneDidBecomeActive: (() -> Void)?
public var sceneWillResignActive: (() -> Void)?
public var sceneWillEnterForeground: (() -> Void)?
public var sceneDidEnterBackground: (() -> Void)?
}
| 31.703704 | 75 | 0.67757 |
1191e41aa82d86ad8b4fa915d8084f4bcf819a31 | 764 | //
// HasFullTextQuery.swift
// ElastiQ
//
// Created by suguru-kishimoto on 2017/09/04.
// Copyright © 2017年 Suguru Kishimoto. All rights reserved.
//
import Foundation
public protocol HasFullTextQuery {
}
extension HasFullTextQuery where Self: HasParameter {
@discardableResult
public func match(
_ key: QueryKey,
_ value: QueryValue,
`operator`: ElastiQ.FullTextQueries.Match.Operator? = nil,
zeroTermsQuery : ElastiQ.FullTextQueries.Match.ZeroTermsQuery = .unknown,
cutoffFrequency: QueryNumberValue? = nil) -> Self {
add(ElastiQ.FullTextQueries.Match(key: key.key, value: value, operator: `operator`, zeroTermsQuery: zeroTermsQuery, cutoffFrequency: cutoffFrequency))
return self
}
}
| 29.384615 | 158 | 0.705497 |
2347353ed27959d87dc6ad01101d86f2b2e8d4dd | 5,385 | //
// Constants.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-24.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
import WalletKit
let π: CGFloat = .pi
struct Padding {
var increment: CGFloat
subscript(multiplier: Int) -> CGFloat {
return CGFloat(multiplier) * increment
}
static var half: CGFloat {
return C.padding[1]/2.0
}
}
// swiftlint:disable type_name
/// Constants
struct C {
static let padding = Padding(increment: 8.0)
struct Sizes {
static let buttonHeight: CGFloat = 48.0
static let headerHeight: CGFloat = 48.0
static let largeHeaderHeight: CGFloat = 220.0
static let logoAspectRatio: CGFloat = 125.0/417.0
static let cutoutLogoAspectRatio: CGFloat = 342.0/553.0
static let roundedCornerRadius: CGFloat = 6.0
static let homeCellCornerRadius: CGFloat = 6.0
static let brdLogoHeight: CGFloat = 32.0
static let brdLogoTopMargin: CGFloat = E.isIPhoneX ? C.padding[9] + 35.0 : C.padding[9] + 20.0
}
static var defaultTintColor: UIColor = {
return UIView().tintColor
}()
static let animationDuration: TimeInterval = 0.3
static let secondsInDay: TimeInterval = 86400
static let secondsInMinute: TimeInterval = 60
static let maxMoney: UInt64 = 21000000*100000000
static let satoshis: UInt64 = 100000000
static let walletQueue = "com.breadwallet.walletqueue"
static let null = "(null)"
static let maxMemoLength = 250
static let feedbackEmail = "[email protected]"
static let iosEmail = "[email protected]"
static let reviewLink = "https://itunes.apple.com/app/breadwallet-bitcoin-wallet/id885251393?action=write-review"
static var standardPort: Int {
return E.isTestnet ? 18333 : 8333
}
static let bip39CreationTime = TimeInterval(1388534400) - NSTimeIntervalSince1970
static let bCashForkBlockHeight: UInt32 = E.isTestnet ? 1155876 : 478559
static let bCashForkTimeStamp: TimeInterval = E.isTestnet ? (1501597117 - NSTimeIntervalSince1970) : (1501568580 - NSTimeIntervalSince1970)
static let txUnconfirmedHeight = Int32.max
/// Path where core library stores its persistent data
static var coreDataDirURL: URL {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return documentsURL.appendingPathComponent("core-data", isDirectory: true)
}
static let consoleLogFileName = "log.txt"
static let previousConsoleLogFileName = "previouslog.txt"
// Returns the console log file path for the current instantiation of the app.
static var logFilePath: URL {
let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return cachesURL.appendingPathComponent(consoleLogFileName)
}
// Returns the console log file path for the previous instantiation of the app.
static var previousLogFilePath: URL {
let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return cachesURL.appendingPathComponent(previousConsoleLogFileName)
}
static let usdCurrencyCode = "USD"
static let euroCurrencyCode = "EUR"
static let britishPoundCurrencyCode = "GBP"
static let danishKroneCurrencyCode = "DKK"
static let erc20Prefix = "erc20:"
static var backendHost: String {
if let debugBackendHost = UserDefaults.debugBackendHost {
return debugBackendHost
} else {
return (E.isDebug || E.isTestFlight) ? "stage2.breadwallet.com" : "api.breadwallet.com"
}
}
static var webBundle: String {
if let debugWebBundle = UserDefaults.debugWebBundleName {
return debugWebBundle
} else {
// names should match AssetBundles.plist
return (E.isDebug || E.isTestFlight) ? "brd-web-3-staging" : "brd-web-3"
}
}
static var bdbHost: String {
return "api.blockset.com"
}
static let bdbClientTokenRecordId = "BlockchainDBClientID"
static let daiContractAddress = "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359"
static let daiContractCode = "DAI"
static let tusdContractAddress = "0x0000000000085d4780B73119b644AE5ecd22b376"
static let tusdContractCode = "TUSD"
static let fixerAPITokenRecordId = "FixerAPIToken"
}
enum Words {
//Returns the wordlist of the current localization
static var wordList: [NSString]? {
guard let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist") else { return nil }
return NSArray(contentsOfFile: path) as? [NSString]
}
//Returns the wordlist that matches to localization of the phrase
static func wordList(forPhrase phrase: String) -> [NSString]? {
var result = [NSString]()
Bundle.main.localizations.forEach { lang in
if let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist", inDirectory: nil, forLocalization: lang) {
if let words = NSArray(contentsOfFile: path) as? [NSString],
Account.validatePhrase(phrase, words: words.map { String($0) }) {
result = words
}
}
}
return result
}
}
| 37.657343 | 143 | 0.67688 |
71fe33890f4adae05d4ea406498d173fbbcb2130 | 5,935 | //
// LungViewController.swift
// Child
//
// Created by Matsui Keiji on 2019/03/05.
// Copyright © 2019 Matsui Keiji. All rights reserved.
//
import UIKit
import CoreData
class LungViewController: UIViewController {
let appName:AppName = .haigan
@IBOutlet var TXButton:UIButton!
@IBOutlet var TisButton:UIButton!
@IBOutlet var T1miButton:UIButton!
@IBOutlet var T1aButton:UIButton!
@IBOutlet var T1bButton:UIButton!
@IBOutlet var T1cButton:UIButton!
@IBOutlet var T2aButton:UIButton!
@IBOutlet var T2bButton:UIButton!
@IBOutlet var T3Button:UIButton!
@IBOutlet var T4Button:UIButton!
@IBOutlet var TXChecker:UILabel!
@IBOutlet var TisChecker:UILabel!
@IBOutlet var T1miChecker:UILabel!
@IBOutlet var T1aChecker:UILabel!
@IBOutlet var T1bChecker:UILabel!
@IBOutlet var T1cChecker:UILabel!
@IBOutlet var T2aChecker:UILabel!
@IBOutlet var T2bChecker:UILabel!
@IBOutlet var T3Checker:UILabel!
@IBOutlet var T4Checker:UILabel!
@IBOutlet var TsugiButton:UIButton!
@IBOutlet var TisChushakuLabel:UILabel!
@IBOutlet var myToolBar:UIToolbar!
let myContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//saveStringはSaveViewControllerのtableで表示される
//detailStringはSaveDetailViewControllerのtextViewで表示される
var saveString = "St. 0"
var detailString = "Tis 上皮内癌\n\nTis N0 M0 stage 0"
override func viewDidLoad() {
super.viewDidLoad()
lungT = 0
lungN = 0
lungM = 0
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
if height > 800.0 && height < 1000.0{
myToolBar.frame = CGRect(x: 0, y: height * 0.92, width: width, height: height * 0.055)
}
if height > 1000.0 {
myToolBar.frame = CGRect(x: 0, y: height * 0.94, width: width, height: height * 0.05)
}
hideAllCheckers()
TXChecker.isHidden = false
myToolBar.isHidden = true
}
func hideAllCheckers(){
TXChecker.isHidden = true
TisChecker.isHidden = true
T1miChecker.isHidden = true
T1aChecker.isHidden = true
T1bChecker.isHidden = true
T1cChecker.isHidden = true
T2aChecker.isHidden = true
T2bChecker.isHidden = true
T3Checker.isHidden = true
T4Checker.isHidden = true
TsugiButton.isHidden = false
myToolBar.isHidden = true
TisChushakuLabel.isHidden = true
}
@IBAction func TXButtonTapped(){
hideAllCheckers()
TXChecker.isHidden = false
lungT = 0
}
@IBAction func TisButtonTapped(){
hideAllCheckers()
TisChecker.isHidden = false
TsugiButton.isHidden = true
TisChushakuLabel.isHidden = false
myToolBar.isHidden = false
lungT = 1
}
@IBAction func T1miButtonTapped(){
hideAllCheckers()
T1miChecker.isHidden = false
lungT = 2
}
@IBAction func T1aButtonTapped(){
hideAllCheckers()
T1aChecker.isHidden = false
lungT = 3
}
@IBAction func T1bButtonTapped(){
hideAllCheckers()
T1bChecker.isHidden = false
lungT = 4
}
@IBAction func T1cButtonTapped(){
hideAllCheckers()
T1cChecker.isHidden = false
lungT = 5
}
@IBAction func T2aButtonTapped(){
hideAllCheckers()
T2aChecker.isHidden = false
lungT = 6
}
@IBAction func T2bButtonTapped(){
hideAllCheckers()
T2bChecker.isHidden = false
lungT = 7
}
@IBAction func T3ButtonTapped(){
hideAllCheckers()
T3Checker.isHidden = false
lungT = 8
}
@IBAction func T4ButtonTapped(){
hideAllCheckers()
T4Checker.isHidden = false
lungT = 9
}
@IBAction func myActionSave(){
let titleString = "注釈入力"
let messageString = "注釈(メモ、名前等)が入力できます\n(日付とStageは自動的に入力されます)"
let alert = UIAlertController(title:titleString, message: messageString, preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "入力完了", style: UIAlertAction.Style.default, handler:{(action:UIAlertAction!) -> Void in
let textField = alert.textFields![0]
let childData = ChildData(context: self.myContext)
childData.title = self.appName.rawValue
childData.date = Date()
childData.memo = textField.text
childData.value = self.saveString
childData.detailValue = self.detailString
(UIApplication.shared.delegate as! AppDelegate).saveContext()
let id = self.appName.rawValue + "1Save"
self.performSegue(withIdentifier: id, sender: true)
})//let okAction = UIAlertAction
let cancelAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{(action:UIAlertAction!) -> Void in
})//let cancelAction = UIAlertAction
alert.addAction(okAction)
alert.addAction(cancelAction)
// UIAlertControllerにtextFieldを追加
alert.addTextField { (textField:UITextField!) -> Void in }
self.view?.window?.rootViewController?.present(alert, animated: true, completion: nil)
}//@IBAction func myActionSave()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier != "toLungNext" {
let sendText = segue.destination as! SaveViewController
sendText.myText = appName.rawValue
}
}//override func prepare(for segue
@IBAction func TsugiButtonTapped(){
performSegue(withIdentifier: "toLungNext", sender: true)
}
@IBAction func fromLungNextToHome(_ Segue:UIStoryboardSegue){
}
}
| 32.081081 | 135 | 0.638079 |
9b620bb4e88419a87c2187860e57157600135a21 | 330 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
enum ReferendumVotingCase: Int, Encodable {
case support
case unsupport
}
struct ReferendumVote: Encodable {
let referendumId: String
let votes: String
let votingCase: ReferendumVotingCase
}
| 18.333333 | 52 | 0.733333 |
1d5be392e7705293c37775e2fe42b788cc089fed | 8,545 | //
// PetPhotoCollectionViewCell.swift
// toPether
//
// Created by 林宜萱 on 2021/10/18.
//
// swiftlint:disable function_body_length
import UIKit
import Firebase
import FirebaseFirestore
protocol PetCollectionViewCellDelegate: AnyObject {
func pushToInviteVC(pet: Pet)
}
class PetCollectionViewCell: UICollectionViewCell {
weak var delegate: PetCollectionViewCellDelegate?
private var petImageView: RoundCornerImageView!
private var petshadowView: ShadowView!
private var petInfoButton: BorderButton!
private var petName: UILabel!
private var petAge: UILabel!
private var genderImageView: UIImageView!
private let memberStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private var circleButton: CircleButton!
private var addMemberButton: CircleButton!
private var listener: ListenerRegistration?
var pet: Pet?
override init(frame: CGRect) {
super.init(frame: frame)
petImageView = RoundCornerImageView(img: nil)
contentView.addSubview(petImageView)
NSLayoutConstraint.activate([
petImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 24),
petImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24),
petImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24),
petImageView.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 1 / 2, constant: 20)
])
petshadowView = ShadowView(cornerRadius: 20, color: .mainBlue, offset: CGSize(width: 3.0, height: 3.0), opacity: 0.2, radius: 5)
contentView.addSubview(petshadowView)
NSLayoutConstraint.activate([
petshadowView.topAnchor.constraint(equalTo: petImageView.topAnchor),
petshadowView.leadingAnchor.constraint(equalTo: petImageView.leadingAnchor),
petshadowView.trailingAnchor.constraint(equalTo: petImageView.trailingAnchor),
petshadowView.bottomAnchor.constraint(equalTo: petImageView.bottomAnchor)
])
contentView.bringSubviewToFront(petImageView)
petInfoButton = BorderButton()
petInfoButton.setShadow(color: .mainBlue, offset: CGSize(width: 3.0, height: 3.0), opacity: 0.1, radius: 6)
contentView.addSubview(petInfoButton)
NSLayoutConstraint.activate([
petInfoButton.topAnchor.constraint(equalTo: petImageView.bottomAnchor, constant: 16),
petInfoButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
petInfoButton.widthAnchor.constraint(equalTo: contentView.widthAnchor, constant: -52),
petInfoButton.heightAnchor.constraint(equalToConstant: 80)
])
petName = UILabel()
petName.font = UIFont.medium(size: 22)
petName.textColor = .mainBlue
petName.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(petName)
NSLayoutConstraint.activate([
petName.topAnchor.constraint(equalTo: petInfoButton.topAnchor, constant: 12),
petName.leadingAnchor.constraint(equalTo: petInfoButton.leadingAnchor, constant: 16),
petName.trailingAnchor.constraint(equalTo: petInfoButton.trailingAnchor, constant: -16),
petName.heightAnchor.constraint(equalToConstant: 28)
])
petAge = UILabel()
petAge.textColor = .deepBlueGrey
petAge.font = UIFont.regular(size: 18)
petAge.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(petAge)
NSLayoutConstraint.activate([
petAge.topAnchor.constraint(equalTo: petName.bottomAnchor, constant: 4),
petAge.leadingAnchor.constraint(equalTo: petInfoButton.leadingAnchor, constant: 16),
petAge.widthAnchor.constraint(equalTo: petInfoButton.widthAnchor, multiplier: 0.5),
petAge.heightAnchor.constraint(equalToConstant: 22)
])
genderImageView = UIImageView()
genderImageView.contentMode = .scaleAspectFill
genderImageView.clipsToBounds = true
genderImageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(genderImageView)
NSLayoutConstraint.activate([
genderImageView.centerYAnchor.constraint(equalTo: petAge.centerYAnchor),
genderImageView.trailingAnchor.constraint(equalTo: petInfoButton.trailingAnchor, constant: -16),
genderImageView.widthAnchor.constraint(equalToConstant: 22),
genderImageView.heightAnchor.constraint(equalToConstant: 22)
])
let tap = UITapGestureRecognizer(target: self, action: #selector(tapStackView))
memberStackView.addGestureRecognizer(tap)
contentView.addSubview(memberStackView)
NSLayoutConstraint.activate([
memberStackView.topAnchor.constraint(equalTo: petInfoButton.bottomAnchor, constant: 12),
memberStackView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor)
])
addMemberButton = CircleButton(img: Img.iconsAddWhite.obj, bgColor: .mainYellow, borderColor: .clear)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reload(pet: Pet) {
self.pet = pet // initialize pet for reloading each time
addListener(pet: pet)
}
func updateCell(pet: Pet, members: [Member]) {
self.pet = pet
petImageView.image = pet.photoImage
petName.text = pet.name
petAge.text = pet.ageInfo
if pet.gender == "male" {
genderImageView.image = Img.iconsGenderMale.obj
} else {
genderImageView.image = Img.iconsGenderFemale.obj
}
memberStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
updateMembers(members)
}
func addListener(pet: Pet) {
listener?.remove() // remove instance listener, Stop listening to changes
listener = PetManager.shared.addPetListener(pet: pet, completion: { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let pet):
// self.pet?.memberIds.count != pet.memberIds.count &&
if !pet.memberIds.isEmpty {
MemberManager.shared.queryMembers(ids: pet.memberIds) { [weak self] result in
switch result {
case .success(let members):
guard let self = self else { return }
self.updateCell(pet: pet, members: members)
case .failure(let error):
print(error)
}
}
}
case .failure(let error):
print("addListener error", error)
}
})
}
private func updateMembers(_ members: [Member]) {
members.forEach { member in
circleButton = CircleButton(name: member.name.first?.description ?? "")
circleButton.layer.cornerRadius = 32 / 2
NSLayoutConstraint.activate([
circleButton.heightAnchor.constraint(equalToConstant: 32),
circleButton.widthAnchor.constraint(equalToConstant: 32)
])
memberStackView.addArrangedSubview(circleButton)
circleButton.isUserInteractionEnabled = false
}
if members.count < 7 {
addMemberButton.layer.cornerRadius = 32 / 2
NSLayoutConstraint.activate([
addMemberButton.heightAnchor.constraint(equalToConstant: 32),
addMemberButton.widthAnchor.constraint(equalToConstant: 32)
])
memberStackView.addArrangedSubview(addMemberButton)
addMemberButton.isUserInteractionEnabled = false
}
}
@objc func tapStackView(sender: AnyObject) {
guard let pet = pet else { return }
delegate?.pushToInviteVC(pet: pet)
}
}
| 41.480583 | 136 | 0.6488 |
8ad970241cd977955010f90ed8ebc55c1c53e747 | 3,744 | //
// Logging.swift
// Keldeo
//
// Created by bl4ckra1sond3tre on 2018/8/20.
// Copyright © 2018 blessingsoftware. All rights reserved.
//
import Foundation
public enum Level: Int {
case off = 0
case error = 1 // Flag.error | Level.off
case warning = 3 // Flag.warning | Level.error
case info = 7 // Flag.info | Level.warning
case debug = 15 // Flag.debug | Level.info
}
public struct Flag: OptionSet {
public let rawValue: Int
public static let error = Flag(rawValue: 1 << 0) // 1
public static let warning = Flag(rawValue: 1 << 1) // 2
public static let info = Flag(rawValue: 1 << 2) // 4
public static let debug = Flag(rawValue: 1 << 3) // 8
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
/// Logging protocol, describes a logger behavior.
public protocol Logging: Hashable {
/// Log formatter for format log message before output
var formatter: Formatter { get }
/// Logger name
var name: String { get }
/// Logger level for filter output
var level: Level { get }
/// Log method, use this method to output log message.
///
/// - Parameter message: log message
func log(message: Message)
/// Implemented to flush all pending IO
func flush()
/// Timing for setup tasks
func start()
/// Timing for teardown tasks
func teardown()
}
public extension Logging {
var name: String {
return "Unified"
}
func flush() {}
func start() {}
func teardown() {}
}
// MARK: - AnyLogger
internal func _abstract(file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("Abstract method must be overridden", file: file, line: line)
}
protocol AnyLoggerBox {
func unbox<T: Logging>() -> T?
var formatter: Formatter { get }
var level: Level { get }
func log(message: Message)
func start()
func teardown()
func flush()
// hashable
var hashValue: Int { get }
func isEqual(to: AnyLoggerBox) -> Bool?
}
struct ConcreteLoggerBox<Base: Logging>: AnyLoggerBox {
var base: Base
init(_ base: Base) {
self.base = base
}
var formatter: Formatter {
return base.formatter
}
var level: Level {
return base.level
}
func unbox<T : Logging>() -> T? {
return (self as AnyLoggerBox as? ConcreteLoggerBox<T>)?.base
}
func log(message: Message) {
base.log(message: message)
}
func flush() {
base.flush()
}
func start() {
base.start()
}
func teardown() {
base.teardown()
}
var hashValue: Int {
return base.hashValue
}
func isEqual(to other: AnyLoggerBox) -> Bool? {
guard let other: Base = other.unbox() else {
return nil
}
return other == base
}
}
public struct AnyLogger {
private var box: AnyLoggerBox
public init<T: Logging>(_ box: T) {
self.box = ConcreteLoggerBox(box)
}
}
extension AnyLogger: Logging {
public var formatter: Formatter {
return box.formatter
}
public var level: Level {
return box.level
}
public func log(message: Message) {
box.log(message: message)
}
public func flush() {
box.flush()
}
public func start() {
box.start()
}
public func teardown() {
box.teardown()
}
}
extension AnyLogger: Hashable {
public static func == (lhs: AnyLogger, rhs: AnyLogger) -> Bool {
if let result = lhs.box.isEqual(to: rhs.box) {
return result
}
return false
}
public func hash(into hasher: inout Hasher) {
hasher.combine(box.hashValue)
}
}
| 19.5 | 82 | 0.590812 |
8ac4f1971d6c74a1e81cf53043e0c93df1e7c867 | 4,795 | //
// ShapeDragHandler.swift
// Drawsana
//
// Created by Manu Mohan on 21/02/20.
//
import Foundation
class ShapeDragHandler {
let shape: (ShapeWithBezierPath & ShapeWithTransform & ShapeWithBoundingRect)
weak var tool: ShapeEditingTool?
var startPoint: CGPoint = .zero
init(
shape: (ShapeWithBezierPath & ShapeWithTransform & ShapeWithBoundingRect),
tool: ShapeEditingTool
) {
self.shape = shape
self.tool = tool
}
func handleDragStart(context _: ToolOperationContext, point: CGPoint) {
startPoint = point
}
func handleDragContinue(context _: ToolOperationContext, point _: CGPoint, velocity _: CGPoint) {}
func handleDragEnd(context _: ToolOperationContext, point _: CGPoint) {}
func handleDragCancel(context _: ToolOperationContext, point _: CGPoint) {}
}
/// User is dragging the text itself to a new location
class ShapeMoveHandler: ShapeDragHandler {
private var originalTransform: ShapeTransform
override init(
shape: (ShapeWithBezierPath & ShapeWithTransform & ShapeWithBoundingRect),
tool: ShapeEditingTool
) {
originalTransform = shape.transform
super.init(shape: shape, tool: tool)
}
override func handleDragContinue(context _: ToolOperationContext, point: CGPoint, velocity _: CGPoint) {
let delta = point - startPoint
shape.transform = originalTransform.translated(by: delta)
// tool?.updateTextView()
}
override func handleDragEnd(context: ToolOperationContext, point: CGPoint) {
let delta = CGPoint(x: point.x - startPoint.x, y: point.y - startPoint.y)
context.operationStack.apply(operation: ChangeTransformOperation(
shape: shape,
transform: originalTransform.translated(by: delta),
originalTransform: originalTransform
))
}
override func handleDragCancel(context: ToolOperationContext, point _: CGPoint) {
shape.transform = originalTransform
context.toolSettings.isPersistentBufferDirty = true
// tool?.updateShapeFrame()
}
}
/// User is dragging the lower-right handle to change the size and rotation
/// of the text box
class ShapeResizeAndRotateHandler: ShapeDragHandler {
private var originalTransform: ShapeTransform
override init(
shape: (ShapeWithBezierPath & ShapeWithTransform & ShapeWithBoundingRect),
tool: ShapeEditingTool
) {
originalTransform = shape.transform
super.init(shape: shape, tool: tool)
}
private func getResizeAndRotateTransform(point: CGPoint) -> ShapeTransform {
let originalDelta = startPoint - shape.transform.translation
let newDelta = point - shape.transform.translation
let originalDistance = originalDelta.length
let newDistance = newDelta.length
let originalAngle = atan2(originalDelta.y, originalDelta.x)
let newAngle = atan2(newDelta.y, newDelta.x)
let scaleChange = newDistance / originalDistance
let angleChange = newAngle - originalAngle
return originalTransform.scaled(by: scaleChange).rotated(by: angleChange)
}
override func handleDragContinue(context _: ToolOperationContext, point: CGPoint, velocity _: CGPoint) {
shape.transform = getResizeAndRotateTransform(point: point)
// tool?.updateTextView()
}
override func handleDragEnd(context: ToolOperationContext, point: CGPoint) {
context.operationStack.apply(operation: ChangeTransformOperation(
shape: shape,
transform: getResizeAndRotateTransform(point: point),
originalTransform: originalTransform
))
}
override func handleDragCancel(context: ToolOperationContext, point _: CGPoint) {
shape.transform = originalTransform
context.toolSettings.isPersistentBufferDirty = true
// tool?.updateShapeFrame()
}
}
/// User is dragging the middle-right handle to change the width of the text
/// box
class ShapeChangeWidthHandler: ShapeDragHandler {
private var originalWidth: CGFloat?
private var originalBoundingRect: CGRect = .zero
override init(
shape: (ShapeWithBezierPath & ShapeWithTransform & ShapeWithBoundingRect),
tool: ShapeEditingTool
) {
originalWidth = shape.boundingRect.width
originalBoundingRect = shape.boundingRect
super.init(shape: shape, tool: tool)
}
override func handleDragContinue(context _: ToolOperationContext, point: CGPoint, velocity _: CGPoint) {
}
override func handleDragEnd(context: ToolOperationContext, point _: CGPoint) {
}
override func handleDragCancel(context: ToolOperationContext, point _: CGPoint) {
}
}
| 34.25 | 108 | 0.697602 |
d9402ee9dde7b5f3d6426222b86a7224a61bf7e9 | 1,232 | //
// GuitarString.swift
// Guitar
//
// Created by Gabrielle Miller-Messner on 4/13/16.
// Copyright © 2016 Gabrielle Miller-Messner. All rights reserved.
//
import Cocoa
@objc enum error: Int, Error {
case Broken
case OutOfTune
}
@objc class GuitarString: NSObject {
var broken: Bool = false
var outOfTune: Bool = false
func pluck(velocity: Float) throws {
if broken {
// can't play a broken string
throw error.Broken
}
if outOfTune {
// you can still play an out of tune string, this is just to illustrate another error type
throw error.OutOfTune
}
// We're playing the string really hard.
if velocity > 0.8 {
if arc4random() % 2 == 0 {
// We knocked the string out of tune. The next time we play, it will sound bad.
outOfTune = true
}
if arc4random() % 2 == 1 {
// We broke the string! This sounds bad when it happens, so throw an error right away.
broken = true
throw error.Broken
}
}
print("twang 🎶")
}
}
| 25.142857 | 102 | 0.528409 |
ef7288a506650ff2f00920f563f655ce00ea83d2 | 480 | //
// Contants.swift
// PruebaiOS
//
// Created by Ale on 7/31/19.
// Copyright © 2019 everis. All rights reserved.
//
import Foundation
enum ApiKeys: String {
case url = "https://api.themoviedb.org/3/discover/movie"
case detail = "https://api.themoviedb.org/3/movie/"
case apiKey = "bcdd5bee98f3d2a50025a4e9ff547f2c"
case imageUrl200 = "https://image.tmdb.org/t/p/w200"
case imageUrl500 = "https://image.tmdb.org/t/p/w500"
case language = "en-US"
}
| 25.263158 | 60 | 0.672917 |
64f4c09901ce39d6613e75c74d2f09ee2076a078 | 2,327 | // RUN: %target-swift-frontend -Xllvm -tf-dynamic-compilation=false -Xllvm -tf-dump-intermediates -emit-sil %s | %FileCheck %s
import TensorFlow
public func basicDebugValues(_ x: Tensor<Float>) {
let y = x + 1
let z = y.squared()
}
// FIXME: `debug_value_addr` for `z` is not currently preserved due to SSA promotion in deabstraction.
public func debugValuesInLoop(_ x: Tensor<Float>, _ n: Int) {
var z = x.squared()
for i in 0..<n {
z += x
}
}
// Opaque handles should not trigger send/receive even at -Onone, so we won't
// expect their `debug_value` to work.
public func noCopyForOpaqueHandles() {
let values = Tensor<Float>([1.0])
let dataset: VariantHandle =
#tfop("TensorSliceDataset", [values],
Toutput_types$dtype: [Float.tensorFlowDataType], output_shapes: [TensorShape()])
}
// CHECK-LABEL: --- TFPartition Accelerator Result: {{.*}}basicDebugValues
// CHECK: @{{.*}}basicDebugValues{{.*}}.tf
// CHECK: [[ONE:%.*]] = graph_op "Const"
// CHECK: [[ADD_RESULT:%.*]] = graph_op "Add"
// CHECK: graph_op "Square"([[ADD_RESULT]] : $TensorHandle<Float>) {T$dtype: i32 1, __device: "/job:localhost/replica:0/task:0/device:CPU:0"} : $TensorHandle<Float>
// CHECK-LABEL: --- TFPartition Accelerator Result: {{.*}}debugValuesInLoop
// CHECK: bb0
// CHECK: [[SQUARED:%.*]] = graph_op "Square"
// CHECK-NEXT: br bb1([[SQUARED]] : $TensorHandle<Float>)
// CHECK: bb1
// CHECK: graph_op "tfc.RecvFromHost"()
// CHECK: [[COND:%.*]] = graph_op "tf_tensor_to_i1"
// CHECK: cond_br [[COND]], bb2, bb3
// CHECK: bb2:
// CHECK: [[ADD_RESULT:%.*]] = graph_op "Add"
// CHECK-NEXT: br bb1([[ADD_RESULT]]
// CHECK-LABEL: ---- PARTITION STATE FOR FUNCTION ${{.*}}noCopyForOpaqueHandle
// CHECK: result values:
// CHECK-NOT: graph_op "TensorSliceDataset"([%4 : $TensorHandle<Float>])
// CHECK-LABEL: --- TFPartition Host Result: {{.*}}basicDebugValues
// CHECK: debug_value %{{.*}} : $Tensor<Float>, let, name "x", argno 1
// CHECK: debug_value %{{.*}} : $Tensor<Float>, let, name "y"
// CHECK: debug_value %{{.*}} : $Tensor<Float>, let, name "z"
// CHECK-LABEL: --- TFPartition Host Result: {{.*}}debugValuesInLoop{{.*}}
// CHECK: bb0(%0 : $Tensor<Float>):
// CHECK: debug_value %{{.*}} : $Tensor<Float>, let, name "x", argno 1
// CHECK: debug_value %{{.*}} : $Int, let, name "i"
| 37.532258 | 164 | 0.646755 |
50fbeb583d8a62b2d1570ac71f3dffad9f322e2c | 455 | //
// IanKeen.swift
// CodeChallenge
//
// Created by Ryan Arana on 11/1/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let ianKeenTwoSumEntry = CodeChallengeEntry<TwoSumChallenge>(name: "IanKeen") { input in
for (index, digit) in input.numbers.enumerated() {
if let other = input.numbers.index(of: input.target - digit) {
return (index + 1, Int(other) + 1)
}
}
return nil
}
| 23.947368 | 88 | 0.643956 |
2f6eeb13052b3e746cc2b223c1e025b7a11ffaae | 1,452 | //
// MIT License
//
// Copyright (c) 2020 micheltlutz
//
// 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
/**
Small tag element class
### Usage Example: ###
````
Small("Text Small")
````
*/
public class Small: TypographyElementBase {
///Override tag element for element. Default is `small`
override var tag: String {
get {
return "small"
}
}
}
| 33.767442 | 81 | 0.713499 |
f93358cf4f6236e33b85302ad52fb117714ff957 | 1,539 | //
// DataDetailParameterable.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Stanwood GmbH (www.stanwood.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.
//
protocol DataDetailParameterable {
var networkData: NetworkData { get }
}
class DataDetailParameters: DebuggerParamaters, DataDetailParameterable {
let networkData: NetworkData
init(appData: DebuggerData, data: NetworkData) {
networkData = data
super.init(appData: appData)
}
}
| 38.475 | 81 | 0.737492 |
14065d546218186db257f3510e9643e1fca069f6 | 1,236 | //
// Copyright © 2020 Paris Android User Group. All rights reserved.
//
import Foundation
import FirebaseFirestore
import Combine
import FirebaseCrashlytics
/// Object that provides speakers from Firestore
class FirestoreSpeakersProvider: SpeakersProvider {
var speakersPublisher = PassthroughSubject<[String: SpeakerData], Error>()
init(database: Firestore) {
database.collection("speakers").getDocuments { [weak self] (querySnapshot, err) in
guard let self = self else { return }
if let err = err {
print("Error getting speakers documents: \(err)")
self.speakersPublisher.send(completion: .failure(err))
} else {
do {
var speakers = [String: SpeakerData]()
for document in querySnapshot!.documents {
speakers[document.documentID] = try document.decoded()
}
self.speakersPublisher.send(speakers)
} catch let error {
Crashlytics.crashlytics().record(error: error)
self.speakersPublisher.send(completion: .failure(error))
}
}
}
}
}
| 35.314286 | 90 | 0.583333 |
26748b799bdcc0a5f762c193f113375477a77cd2 | 2,639 | //
// ReachabilityService.swift
// RxExample
//
// Created by Vodovozov Gleb on 10/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
#if swift(>=3.2)
import class Dispatch.DispatchQueue
#else
import class Dispatch.queue.DispatchQueue
#endif
public enum ReachabilityStatus {
case reachable(viaWiFi: Bool)
case unreachable
}
extension ReachabilityStatus {
var reachable: Bool {
switch self {
case .reachable:
return true
case .unreachable:
return false
}
}
}
protocol ReachabilityService {
var reachability: Observable<ReachabilityStatus> { get }
}
enum ReachabilityServiceError: Error {
case failedToCreate
}
class DefaultReachabilityService
: ReachabilityService {
static var sharedReachabilityService = try! DefaultReachabilityService()
private let _reachabilitySubject: BehaviorSubject<ReachabilityStatus>
var reachability: Observable<ReachabilityStatus> {
return _reachabilitySubject.asObservable()
}
let _reachability: Reachability
init() throws {
guard let reachabilityRef = Reachability() else { throw ReachabilityServiceError.failedToCreate }
let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable)
// so main thread isn't blocked when reachability via WiFi is checked
let backgroundQueue = DispatchQueue(label: "reachability.wificheck")
reachabilityRef.whenReachable = { reachability in
backgroundQueue.async {
reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.isReachableViaWiFi)))
}
}
reachabilityRef.whenUnreachable = { reachability in
backgroundQueue.async {
reachabilitySubject.on(.next(.unreachable))
}
}
try reachabilityRef.startNotifier()
_reachability = reachabilityRef
_reachabilitySubject = reachabilitySubject
}
deinit {
_reachability.stopNotifier()
}
}
extension ObservableConvertibleType {
func retryOnBecomesReachable(_ valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> {
return self.asObservable()
.catchError { (e) -> Observable<E> in
reachabilityService.reachability
.skip(1)
.filter { $0.reachable }
.flatMap { _ in
Observable.error(e)
}
.startWith(valueOnFailure)
}
.retry()
}
}
| 26.928571 | 113 | 0.64532 |
33d6701fb6e819d5095704d5044fc9052a7af0c6 | 12,644 | import CLibMongoC
import Foundation
import NIO
/// Direct wrapper of a `mongoc_change_stream_t`.
private struct MongocChangeStream: MongocCursorWrapper {
internal let pointer: OpaquePointer
internal static var isLazy: Bool { false }
fileprivate init(stealing ptr: OpaquePointer) {
self.pointer = ptr
}
internal func errorDocument(bsonError: inout bson_error_t, replyPtr: UnsafeMutablePointer<BSONPointer?>) -> Bool {
mongoc_change_stream_error_document(self.pointer, &bsonError, replyPtr)
}
internal func next(outPtr: UnsafeMutablePointer<BSONPointer?>) -> Bool {
mongoc_change_stream_next(self.pointer, outPtr)
}
internal func more() -> Bool {
true
}
internal func destroy() {
mongoc_change_stream_destroy(self.pointer)
}
}
/// A token used for manually resuming a change stream. Pass this to the `resumeAfter` field of
/// `ChangeStreamOptions` to resume or start a change stream where a previous one left off.
/// - SeeAlso: https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream
public struct ResumeToken: Codable, Equatable {
private let resumeToken: BSONDocument
internal init(_ resumeToken: BSONDocument) {
self.resumeToken = resumeToken
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.resumeToken)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.resumeToken = try container.decode(BSONDocument.self)
}
}
// TODO: SWIFT-981: Remove this.
/// The key we use for storing a change stream's namespace in it's `userInfo`. This allows types
/// using the decoder e.g. `ChangeStreamEvent` to access the namespace even if it is not present in the raw
/// document the server returns. Ok to force unwrap as initialization never fails.
// swiftlint:disable:next force_unwrapping
internal let changeStreamNamespaceKey = CodingUserInfoKey(rawValue: "namespace")!
// sourcery: skipSyncExport
/// A MongoDB change stream.
/// - SeeAlso: https://docs.mongodb.com/manual/changeStreams/
public class ChangeStream<T: Codable>: CursorProtocol {
internal typealias Element = T
/// The client this change stream descended from.
private let client: MongoClient
/// Decoder for decoding documents into type `T`.
private let decoder: BSONDecoder
/// The cursor this change stream is wrapping.
private let wrappedCursor: Cursor<MongocChangeStream>
/// Process an event before returning it to the user, or does nothing and returns nil if the provided event is nil.
private func processEvent(_ event: BSONDocument?) throws -> T? {
guard let event = event else {
return nil
}
return try self.processEvent(event)
}
/// Process an event before returning it to the user.
private func processEvent(_ event: BSONDocument) throws -> T {
// Update the resumeToken with the `_id` field from the document.
guard let resumeToken = event["_id"]?.documentValue else {
throw MongoError.InternalError(message: "_id field is missing from the change stream document.")
}
self.resumeToken = ResumeToken(resumeToken)
return try self.decoder.decode(T.self, from: event)
}
internal init(
stealing changeStreamPtr: OpaquePointer,
connection: Connection,
client: MongoClient,
namespace: MongoNamespace,
session: ClientSession?,
decoder: BSONDecoder,
options: ChangeStreamOptions?
) throws {
let mongocChangeStream = MongocChangeStream(stealing: changeStreamPtr)
self.wrappedCursor = try Cursor(
mongocCursor: mongocChangeStream,
connection: connection,
session: session,
type: .tailableAwait
)
self.client = client
self.decoder = BSONDecoder(copies: decoder, options: nil)
self.decoder.userInfo[changeStreamNamespaceKey] = namespace
// TODO: SWIFT-519 - Starting 4.2, update resumeToken to startAfter (if set).
// startAfter takes precedence over resumeAfter.
if let resumeAfter = options?.resumeAfter {
self.resumeToken = resumeAfter
}
}
/**
* Indicates whether this change stream has the potential to return more data.
*
* This change stream will be dead after `next` returns `nil`, but it may still be alive after `tryNext` returns
* `nil`.
*
* After either of `next` or `tryNext` return a non-`DecodingError` error, this change stream will be dead. It may
* still be alive after either returns a `DecodingError`, however.
*
* - Warning:
* If this change stream is alive when it goes out of scope, it will leak resources. To ensure it is dead
* before it leaves scope, invoke `ChangeStream.kill(...)` on it.
*/
public func isAlive() -> EventLoopFuture<Bool> {
self.client.operationExecutor.execute {
self.wrappedCursor.isAlive
}
}
/// The `ResumeToken` associated with the most recent event seen by the change stream.
public internal(set) var resumeToken: ResumeToken?
/**
* Get the next `T` from this change stream.
*
* This method will continue polling until an event is returned from the server, an error occurs,
* or the change stream is killed. Each attempt to retrieve results will wait for a maximum of `maxAwaitTimeMS`
* (specified on the `ChangeStreamOptions` passed to the method that created this change stream) before trying
* again.
*
* A thread from the driver's internal thread pool will be occupied until the returned future is completed, so
* performance degradation is possible if the number of polling change streams is too close to the total number of
* threads in the thread pool. To configure the total number of threads in the pool, set the
* `MongoClientOptions.threadPoolSize` option during client creation.
*
* Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from
* this method is unresolved. Doing so will result in undefined behavior.
*
* - Returns:
* An `EventLoopFuture<T?>` evaluating to the next `T` in this change stream, `nil` if the change stream is
* exhausted, or an error if one occurred. The returned future will not resolve until one of those conditions is
* met, potentially after multiple requests to the server.
*
* If the future evaluates to an error, it is likely one of the following:
* - `MongoError.CommandError` if an error occurs while fetching more results from the server.
* - `MongoError.LogicError` if this function is called after the change stream has died.
* - `MongoError.LogicError` if this function is called and the session associated with this change stream is
* inactive.
* - `DecodingError` if an error occurs decoding the server's response.
*/
public func next() -> EventLoopFuture<T?> {
self.client.operationExecutor.execute {
try self.processEvent(self.wrappedCursor.next())
}
}
/**
* Attempt to get the next `T` from this change stream, returning `nil` if there are no results.
*
* The change stream will wait server-side for a maximum of `maxAwaitTimeMS` (specified on the `ChangeStreamOptions`
* passed to the method that created this change stream) before returning `nil`.
*
* This method may be called repeatedly while `isAlive` is true to retrieve new data.
*
* Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from
* this method is unresolved. Doing so will result in undefined behavior.
*
* - Returns:
* An `EventLoopFuture<T?>` containing the next `T` in this change stream, an error if one occurred, or `nil` if
* there was no data.
*
* If the future evaluates to an error, it is likely one of the following:
* - `MongoError.CommandError` if an error occurs while fetching more results from the server.
* - `MongoError.LogicError` if this function is called after the change stream has died.
* - `MongoError.LogicError` if this function is called and the session associated with this change stream is
* inactive.
* - `DecodingError` if an error occurs decoding the server's response.
*/
public func tryNext() -> EventLoopFuture<T?> {
self.client.operationExecutor.execute {
try self.processEvent(self.wrappedCursor.tryNext())
}
}
/**
* Consolidate the currently available results of the change stream into an array of type `T`.
*
* Since `toArray` will only fetch the currently available results, it may return more data if it is called again
* while the change stream is still alive.
*
* Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from
* this method is unresolved. Doing so will result in undefined behavior.
*
* - Returns:
* An `EventLoopFuture<[T]>` evaluating to the results currently available in this change stream, or an error.
*
* If the future evaluates to an error, that error is likely one of the following:
* - `MongoError.CommandError` if an error occurs while fetching more results from the server.
* - `MongoError.LogicError` if this function is called after the change stream has died.
* - `MongoError.LogicError` if this function is called and the session associated with this change stream is
* inactive.
* - `DecodingError` if an error occurs decoding the server's responses.
*/
public func toArray() -> EventLoopFuture<[T]> {
self.client.operationExecutor.execute {
try self.wrappedCursor.toArray().map(self.processEvent)
}
}
/**
* Calls the provided closure with each event in the change stream as it arrives.
*
* A thread from the driver's internal thread pool will be occupied until the returned future is completed, so
* performance degradation is possible if the number of polling change streams is too close to the total number of
* threads in the thread pool. To configure the total number of threads in the pool, set the
* `MongoClientOptions.threadPoolSize` option during client creation.
*
* Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from
* this method is unresolved. Doing so will result in undefined behavior.
*
* - Returns:
* An `EventLoopFuture<Void>` which will complete once the change stream is closed or once an error is
* encountered.
*
* If the future evaluates to an error, that error is likely one of the following:
* - `MongoError.CommandError` if an error occurs while fetching more results from the server.
* - `MongoError.LogicError` if this function is called after the change stream has died.
* - `MongoError.LogicError` if this function is called and the session associated with this change stream is
* inactive.
* - `DecodingError` if an error occurs decoding the server's responses.
*/
public func forEach(_ body: @escaping (T) throws -> Void) -> EventLoopFuture<Void> {
self.client.operationExecutor.execute {
while let next = try self.processEvent(self.wrappedCursor.next()) {
try body(next)
}
}
}
/**
* Kill this change stream.
*
* This method MAY be called even if there are unresolved futures created from other `ChangeStream` methods.
*
* This method MAY be called if the change stream is already dead. It will have no effect.
*
* - Warning:
* If this change stream is alive when it goes out of scope, it will leak resources. To ensure it
* is dead before it leaves scope, invoke this method.
*
* - Returns:
* An `EventLoopFuture` that evaluates when the change stream has completed closing. This future should not fail.
*/
public func kill() -> EventLoopFuture<Void> {
self.client.operationExecutor.execute {
self.wrappedCursor.kill()
}
}
}
| 45.318996 | 120 | 0.678266 |
5dbda5a5a277620d9bca884051692fb2497b7a85 | 2,364 | import FluentProvider
final class Reminder: Model {
let storage = Storage()
let title: String
let description: String
let userID: Identifier?
struct Properties {
static let id = "id"
static let title = "title"
static let description = "description"
static let userID = "user_id"
}
init(row: Row) throws {
title = try row.get(Properties.title)
description = try row.get(Properties.description)
userID = try row.get(User.foreignIdKey)
}
init(title: String, description: String, user: User) {
self.title = title
self.description = description
self.userID = user.id
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Properties.title, title)
try row.set(Properties.description, description)
try row.set(User.foreignIdKey, userID)
return row
}
}
// Create the tables when app first runs
extension Reminder: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
// Create columns
builder.id()
builder.string(Properties.title)
builder.string(Properties.description)
builder.parent(User.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// Get categories
extension Reminder {
var categories: Siblings<Reminder, Category, Pivot<Reminder, Category>> {
return siblings()
}
}
// Represent Reminder as JSON object
extension Reminder: JSONConvertible {
convenience init(json: JSON) throws {
let userId: Identifier = try json.get(Properties.userID)
guard let user = try User.find(userId) else {
throw Abort.badRequest
}
try self.init(title: json.get(Properties.title), description: json.get(Properties.description), user: user)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Properties.id, id)
try json.set(Properties.title, title)
try json.set(Properties.description, description)
try json.set(Properties.userID, userID)
return json
}
}
// Since there is a JSON representation
extension Reminder: ResponseRepresentable {}
| 27.811765 | 115 | 0.623942 |
fec81c7c0d4b27be9dc257f5878414cf66c1f17c | 2,041 | import UIKit
import Logging
import Foundation
class FileImporter: Importer {
let logger = Logger(label: "file-importer")
enum Error: String, Swift.Error {
case cantOpenDoc = "error opening doc"
}
@MainActor
func importKey(from url: URL) async throws -> ArchiveItem {
switch try? Data(contentsOf: url) {
case .some: return try await importLocalKey(from: url)
case .none: return try await importCloudKey(from: url)
}
}
}
extension FileImporter {
func importLocalKey(from url: URL) async throws -> ArchiveItem {
let filename = url.lastPathComponent
logger.debug("importing internal key: \(filename)")
let data = try Data(contentsOf: url)
try FileManager.default.removeItem(at: url)
return try .init(filename: filename, data: data)
}
}
extension FileImporter {
private class KeyDocument: UIDocument {
var data: Data?
override func load(
fromContents contents: Any,
ofType typeName: String?
) throws {
self.data = contents as? Data
}
}
@MainActor
func importCloudKey(from url: URL) async throws -> ArchiveItem {
let filename = url.lastPathComponent
logger.debug("importing icloud key: \(filename)")
let doc = KeyDocument(fileURL: url)
guard await doc.open(), let data = doc.data else {
throw Error.cantOpenDoc
}
return try .init(filename: filename, data: data)
}
}
// MARK: Sharing
func shareFile(_ key: ArchiveItem) {
let urls = FileManager.default.urls(
for: .cachesDirectory, in: .userDomainMask)
guard let publicDirectory = urls.first else {
return
}
let fileURL = publicDirectory.appendingPathComponent(key.filename)
FileManager.default.createFile(
atPath: fileURL.path,
contents: key.content.data(using: .utf8))
share([fileURL]) {_, _, _, _ in
try? FileManager.default.removeItem(at: fileURL)
}
}
| 26.506494 | 70 | 0.634003 |
627dc3ff54b3d40a6fc7d81da54e24d9295448cd | 446 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
{let c{if{
{
{{return{{
}
let v{
func b{{{class
case,
| 27.875 | 78 | 0.7287 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.