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
|
---|---|---|---|---|---|
f40d6ce9294032304264aaa784769aa513122a93 | 4,821 | //
// ViewController.swift
// Ej1Beacons
//
// Created by lucas on 28/04/2019.
// Copyright © 2019 lucas. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
// Encontramos todos los beacons con el UUID específicado
//let proximityUUID = UUID(uuidString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")
let proximityUUID = UUID(uuidString:
"BA901297-63DA-4DE4-9E5B-BEA09106319D")
//let proximityUUID = UUID(uuidString:"2655be5c-bf96-4e92-9859-2988e71efd01")
let regionID = "es.ua.mastermoviles.A"
let majorNumber = CLBeaconMajorValue(5)
// Creamos la región y empezamos a monitorizarla
let region = CLBeaconRegion (proximityUUID: proximityUUID!,
major: majorNumber,
identifier: regionID)
region.notifyEntryStateOnDisplay = true
self.locationManager.startMonitoring(for: region)
print("Empezamos a monitorizar región")
/*
El método didEnterRegion no se ejecutará nunca si no se detecta una entrada en la región. Por tanto, si iniciamos el escaneado estando cerca del beacon simulado, nunca llega a ejecutarse didEnterRegion porque no ha habido un cambio de estar fuera, a estar dentro del alcance del beacon.
Siguiendo estos pasos, podemos hacer que funcione siempre sin tener que desplazarnos físicamente:
1. Nos aseguramos de que el simulador de beacon no está transmitiendo.
2. Comenzamos a escanear.
3. Esperamos a que se ejecute el evento locationManager(... didDetermineState ...) indicando que estamos fuera de la región.
4. Ahora iniciamos la transmisión en el simulador.
5. El escáner detectará la entrada en la región, y comenzar el ranging.
if CLLocationManager.isRangingAvailable() {
locationManager.startRangingBeacons(in: region as! CLBeaconRegion)
print("Empezamos a sondear proximidad")
}
*/
}
func locationManager(_ manager: CLLocationManager,
didEnterRegion region: CLRegion) {
print ("detectamos región")
if region is CLBeaconRegion {
// Empezamos a detectar la proximidad.
if CLLocationManager.isRangingAvailable() {
manager.startRangingBeacons(in: region as! CLBeaconRegion)
print("Empezamos a sondear proximidad")
}
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
print("didDetermineState:")
print(state.rawValue)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if region is CLBeaconRegion {
// Detenemos la detección de proximidad.
if CLLocationManager.isRangingAvailable() {
manager.stopRangingBeacons(in: region as! CLBeaconRegion)
}
}
}
func locationManager(_ manager: CLLocationManager,
didRangeBeacons beacons: [CLBeacon],
in region: CLBeaconRegion) {
if beacons.count > 0 {
updateDistance(beacons.first!.proximity)
} else {
updateDistance(.unknown)
}
}
func updateDistance(_ distance: CLProximity) {
UIView.animate(withDuration: 0.8) {
switch distance {
case .unknown:
self.view.backgroundColor = UIColor.gray
case .far:
self.view.backgroundColor = UIColor.blue
case .near:
self.view.backgroundColor = UIColor.orange
case .immediate:
self.view.backgroundColor = UIColor.red
}
}
}
}
| 34.934783 | 295 | 0.613566 |
e619478ec2dd7a9028fe7afa87a1261c8124bca9 | 857 | //
// FourthViewController.swift
// LargeTitlesAndSearchBar
//
// Created by Julian Caicedo on 24.08.18.
// Copyright © 2018 Julian Caicedo. All rights reserved.
//
import UIKit
class FourthViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
navigationItem.title = "XIB NO CONTAINER"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .fastForward, target: self, action: #selector(tappedNext))
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .always
}
}
@IBAction func tappedNext() {
self.show(FifthViewController(), sender: nil)
}
}
| 25.205882 | 135 | 0.715286 |
de40836fe57181f2b832248e382db5c23174d0a6 | 4,516 | //
// Query.swift
// PetWorld
//
// Created by me on 9/7/17.
// Copyright © 2017 me. All rights reserved.
//
import Foundation
//Query params
//Example of possible query...
/*?include=owner&where={
"owner": {
"$in": [x, y, z]
}
}
*/
class Query{
private var includes: [String] = []
private var whereConstraints: [String: Any] = [:]
func includeKey(key: String){
includes.append(key)
}
func includeKeys(keys: [String]){
includes = keys
}
//For the $in monodb operator
//Key is the resources property to be compared to
//'containedIn' is the value to compare to resource property
/*
where: {
"key": { "$in": // containedIn [val1, val2, val3] },
"anotherKey": ....,
"andantherone": ...,
}
*/
func whereKey(key: String, containedIn: [String]){
let operatorComparison = ["$in": containedIn]
whereConstraints[key] = operatorComparison
}
func whereKey(key: String, equals: Any){
whereConstraints[key] = equals
}
func whereKey(key: String, hasPrefix: String, caseInsensitive: Bool = true){
var operatorComparison: [String: Any] = ["$regex": hasPrefix]
if caseInsensitive {
operatorComparison["$options"] = "i"
}
whereConstraints[key] = operatorComparison
}
/*Process include and where fields before adding them to url*/
func createQuery() -> [URLQueryItem]{
var queryItems: [URLQueryItem] = []
//Add include fields
let preparedIncludeKeys: String = prepIncludes()
queryItems.append(URLQueryItem(name: "include", value: preparedIncludeKeys))
//Added where fields
//Convert dictionary to json string
var unencodedJsonString = Query.stringifyJSON(dictionary: whereConstraints)
//If not possible then stop
if unencodedJsonString == "" {
print("Could not stringify json correctly")
return queryItems
}
//URL encode json string
guard let encodedJsonString = Query.urlEncodeQueryParam(param: unencodedJsonString) else {
print("Could not encode json string properly")
return queryItems
}
queryItems.append(URLQueryItem(name: "where", value: encodedJsonString))
return queryItems
}
class func createQueryString(queryParams: [String: String]) -> String{
//Start of query
var queryString = "?"
for (key, value) in queryParams{
//?key1=value&key2=value2&key3=value3
queryString = "\(queryString)\(key)=\(value)&"
print("queryString: \(queryString)")
}
print("size: \(queryString.characters.count)")
print("endIndex \(queryString)" )
//Remove the ampersand at the end
queryString = queryString.substring(to: queryString.index(before: queryString.endIndex))
return queryString
}
//Prepares include statements as [includee command]=[val1],[val2],[val3]
private func prepIncludes() -> String{
var includeString = ""
if self.includes.count <= 0 {
return "";
}
for property in self.includes{
includeString.append("\(property),")
}
return includeString.substring(to: includeString.index(before: includeString.endIndex))
}
class func stringifyJSON(dictionary: Dictionary<String, Any>, pretty: Bool = true) -> String{
guard let jsonData = dictionary.toJson() else {
return ""
}
if let jsonString = String(data: jsonData, encoding: String.Encoding.utf8){
print("jsonString: \(jsonString)")
return jsonString as String
}
return ""
}
class func urlEncodeQueryParam(param: String) -> String?{
return param.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
}
}
extension Dictionary{
func toJson() -> Data? {
do{
var jsonData: Data? = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
return jsonData
}catch{
return nil
}
return nil
}
}
| 25.954023 | 140 | 0.575509 |
56bf2adf2084a2873c69daf8e294d1b1921e0cc5 | 2,519 | //
// CampaignControllerTriggerPurchaseResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct CampaignControllerTriggerPurchaseResponse: Codable {
public enum TriggerType: String, Codable {
case share = "SHARE"
case purchase = "PURCHASE"
case event = "EVENT"
case score = "SCORE"
case zoneState = "ZONE_STATE"
case apiVersion = "API_VERSION"
case referredByEvent = "REFERRED_BY_EVENT"
case legacyQuality = "LEGACY_QUALITY"
case expression = "EXPRESSION"
case access = "ACCESS"
case dataIntelligenceEvent = "DATA_INTELLIGENCE_EVENT"
case hasPriorStep = "HAS_PRIOR_STEP"
case maxmind = "MAXMIND"
case rewardEvent = "REWARD_EVENT"
case hasPriorReward = "HAS_PRIOR_REWARD"
}
public enum Operator: String, Codable {
case lessThan = "LESS_THAN"
case greaterThan = "GREATER_THAN"
}
public var triggerId: String?
public var triggerType: TriggerType?
public var triggerPhase: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerPhase?
public var triggerName: BuildtimeEvaluatableControllerBuildtimeContextString?
public var componentReferences: [CampaignComponentReferenceResponse]?
public var periodSinceLastPurchase: Int64?
public var _operator: Operator?
public init(triggerId: String? = nil, triggerType: TriggerType? = nil, triggerPhase: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerPhase? = nil, triggerName: BuildtimeEvaluatableControllerBuildtimeContextString? = nil, componentReferences: [CampaignComponentReferenceResponse]? = nil, periodSinceLastPurchase: Int64? = nil, _operator: Operator? = nil) {
self.triggerId = triggerId
self.triggerType = triggerType
self.triggerPhase = triggerPhase
self.triggerName = triggerName
self.componentReferences = componentReferences
self.periodSinceLastPurchase = periodSinceLastPurchase
self._operator = _operator
}
public enum CodingKeys: String, CodingKey {
case triggerId = "trigger_id"
case triggerType = "trigger_type"
case triggerPhase = "trigger_phase"
case triggerName = "trigger_name"
case componentReferences = "component_references"
case periodSinceLastPurchase = "period_since_last_purchase"
case _operator = "operator"
}
}
| 39.359375 | 382 | 0.719333 |
d636f2eb0887f35dd13a606567d948d246657acc | 3,514 | // Created on 25/01/21.
import VandMarvelUIKit
import SnapKit
public protocol VMFavoriteCharactersViewDelegate: AnyObject {
func favoriteCharactersViewNumberOfCharacters(_ view: VMFavoriteCharactersView) -> Int?
func favoriteCharacters(_ view: VMFavoriteCharactersView, characterAtRow row: Int) -> VMCharacter?
func favoriteCharacters(_ view: VMFavoriteCharactersView, didSelectCharacterAtRow row: Int)
func favoriteCharacters(_ view: VMFavoriteCharactersView, didUnfavoriteCharacterAtRow row: Int)
}
public class VMFavoriteCharactersView: UIView, VMViewCode {
public init() {
super.init(frame: .zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public weak var delegate: VMFavoriteCharactersViewDelegate?
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.register(VMCharacterDisplayTableViewCell.self)
tableView.dataSource = self
tableView.delegate = self
return tableView
}()
private let emptyLabel: UILabel = {
let label = UILabel()
label.textColor = VMColor.neutral.color
label.font = VMFont.body(size: .md).font
label.numberOfLines = 0
label.isHidden = true
return label
}()
public func buildHierarchy() {
addSubview(tableView)
addSubview(emptyLabel)
}
public func setupConstraints() {
tableView.snp.makeConstraints { maker in
maker.edges.equalTo(safeAreaLayoutGuide)
}
emptyLabel.snp.makeConstraints { maker in
maker.centerX.equalTo(safeAreaLayoutGuide)
maker.centerY.equalTo(safeAreaLayoutGuide).offset(-24)
}
}
public func configViews() {
}
public func reloadData() {
tableView.isHidden = false
emptyLabel.isHidden = true
tableView.reloadData()
}
public func showEmptyState(withMessage message: String) {
tableView.isHidden = true
emptyLabel.isHidden = false
emptyLabel.text = message
}
}
extension VMFavoriteCharactersView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
delegate?.favoriteCharactersViewNumberOfCharacters(self) ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(VMCharacterDisplayTableViewCell.self, for: indexPath)
if let character = delegate?.favoriteCharacters(self, characterAtRow: indexPath.row) {
cell.isLoading = false
cell.name = character.name
cell.thumbnail = character.image
} else {
cell.isLoading = true
}
return cell
}
public func tableView(
_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath
) {
guard editingStyle == .delete else { return }
delegate?.favoriteCharacters(self, didUnfavoriteCharacterAtRow: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
extension VMFavoriteCharactersView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.favoriteCharacters(self, didSelectCharacterAtRow: indexPath.row)
}
}
| 29.283333 | 107 | 0.682982 |
148d86dd3ad6743f4c86224eca195150ca547088 | 13,258 | import Foundation
import TSCBasic
import TuistGraph
public protocol GraphLoading {
func loadWorkspace(workspace: Workspace, projects: [Project]) throws -> Graph
func loadProject(at path: AbsolutePath, projects: [Project]) throws -> (Project, Graph)
}
// MARK: - GraphLoader
// swiftlint:disable:next type_body_length
public final class GraphLoader: GraphLoading {
private let frameworkMetadataProvider: FrameworkMetadataProviding
private let libraryMetadataProvider: LibraryMetadataProviding
private let xcframeworkMetadataProvider: XCFrameworkMetadataProviding
private let systemFrameworkMetadataProvider: SystemFrameworkMetadataProviding
public convenience init() {
self.init(
frameworkMetadataProvider: FrameworkMetadataProvider(),
libraryMetadataProvider: LibraryMetadataProvider(),
xcframeworkMetadataProvider: XCFrameworkMetadataProvider(),
systemFrameworkMetadataProvider: SystemFrameworkMetadataProvider()
)
}
public init(
frameworkMetadataProvider: FrameworkMetadataProviding,
libraryMetadataProvider: LibraryMetadataProviding,
xcframeworkMetadataProvider: XCFrameworkMetadataProviding,
systemFrameworkMetadataProvider: SystemFrameworkMetadataProviding
) {
self.frameworkMetadataProvider = frameworkMetadataProvider
self.libraryMetadataProvider = libraryMetadataProvider
self.xcframeworkMetadataProvider = xcframeworkMetadataProvider
self.systemFrameworkMetadataProvider = systemFrameworkMetadataProvider
}
// MARK: - GraphLoading
public func loadWorkspace(workspace: Workspace, projects: [Project]) throws -> Graph {
let cache = Cache(projects: projects)
let cycleDetector = GraphCircularDetector()
try workspace.projects.forEach { project in
try loadProject(
path: project,
cache: cache,
cycleDetector: cycleDetector
)
}
let updatedWorkspace = workspace.replacing(projects: cache.loadedProjects.keys.sorted())
let graph = Graph(
name: updatedWorkspace.name,
path: updatedWorkspace.path,
workspace: updatedWorkspace,
projects: cache.loadedProjects,
packages: cache.packages,
targets: cache.loadedTargets,
dependencies: cache.dependencies
)
return graph
}
public func loadProject(at path: AbsolutePath, projects: [Project]) throws -> (Project, Graph) {
let cache = Cache(projects: projects)
guard let rootProject = cache.allProjects[path] else {
throw GraphLoadingError.missingProject(path)
}
let cycleDetector = GraphCircularDetector()
try loadProject(path: path, cache: cache, cycleDetector: cycleDetector)
let workspace = Workspace(
path: path,
xcWorkspacePath: path.appending(component: "\(rootProject.name).xcworkspace"),
name: rootProject.name,
projects: cache.loadedProjects.keys.sorted()
)
let graph = Graph(
name: rootProject.name,
path: path,
workspace: workspace,
projects: cache.loadedProjects,
packages: cache.packages,
targets: cache.loadedTargets,
dependencies: cache.dependencies
)
return (rootProject, graph)
}
// MARK: - Private
private func loadProject(
path: AbsolutePath,
cache: Cache,
cycleDetector: GraphCircularDetector
) throws {
guard !cache.projectLoaded(path: path) else {
return
}
guard let project = cache.allProjects[path] else {
throw GraphLoadingError.missingProject(path)
}
cache.add(project: project)
try project.targets.forEach {
try loadTarget(
path: path,
name: $0.name,
cache: cache,
cycleDetector: cycleDetector
)
}
}
private func loadTarget(
path: AbsolutePath,
name: String,
cache: Cache,
cycleDetector: GraphCircularDetector
) throws {
guard !cache.targetLoaded(path: path, name: name) else {
return
}
guard cache.allProjects[path] != nil else {
throw GraphLoadingError.missingProject(path)
}
guard let referencedTargetProject = cache.allTargets[path],
let target = referencedTargetProject[name]
else {
throw GraphLoadingError.targetNotFound(name, path)
}
cache.add(target: target, path: path)
let dependencies = try target.dependencies.map {
try loadDependency(
path: path,
fromTarget: target.name,
fromPlatform: target.platform,
dependency: $0,
cache: cache,
cycleDetector: cycleDetector
)
}
try cycleDetector.complete()
if !dependencies.isEmpty {
cache.dependencies[.target(name: name, path: path)] = Set(dependencies)
}
}
private func loadDependency(
path: AbsolutePath,
fromTarget: String,
fromPlatform: Platform,
dependency: TargetDependency,
cache: Cache,
cycleDetector: GraphCircularDetector
) throws -> GraphDependency {
switch dependency {
case let .target(toTarget):
// A target within the same project.
let circularFrom = GraphCircularDetectorNode(path: path, name: fromTarget)
let circularTo = GraphCircularDetectorNode(path: path, name: toTarget)
cycleDetector.start(from: circularFrom, to: circularTo)
try loadTarget(
path: path,
name: toTarget,
cache: cache,
cycleDetector: cycleDetector
)
return .target(name: toTarget, path: path)
case let .project(toTarget, projectPath):
// A target from another project
let circularFrom = GraphCircularDetectorNode(path: path, name: fromTarget)
let circularTo = GraphCircularDetectorNode(path: projectPath, name: toTarget)
cycleDetector.start(from: circularFrom, to: circularTo)
try loadProject(path: projectPath, cache: cache, cycleDetector: cycleDetector)
try loadTarget(
path: projectPath,
name: toTarget,
cache: cache,
cycleDetector: cycleDetector
)
return .target(name: toTarget, path: projectPath)
case let .framework(frameworkPath):
return try loadFramework(path: frameworkPath, cache: cache)
case let .library(libraryPath, publicHeaders, swiftModuleMap):
return try loadLibrary(
path: libraryPath,
publicHeaders: publicHeaders,
swiftModuleMap: swiftModuleMap,
cache: cache
)
case let .xcFramework(frameworkPath):
return try loadXCFramework(path: frameworkPath, cache: cache)
case let .sdk(name, status):
return try loadSDK(name: name, platform: fromPlatform, status: status, source: .system)
case let .cocoapods(podsPath):
return .cocoapods(path: podsPath)
case let .package(product):
return try loadPackage(fromPath: path, productName: product)
case .xctest:
return try loadXCTestSDK(platform: fromPlatform)
}
}
private func loadFramework(path: AbsolutePath, cache: Cache) throws -> GraphDependency {
if let loaded = cache.frameworks[path] {
return loaded
}
let metadata = try frameworkMetadataProvider.loadMetadata(at: path)
let framework: GraphDependency = .framework(
path: metadata.path,
binaryPath: metadata.binaryPath,
dsymPath: metadata.dsymPath,
bcsymbolmapPaths: metadata.bcsymbolmapPaths,
linking: metadata.linking,
architectures: metadata.architectures,
isCarthage: metadata.isCarthage
)
cache.add(framework: framework, at: path)
return framework
}
private func loadLibrary(
path: AbsolutePath,
publicHeaders: AbsolutePath,
swiftModuleMap: AbsolutePath?,
cache: Cache
) throws -> GraphDependency {
if let loaded = cache.libraries[path] {
return loaded
}
let metadata = try libraryMetadataProvider.loadMetadata(
at: path,
publicHeaders: publicHeaders,
swiftModuleMap: swiftModuleMap
)
let library: GraphDependency = .library(
path: metadata.path,
publicHeaders: metadata.publicHeaders,
linking: metadata.linking,
architectures: metadata.architectures,
swiftModuleMap: metadata.swiftModuleMap
)
cache.add(library: library, at: path)
return library
}
private func loadXCFramework(path: AbsolutePath, cache: Cache) throws -> GraphDependency {
if let loaded = cache.xcframeworks[path] {
return loaded
}
let metadata = try xcframeworkMetadataProvider.loadMetadata(at: path)
let xcframework: GraphDependency = .xcframework(
path: metadata.path,
infoPlist: metadata.infoPlist,
primaryBinaryPath: metadata.primaryBinaryPath,
linking: metadata.linking
)
cache.add(xcframework: xcframework, at: path)
return xcframework
}
private func loadSDK(name: String,
platform: Platform,
status: SDKStatus,
source: SDKSource) throws -> GraphDependency
{
let metadata = try systemFrameworkMetadataProvider.loadMetadata(sdkName: name, status: status, platform: platform, source: source)
return .sdk(name: metadata.name, path: metadata.path, status: metadata.status, source: metadata.source)
}
private func loadXCTestSDK(platform: Platform) throws -> GraphDependency {
let metadata = try systemFrameworkMetadataProvider.loadXCTestMetadata(platform: platform)
return .sdk(name: metadata.name, path: metadata.path, status: metadata.status, source: metadata.source)
}
private func loadPackage(fromPath: AbsolutePath, productName: String) throws -> GraphDependency {
// TODO: `fromPath` isn't quite correct as it reflects the path where the dependency was declared
// and doesn't uniquely identify it. It's been copied from the previous implementation to maintain
// existing behaviour and should be fixed separately
.packageProduct(
path: fromPath,
product: productName
)
}
private final class Cache {
let allProjects: [AbsolutePath: Project]
let allTargets: [AbsolutePath: [String: Target]]
var loadedProjects: [AbsolutePath: Project] = [:]
var loadedTargets: [AbsolutePath: [String: Target]] = [:]
var dependencies: [GraphDependency: Set<GraphDependency>] = [:]
var frameworks: [AbsolutePath: GraphDependency] = [:]
var libraries: [AbsolutePath: GraphDependency] = [:]
var xcframeworks: [AbsolutePath: GraphDependency] = [:]
var packages: [AbsolutePath: [String: Package]] = [:]
init(projects: [Project]) {
let allProjects = Dictionary(uniqueKeysWithValues: projects.map { ($0.path, $0) })
let allTargets = allProjects.mapValues {
Dictionary(uniqueKeysWithValues: $0.targets.map { ($0.name, $0) })
}
self.allProjects = allProjects
self.allTargets = allTargets
}
func add(project: Project) {
loadedProjects[project.path] = project
project.packages.forEach {
packages[project.path, default: [:]][$0.name] = $0
}
}
func add(target: Target, path: AbsolutePath) {
loadedTargets[path, default: [:]][target.name] = target
}
func add(framework: GraphDependency, at path: AbsolutePath) {
frameworks[path] = framework
}
func add(xcframework: GraphDependency, at path: AbsolutePath) {
xcframeworks[path] = xcframework
}
func add(library: GraphDependency, at path: AbsolutePath) {
libraries[path] = library
}
func targetLoaded(path: AbsolutePath, name: String) -> Bool {
loadedTargets[path]?[name] != nil
}
func projectLoaded(path: AbsolutePath) -> Bool {
loadedProjects[path] != nil
}
}
}
private extension Package {
var name: String {
switch self {
case let .local(path: path):
return path.pathString
case let .remote(url: url, requirement: _):
return url
}
}
}
| 36.027174 | 138 | 0.617363 |
fc0bd0885dba070f0911c82b357789aa3de03d5a | 539 | //
// UICollectionViewLayoutInvalidationContext.swift
// Panda
//
// Baby of PandaMom. DO NOT TOUCH.
//
import UIKit
extension PandaChain where Object: UICollectionViewLayoutInvalidationContext {
@discardableResult
public func contentOffsetAdjustment(_ value: CGPoint) -> PandaChain {
object.contentOffsetAdjustment = value
return self
}
@discardableResult
public func contentSizeAdjustment(_ value: CGSize) -> PandaChain {
object.contentSizeAdjustment = value
return self
}
}
| 23.434783 | 78 | 0.716141 |
9b565dec627ef948c48da6635ed6179b402c961a | 2,153 | //
// AppDelegate.swift
// SwiftWeatherApp
//
// Created by Jonathan Lin on 2015/4/11.
// Copyright (c) 2015年 LittleLin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.808511 | 285 | 0.754761 |
1c1265e1ae3f881653691532e14b991d14638845 | 2,259 | //
// Channel.swift
// SwiftChan
//
// Created by Willa Drengwitz on 9/1/15.
// Copyright (c) 2015 Eksdyne Research. All rights reserved.
//
import Foundation
public protocol SupportSend {
associatedtype ValueType
func send(value: ValueType)
}
public protocol SupportReceive {
associatedtype ValueType
func receive() -> ValueType
}
extension SupportSend {
public var sendOnly: Self { return self }
public func asSendOnly() -> Self {
return self
}
}
extension SupportReceive {
public var receiveOnly: Self { return self }
public func asReceiveOnly() -> Self {
return self
}
}
typealias RWChannel = protocol<SupportSend, SupportReceive>
public class GCDChan<Element> {
private var waiting = (receivers: [GCDHandoff<Element>](),
senders: [GCDHandoff<Element>]())
let q: dispatch_queue_t = {
let uuid = NSUUID().UUIDString
return dispatch_queue_create("org.eksdyne.SynchronousChan.\(uuid)", DISPATCH_QUEUE_SERIAL)
}()
public init() {}
}
extension GCDChan: SupportSend {
private var handoffToSend: GCDHandoff<Element> {
var handoff = GCDHandoff<Element>()
dispatch_sync(q) {
switch self.waiting.receivers.count {
case 0:
self.waiting.senders.append(handoff)
default:
handoff = self.waiting.receivers.removeFirst()
}
}
return handoff
}
public func send(v: Element) {
switch handoffToSend.enterAsSenderOf(v) {
case .Completed:
return
default:
send(v)
}
}
}
extension GCDChan: SupportReceive {
private var handoffToReceive: GCDHandoff<Element> {
var handoff = GCDHandoff<Element>()
dispatch_sync(q) {
switch self.waiting.senders.count {
case 0:
self.waiting.receivers.append(handoff)
default:
handoff = self.waiting.senders.removeFirst()
}
}
return handoff
}
public func receive() -> Element {
switch handoffToReceive.enterAsReceiver() {
case .Completed(let value):
return value
default:
return receive()
}
}
}
extension GCDChan: SupportSelectReceive {
public func receive() -> GCDHandoff<Element> {
return handoffToReceive
}
}
extension GCDChan: SupportSelectSend {
public func send() -> GCDHandoff<Element> {
return handoffToSend
}
}
public struct ASyncReceive<V> {
let callback: (V) -> Void
}
| 19.474138 | 92 | 0.704737 |
2917fcfa24a401905b24f0c6f5a69c2e22aa4b36 | 198 | //
// PresentableAnswer.swift
// QuizApp
//
// Created by Priyal PORWAL on 14/11/21.
//
struct PresentableAnswer {
let question: String
let answer: String
let wrongAnswer: String?
}
| 15.230769 | 41 | 0.671717 |
3808c1ddaf01f07e06b5bbc79e52de8f2bfcd43e | 3,282 | import UIKit
final class AnimatableImageView: UIView {
fileprivate let imageView = UIImageView()
override var contentMode: UIView.ContentMode {
didSet { update() }
}
override var frame: CGRect {
didSet { update() }
}
var image: UIImage? {
didSet {
imageView.image = image
update()
}
}
init() {
super.init(frame: .zero)
clipsToBounds = true
addSubview(imageView)
imageView.contentMode = .scaleToFill
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension AnimatableImageView {
func update() {
guard let image = image else { return }
switch contentMode {
case .scaleToFill:
imageView.bounds = Utilities.rect(forSize: bounds.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFit:
imageView.bounds = Utilities.aspectFitRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFill:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .redraw:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .center:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .top:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerTop(forSize: image.size, insideSize: bounds.size)
case .bottom:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerBottom(forSize: image.size, insideSize: bounds.size)
case .left:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerLeft(forSize: image.size, insideSize: bounds.size)
case .right:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerRight(forSize: image.size, insideSize: bounds.size)
case .topLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topLeft(forSize: image.size, insideSize: bounds.size)
case .topRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topRight(forSize: image.size, insideSize: bounds.size)
case .bottomLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomLeft(forSize: image.size, insideSize: bounds.size)
case .bottomRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomRight(forSize: image.size, insideSize: bounds.size)
@unknown default:
return
}
}
}
| 40.02439 | 99 | 0.634674 |
891c82ebbf3ad534877bdcf3fd09c770c65db82c | 526 | //
// IntroView.swift
// SwiftPamphletApp
//
// Created by Ming Dai on 2021/12/31.
//
import SwiftUI
struct IntroView: View {
var body: some View {
VStack(spacing: 15) {
Image("logo")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 120, height: 120)
Text("戴铭的开发小册子").bold().font(.largeTitle)
Text("一本活的开发手册")
Text("版本4.3").font(.footnote)
}
.frame(minWidth: SPC.detailMinWidth)
}
}
| 21.916667 | 53 | 0.522814 |
de28a099f1c8aaa804c1d2a486d131c9a14e76ec | 8,821 | //
// DriversLicenseReader.swift
// TRETJapanNFCReader
//
// Created by treastrain on 2019/06/28.
// Copyright © 2019 treastrain / Tanaka Ryoga. All rights reserved.
//
#if os(iOS)
import UIKit
import CoreNFC
#if canImport(TRETJapanNFCReader_Core)
import TRETJapanNFCReader_Core
#endif
#if canImport(TRETJapanNFCReader_MIFARE)
import TRETJapanNFCReader_MIFARE
#endif
@available(iOS 13.0, *)
public typealias DriversLicenseReaderViewController = UIViewController & DriversLicenseReaderSessionDelegate
@available(iOS 13.0, *)
internal typealias DriversLicenseCardTag = NFCISO7816Tag
@available(iOS 13.0, *)
public class DriversLicenseReader: MiFareReader {
internal let delegate: DriversLicenseReaderSessionDelegate?
private var driversLicenseCardItems: [DriversLicenseCardItem] = []
private var pin1: [UInt8] = []
private var pin2: [UInt8] = []
private init() {
fatalError()
}
/// DriversLicenseReader を初期化する。
/// - Parameter delegate: DriversLicenseReaderSessionDelegate
public init(delegate: DriversLicenseReaderSessionDelegate) {
self.delegate = delegate
super.init(delegate: delegate)
}
/// DriversLicenseReader を初期化する。
/// - Parameter viewController: DriversLicenseReaderSessionDelegate を適用した UIViewController
public init(viewController: DriversLicenseReaderViewController) {
self.delegate = viewController
super.init(viewController: viewController)
}
/// 運転免許証からデータを読み取る
/// - Parameter items: 運転免許証から読み取りたいデータ
/// - Parameter pin1: 暗証番号1
/// - Parameter pin2: 暗証番号2
public func get(items: [DriversLicenseCardItem], pin1: String = "", pin2: String = "") {
if items.contains(.matters) || items.contains(.registeredDomicile) || items.contains(.photo) {
if let pin = convertPINStringToJISX0201(pin1) {
self.pin1 = pin
} else {
self.delegate?.japanNFCReaderSession(didInvalidateWithError: DriversLicenseReaderError.incorrectPINFormat)
return
}
}
if items.contains(.registeredDomicile) || items.contains(.photo) {
if let pin = convertPINStringToJISX0201(pin2) {
self.pin2 = pin
} else {
self.delegate?.japanNFCReaderSession(didInvalidateWithError: DriversLicenseReaderError.incorrectPINFormat)
return
}
}
self.driversLicenseCardItems = items
self.beginScanning()
}
private func beginScanning() {
guard self.checkReadingAvailable() else {
print("""
------------------------------------------------------------
【運転免許証を読み取るには】
運転免許証を読み取るには、開発している iOS Application の Info.plist に "ISO7816 application identifiers for NFC Tag Reader Session (com.apple.developer.nfc.readersession.iso7816.select-identifiers)" を追加します。ISO7816 application identifiers for NFC Tag Reader Session には以下を含める必要があります。
\t• Item 0: A0000002310100000000000000000000
\t• Item 1: A0000002310200000000000000000000
\t• Item 2: A0000002480300000000000000000000
------------------------------------------------------------
""")
return
}
self.session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self)
self.session?.alertMessage = Localized.nfcReaderSessionAlertMessage.string()
self.session?.begin()
}
public override func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
super.tagReaderSession(session, didInvalidateWithError: error)
if let readerError = error as? NFCReaderError {
if (readerError.code != .readerSessionInvalidationErrorFirstNDEFTagRead)
&& (readerError.code != .readerSessionInvalidationErrorUserCanceled) {
print("""
------------------------------------------------------------
【運転免許証を読み取るには】
運転免許証を読み取るには、開発している iOS Application の Info.plist に "ISO7816 application identifiers for NFC Tag Reader Session (com.apple.developer.nfc.readersession.iso7816.select-identifiers)" を追加します。ISO7816 application identifiers for NFC Tag Reader Session には以下を含める必要があります。
\t• Item 0: A0000002310100000000000000000000
\t• Item 1: A0000002310200000000000000000000
\t• Item 2: A0000002480300000000000000000000
------------------------------------------------------------
""")
}
}
self.delegate?.japanNFCReaderSession(didInvalidateWithError: error)
}
public override func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
if tags.count > 1 {
let retryInterval = DispatchTimeInterval.milliseconds(1000)
let alertedMessage = session.alertMessage
session.alertMessage = Localized.nfcTagReaderSessionDidDetectTagsMoreThan1TagIsDetectedMessage.string()
DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval, execute: {
session.restartPolling()
session.alertMessage = alertedMessage
})
return
}
let tag = tags.first!
session.connect(to: tag) { (error) in
if nil != error {
session.invalidate(errorMessage: Localized.nfcTagReaderSessionConnectErrorMessage.string())
return
}
guard case NFCTag.iso7816(let driversLicenseCardTag) = tag else {
let retryInterval = DispatchTimeInterval.milliseconds(1000)
let alertedMessage = session.alertMessage
session.alertMessage = Localized.nfcTagReaderSessionDifferentTagTypeErrorMessage.string()
DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval, execute: {
session.restartPolling()
session.alertMessage = alertedMessage
})
return
}
switch driversLicenseCardTag.initialSelectedAID {
case "A0000002310100000000000000000000", "A0000002310200000000000000000000", "A0000002480300000000000000000000" :
break
default:
let retryInterval = DispatchTimeInterval.milliseconds(1000)
let alertedMessage = session.alertMessage
session.alertMessage = Localized.nfcTagReaderSessionDifferentTagTypeErrorMessage.string()
DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval, execute: {
session.restartPolling()
session.alertMessage = alertedMessage
})
return
}
session.alertMessage = Localized.nfcTagReaderSessionReadingMessage.string()
let driversLicenseCard = DriversLicenseCard(tag: driversLicenseCardTag)
self.getItems(session, driversLicenseCard) { (driversLicenseCard) in
session.alertMessage = Localized.nfcTagReaderSessionDoneMessage.string()
session.invalidate()
self.delegate?.driversLicenseReaderSession(didRead: driversLicenseCard)
}
}
}
private func getItems(_ session: NFCTagReaderSession, _ driversLicenseCard: DriversLicenseCard, completion: @escaping (DriversLicenseCard) -> Void) {
var driversLicenseCard = driversLicenseCard
DispatchQueue(label: "TRETJPNRDriversLicenseReader", qos: .default).async {
for item in self.driversLicenseCardItems {
switch item {
case .commonData:
driversLicenseCard = self.readCommonData(session, driversLicenseCard)
case .pinSetting:
driversLicenseCard = self.readPINSetting(session, driversLicenseCard)
case .matters:
driversLicenseCard = self.readMatters(session, driversLicenseCard, pin1: self.pin1)
case .registeredDomicile:
driversLicenseCard = self.readRegisteredDomicile(session, driversLicenseCard, pin1: self.pin1, pin2: self.pin2)
case .photo:
driversLicenseCard = self.readPhoto(session, driversLicenseCard, pin1: self.pin1, pin2: self.pin2)
}
}
self.pin1 = []
self.pin2 = []
completion(driversLicenseCard)
}
}
}
#endif
| 43.885572 | 281 | 0.614216 |
7a12a58a5f7643eeaf3f2e1a379a3252b8a20935 | 692 | //
// CoreDataIdentifiable.swift
// CoreCoreData
//
// Created by Robert Nguyen on 3/8/19.
//
import CoreData
import CoreRepository
import FoundationExtInternal
public protocol ManagedObjectWrapper {
associatedtype Object: NSManagedObject
init(object: Object)
func toObject() -> Object
}
extension MetaObjectEntity {
@inlinable
var isValid: Bool {
guard ttl <= 0 else {
return true
}
let localUpdatedDate = Date(timeIntervalSince1970: localUpdatedTimestamp)
return localUpdatedDate.addingTimeInterval(ttl) <= Date()
}
}
public protocol CoreDataIdentifiable: Identifiable {
static func keyPathForID() -> String
}
| 20.969697 | 81 | 0.700867 |
8ad73bafba658d8e8e55f20fbc9740690827084f | 4,638 | //
// ViewController.swift
// GitHubSearchApp
//
// Created by burt on 2018. 9. 25..
// Copyright © 2018년 Burt.K. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SnapKit
import ReactComponentKit
import BKRouter
class SearchViewController: UIViewController {
private let disposeBag = DisposeBag()
private let viewModel = SearchViewModel()
private lazy var searchControllerComponent: SearchControllerComponent = {
return SearchControllerComponent(token: viewModel.token)
}()
private lazy var helloComponent: HelloViewControllerComponent = {
return HelloViewControllerComponent(token: viewModel.token)
}()
private lazy var emptyComponent: EmptyViewControllerComponent = {
return EmptyViewControllerComponent(token: viewModel.token)
}()
private lazy var errorComponent: ErrorViewControllerComponent = {
return ErrorViewControllerComponent(token: viewModel.token)
}()
private lazy var loadingComponent: LoadingViewControllerComponent = {
return LoadingViewControllerComponent(token: viewModel.token)
}()
private lazy var tableViewComponent: UITableViewComponent = {
let component = UITableViewComponent(token: viewModel.token)
component.tableView.showsVerticalScrollIndicator = false
return component
}()
private lazy var tableViewAdapter: UITableViewAdapter = {
let adapter = UITableViewAdapter(tableViewComponent: tableViewComponent)
return adapter
}()
override func viewDidLoad() {
super.viewDidLoad()
self.definesPresentationContext = true
setupNavigationBar()
setupComponents()
bindingViewModel()
viewModel.showEmptyView()
}
private func setupComponents() {
add(viewController: searchControllerComponent)
view.addSubview(tableViewComponent)
tableViewComponent.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
tableViewComponent.register(component: UserItemComponent.self)
tableViewComponent.register(component: RepoItemComponent.self)
tableViewComponent.register(component: LoadMoreComponent.self)
tableViewComponent.adapter = tableViewAdapter
}
private func setupNavigationBar() {
title = "GitHub Search"
navigationController?.navigationBar.prefersLargeTitles = false
searchControllerComponent.installSearchControllerOn(navigationItem: navigationItem)
}
private func bindingViewModel() {
viewModel
.output
.viewState
.asDriver()
.drive(onNext: handle(viewState:))
.disposed(by: disposeBag)
viewModel
.output
.sections
.asDriver()
.drive(onNext: { [weak self] (sectionModels) in
self?.tableViewAdapter.set(sections: sectionModels, with: .fade)
})
.disposed(by: disposeBag)
viewModel
.output
.route
.asDriver()
.drive(onNext: { [weak self] (url) in
guard let strongSelf = self, let url = url else { return }
Router.shared.present(from: strongSelf, to: "myapp://scene?page=webView", animated: true, userData: ["url": url])
})
.disposed(by: disposeBag)
}
private func handle(viewState: SearchState.ViewState) {
helloComponent.removeFromSuperViewController()
emptyComponent.removeFromSuperViewController()
loadingComponent.removeFromSuperViewController()
errorComponent.removeFromSuperViewController()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
switch viewState {
case .hello:
self.add(viewController: helloComponent, aboveSubview: tableViewComponent)
case .empty:
self.add(viewController: emptyComponent, aboveSubview: tableViewComponent)
case .loading:
self.add(viewController: loadingComponent, aboveSubview: tableViewComponent)
case .loadingIncicator:
self.add(viewController: loadingComponent, aboveSubview: tableViewComponent)
UIApplication.shared.isNetworkActivityIndicatorVisible = true
case .list:
break
case .error(let action):
errorComponent.retryAction = action
self.add(viewController: errorComponent, aboveSubview: tableViewComponent)
}
}
}
| 34.102941 | 129 | 0.659552 |
e5e6f61f409ce46974e3b822075c7ece79a1861f | 1,655 | //
// URLRequest+Alamofire.swift
//
// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
public extension URLRequest {
/// Returns the `httpMethod` as Alamofire's `HTTPMethod` type.
var method: HTTPMethod? {
get { httpMethod.flatMap(HTTPMethod.init) }
set { httpMethod = newValue?.rawValue }
}
func validate() throws {
if method == .get, let bodyData = httpBody {
throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData))
}
}
}
| 41.375 | 93 | 0.722659 |
dea6e7b11c3fc7909de132110346390861fc98c2 | 5,725 | /*
Copyright (c) 2021, Kurt Revis. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Kurt Revis, nor Snoize, nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import CoreMIDI
// MARK: CoreMIDI Object Wrapper
protocol CoreMIDIObjectWrapper: AnyObject, Hashable {
var midiContext: CoreMIDIContext { get }
var midiObjectRef: MIDIObjectRef { get }
}
extension CoreMIDIObjectWrapper {
// MARK: Equatable default implementation
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.midiContext.client == rhs.midiContext.client && lhs.midiObjectRef == rhs.midiObjectRef
}
// MARK: Hashable default implementation
public func hash(into hasher: inout Hasher) {
hasher.combine(midiContext.client)
hasher.combine(midiObjectRef)
}
}
// FUTURE: CoreMIDIObjectWrapper could conform to Identifiable, with an id
// containing the midiContext (or midiContext.client) and midiObjectRef.
// That could be a struct that we define, or a tuple (when Swift supports
// tuples being Hashable).
// (But remember that Identifiable requires macOS 10.15 or later.)
// MARK: MIDI Property Accessors
protocol CoreMIDIPropertyValue {
static func getValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString) -> Self?
static func setValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString, _ value: Self?)
}
extension Int32: CoreMIDIPropertyValue {
static func getValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString) -> Self? {
var value: Int32 = 0
if midiContext.interface.objectGetIntegerProperty(midiObjectRef, property, &value) == noErr {
return value
}
else {
return nil
}
}
static func setValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString, _ value: Self?) {
if let someValue = value {
_ = midiContext.interface.objectSetIntegerProperty(midiObjectRef, property, someValue)
}
else {
_ = midiContext.interface.objectRemoveProperty(midiObjectRef, property)
}
}
}
extension String: CoreMIDIPropertyValue {
static func getValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString) -> Self? {
var unmanagedValue: Unmanaged<CFString>?
if midiContext.interface.objectGetStringProperty(midiObjectRef, property, &unmanagedValue) == noErr {
return unmanagedValue?.takeUnretainedValue() as String?
}
else {
return nil
}
}
static func setValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString, _ value: Self?) {
if let someValue = value {
_ = midiContext.interface.objectSetStringProperty(midiObjectRef, property, someValue as CFString)
}
else {
_ = midiContext.interface.objectRemoveProperty(midiObjectRef, property)
}
}
}
extension Data: CoreMIDIPropertyValue {
static func getValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString) -> Self? {
var unmanagedValue: Unmanaged<CFData>?
if midiContext.interface.objectGetDataProperty(midiObjectRef, property, &unmanagedValue) == noErr {
return unmanagedValue?.takeUnretainedValue() as Data?
}
else {
return nil
}
}
static func setValue(_ midiContext: CoreMIDIContext, _ midiObjectRef: MIDIObjectRef, _ property: CFString, _ value: Self?) {
if let someValue = value {
_ = midiContext.interface.objectSetDataProperty(midiObjectRef, property, someValue as CFData)
}
else {
_ = midiContext.interface.objectRemoveProperty(midiObjectRef, property)
}
}
}
extension CoreMIDIObjectWrapper {
subscript<T: CoreMIDIPropertyValue>(property: CFString) -> T? {
get {
T.getValue(midiContext, midiObjectRef, property)
}
set {
T.setValue(midiContext, midiObjectRef, property, newValue)
}
}
}
// MARK: Property Changes
protocol CoreMIDIPropertyChangeHandling {
func midiPropertyChanged(_ property: CFString)
func invalidateCachedProperties()
}
| 38.682432 | 755 | 0.716332 |
91e3ac00a03d1c490733b96b54d1d2abfceb0289 | 7,720 | //
// FloatyItem.swift
//
// Created by LeeSunhyoup on 2015. 10. 5..
// Copyright © 2015년 kciter. All rights reserved.
//
import UIKit
@objc public enum FloatyItemLabelPositionType: Int {
case left
case right
}
/**
Floating Action Button Object's item.
*/
open class FloatyItem: UIView {
// MARK: - Properties
/**
This object's button size.
*/
@objc open var size: CGFloat = 42 {
didSet {
self.frame = CGRect(x: 0, y: 0, width: size, height: size)
titleLabel.frame.origin.y = self.frame.height/2-titleLabel.frame.size.height/2
_iconImageView?.center = CGPoint(x: size/2, y: size/2) + imageOffset
self.setNeedsDisplay()
}
}
/**
Button color.
*/
@objc open var buttonColor: UIColor = UIColor.white
/**
Title label color.
*/
@objc open var titleColor: UIColor = UIColor.white {
didSet {
titleLabel.textColor = titleColor
}
}
/**
Enable/disable shadow.
*/
@objc open var hasShadow: Bool = true
/**
Circle Shadow color.
*/
@objc open var circleShadowColor: UIColor = UIColor.black
/**
Title Shadow color.
*/
@objc open var titleShadowColor: UIColor = UIColor.black
/**
If you touch up inside button, it execute handler.
*/
@objc open var handler: ((FloatyItem) -> Void)? = nil
@objc open var imageOffset: CGPoint = CGPoint.zero
@objc open var imageSize: CGSize = CGSize(width: 25, height: 25) {
didSet {
_iconImageView?.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
_iconImageView?.center = CGPoint(x: size/2, y: size/2) + imageOffset
}
}
/**
Reference to parent
*/
open weak var actionButton: Floaty?
/**
Shape layer of button.
*/
fileprivate var circleLayer: CAShapeLayer = CAShapeLayer()
/**
If you keeping touch inside button, button overlaid with tint layer.
*/
fileprivate var tintLayer: CAShapeLayer = CAShapeLayer()
/**
Item's title label position.
deafult is left
*/
@objc open var titleLabelPosition: FloatyItemLabelPositionType = .left {
didSet {
if(titleLabelPosition == .left) {
titleLabel.frame.origin.x = -titleLabel.frame.size.width - 10
} else { //titleLabel will be on right
titleLabel.frame.origin.x = iconImageView.frame.origin.x + iconImageView.frame.size.width + 20
}
}
}
/**
Item's title label.
*/
var _titleLabel: UILabel? = nil
@objc open var titleLabel: UILabel {
get {
if _titleLabel == nil {
_titleLabel = UILabel()
_titleLabel?.textColor = titleColor
_titleLabel?.font = FloatyManager.defaultInstance().font
addSubview(_titleLabel!)
}
return _titleLabel!
}
}
/**
Item's title.
*/
@objc open var title: String? = nil {
didSet {
titleLabel.text = title
titleLabel.sizeToFit()
if(titleLabelPosition == .left) {
titleLabel.frame.origin.x = -titleLabel.frame.size.width - 10
} else { //titleLabel will be on right
titleLabel.frame.origin.x = iconImageView.frame.origin.x + iconImageView.frame.size.width + 20
}
titleLabel.frame.origin.y = self.size/2-titleLabel.frame.size.height/2
if FloatyManager.defaultInstance().rtlMode {
titleLabel.transform = CGAffineTransform(scaleX: -1.0, y: 1.0);
}else {
titleLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0);
}
}
}
/**
Item's icon image view.
*/
var _iconImageView: UIImageView? = nil
@objc open var iconImageView: UIImageView {
get {
if _iconImageView == nil {
_iconImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
_iconImageView?.center = CGPoint(x: size/2, y: size/2) + imageOffset
_iconImageView?.contentMode = UIView.ContentMode.scaleAspectFill
addSubview(_iconImageView!)
}
return _iconImageView!
}
}
/**
Item's icon.
*/
@objc open var icon: UIImage? = nil {
didSet {
iconImageView.image = icon
}
}
/**
Item's icon tint color change
*/
@objc open var iconTintColor: UIColor! = nil {
didSet {
let image = iconImageView.image?.withRenderingMode(.alwaysTemplate)
_iconImageView?.tintColor = iconTintColor
_iconImageView?.image = image
}
}
/**
itemBackgroundColor change
*/
public var itemBackgroundColor: UIColor? = nil {
didSet { circleLayer.backgroundColor = itemBackgroundColor?.cgColor }
}
// MARK: - Initialize
/**
Initialize with default property.
*/
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: size, height: size))
backgroundColor = UIColor.clear
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Set size, frame and draw layers.
*/
open override func draw(_ rect: CGRect) {
super.draw(rect)
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
createCircleLayer()
setShadow()
if _titleLabel != nil {
bringSubviewToFront(_: titleLabel)
}
if _iconImageView != nil {
bringSubviewToFront(_: iconImageView)
}
}
fileprivate func createCircleLayer() {
// circleLayer.frame = CGRectMake(frame.size.width - size, 0, size, size)
let castParent : Floaty = superview as! Floaty
circleLayer.frame = CGRect(x: castParent.itemSize/2 - (size/2), y: 0, width: size, height: size)
circleLayer.backgroundColor = buttonColor.cgColor
circleLayer.cornerRadius = size/2
layer.addSublayer(circleLayer)
}
fileprivate func createTintLayer() {
// tintLayer.frame = CGRectMake(frame.size.width - size, 0, size, size)
let castParent : Floaty = superview as! Floaty
tintLayer.frame = CGRect(x: castParent.itemSize/2 - (size/2), y: 0, width: size, height: size)
tintLayer.backgroundColor = UIColor.white.withAlphaComponent(0.2).cgColor
tintLayer.cornerRadius = size/2
layer.addSublayer(tintLayer)
}
fileprivate func setShadow() {
if !hasShadow {
return
}
circleLayer.shadowOffset = CGSize(width: 1, height: 1)
circleLayer.shadowRadius = 2
circleLayer.shadowColor = circleShadowColor.cgColor
circleLayer.shadowOpacity = 0.4
titleLabel.layer.shadowOffset = CGSize(width: 1, height: 1)
titleLabel.layer.shadowRadius = 2
titleLabel.layer.shadowColor = titleShadowColor.cgColor
titleLabel.layer.shadowOpacity = 0.4
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 {
let touch = touches.first
if touch?.tapCount == 1 {
if touch?.location(in: self) == nil { return }
createTintLayer()
}
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 {
let touch = touches.first
if touch?.tapCount == 1 {
if touch?.location(in: self) == nil { return }
createTintLayer()
}
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
tintLayer.removeFromSuperlayer()
if touches.count == 1 {
let touch = touches.first
if touch?.tapCount == 1 {
if touch?.location(in: self) == nil { return }
if actionButton != nil && actionButton!.autoCloseOnTap {
actionButton!.close()
}
handler?(self)
}
}
}
}
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
| 26.438356 | 113 | 0.634845 |
1a7201846b3d64dc8cd02743c848e0881e81fbfc | 8,292 | import XCTest
@testable import Mds
class DownloadManagerTests: DownloadManagerTestsBase {
private func verifyDownloads(_ expectedDownloads: [DownloadItem], file: StaticString = #file, line: UInt = #line) {
XCTAssertDownloadItems(target.getDownloads(), expectedDownloads, file: file, line: line)
}
func testGetDownloads() {
let track1 = TrackStub()
let recordId11 = track1.addRecord(fileSize: 4200, serverId: .MdsOnlineRu, partNumber: 1)
let recordId12 = track1.addRecord(fileSize: 3300, serverId: .MdsOnlineRu, partNumber: 2)
_ = track1.addRecord(fileSize: 2400, serverId: .KallistoRu, partNumber: 0)
let track2 = TrackStub()
let recordId2 = track2.addRecord(fileSize: 1234, serverId: .MdsOnlineRu, partNumber: 0)
verifyDownloads([])
updateState(ofRecord: recordId11, .cached(URL(fileURLWithPath: "/file11.mp3"), 100500))
verifyDownloads([
DownloadItem(trackId: track1.trackId, state: .incomplete(.MdsOnlineRu, getProgress(42, 42+33))),
])
updateState(ofRecord: recordId2, .caching(getProgress(10, 20)))
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: .downloading(.MdsOnlineRu, getProgress(1, 2))),
DownloadItem(trackId: track1.trackId, state: .incomplete(.MdsOnlineRu, getProgress(42, 42+33))),
])
updateState(ofRecord: recordId12, .caching(getProgress(10, 30)))
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: .downloading(.MdsOnlineRu, getProgress(1, 2))),
DownloadItem(trackId: track1.trackId, state: .downloading(.MdsOnlineRu, getProgress(42+11, 42+33))),
])
updateState(ofRecord: recordId2, .cached(URL(fileURLWithPath: "/file2.mp3"), 1234))
let expectedTrack2State: DownloadState = .downloaded(.MdsOnlineRu, 1234)
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
DownloadItem(trackId: track1.trackId, state: .downloading(.MdsOnlineRu, getProgress(42+11, 42+33))),
])
updateState(ofRecord: recordId11, .notCached)
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
DownloadItem(trackId: track1.trackId, state: .downloading(.MdsOnlineRu, getProgress(11, 42+33))),
])
updateState(ofRecord: recordId12, .notCached)
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
])
updateState(ofRecord: recordId12, .caching(getProgress(20, 30)))
verifyDownloads([
DownloadItem(trackId: track1.trackId, state: .downloading(.MdsOnlineRu, getProgress(22, 42+33))),
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
])
updateState(ofRecord: recordId12, .cached(URL(fileURLWithPath: "/file12.mp3"), 3300))
verifyDownloads([
DownloadItem(trackId: track1.trackId, state: .incomplete(.MdsOnlineRu, getProgress(33, 42+33))),
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
])
updateState(ofRecord: recordId12, .notCached)
verifyDownloads([
DownloadItem(trackId: track2.trackId, state: expectedTrack2State),
])
}
func testEstimateSizePositive() {
let track1 = TrackStub()
let recordId11 = track1.addRecord(fileSize: 4200, serverId: .MdsOnlineRu, partNumber: 1)
let recordId12 = track1.addRecord(fileSize: 3300, serverId: .MdsOnlineRu, partNumber: 2)
_ = track1.addRecord(fileSize: 2400, serverId: .KallistoRu, partNumber: 0)
var callbackResult: Int64? = nil
var callbackCalledTimes = 0
target.estimateSize(ofTrack: track1, fromServer: .MdsOnlineRu) { size in
callbackResult = size
callbackCalledTimes += 1
}
XCTAssertEqual(callbackCalledTimes, 0)
let requests = cacheMock.estimateSizeRequests
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].0.recordId, recordId11)
XCTAssertEqual(requests[1].0.recordId, recordId12)
requests[0].1(42)
XCTAssertEqual(callbackCalledTimes, 0)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
requests[1].1(18)
XCTAssertEqual(callbackCalledTimes, 1)
XCTAssertEqual(callbackResult, 60)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
}
func testEstimateSizeFirstFailed() {
let track1 = TrackStub()
let recordId11 = track1.addRecord(fileSize: 4200, serverId: .MdsOnlineRu, partNumber: 1)
let recordId12 = track1.addRecord(fileSize: 3300, serverId: .MdsOnlineRu, partNumber: 2)
_ = track1.addRecord(fileSize: 2400, serverId: .KallistoRu, partNumber: 0)
var callbackResult: Int64? = nil
var callbackCalledTimes = 0
target.estimateSize(ofTrack: track1, fromServer: .MdsOnlineRu) { size in
callbackResult = size
callbackCalledTimes += 1
}
XCTAssertEqual(callbackCalledTimes, 0)
let requests = cacheMock.estimateSizeRequests
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].0.recordId, recordId11)
XCTAssertEqual(requests[1].0.recordId, recordId12)
requests[0].1(nil)
XCTAssertEqual(callbackCalledTimes, 1)
XCTAssertEqual(callbackResult, nil)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
requests[1].1(18)
XCTAssertEqual(callbackCalledTimes, 1) // no new callbacks
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
}
func testEstimateSizeSecondFailed() {
let track1 = TrackStub()
let recordId11 = track1.addRecord(fileSize: 4200, serverId: .MdsOnlineRu, partNumber: 1)
let recordId12 = track1.addRecord(fileSize: 3300, serverId: .MdsOnlineRu, partNumber: 2)
_ = track1.addRecord(fileSize: 2400, serverId: .KallistoRu, partNumber: 0)
var callbackResult: Int64? = nil
var callbackCalledTimes = 0
target.estimateSize(ofTrack: track1, fromServer: .MdsOnlineRu) { size in
callbackResult = size
callbackCalledTimes += 1
}
XCTAssertEqual(callbackCalledTimes, 0)
let requests = cacheMock.estimateSizeRequests
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].0.recordId, recordId11)
XCTAssertEqual(requests[1].0.recordId, recordId12)
requests[0].1(42)
XCTAssertEqual(callbackCalledTimes, 0)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
requests[1].1(nil)
XCTAssertEqual(callbackCalledTimes, 1)
XCTAssertEqual(callbackResult, nil)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
}
func testEstimateSizeBothFailed() {
let track1 = TrackStub()
let recordId11 = track1.addRecord(fileSize: 4200, serverId: .MdsOnlineRu, partNumber: 1)
let recordId12 = track1.addRecord(fileSize: 3300, serverId: .MdsOnlineRu, partNumber: 2)
_ = track1.addRecord(fileSize: 2400, serverId: .KallistoRu, partNumber: 0)
var callbackResult: Int64? = nil
var callbackCalledTimes = 0
target.estimateSize(ofTrack: track1, fromServer: .MdsOnlineRu) { size in
callbackResult = size
callbackCalledTimes += 1
}
XCTAssertEqual(callbackCalledTimes, 0)
let requests = cacheMock.estimateSizeRequests
XCTAssertEqual(requests.count, 2)
XCTAssertEqual(requests[0].0.recordId, recordId11)
XCTAssertEqual(requests[1].0.recordId, recordId12)
requests[0].1(nil)
XCTAssertEqual(callbackCalledTimes, 1)
XCTAssertEqual(callbackResult, nil)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
requests[1].1(nil)
XCTAssertEqual(callbackCalledTimes, 1)
XCTAssertEqual(cacheMock.estimateSizeRequests.count, 2) // no new requests
}
}
| 43.873016 | 119 | 0.669802 |
f7d7924f872f1231411f69203278f4468b367330 | 646 | //
// GCD.swift
// TSBoilerplateSwift
//
// Created by Tim Sawtell on 25/06/2014.
// Copyright (c) 2014 Sawtell Software. All rights reserved.
//
import Foundation
func waitThenRunOnMain(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func waitThenRunOnGlobal(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_global_queue(0, 0), closure)
} | 23.925926 | 61 | 0.626935 |
716ec9151df2f1fa962f1a9b6d27ed22887722cd | 1,282 | //
// AppDelegate.swift
// Set game
//
// Created by Artur Shellunts on 23.07.21.
//
import UIKit
@main
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.
}
}
| 34.648649 | 176 | 0.785491 |
f70f6e723be9dab1a1459567c80158774645c3d2 | 1,257 | //
// ApplicationLogParser.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 24.04.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
import CoreFoundation
/// `ApplicationLogReader` class is responsible to read given log files line by line
class ApplicationLogReader {
// MAKR: - Interface
private var configuration: Configuration
init(configuration: Configuration = Configuration.default()) {
self.configuration = configuration
}
/// Reads the given log starting from the given line number
///
/// - Parameters:
/// - logText: log text to read
/// - lineNumber: starting line number in case developer wants to skip some
/// - Returns: read array of `ApplicationLogLine`
func readline(of logText: String, startingFrom lineNumber: Int = 0) -> [ApplicationLogLine] {
// We know that AppCode has test output with HTML escaped characters
let textLines = logText.components(separatedBy: .newlines).map { $0.htmlUnescape() }
if textLines.count <= lineNumber {
return []
}
return textLines[lineNumber...(textLines.count - 1)].map { ApplicationLogLine(line: $0, configuration: configuration) }
}
}
| 33.972973 | 127 | 0.682578 |
e9a4e25ae745b62462b9b8b08d42a80b96499e2e | 5,497 | //
// AssetArchive.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2019-02-13.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
import Foundation
open class AssetArchive {
let name: String
private let fileManager: FileManager
private let archiveUrl: URL
private var archivePath: String { return archiveUrl.path }
private var extractedPath: String { return extractedUrl.path }
let extractedUrl: URL
private unowned let apiClient: BRAPIClient
private var archiveExists: Bool {
return fileManager.fileExists(atPath: archivePath)
}
private var extractedDirExists: Bool {
return fileManager.fileExists(atPath: extractedPath)
}
var version: String? {
guard let archiveContents = try? Data(contentsOf: archiveUrl) else {
return nil
}
return archiveContents.sha256.hexString
}
init?(name: String, apiClient: BRAPIClient) {
self.name = name
self.apiClient = apiClient
self.fileManager = FileManager.default
let bundleDirUrl = apiClient.bundleDirUrl
archiveUrl = bundleDirUrl.appendingPathComponent("\(name).tar")
extractedUrl = bundleDirUrl.appendingPathComponent("\(name)-extracted", isDirectory: true)
}
func update(completionHandler: @escaping (_ error: Error?) -> Void) {
do {
try ensureExtractedPath()
//If directory creation failed due to file existing
} catch let error as NSError where error.code == 512 && error.domain == NSCocoaErrorDomain {
do {
try fileManager.removeItem(at: apiClient.bundleDirUrl)
try fileManager.createDirectory(at: extractedUrl, withIntermediateDirectories: true, attributes: nil)
} catch let e {
return completionHandler(e)
}
} catch let e {
return completionHandler(e)
}
copyBundledArchive()
apiClient.getAssetVersions(name) { versions, err in
DispatchQueue.global(qos: .utility).async {
if let err = err {
print("[AssetArchive] could not get asset versions. error: \(err)")
return completionHandler(err)
}
guard let versions = versions, let version = self.version else {
return completionHandler(BRAPIClientError.unknownError)
}
if versions.firstIndex(of: version) == versions.count - 1 {
print("[AssetArchive] already at most recent version of bundle \(self.name)")
self.extract { error in
completionHandler(error)
}
} else {
self.downloadCompleteArchive(completionHandler: completionHandler)
}
}
}
}
fileprivate func extract(completionHandler: @escaping (_ error: Error?) -> Void) {
do {
try BRTar.createFilesAndDirectoriesAtPath(extractedPath, withTarPath: archivePath)
completionHandler(nil)
} catch let error {
completionHandler(error)
print("[AssetArchive] error extracting bundle: \(error)")
}
}
fileprivate func downloadCompleteArchive(completionHandler: @escaping (_ error: Error?) -> Void) {
apiClient.downloadAssetArchive(name) { (data, err) in
DispatchQueue.global(qos: .utility).async {
if let err = err {
print("[AssetArchive] error downloading complete archive \(self.name) error=\(err)")
return completionHandler(err)
}
guard let data = data else {
return completionHandler(BRAPIClientError.unknownError)
}
do {
try data.write(to: self.archiveUrl, options: .atomic)
self.extract { error in
return completionHandler(error)
}
} catch let e {
print("[AssetArchive] error extracting complete archive \(self.name) error=\(e)")
return completionHandler(e)
}
}
}
}
fileprivate func ensureExtractedPath() throws {
if !extractedDirExists {
try fileManager.createDirectory(atPath: extractedPath,
withIntermediateDirectories: true,
attributes: nil
)
}
}
fileprivate func copyBundledArchive() {
if let bundledArchiveUrl = Bundle.main.url(forResource: name, withExtension: "tar") {
do {
if archiveExists {
try fileManager.removeItem(atPath: archivePath)
}
try fileManager.copyItem(at: bundledArchiveUrl, to: archiveUrl)
print("[AssetArchive] used bundled archive for \(name)")
} catch let error {
print("[AssetArchive] unable to copy bundled archive `\(name)` \(bundledArchiveUrl) -> \(archiveUrl): \(error)")
}
}
}
}
| 36.892617 | 128 | 0.54557 |
8a5b3e5b1002c2cca2802c20b3bed698a34ee07d | 2,475 | import ArgumentParser
import Combine
import Foundation
struct GHChanges: ParsableCommand {
@Option(
name: [.customLong("repo"), .short],
help: ArgumentHelp(
"Path to git working directory with GitHub set in remote.",
valueName: "path"
)
)
var repoDir: String = "./"
@Option(help: "Github API token with a permission for repo:read")
var token: String = ""
@Option(
name: .customLong("from"),
help: ArgumentHelp(
"Git reference at start. Generally set a latest release tag",
valueName: "ref"
)
)
var refFrom: String = ""
@Option(
name: .customLong("to"),
help: ArgumentHelp("Git ref at end", valueName: "ref")
)
var refTo: String = "HEAD"
@Flag(name: [.long, .customShort("a")], help: "Append more information.")
var withAppendix: Bool = false
mutating func run() throws {
// ## Note
// Only merge commits are supported.
// This is not a problem as the default branch is protected.
// In the future, we need to support direct single commit.
var result: Result<[PullRequest], Error>!
getPullRequests: do {
let group = DispatchGroup()
group.enter()
try GitRepository(at: repoDir, token: token)
.getPullRequests(from: refFrom, to: refTo) {
result = $0
group.leave()
}
group.wait()
}
let pullRequests = try result.get()
guard !pullRequests.isEmpty else {
// TODO: Exit as error
return
}
let visitor = ChangeVisitor()
pullRequests.forEach({ visitor.visit(pullRequest: $0) })
let output = ChangeNoteGenerator.make(
with: visitor.summary,
withAppendix: withAppendix
)
print(output)
}
mutating func validate() throws {
#if DEBUG
// repoDir = ""
// token = ""
// refFrom = ""
// refTo = ""
// withAppendix = true
#endif
if repoDir.isEmpty {
throw ValidationError("repo is a reqired option.")
}
if token.isEmpty {
throw ValidationError("token is a reqired option.")
}
if refFrom.isEmpty {
throw ValidationError("from is a reqired option.")
}
}
}
GHChanges.main()
| 24.75 | 77 | 0.538182 |
e03e8ac44fbd14e019106b0a8c2f510426ec12fc | 2,557 | //
// MoyaNetworkService.swift
// MVVMExample
//
// Created by pham.minh.tien on 6/17/20.
// Copyright © 2020 Sun*. All rights reserved.
//
import Foundation
import MVVM
import Moya
import RxSwift
import RxCocoa
import SwiftyJSON
// MARK: Guideline
/// - Setting request header(authentication, contentType,....) in MoyaAPIService.
/// - Setting Enpoint In MoyaAPIService
class MoyaService {
var tmpBag: DisposeBag?
let curlString = BehaviorRelay<String?>(value: "")
private lazy var moyaProvider = MoyaProvider<MoyaAPIService>(plugins: [
NetworkLoggerPlugin(configuration: .init(formatter: .init(),
output: { target, array in
_ = target.method
if let curlStr = array.first, curlStr.contains("curl") {
self.curlString.accept(curlStr)
}
},
logOptions: .formatRequestAscURL))
])
func search(keyword: String, page: Int) -> Single<FlickrSearchResponse> {
return Single.create { single in
self.moyaProvider.rx.request(.flickrSearch(keyword: keyword, page: page))
.filterSuccessfulStatusCodes()
.map({ response -> FlickrSearchResponse? in
/// Implement logic maping if need. Maping API Response to FlickrSearchResponse object.
let jsonData = JSON(response.data)
if let dictionary = jsonData.dictionaryObject, let flickrSearchResponse = FlickrSearchResponse(JSON: dictionary) {
flickrSearchResponse.response_description = jsonData
return flickrSearchResponse
}
return nil
})
.subscribe(onSuccess: { flickrSearchResponse in
if let response = flickrSearchResponse {
single(.success(response))
} else {
let err = NSError(domain: "", code: 404, userInfo: ["message": "Data not fount"])
single(.error(err))
}
}) { error in
single(.error(error))
} => self.tmpBag
return Disposables.create { self.tmpBag = DisposeBag() }
}
}
}
| 41.241935 | 134 | 0.510364 |
ef19b930e086a7fa4878d59f05e9ecb83d15267e | 2,690 | /// Capable of being converted to/from `PostgreSQLData`
public protocol PostgreSQLDataConvertible {
/// This type's preferred data type.
static var postgreSQLDataType: PostgreSQLDataType { get }
/// This type's preferred array type.
static var postgreSQLDataArrayType: PostgreSQLDataType { get }
/// Creates a `Self` from the supplied `PostgreSQLData`
static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Self
/// Converts `Self` to a `PostgreSQLData`
func convertToPostgreSQLData() throws -> PostgreSQLData
}
extension PostgreSQLData {
/// Gets a `String` from the supplied path or throws a decoding error.
public func decode<T>(_ type: T.Type) throws -> T where T: PostgreSQLDataConvertible {
return try T.convertFromPostgreSQLData(self)
}
}
extension PostgreSQLData: PostgreSQLDataConvertible {
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataType`
public static var postgreSQLDataType: PostgreSQLDataType { return .void }
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataArrayType`
public static var postgreSQLDataArrayType: PostgreSQLDataType { return .void }
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> PostgreSQLData {
return data
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return self
}
}
extension RawRepresentable where RawValue: PostgreSQLDataConvertible {
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataType`
public static var postgreSQLDataType: PostgreSQLDataType {
return RawValue.postgreSQLDataType
}
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataArrayType`
public static var postgreSQLDataArrayType: PostgreSQLDataType {
return RawValue.postgreSQLDataArrayType
}
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Self {
let aRawValue = try RawValue.convertFromPostgreSQLData(data)
guard let enumValue = Self(rawValue: aRawValue) else {
throw PostgreSQLError(identifier: "invalidRawValue", reason: "Unable to decode RawRepresentable from the database value.", source: .capture())
}
return enumValue
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return try self.rawValue.convertToPostgreSQLData()
}
}
| 40.757576 | 154 | 0.745353 |
cc4391c4b0c047349188567e2a732ecb075ce329 | 1,105 | import Foundation
import ObjectMapper
open class IVRMenuActionsInfo: Mappable {
/*
Key. The following values are supported: numeric: '1' to '9' Star Hash NoInput
*/
open var `input`: String?
/*
Internal identifier of an answering rule
*/
open var `action`: String?
/*
For 'Connect' or 'Voicemail' actions only. Extension reference
*/
open var `extension`: IVRMenuExtensionInfo?
/*
For 'Transfer' action only. PSTN number in E.164 format
*/
open var `phoneNumber`: String?
public init() {
}
required public init?(map: Map) {
}
convenience public init(input: String? = nil, action: String? = nil, extension: IVRMenuExtensionInfo? = nil, phoneNumber: String? = nil) {
self.init()
self.input = `input`
self.action = `action`
self.extension = `extension`
self.phoneNumber = `phoneNumber`
}
open func mapping(map: Map) {
`input` <- map["input"]
`action` <- map["action"]
`extension` <- map["extension"]
`phoneNumber` <- map["phoneNumber"]
}
}
| 29.078947 | 142 | 0.606335 |
469a9d9a69fd233c2303f0c49608bdc0a3c8c559 | 5,436 | //: [Previous](@previous)
import Foundation
test("Compose >->") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let add1_double_square = add1 >-> double >-> square
expectEqual(add1_double_square(1), 16)
}
test("Compose <-<") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let square_double_add1 = add1 <-< double <-< square
expectEqual(square_double_add1(1), 3)
}
test("Array Compose >->") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let add1_double_square: (Int) -> [Int] = (add1 >-> pure)
>-> (double >-> pure)
>-> (square >-> pure)
expectEqual(add1_double_square(1), [16])
}
test("Array Compose <-<") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let square_double_add1: (Int) -> [Int] = (pure <-< add1)
<-< (pure <-< double)
<-< (pure <-< square)
expectEqual(square_double_add1(1), [3])
}
test("Optional Compose >->") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let add1_double_square: (Int) -> Int? = (add1 >-> pure)
>-> (double >-> pure)
>-> (square >-> pure)
expectEqual(add1_double_square(1), 16)
}
test("Optional Compose <-<") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let square_double_add1: (Int) -> Int? = (pure <-< add1)
<-< (pure <-< double)
<-< (pure <-< square)
expectEqual(square_double_add1(1), 3)
}
test("Result Compose >->") {
struct TestError: Swift.Error, Equatable { }
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let add1_double_square: (Int) -> Result<Int,TestError> = (add1 >-> pure)
>-> (double >-> pure)
>-> (square >-> pure)
expectEqual(add1_double_square(1).value, 16)
}
test("Result Compose <-<") {
struct TestError: Swift.Error, Equatable { }
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let square_double_add1: (Int) -> Result<Int,TestError> = (pure <-< add1)
<-< (pure <-< double)
<-< (pure <-< square)
expectEqual(square_double_add1(1).value, 3)
}
test("Pipe |>") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let result = 1 |> add1 |> double |> square
expectEqual(result, 16)
}
test("Array Bind >>-") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let result = [1, 2, 3]
>>- (add1 >-> pure)
>>- (double >-> pure)
>>- (square >-> pure)
expectEqual(result, [16, 36, 64])
}
test("Array Bind -<<") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let result = (pure <-< add1)
-<< (pure <-< double)
-<< (pure <-< square)
-<< [1, 2, 3]
expectEqual(result, [3, 9, 19])
}
test("Optional Bind >>-") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let some = Optional.some(1) >>- add1 >>- double >>- square
let none = Optional.none >>- add1 >>- double >>- square
expectEqual(some, 16)
expectEqual(none, nil)
}
test("Optional Bind -<<") {
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let some = add1 -<< double -<< square -<< Optional.some(1)
let none = add1 -<< double -<< square -<< Optional.none
expectEqual(some, 3)
expectEqual(none, nil)
}
test("Result Bind >>-") {
struct TestError: Swift.Error, Equatable { }
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let success = Result<Int, TestError>(1)
>>- (add1 >-> pure)
>>- (double >-> pure)
>>- (square >-> pure)
let failure = Result<Int, TestError>(TestError())
>>- (add1 >-> pure)
>>- (double >-> pure)
>>- (square >-> pure)
expectEqual(success.value, 16)
expectEqual(failure.error, TestError())
}
test("Result Bind -<<") {
struct TestError: Swift.Error, Equatable { }
let add1: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 + $0 }
let square: (Int) -> Int = { $0 * $0 }
let success = (add1 >-> pure)
-<< (double >-> pure)
-<< (square >-> pure)
-<< Result<Int, TestError>(1)
let failure = (add1 >-> pure)
-<< (double >-> pure)
-<< (square >-> pure)
-<< Result<Int, TestError>(TestError())
expectEqual(success.value, 3)
expectEqual(failure.error, TestError())
}
runAllTests()
//: [Next](@next)
| 26.647059 | 76 | 0.473694 |
29d6453c225054f1b628861cacfb619d256fc131 | 387 | //
// MessageCell.swift
// ParseChat
//
// Created by Harold on 12/14/17.
// Copyright © 2017 Harold . All rights reserved.
//
import UIKit
class MessageCell: UICollectionViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
| 14.884615 | 50 | 0.622739 |
76f437b9af8e14f526e1294c43cc1f6061fdd3ab | 3,242 | //
// AppDelegate.swift
// GIFSet-Example
//
// Created by Alfred Hanssen on 3/23/16.
// Copyright © 2016 Alfie Hanssen. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 50.65625 | 285 | 0.755706 |
20d1a39459ddf942925c7c59e70c902be1a75502 | 1,948 | //
// FlexView.swift
// WolfPowerViews
//
// Created by Wolf McNally on 2/14/17.
// Copyright © 2017 WolfMcNally.com. All rights reserved.
//
import UIKit
import WolfCore
public enum FlexContent {
case string(String)
case image(UIImage)
case imageString(UIImage, String)
}
public class FlexView: View {
public var content: FlexContent? {
didSet {
sync()
}
}
private var horizontalStackView: HorizontalStackView = {
let view = HorizontalStackView()
return view
}()
public private(set) var label: Label!
public private(set) var imageView: ImageView!
public init() {
super.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func setup() {
super.setup()
isUserInteractionEnabled = false
self => [
horizontalStackView
]
horizontalStackView.constrainFrameToFrame()
horizontalStackView.setPriority(crH: .required)
}
private func removeContentViews() {
horizontalStackView.removeAllSubviews()
label = nil
imageView = nil
}
private func setContentViews(_ views: [UIView]) {
horizontalStackView => views
}
private func sync() {
removeContentViews()
switch content {
case .string(let text)?:
label = Label()
label.text = text
setContentViews([label])
case .image(let image)?:
imageView = ImageView()
imageView.image = image
setContentViews([imageView])
case .imageString(let image, let string)?:
label = Label()
imageView = ImageView()
label.text = string
imageView.image = image
setContentViews([imageView, label])
case nil:
break
}
}
}
| 22.136364 | 60 | 0.582136 |
ab11bc60f1225686f95ecf939e71ead3f6c6cf5b | 6,010 | //
// WorldStateManager.swift
// Spark
//
// Created by Alex Roman on 10/29/21.
//
import Foundation
import SceneKit
import GameplayKit
class WorldState {
var health: Int!
var growth: Double!
var tree: Tree!
var grass: Grass?
var terrains = [Terrain]()
//var spawnMap = [[SCNNode]]!
//default
init() {
initializeTerrain(_of: 1, 1, 0)
health = 100;
growth = 0;
tree = Tree(fileName: "tree", fileType: "scn", dir: "/Art.scnassets/Vegetation")
grass = Grass(fileName: "grass", fileType: "scn", dir: "/Art.scnassets/Vegetation")
}
func initializeTerrain(_of width: Int,_ length: Int,_ height:Int){
let terrain = Terrain(width:width , length: length , height: height)
// spawnMap = [[SCNNode]](repeating: [SCNNode](repeating: SCNNode(), count: width), count: length)
terrains.append(terrain);
}
func update(){
var randNum = Int.random(in: 0...2)
var randNum2 = Int.random(in: 0...200)
if (1 == 2){
randomlySpawnCopy(grass!, on: terrains[0])
}
if (randNum2 == 6){
randomlySpawnCopy(tree, on: terrains[0])
}
}
/// Places the object at the coordinate space in the world
/// - Parameters:
/// - object: The object
/// - coordinate: The placement location
func place(_ object: WorldObject, at coordinate: SCNVector3 ){
object.refNode.worldPosition.x = coordinate.x
object.refNode.worldPosition.y = coordinate.y
object.refNode.worldPosition.z = coordinate.z
}
/// Places a copy of the object at the coordinate location of the Terrain. While place objects at center of the grid
/// - Parameters:
/// - object:
/// - coordinate:
/// - terrain:
func spawnCopy(_ object: WorldObject, at coordinate: GridPoint, on terrain: Terrain) throws {
guard (terrain.gridContains(x: coordinate.x, y: coordinate.y, z: coordinate.z)) else {
throw WorldDataError.spawnOutOfBounds
}
var modelCopy: SCNNode!
let z = coordinate.z
let x = coordinate.x
let terrainSectorNode = terrain.grid[z][x]
modelCopy = object.refNode.clone()
place(object, at: SCNVector3(coordinate.x, coordinate.y, coordinate.z))
}
func randomlySpawnCopy(_ object: WorldObject, on terrain: Terrain) {
//random Terrain sector
var modelCopy: SCNNode?
let z = Int.random(in: 0...terrain.width-1)
let x = Int.random(in: 0...terrain.length-1)
let terrainSectorNode = terrain.grid[z][x]
//clone the model
modelCopy = object.refNode!.clone()
//add clone to terrain sector node
terrainSectorNode.addChildNode(modelCopy!)
//get all vertices of terrain
let vertices = terrainSectorNode.childNodes[0].childNodes[0].geometry?.vertices()
//get valid spawn coordinates from vertices
let spawnCoordinate = validSpawnCoordinate(vertices: vertices!)
//translate the clone to the coordinates
modelCopy?.localTranslate(by: coordinateTranslation(from: modelCopy!.position, to: (modelCopy?.convertPosition(spawnCoordinate, from: terrainSectorNode.childNodes[0].childNodes[0]))! ) )
}
func restrictSpawn(at bounds: SCNBoundingVolume){
}
func randomlySpawnCopy(_ object: WorldObject, on terrain: Terrain, with offset: Float) {
//random Terrain sector
var modelCopy: SCNNode?
let z = Int.random(in: 0...terrain.width-1)
let x = Int.random(in: 0...terrain.length-1)
let terrainSectorNode = terrain.grid[z][x]
//clone the model
modelCopy = object.refNode!.clone()
//add clone to terrain sector node
terrainSectorNode.addChildNode(modelCopy!)
//get all vertices of terrain
let vertices = terrainSectorNode.childNodes[0].childNodes[0].geometry?.vertices()
//get valid spawn coordinates from vertices
let spawnCoordinate = validSpawnCoordinate(vertices: vertices!)
//translate the clone to the coordinates
modelCopy?.localTranslate(by: coordinateTranslation(from: modelCopy!.position, to: (modelCopy?.convertPosition(spawnCoordinate, from: terrainSectorNode.childNodes[0].childNodes[0]))! ) )
}
// private func randomlyOffsetVector(_ position:SCNVector3, by offset: Float,with bound: SCNBoundingVolume ) -> SCNVector3 {
// // pick random offset
// let randomizer = GKRandomDistribution()
//
//
//
// //case: all positions can be offset
//
//
// //case: an offset will cause the position to be out bounds
// }
//
/// Generates a randomize spawn point from a list of vertices
/// - Parameter node: The terrain node
func validSpawnCoordinate(vertices: [SCNVector3]) -> SCNVector3{
var spawnCoordinate:SCNVector3 = SCNVector3()
let randIndex = Int.random(in: 0...(vertices.count - 1))
spawnCoordinate = vertices[randIndex]
return spawnCoordinate
}
/// Calculates a translation vector by calculating the minimum distance between two coordinate points
/// - Parameters:
/// - startingVector: The initial positon
/// - EndVector: The final or target position
/// - Returns: The euclidian distance between the two
func coordinateTranslation(from startingVector: SCNVector3, to endVector: SCNVector3) -> SCNVector3{
var translationVector: SCNVector3 = SCNVector3()
translationVector.x = endVector.x - startingVector.x
translationVector.y = endVector.y - startingVector.y
translationVector.z = endVector.z - startingVector.z
return translationVector
}
}
extension WorldState {
}
| 33.764045 | 194 | 0.624958 |
9083227a2aeedc906b0b5654549af5a98fb63bc6 | 231 | //
// UINavigationController+Ext.swift
// ClockClock
//
// Created by Korel Hayrullah on 14.09.2021.
//
import UIKit
extension UINavigationController {
var rootViewController: UIViewController? {
return children.first
}
}
| 15.4 | 45 | 0.74026 |
1df13693a07f6f10d2d4d6809e21f1e384b69b24 | 6,014 | //
// DailySurveyViewController.swift
// CardinalKit_Example
//
// Created by Esteban Ramos on 18/04/22.
// Copyright © 2022 CocoaPods. All rights reserved.
//
import Foundation
import CareKit
import ResearchKit
import CareKitUI
class DailySurveyTask:ORKNavigableOrderedTask{
init(showInstructions:Bool = true){
var steps = [ORKStep]()
if(showInstructions){
// Instruction step
let instructionStep = ORKInstructionStep(identifier: "IntroStep")
instructionStep.title = "Daily Questionnaire"
instructionStep.text = "Please complete this survey daily to assess your own health."
steps += [instructionStep]
}
//How would you rate your health today?
let healthScaleAnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 5, minimumValue: 1, defaultValue: 3, step: 1, vertical: false, maximumValueDescription: "Excellent", minimumValueDescription: "Poor")
let healthScaleQuestionStep = ORKQuestionStep(identifier: "HealthScaleQuestionStep", title: "Question #1", question: "How would you rate your overall health today:", answer: healthScaleAnswerFormat)
steps += [healthScaleQuestionStep]
//How would you rate your mental health today?
let mentalhealthScaleAnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 5, minimumValue: 1, defaultValue: 3, step: 1, vertical: false, maximumValueDescription: "Excellent", minimumValueDescription: "Poor")
let mentalhealthScaleQuestionStep = ORKQuestionStep(identifier: "mentalHealthScaleQuestionStep", title: "Question #2", question: "How would you rate your mental health today:", answer: mentalhealthScaleAnswerFormat)
steps += [mentalhealthScaleQuestionStep]
let booleanAnswer = ORKBooleanAnswerFormat(yesString: "Yes", noString: "No")
let booleanQuestionStep = JHMapQuestionStep(identifier: "mapstep", title: "Question #3", question: "Is this map of your daily activity accurate? If NO, why not?", answer: booleanAnswer)
steps += [booleanQuestionStep]
let textQuestionStep = ORKQuestionStep(identifier: "whyNot", title: "Please explain why not", question: nil, answer: ORKTextAnswerFormat())
textQuestionStep.isOptional = false
steps += [textQuestionStep]
//SUMMARY
let summaryStep = ORKCompletionStep(identifier: "SummaryStep")
summaryStep.title = "Thank you."
summaryStep.text = "We appreciate your time."
steps += [summaryStep]
super.init(identifier: "DailySurveyTask", steps: steps)
let resultSelector = ORKResultSelector(resultIdentifier: "mapstep")
let booleanAnswerType = ORKResultPredicate.predicateForBooleanQuestionResult(with: resultSelector, expectedAnswer: false)
let predicateRule = ORKPredicateStepNavigationRule(resultPredicates: [booleanAnswerType],
destinationStepIdentifiers: ["whyNot"],
defaultStepIdentifier: "SummaryStep",
validateArrays: true)
self.setNavigationRule(predicateRule, forTriggerStepIdentifier: "mapstep")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class DailySurveyViewController: OCKInstructionsTaskViewController, ORKTaskViewControllerDelegate {
// 2. This method is called when the use taps the button!
override func taskView(_ taskView: UIView & OCKTaskDisplayable, didCompleteEvent isComplete: Bool, at indexPath: IndexPath, sender: Any?) {
// 2a. If the task was marked incomplete, fall back on the super class's default behavior or deleting the outcome.
if !isComplete {
super.taskView(taskView, didCompleteEvent: isComplete, at: indexPath, sender: sender)
return
}
let surveyViewController = ORKTaskViewController(task: DailySurveyTask(), taskRun: nil)
surveyViewController.delegate = self
// 3a. Present the survey to the user
present(surveyViewController, animated: true, completion: nil)
}
// 3b. This method will be called when the user completes the survey.
func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
taskViewController.dismiss(animated: true, completion: nil)
guard reason == .completed else {
taskView.completionButton.isSelected = false
return
}
controller.appendOutcomeValue(value: true, at: IndexPath(item: 0, section: 0), completion: nil)
}
func taskViewController(_ taskViewController: ORKTaskViewController, viewControllerFor step: ORKStep) -> ORKStepViewController? {
if step.identifier == "mapstep"{
return JHMapQuestionStepViewController(step: step)
}
else{
switch step{
case is ORKInstructionStep:
return ORKInstructionStepViewController(step: step)
case is ORKCompletionStep:
return ORKCompletionStepViewController(step: step)
default:
return ORKQuestionStepViewController(step: step)
}
}
}
}
class DailySurveyViewSynchronizer: OCKInstructionsTaskViewSynchronizer {
// Customize the initial state of the view
override func makeView() -> OCKInstructionsTaskView {
let instructionsView = super.makeView()
instructionsView.completionButton.label.text = "Start"
return instructionsView
}
override func updateView(_ view: OCKInstructionsTaskView, context: OCKSynchronizationContext<OCKTaskEvents>) {
super.updateView(view, context: context)
view.headerView.detailLabel.text = "Complete Every Day at 7:00 PM"
}
}
| 47.354331 | 223 | 0.681244 |
ede038b7654ced9aabb41652dd9fe40d03ece74b | 1,622 | //
// BaseUITableViewController.swift
// TTBaseUIKitExample
//
// Created by Truong Quang Tuan on 6/7/19.
// Copyright © 2019 Truong Quang Tuan. All rights reserved.
//
import Foundation
import TTBaseUIKit
class BaseUITableViewController: TTBaseUITableViewController {
override var navType: TTBaseUIViewController<TTBaseUIView>.NAV_STYLE { get { return .STATUS_NAV}}
var lgNavType:BaseUINavigationView.TYPE { get { return .DEFAULT}}
var backType:BaseUINavigationView.NAV_BACK = .BACK_POP
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return }
guard let headerView = strongSelf.tableView.tableHeaderView else { return }
headerView.layoutIfNeeded()
let header = strongSelf.tableView.tableHeaderView
strongSelf.tableView.tableHeaderView = header
}
}
override func updateBaseUI() {
super.updateBaseUI()
self.navBar = BaseUINavigationView(withType: self.lgNavType)
self.setDelegate()
}
}
//For Base private funcs
extension BaseUITableViewController : BaseUINavigationViewDelegate{
fileprivate func setDelegate() {
if let lgNav = self.navBar as? BaseUINavigationView { lgNav.delegate = self }
}
func navDidTouchUpBackButton(withNavView nav: BaseUINavigationView) {
self.navigationController?.popViewController(animated: true)
}
}
| 32.44 | 112 | 0.709001 |
1d6253999d010b4516788e8a0ef23a24e486b64b | 10,030 | //
// Copyright © 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
/// A view controller that manages the interface of the Generate Offline Map
/// (Basemap by Reference) sample.
class GenerateOfflineMapBasemapByReferenceViewController: UIViewController {
/// The map view managed by the view controller.
@IBOutlet weak var mapView: AGSMapView! {
didSet {
mapView.map = makeMap()
// Set inset of overlay.
let padding: CGFloat = 30
mapView.layoutMargins = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
}
}
/// The view used to show the geographic area for which the map data should
/// be taken offline.
@IBOutlet weak var areaOfInterestView: UIView!
/// The button item that starts generating an offline map.
@IBOutlet weak var generateButtonItem: UIBarButtonItem!
/// Creates a map.
///
/// - Returns: A new `AGSMap` object.
func makeMap() -> AGSMap {
let portal = AGSPortal.arcGISOnline(withLoginRequired: false)
let portalItem = AGSPortalItem(portal: portal, itemID: "acc027394bc84c2fb04d1ed317aac674")
let map = AGSMap(item: portalItem)
map.load { [weak self] _ in self?.mapDidLoad() }
return map
}
/// Called in response to the map load operation completing.
func mapDidLoad() {
guard let map = mapView.map else { return }
if let error = map.loadError {
presentAlert(error: error)
} else {
generateButtonItem.isEnabled = true
}
}
/// Called in response to the Generate Offline Map button item being tapped.
@IBAction func generateOfflineMap() {
generateButtonItem.isEnabled = false
mapView.isUserInteractionEnabled = false
let offlineMapTask = AGSOfflineMapTask(onlineMap: mapView.map!)
offlineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest: areaOfInterest) { [weak self] (parameters, error) in
if let parameters = parameters {
self?.offlineMapTask(offlineMapTask, didCreate: parameters)
} else if let error = error {
self?.offlineMapTask(offlineMapTask, didFailToCreateParametersWith: error)
}
}
}
func offlineMapTask(_ offlineMapTask: AGSOfflineMapTask, didCreate parameters: AGSGenerateOfflineMapParameters) {
let filename = parameters.referenceBasemapFilename as NSString
let name = filename.deletingPathExtension
let `extension` = filename.pathExtension
if let url = Bundle.main.url(forResource: name, withExtension: `extension`) {
let message: String = {
let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
return String(format: "“%@” has a local version of the basemap used by the map. Would you like to use the local or the online basemap?", displayName)
}()
let alertController = UIAlertController(title: "Choose Basemap", message: message, preferredStyle: .actionSheet)
let offlineAction = UIAlertAction(title: "Local", style: .default) { (_) in
parameters.referenceBasemapDirectory = url.deletingLastPathComponent()
self.takeMapOffline(task: offlineMapTask, parameters: parameters)
}
alertController.addAction(offlineAction)
let onlineAction = UIAlertAction(title: "Online", style: .default) { (_) in
self.takeMapOffline(task: offlineMapTask, parameters: parameters)
}
alertController.addAction(onlineAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
self.generateButtonItem.isEnabled = true
self.mapView.isUserInteractionEnabled = true
}
alertController.addAction(cancelAction)
alertController.preferredAction = offlineAction
alertController.popoverPresentationController?.barButtonItem = generateButtonItem
present(alertController, animated: true)
} else {
takeMapOffline(task: offlineMapTask, parameters: parameters)
}
}
func offlineMapTask(_ offlineMapTask: AGSOfflineMapTask, didFailToCreateParametersWith error: Error) {
presentAlert(error: error)
generateButtonItem.isEnabled = true
mapView.isUserInteractionEnabled = true
}
/// The geographic area for which the map data should be taken offline.
var areaOfInterest: AGSEnvelope {
let frame = mapView.convert(areaOfInterestView.frame, from: view)
// The lower-left corner.
let minPoint = mapView.screen(toLocation: frame.origin)
// The upper-right corner.
let maxPoint = mapView.screen(toLocation: CGPoint(x: frame.maxX, y: frame.maxY))
return AGSEnvelope(min: minPoint, max: maxPoint)
}
/// The generate offline map job.
var generateOfflineMapJob: AGSGenerateOfflineMapJob?
/// The view that displays the progress of the job.
var downloadProgressView: DownloadProgressView?
func takeMapOffline(task offlineMapTask: AGSOfflineMapTask, parameters: AGSGenerateOfflineMapParameters) {
guard let downloadDirectoryURL = try? FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: Bundle.main.bundleURL, create: true).appendingPathComponent(UUID().uuidString) else {
assertionFailure("Could not create temporary directory.")
return
}
let job = offlineMapTask.generateOfflineMapJob(with: parameters, downloadDirectory: downloadDirectoryURL)
job.start(statusHandler: nil, completion: { [weak self] (result, error) in
guard let self = self else { return }
if let result = result {
self.offlineMapGenerationDidSucceed(with: result)
} else if let error = error {
self.offlineMapGenerationDidFail(with: error)
}
})
self.generateOfflineMapJob = job
let downloadProgressView = DownloadProgressView()
downloadProgressView.delegate = self
downloadProgressView.show(withStatus: "Generating ofline map…", progress: 0)
downloadProgressView.observedProgress = job.progress
self.downloadProgressView = downloadProgressView
}
/// Called when the generate offline map job finishes successfully.
///
/// - Parameter result: The result of the generate offline map job.
func offlineMapGenerationDidSucceed(with result: AGSGenerateOfflineMapResult) {
// Dismiss download progress view.
downloadProgressView?.dismiss()
downloadProgressView = nil
// Show any layer or table errors to the user.
if let layerErrors = result.layerErrors as? [AGSLayer: Error],
let tableErrors = result.tableErrors as? [AGSFeatureTable: Error],
!(layerErrors.isEmpty && tableErrors.isEmpty) {
let errorMessages = layerErrors.map { "\($0.key.name): \($0.value.localizedDescription)" } +
tableErrors.map { "\($0.key.displayName): \($0.value.localizedDescription)" }
let message: String = {
let format = "The following error(s) occurred while generating the offline map:\n\n%@"
return String(format: format, errorMessages.joined(separator: "\n"))
}()
presentAlert(title: "Offline Map Generated with Errors", message: message)
}
areaOfInterestView.isHidden = true
mapView.map = result.offlineMap
mapView.setViewpoint(AGSViewpoint(targetExtent: areaOfInterest))
mapView.isUserInteractionEnabled = true
}
/// Called when the generate offline map job fails.
///
/// - Parameter error: The error that caused the generation to fail.
func offlineMapGenerationDidFail(with error: Error) {
if (error as NSError).code != NSUserCancelledError {
self.presentAlert(error: error)
}
self.generateButtonItem.isEnabled = true
mapView.isUserInteractionEnabled = true
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
"GenerateOfflineMapBasemapByReferenceViewController"
]
}
}
extension GenerateOfflineMapBasemapByReferenceViewController: DownloadProgressViewDelegate {
func downloadProgressViewDidCancel(_ downloadProgressView: DownloadProgressView) {
downloadProgressView.observedProgress?.cancel()
self.generateButtonItem.isEnabled = true
mapView.isUserInteractionEnabled = true
}
}
@IBDesignable
class GenerateOfflineMapBasemapByReferenceOverlayView: UIView {
@IBInspectable var borderColor: UIColor? {
get {
return layer.borderColor.map(UIColor.init(cgColor:))
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
}
| 44.380531 | 224 | 0.665304 |
bf25cefa3a1bc5e0a8078dfc16b3c8fc609dfc28 | 669 | //
// CompoundPredicateOperators.swift
// SwiftUIRules
//
// Created by Helge Heß on 01.09.19.
//
// e.g. !predicate
public prefix func !<P: RulePredicate>(_ base: P) -> RuleNotPredicate<P> {
RuleNotPredicate(predicate: base)
}
// e.g. \.state == done && \.color == yellow
public
func &&<LHS, RHS>(lhs: LHS, rhs: RHS) -> RuleAndPredicate2<LHS, RHS>
where LHS: RulePredicate, RHS: RulePredicate
{
RuleAndPredicate2(lhs, rhs)
}
// e.g. \.state == done || \.color == yellow
public
func ||<LHS, RHS>(lhs: LHS, rhs: RHS) -> RuleOrPredicate2<LHS, RHS>
where LHS: RulePredicate, RHS: RulePredicate
{
RuleOrPredicate2(lhs, rhs)
}
| 24.777778 | 74 | 0.635277 |
9ce25168e47f244b14162b4f66e47cf35e31e721 | 556 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "RxCombine",
platforms: [
.macOS(.v10_15), .iOS(.v12), .tvOS(.v13), .watchOS(.v6)
],
products: [
.library(
name: "RxCombine",
targets: ["RxCombine"]),
],
dependencies: [
.package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0")
],
targets: [
.target(
name: "RxCombine",
dependencies: ["RxSwift", "RxRelay"],
path: "Sources")
]
)
| 22.24 | 80 | 0.510791 |
eb6bd6a25a7704b098c3394348b5011a8eb086ad | 86 | public protocol FailureReporter: class {
func reportFailure(_ failure: Failure)
}
| 21.5 | 42 | 0.767442 |
2919856b84a194e315b433222e19c329be1b826e | 669 | // JobAction enumerates the values for job action.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
public enum JobActionEnum: String, Codable
{
// JobActionDisable specifies the job action disable state for job action.
case JobActionDisable = "disable"
// JobActionNone specifies the job action none state for job action.
case JobActionNone = "none"
// JobActionTerminate specifies the job action terminate state for job action.
case JobActionTerminate = "terminate"
}
| 41.8125 | 96 | 0.754858 |
fcf4eb73e2e2536be3996989a68d9eef5f10b7d3 | 730 | import ArgumentParser
import Foundation
import TSCBasic
/// Command that builds a target from the project in the current directory.
struct LintProjectCommand: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(
commandName: "project",
_superCommandName: "lint",
abstract: "Lints a workspace or a project that check whether they are well configured"
)
}
@Option(
name: .shortAndLong,
help: "The path to the directory that contains the workspace or project to be linted",
completion: .directory
)
var path: String?
func run() throws {
try LintProjectService().run(path: path)
}
}
| 28.076923 | 98 | 0.665753 |
22cd50f48b1f55a99a6eb797d9fe43788961bf07 | 2,017 | //
// CardImageController.swift
// DereGuide
//
// Created by zzk on 2017/1/22.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class CardImageController: BaseViewController {
var card: CGSSCard!
let imageView = BannerView()
private(set) lazy var item = UIBarButtonItem(image: #imageLiteral(resourceName: "702-share-toolbar"), style: .plain, target: self, action: #selector(shareAction(item:)))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.width.lessThanOrEqualToSuperview()
make.top.greaterThanOrEqualTo(topLayoutGuide.snp.bottom)
make.bottom.lessThanOrEqualTo(bottomLayoutGuide.snp.top)
make.height.equalTo(imageView.snp.width).multipliedBy(340.0 / 272.0)
make.center.equalToSuperview()
}
imageView.style = .custom
prepareToolbar()
if let url = URL(string: card.cardImageRef) {
imageView.sd_setImage(with: url, completed: { (image, error, cache, url) in
self.item.isEnabled = true
})
}
}
func prepareToolbar() {
item.isEnabled = false
toolbarItems = [item]
}
@objc func shareAction(item: UIBarButtonItem) {
guard let image = imageView.image else { return }
let urlArray = [image]
let activityVC = UIActivityViewController(activityItems: urlArray, applicationActivities: nil)
activityVC.popoverPresentationController?.barButtonItem = item
// activityVC.popoverPresentationController?.sourceRect = CGRect(x: item.width / 2, y: 0, width: 0, height: 0)
// 需要屏蔽的模块
let cludeActivitys:[UIActivity.ActivityType] = []
// 排除活动类型
activityVC.excludedActivityTypes = cludeActivitys
// 呈现分享界面
present(activityVC, animated: true, completion: nil)
}
}
| 32.532258 | 173 | 0.628161 |
0ea71cb716070abc49ec41928e57590e13819c38 | 390 | //
// Photo.swift
// TEDxConnect
//
// Created by Tadeh Alexani on 9/1/20.
// Copyright © 2020 Alexani. All rights reserved.
//
import Foundation
struct Photo: Decodable, Hashable {
var image: String
var thumbnail: String
static var example: Photo {
Photo(image: Images.example, thumbnail: Images.example)
}
}
struct PhotoResponse: Decodable {
var photo: [Photo]
}
| 16.25 | 59 | 0.687179 |
204516f4f16d2ede0d05859871a48a9e56b403b4 | 1,342 | //
// GlobalConst.swift
// MySwiftDemo
//
// Created by apple on 18/2/27.
// Copyright © 2018年 ImbaWales. All rights reserved.
//
import UIKit
// MARK: - 设备信息
/// 当前app版本号
let GetAppCurrentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
/// 获取设备系统号
let GetSystemVersion = UIDevice.current.systemVersion
/// iPhone设备
let isIPhone = (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone ? true : false)
/// iPad设备
let isIPad = (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ? true : false)
/// iPhone4设备
let isIPhone4 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.height) < 568.0 ? true : false)
/// iPhone5设备
let isIPhone5 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.height) == 568.0 ? true : false)
/// iPhone6设备
let isIPhone6 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.height) == 667.0 ? true : false)
/// iPhone6Plus设备
let isIPhone6P = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.height) == 736.0 ? true : false)
// MARK: - 尺寸
/// 屏幕高
let SCREEN_HEIGHT = UIScreen.main.bounds.height
/// 屏幕宽
let SCREEN_WIDTH = UIScreen.main.bounds.width
/// tabbar切换视图控制器高度
let kTabbarHeight = 49.0
/// 搜索视图高度
let kSearchBarHeight = 45.0
/// 状态栏高度
let kStatusBarHeight = 20.0
/// 导航栏高度
let kNavigationHeight = 44.0
| 27.958333 | 108 | 0.733234 |
eb531cb60ee88c1cb291d278bc1ebc24431c0610 | 322 | //
// Date+Milliseconds.swift
// Discord-Apple Music Rich Presence
//
// Created by Eric Rabil on 5/17/20.
// Copyright © 2020 Ayden Panhuyzen. All rights reserved.
//
import Foundation
extension Date {
var millisecondsSince1970: Int {
return Int((self.timeIntervalSince1970 * 1000.0).rounded())
}
}
| 20.125 | 67 | 0.686335 |
90bf358983f98c21fc0bcb2d951c7fcab790d5cf | 7,111 | //
// FiveStrokeViewController.swift
// iOSDemo
//
// Created by Stan Hu on 2019/4/8.
// Copyright © 2019 Stan Hu. All rights reserved.
//
import UIKit
import Gifu
class FiveStrokeViewController: UIViewController,UITextFieldDelegate {
let txtSearch = UITextField()
let btnSearch = UIButton()
let tb = UITableView()
var arrFiveStrokes:[FiveStroke]!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
arrFiveStrokes = FiveStroke.FiveStrokeLog.Value!
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear for five stroke")
FiveStroke.FiveStrokeLog.Value! = arrFiveStrokes
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
navigationItem.title = "五笔反查"
let btnClearLog = UIButton(type: .custom)
btnClearLog.setImage(UIImage(named: "btn_video_delete_confirm"), for: .normal)
btnClearLog.frame = CGRect(x: 0, y: 0, w: 34, h: 34)
btnClearLog.widthAnchor.constraint(equalToConstant: 35).isActive = true
btnClearLog.heightAnchor.constraint(equalToConstant: 35).isActive = true
btnClearLog.addTarget(self, action: #selector(clearLog), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btnClearLog)
txtSearch.returnKeyType = .search
txtSearch.delegate = self
txtSearch.layer.borderWidth = 1
txtSearch.layer.borderColor = UIColor.blue.cgColor
txtSearch.placeholder = "输入中文查询,多个文字不用分割"
txtSearch.addOffsetView(value: 10)
txtSearch.addTo(view: view).snp.makeConstraints { (m) in
m.left.equalTo(5)
m.top.equalTo(NavigationBarHeight + 5)
m.height.equalTo(36)
m.right.equalTo(-75)
}
btnSearch.backgroundColor = UIColor.lightGray
btnSearch.addTarget(self, action: #selector(searchKey), for: .touchUpInside)
btnSearch.color(color: UIColor.blue).title(title: "查询").addTo(view: view).snp.makeConstraints { (m) in
m.top.equalTo(txtSearch)
m.right.equalTo(-5)
m.height.equalTo(36)
m.left.equalTo(txtSearch.snp.right).offset(5)
}
tb.delegate = self
tb.dataSource = self
tb.tableFooterView = UIView()
tb.rowHeight = 50
tb.register(strokeCell.self, forCellReuseIdentifier: "Five")
tb.separatorStyle = .none
view.addSubview(tb)
tb.snp.makeConstraints { (m) in
m.left.right.bottom.equalTo(0)
m.top.equalTo(txtSearch.snp.bottom).offset(5)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchKey()
return true
}
@objc func clearLog(){
UIAlertController.init(title: "清空记录", message: "你要清空搜索记录吗", preferredStyle: .alert).action(title: "取消", handle: nil).action(title: "确定", handle: {(action:UIAlertAction) in
FiveStroke.FiveStrokeLog.clear()
self.arrFiveStrokes.removeAll()
self.tb.reloadData()
}).show()
}
@objc func searchKey(){
txtSearch.resignFirstResponder()
if txtSearch.text!.isEmpty{
Toast.showToast(msg: "请输入文字")
return
}
if !(txtSearch.text! =~ "[\\u4e00-\\u9fa5]"){
Toast.showToast(msg: "请输入中文")
return
}
Toast.showLoading()
FiveStroke.getFiveStroke(key: txtSearch.text!) { (res) in
if !handleResult(result: res){
return
}
self.arrFiveStrokes.insertItems(array: res.data! as! [FiveStroke], index: 0)
self.tb.reloadData()
}
FiveStroke.getFive(key: txtSearch.text!) { res in
}
}
}
extension FiveStrokeViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if arrFiveStrokes == nil{
return 0
}
return arrFiveStrokes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tb.dequeueReusableCell(withIdentifier: "Five", for: indexPath) as! strokeCell
cell.fiveStroke = arrFiveStrokes[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "删除"
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
arrFiveStrokes.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
FiveStroke.FiveStrokeLog.Value! = arrFiveStrokes
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
class strokeCell: UITableViewCell {
let lblText = UILabel()
let lblPinyin = UILabel()
let lblCode = UILabel()
let imgFive = UIImageView()
var fiveStroke:FiveStroke?{
didSet{
guard let f = fiveStroke else {
return
}
lblText.text = f.text
lblPinyin.text = f.spell
lblCode.text = f.code
// let url = URL(string: f.imgDecodeUrl.urlEncoded())!
// imgFive.animate(withGIFURL: url)
// imgFive.startAnimating()
imgFive.setImg(url: f.imgDecodeUrl.urlEncoded())
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
lblText.color(color: UIColor.gray).addTo(view: contentView).snp.makeConstraints { (m) in
m.left.equalTo(10)
m.width.equalTo(30)
m.centerY.equalTo(contentView)
}
lblPinyin.color(color: UIColor.gray).addTo(view: contentView).snp.makeConstraints { (m) in
m.left.equalTo(lblText.snp.right).offset(10)
m.width.equalTo(50)
m.centerY.equalTo(contentView)
}
lblCode.color(color: UIColor.gray).addTo(view: contentView).snp.makeConstraints { (m) in
m.left.equalTo(lblPinyin.snp.right).offset(10)
m.width.equalTo(50)
m.centerY.equalTo(contentView)
}
imgFive.clipsToBounds = true
imgFive.contentMode = .scaleAspectFit
imgFive.addTo(view: contentView).snp.makeConstraints { (m) in
m.right.equalTo(-5)
m.centerY.equalTo(contentView)
m.height.equalTo(34)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.861905 | 179 | 0.611306 |
3ad3480198c26a3670cc42f556b55fc324d11829 | 186 | //
// Types.swift
// CarsApp
//
// Created by Joachim Kret on 31/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
typealias Pair<A, B> = (A, B)
| 15.5 | 55 | 0.650538 |
386e634971583ade7fb44f19e82d93b10378f709 | 862 | //
// String+Extensions.swift
// Clendar
//
// Created by Vinh Nguyen on 24/3/19.
// Copyright © 2019 Vinh Nguyen. All rights reserved.
//
import Foundation
import UIKit
extension String {
func trim(text: String) -> String {
replacingOccurrences(of: text, with: "", options: .literal)
}
}
// https://github.com/vincent-pradeilles/swift-tips#shorter-syntax-to-deal-with-optional-strings
extension Optional where Wrapped == String {
var orEmpty: String {
switch self {
case let .some(value):
return value
case .none:
return ""
}
}
}
extension String {
func parseInt() -> Int? {
// ref: https://stackoverflow.com/questions/30342744/swift-how-to-get-integer-from-string-and-convert-it-into-integer
Int(components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
var asImage: UIImage? { UIImage(named: self) }
}
| 22.684211 | 125 | 0.700696 |
d6db5b148a76bb0b3714d758260fe9b00fff3edf | 4,479 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: content/Data.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
///*
/// Provides definitions, structures, and enumerations related to raw data and data formats.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// Enumerates known data encapsulation or encoding formats, which are commonly found or used to integrate systems. These
/// formats (or, a subset of them) are supported for adaption to and from OpenCannabis.
public enum Opencannabis_Content_DataFormat: SwiftProtobuf.Enum {
public typealias RawValue = Int
/// Sentinel value for an unknown, or unrecognized, data format.
case unknownFormat // = 0
/// Comma-Separated-Values. When referred to with no other demarcation, this enumeration corresponds with
/// [RFC4180 (Common Format and MIME Type for Comma-Separated Values)](https://tools.ietf.org/html/rfc4180).
case csv // = 10
/// Tab-Separated-Values (i.e. CSV, but with tabs). Follows the same quoting and newline guidelines as RFC-4180.
case tsv // = 11
/// Excel-style CSV (Comma-Separated-Values) format.
case excelCsv // = 12
/// Old-style Excel spreadsheet format.
case excelXls // = 13
/// Modern Excel spreadsheet format.
case excelXlsx // = 14
/// MessagePack: length-prefixed JSON-like binary encoding format, schemaless.
case msgpack // = 20
/// Avro: length-prefixed JSON-like binary encoding format, schema'd.
case avro // = 30
/// Structured Query Language-based systems or dialects.
case sql // = 40
/// ProtoJSON/JSON object format, serialized to comply with the OpenCannabis standard.
case json // = 50
/// Proto-text format, serialized to comply with the OpenCannabis standard.
case ocpText // = 61
/// Proto-binary format, serialized to comply with the OpenCannabis standard.
case ocpBinary // = 62
case UNRECOGNIZED(Int)
public init() {
self = .unknownFormat
}
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .unknownFormat
case 10: self = .csv
case 11: self = .tsv
case 12: self = .excelCsv
case 13: self = .excelXls
case 14: self = .excelXlsx
case 20: self = .msgpack
case 30: self = .avro
case 40: self = .sql
case 50: self = .json
case 61: self = .ocpText
case 62: self = .ocpBinary
default: self = .UNRECOGNIZED(rawValue)
}
}
public var rawValue: Int {
switch self {
case .unknownFormat: return 0
case .csv: return 10
case .tsv: return 11
case .excelCsv: return 12
case .excelXls: return 13
case .excelXlsx: return 14
case .msgpack: return 20
case .avro: return 30
case .sql: return 40
case .json: return 50
case .ocpText: return 61
case .ocpBinary: return 62
case .UNRECOGNIZED(let i): return i
}
}
}
#if swift(>=4.2)
extension Opencannabis_Content_DataFormat: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
public static var allCases: [Opencannabis_Content_DataFormat] = [
.unknownFormat,
.csv,
.tsv,
.excelCsv,
.excelXls,
.excelXlsx,
.msgpack,
.avro,
.sql,
.json,
.ocpText,
.ocpBinary,
]
}
#endif // swift(>=4.2)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
extension Opencannabis_Content_DataFormat: SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "UNKNOWN_FORMAT"),
10: .same(proto: "CSV"),
11: .same(proto: "TSV"),
12: .same(proto: "EXCEL_CSV"),
13: .same(proto: "EXCEL_XLS"),
14: .same(proto: "EXCEL_XLSX"),
20: .same(proto: "MSGPACK"),
30: .same(proto: "AVRO"),
40: .same(proto: "SQL"),
50: .same(proto: "JSON"),
61: .same(proto: "OCP_TEXT"),
62: .same(proto: "OCP_BINARY"),
]
}
| 29.86 | 121 | 0.688547 |
1c47adafa6da46f2d9a3337d643071752aaa9fe5 | 249 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S {
func a {
{
var d = [ {
protocol a {
{
}
extension NSSet {
class
case ,
| 16.6 | 87 | 0.710843 |
186bd276fbf9d05e41ca3c7a46b64c4f9b6649a0 | 449 | // 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
// RUN: not %target-swift-frontend %s -typecheck
class B{class b<I{class a<T where g:P{struct d<I:b
| 44.9 | 79 | 0.750557 |
1c5631d3fec33a4b325607e76e8b94686281d208 | 435 | //
// CubicInOutEasing.swift
// Pods
//
// Created by macmini1 on 19.01.16.
//
//
import Foundation
import UIKit
public class CubicInOutEasing:NSObject, EasingFunction {
public func compute(t: CGFloat) -> CGFloat {
if t <= 0.5{
return 4*t*t*t
} else {
return 4*pow((t-1),3)+1
}
}
public func title() -> String {
return "CubicInOut"
}
} | 16.730769 | 56 | 0.524138 |
e0fbc957dc1552eb12763f1bba0d109c687c6735 | 1,677 | //
// ViewController.swift
// Bouncer
//
// Created by Zheng Hao Tan on 7/12/15.
// Copyright (c) 2015 Zheng Hao Tan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let bouncer = BouncerBehavior()
lazy var animator: UIDynamicAnimator = {
UIDynamicAnimator(referenceView: self.view)
}()
override func viewDidLoad() {
super.viewDidLoad()
animator.addBehavior(bouncer)
}
struct Constants {
static let BlockSize = CGSize(width: 40, height: 40)
}
var redBlock: UIView?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if redBlock == nil {
redBlock = addBlock()
redBlock?.backgroundColor = UIColor.redColor()
bouncer.addBlock(redBlock!)
}
let motionManager = AppDelegate.Motion.Manager
if motionManager.accelerometerAvailable {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
(data, _) -> Void in
self.bouncer.gravity.gravityDirection = CGVector(dx: data.acceleration.x, dy: -data.acceleration.y)
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
AppDelegate.Motion.Manager.stopAccelerometerUpdates()
}
func addBlock() -> UIView {
let block = UIView(frame: CGRect(origin: CGPoint.zeroPoint, size: Constants.BlockSize))
block.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
view.addSubview(block)
return block
}
}
| 27.048387 | 119 | 0.624329 |
7a20fa4234babefb2126178960dc0ca15b4aa315 | 33,552 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// FIXME: complexity documentation for most of methods on String is ought to be
// qualified with "amortized" at least, as Characters are variable-length.
/// An arbitrary Unicode string value.
///
/// Unicode-Correct
/// ===============
///
/// Swift strings are designed to be Unicode-correct. In particular,
/// the APIs make it easy to write code that works correctly, and does
/// not surprise end-users, regardless of where you venture in the
/// Unicode character space. For example, the `==` operator checks
/// for [Unicode canonical
/// equivalence](http://www.unicode.org/glossary/#deterministic_comparison),
/// so two different representations of the same string will always
/// compare equal.
///
/// Locale-Insensitive
/// ==================
///
/// The fundamental operations on Swift strings are not sensitive to
/// locale settings. That's because, for example, the validity of a
/// `Dictionary<String, T>` in a running program depends on a given
/// string comparison having a single, stable result. Therefore,
/// Swift always uses the default,
/// un-[tailored](http://www.unicode.org/glossary/#tailorable) Unicode
/// algorithms for basic string operations.
///
/// Importing `Foundation` endows swift strings with the full power of
/// the `NSString` API, which allows you to choose more complex
/// locale-sensitive operations explicitly.
///
/// Value Semantics
/// ===============
///
/// Each string variable, `let` binding, or stored property has an
/// independent value, so mutations to the string are not observable
/// through its copies:
///
/// var a = "foo"
/// var b = a
/// b.append("bar")
/// print("a=\(a), b=\(b)") // a=foo, b=foobar
///
/// Strings use Copy-on-Write so that their data is only copied
/// lazily, upon mutation, when more than one string instance is using
/// the same buffer. Therefore, the first in any sequence of mutating
/// operations may cost `O(N)` time and space, where `N` is the length
/// of the string's (unspecified) underlying representation.
///
/// Views
/// =====
///
/// `String` is not itself a collection of anything. Instead, it has
/// properties that present the string's contents as meaningful
/// collections:
///
/// - `characters`: a collection of `Character` ([extended grapheme
/// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster))
/// elements, a unit of text that is meaningful to most humans.
///
/// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode
/// scalar
/// values](http://www.unicode.org/glossary/#unicode_scalar_value))
/// the 21-bit codes that are the basic unit of Unicode. These
/// values are equivalent to UTF-32 code units.
///
/// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit
/// elements of the string's UTF-16 encoding.
///
/// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit
/// elements of the string's UTF-8 encoding.
///
/// Growth and Capacity
/// ===================
///
/// When a string's contiguous storage fills up, new storage must be
/// allocated and characters must be moved to the new storage.
/// `String` uses an exponential growth strategy that makes `append` a
/// constant time operation *when amortized over many invocations*.
///
/// Objective-C Bridge
/// ==================
///
/// `String` is bridged to Objective-C as `NSString`, and a `String`
/// that originated in Objective-C may store its characters in an
/// `NSString`. Since any arbitrary subclass of `NSString` can
/// become a `String`, there are no guarantees about representation or
/// efficiency in this case. Since `NSString` is immutable, it is
/// just as though the storage was shared by some copy: the first in
/// any sequence of mutating operations causes elements to be copied
/// into unique, contiguous storage which may cost `O(N)` time and
/// space, where `N` is the length of the string representation (or
/// more, if the underlying `NSString` has unusual performance
/// characteristics).
public struct String {
/// An empty `String`.
public init() {
_core = _StringCore()
}
public // @testable
init(_ _core: _StringCore) {
self._core = _core
}
public // @testable
var _core: _StringCore
}
extension String {
@warn_unused_result
public // @testable
static func _fromWellFormedCodeUnitSequence<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> String {
return String._fromCodeUnitSequence(encoding, input: input)!
}
@warn_unused_result
public // @testable
static func _fromCodeUnitSequence<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> String? {
let (stringBufferOptional, _) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: false)
if let stringBuffer = stringBufferOptional {
return String(_storage: stringBuffer)
} else {
return nil
}
}
@warn_unused_result
public // @testable
static func _fromCodeUnitSequenceWithRepair<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> (String, hadError: Bool) {
let (stringBuffer, hadError) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: true)
return (String(_storage: stringBuffer!), hadError)
}
}
extension String : _BuiltinUnicodeScalarLiteralConvertible {
@effects(readonly)
public // @testable
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = String._fromWellFormedCodeUnitSequence(
UTF32.self, input: CollectionOfOne(UInt32(value)))
}
}
extension String : UnicodeScalarLiteralConvertible {
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self = value
}
}
extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
extension String : ExtendedGraphemeClusterLiteralConvertible {
/// Create an instance initialized to `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self = value
}
}
extension String : _BuiltinUTF16StringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF16")
public init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
self = String(
_StringCore(
baseAddress: OpaquePointer(start),
count: Int(utf16CodeUnitCount),
elementShift: 1,
hasCocoaBuffer: false,
owner: nil))
}
}
extension String : _BuiltinStringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
if Bool(isASCII) {
self = String(
_StringCore(
baseAddress: OpaquePointer(start),
count: Int(utf8CodeUnitCount),
elementShift: 0,
hasCocoaBuffer: false,
owner: nil))
}
else {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
}
extension String : StringLiteralConvertible {
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = value
}
}
extension String : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
var result = "\""
for us in self.unicodeScalars {
result += us.escaped(asASCII: false)
}
result += "\""
return result
}
}
extension String {
/// Returns the number of code units occupied by this string
/// in the given encoding.
@warn_unused_result
func _encodedLength<
Encoding: UnicodeCodec
>(encoding: Encoding.Type) -> Int {
var codeUnitCount = 0
let output: (Encoding.CodeUnit) -> Void = { _ in codeUnitCount += 1 }
self._encode(encoding, output: output)
return codeUnitCount
}
// FIXME: this function does not handle the case when a wrapped NSString
// contains unpaired surrogates. Fix this before exposing this function as a
// public API. But it is unclear if it is valid to have such an NSString in
// the first place. If it is not, we should not be crashing in an obscure
// way -- add a test for that.
// Related: <rdar://problem/17340917> Please document how NSString interacts
// with unpaired surrogates
func _encode<
Encoding: UnicodeCodec
>(encoding: Encoding.Type, @noescape output: (Encoding.CodeUnit) -> Void)
{
return _core.encode(encoding, output: output)
}
}
#if _runtime(_ObjC)
/// Compare two strings using the Unicode collation algorithm in the
/// deterministic comparison mode. (The strings which are equivalent according
/// to their NFD form are considered equal. Strings which are equivalent
/// according to the plain Unicode collation algorithm are additionally ordered
/// based on their NFD.)
///
/// See Unicode Technical Standard #10.
///
/// The behavior is equivalent to `NSString.compare()` with default options.
///
/// - returns:
/// * an unspecified value less than zero if `lhs < rhs`,
/// * zero if `lhs == rhs`,
/// * an unspecified value greater than zero if `lhs > rhs`.
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation")
public func _stdlib_compareNSStringDeterministicUnicodeCollation(
lhs: AnyObject, _ rhs: AnyObject
) -> Int32
#endif
extension String : Equatable {
}
@warn_unused_result
public func ==(lhs: String, rhs: String) -> Bool {
if lhs._core.isASCII && rhs._core.isASCII {
if lhs._core.count != rhs._core.count {
return false
}
return _swift_stdlib_memcmp(
lhs._core.startASCII, rhs._core.startASCII,
rhs._core.count) == 0
}
return lhs._compareString(rhs) == 0
}
extension String : Comparable {
}
extension String {
#if _runtime(_ObjC)
/// This is consistent with Foundation, but incorrect as defined by Unicode.
/// Unicode weights some ASCII punctuation in a different order than ASCII
/// value. Such as:
///
/// 0022 ; [*02FF.0020.0002] # QUOTATION MARK
/// 0023 ; [*038B.0020.0002] # NUMBER SIGN
/// 0025 ; [*038C.0020.0002] # PERCENT SIGN
/// 0026 ; [*0389.0020.0002] # AMPERSAND
/// 0027 ; [*02F8.0020.0002] # APOSTROPHE
///
/// - Precondition: Both `self` and `rhs` are ASCII strings.
@warn_unused_result
public // @testable
func _compareASCII(rhs: String) -> Int {
var compare = Int(_swift_stdlib_memcmp(
self._core.startASCII, rhs._core.startASCII,
min(self._core.count, rhs._core.count)))
if compare == 0 {
compare = self._core.count - rhs._core.count
}
// This efficiently normalizes the result to -1, 0, or 1 to match the
// behavior of NSString's compare function.
return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0)
}
#endif
/// Compares two strings with the Unicode Collation Algorithm.
@warn_unused_result
@inline(never)
@_semantics("stdlib_binary_only") // Hide the CF/ICU dependency
public // @testable
func _compareDeterministicUnicodeCollation(rhs: String) -> Int {
// Note: this operation should be consistent with equality comparison of
// Character.
#if _runtime(_ObjC)
return Int(_stdlib_compareNSStringDeterministicUnicodeCollation(
_bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl()))
#else
switch (_core.isASCII, rhs._core.isASCII) {
case (true, false):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf8_utf16(
lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count)))
case (false, true):
// Just invert it and recurse for this case.
return -rhs._compareDeterministicUnicodeCollation(self)
case (false, false):
let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf16_utf16(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
case (true, true):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII)
return Int(_swift_stdlib_unicode_compare_utf8_utf8(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
}
#endif
}
@warn_unused_result
public // @testable
func _compareString(rhs: String) -> Int {
#if _runtime(_ObjC)
// We only want to perform this optimization on objc runtimes. Elsewhere,
// we will make it follow the unicode collation algorithm even for ASCII.
if (_core.isASCII && rhs._core.isASCII) {
return _compareASCII(rhs)
}
#endif
return _compareDeterministicUnicodeCollation(rhs)
}
}
@warn_unused_result
public func <(lhs: String, rhs: String) -> Bool {
return lhs._compareString(rhs) < 0
}
// Support for copy-on-write
extension String {
/// Append the elements of `other` to `self`.
public mutating func append(other: String) {
_core.append(other._core)
}
/// Append `x` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(x: UnicodeScalar) {
_core.append(x)
}
public // SPI(Foundation)
init(_storage: _StringBuffer) {
_core = _StringCore(_storage)
}
}
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringNFDHashValue")
func _stdlib_NSStringNFDHashValue(str: AnyObject) -> Int
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringASCIIHashValue")
func _stdlib_NSStringASCIIHashValue(str: AnyObject) -> Int
#endif
extension String : Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// FIXME(performance): constructing a temporary NSString is extremely
// wasteful and inefficient.
let cocoaString = unsafeBitCast(
self._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
// If we have an ASCII string, we do not need to normalize.
if self._core.isASCII {
return hashOffset ^ _stdlib_NSStringASCIIHashValue(cocoaString)
} else {
return hashOffset ^ _stdlib_NSStringNFDHashValue(cocoaString)
}
#else
if self._core.isASCII {
return _swift_stdlib_unicode_hash_ascii(
UnsafeMutablePointer<Int8>(_core.startASCII),
Int32(_core.count))
} else {
return _swift_stdlib_unicode_hash(
UnsafeMutablePointer<UInt16>(_core.startUTF16),
Int32(_core.count))
}
#endif
}
}
@warn_unused_result
@effects(readonly)
@_semantics("string.concat")
public func + (lhs: String, rhs: String) -> String {
var lhs = lhs
if (lhs.isEmpty) {
return rhs
}
lhs._core.append(rhs._core)
return lhs
}
// String append
public func += (lhs: inout String, rhs: String) {
if lhs.isEmpty {
lhs = rhs
}
else {
lhs._core.append(rhs._core)
}
}
extension String {
/// Constructs a `String` in `resultStorage` containing the given UTF-8.
///
/// Low-level construction interface used by introspection
/// implementation in the runtime library.
@_silgen_name("swift_stringFromUTF8InRawMemory")
public // COMPILER_INTRINSIC
static func _fromUTF8InRawMemory(
resultStorage: UnsafeMutablePointer<String>,
start: UnsafeMutablePointer<UTF8.CodeUnit>,
utf8CodeUnitCount: Int
) {
resultStorage.initialize(with:
String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount)))
}
}
extension String {
public typealias Index = CharacterView.Index
/// The position of the first `Character` in `self.characters` if
/// `self` is non-empty; identical to `endIndex` otherwise.
public var startIndex: Index { return characters.startIndex }
/// The "past the end" position in `self.characters`.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Index { return characters.endIndex }
/// Access the `Character` at `position`.
///
/// - Precondition: `position` is a valid position in `self.characters`
/// and `position != endIndex`.
public subscript(i: Index) -> Character { return characters[i] }
}
@warn_unused_result
public func == (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._base == rhs._base
}
@warn_unused_result
public func < (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._base < rhs._base
}
extension String {
/// Return the characters within the given `bounds`.
///
/// - Complexity: O(1) unless bridging from Objective-C requires an
/// O(N) conversion.
public subscript(bounds: Range<Index>) -> String {
return String(characters[bounds])
}
}
extension String {
public mutating func reserveCapacity(n: Int) {
withMutableCharacters {
(v: inout CharacterView) in v.reserveCapacity(n)
}
}
public mutating func append(c: Character) {
withMutableCharacters {
(v: inout CharacterView) in v.append(c)
}
}
public mutating func append<
S : Sequence where S.Iterator.Element == Character
>(contentsOf newElements: S) {
withMutableCharacters {
(v: inout CharacterView) in v.append(contentsOf: newElements)
}
}
/// Create an instance containing `characters`.
public init<
S : Sequence where S.Iterator.Element == Character
>(_ characters: S) {
self._core = CharacterView(characters)._core
}
}
extension Sequence where Iterator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joined(separator: "-|-") // "foo-|-bar-|-baz"
@warn_unused_result
public func joined(separator separator: String) -> String {
var result = ""
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
let separatorSize = separator.utf16.count
let reservation = self._preprocessingPass {
() -> Int in
var r = 0
for chunk in self {
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
r += separatorSize + chunk.utf16.count
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(n)
}
if separatorSize == 0 {
for x in self {
result.append(x)
}
return result
}
var iter = makeIterator()
if let first = iter.next() {
result.append(first)
while let next = iter.next() {
result.append(separator)
result.append(next)
}
}
return result
}
}
extension String {
/// Replace the characters within `bounds` with the elements of
/// `replacement`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`bounds.count`) if `bounds.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceSubrange<
C: Collection where C.Iterator.Element == Character
>(
bounds: Range<Index>, with newElements: C
) {
withMutableCharacters {
(v: inout CharacterView) in v.replaceSubrange(bounds, with: newElements)
}
}
/// Replace the text in `bounds` with `replacement`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`bounds.count`) if `bounds.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceSubrange(
bounds: Range<Index>, with newElements: String
) {
replaceSubrange(bounds, with: newElements.characters)
}
/// Insert `newElement` at position `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func insert(newElement: Character, at i: Index) {
withMutableCharacters {
(v: inout CharacterView) in v.insert(newElement, at: i)
}
}
/// Insert `newElements` at position `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count + newElements.count`).
public mutating func insert<
S : Collection where S.Iterator.Element == Character
>(contentsOf newElements: S, at i: Index) {
withMutableCharacters {
(v: inout CharacterView) in v.insert(contentsOf: newElements, at: i)
}
}
/// Remove and return the `Character` at position `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func remove(at i: Index) -> Character {
return withMutableCharacters {
(v: inout CharacterView) in v.remove(at: i)
}
}
/// Remove the characters in `bounds`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func removeSubrange(bounds: Range<Index>) {
withMutableCharacters {
(v: inout CharacterView) in v.removeSubrange(bounds)
}
}
/// Replace `self` with the empty string.
///
/// Invalidates all indices with respect to `self`.
///
/// - parameter keepCapacity: If `true`, prevents the release of
/// allocated storage, which can be a useful optimization
/// when `self` is going to be grown again.
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
withMutableCharacters {
(v: inout CharacterView) in v.removeAll(keepingCapacity: keepCapacity)
}
}
}
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringLowercaseString")
func _stdlib_NSStringLowercaseString(str: AnyObject) -> _CocoaString
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringUppercaseString")
func _stdlib_NSStringUppercaseString(str: AnyObject) -> _CocoaString
#else
@warn_unused_result
internal func _nativeUnicodeLowercaseString(str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToLower(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToLower(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
@warn_unused_result
internal func _nativeUnicodeUppercaseString(str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToUpper(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToUpper(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
#endif
// Unicode algorithms
extension String {
// FIXME: implement case folding without relying on Foundation.
// <rdar://problem/17550602> [unicode] Implement case folding
/// A "table" for which ASCII characters need to be upper cased.
/// To determine which bit corresponds to which ASCII character, subtract 1
/// from the ASCII value of that character and divide by 2. The bit is set iff
/// that character is a lower case character.
internal var _asciiLowerCaseTable: UInt64 {
@inline(__always)
get {
return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// The same table for upper case characters.
internal var _asciiUpperCaseTable: UInt64 {
@inline(__always)
get {
return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// Return `self` converted to lower case.
///
/// - Complexity: O(n)
public func lowercased() -> String {
if self._core.isASCII {
let count = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<count {
// For each character in the string, we lookup if it should be shifted
// in our ascii table, then we return 0x20 if it should, 0x0 if not.
// This code is equivalent to:
// switch source[i] {
// case let x where (x >= 0x41 && x <= 0x5a):
// dest[i] = x &+ 0x20
// case let x:
// dest[i] = x
// }
let value = source[i]
let isUpper =
_asciiUpperCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isUpper & 0x1) << 5
// Since we are left with either 0x0 or 0x20, we can safely truncate to
// a UInt8 and add to our ASCII value (this will not overflow numbers in
// the ASCII range).
dest[i] = value &+ UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeLowercaseString(self)
#endif
}
/// Return `self` converted to upper case.
///
/// - Complexity: O(n)
public func uppercased() -> String {
if self._core.isASCII {
let count = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<count {
// See the comment above in lowercaseString.
let value = source[i]
let isLower =
_asciiLowerCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isLower & 0x1) << 5
dest[i] = value &- UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeUppercaseString(self)
#endif
}
}
// Index conversions
extension String.Index {
/// Construct the position in `characters` that corresponds exactly to
/// `unicodeScalarIndex`. If no such position exists, the result is `nil`.
///
/// - Precondition: `unicodeScalarIndex` is an element of
/// `characters.unicodeScalars.indices`.
public init?(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within characters: String
) {
if !unicodeScalarIndex._isOnGraphemeClusterBoundary {
return nil
}
self.init(_base: unicodeScalarIndex)
}
/// Construct the position in `characters` that corresponds exactly to
/// `utf16Index`. If no such position exists, the result is `nil`.
///
/// - Precondition: `utf16Index` is an element of
/// `characters.utf16.indices`.
public init?(
_ utf16Index: String.UTF16Index,
within characters: String
) {
if let me = utf16Index.samePosition(
in: characters.unicodeScalars
)?.samePosition(in: characters) {
self = me
}
else {
return nil
}
}
/// Construct the position in `characters` that corresponds exactly to
/// `utf8Index`. If no such position exists, the result is `nil`.
///
/// - Precondition: `utf8Index` is an element of
/// `characters.utf8.indices`.
public init?(
_ utf8Index: String.UTF8Index,
within characters: String
) {
if let me = utf8Index.samePosition(
in: characters.unicodeScalars
)?.samePosition(in: characters) {
self = me
}
else {
return nil
}
}
/// Returns the position in `utf8` that corresponds exactly
/// to `self`.
///
/// - Precondition: `self` is an element of `String(utf8).indices`.
@warn_unused_result
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in `utf16` that corresponds exactly
/// to `self`.
///
/// - Precondition: `self` is an element of `String(utf16).indices`.
@warn_unused_result
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index {
return String.UTF16View.Index(self, within: utf16)
}
/// Returns the position in `unicodeScalars` that corresponds exactly
/// to `self`.
///
/// - Precondition: `self` is an element of `String(unicodeScalars).indices`.
@warn_unused_result
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarView.Index {
return String.UnicodeScalarView.Index(self, within: unicodeScalars)
}
}
extension String {
@available(*, unavailable, renamed: "append")
public mutating func appendContentsOf(other: String) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "append(contentsOf:)")
public mutating func appendContentsOf<
S : Sequence where S.Iterator.Element == Character
>(newElements: S) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "insert(contentsOf:at:)")
public mutating func insertContentsOf<
S : Collection where S.Iterator.Element == Character
>(newElements: S, at i: Index) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange<
C : Collection where C.Iterator.Element == Character
>(
subRange: Range<Index>, with newElements: C
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange(
subRange: Range<Index>, with newElements: String
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "removeAt")
public mutating func removeAtIndex(i: Index) -> Character {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "removeSubrange")
public mutating func removeRange(subRange: Range<Index>) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lowercased()")
public var lowercaseString: String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased()")
public var uppercaseString: String {
fatalError("unavailable function can't be called")
}
}
extension Sequence where Iterator.Element == String {
@available(*, unavailable, renamed: "joined")
public func joinWithSeparator(separator: String) -> String {
fatalError("unavailable function can't be called")
}
}
| 31.893536 | 94 | 0.682135 |
1d2129f4095f23b4f1a06500aa841b2c0d48c1f2 | 2,249 | //
// Extensions.swift
// SimpleProjects
//
// Created by Kenneth Cluff on 3/14/19.
// Copyright © 2019 Kenneth Cluff. All rights reserved.
//
import UIKit
import os
extension UIAlertController {
func display() {
guard let vc = getViewController() else {
let errorString = String(format: "No way to present error: %@", message ?? "Presenting alert failed for now window. There is a deeper error." )
os_log(OSLogType.debug, "%{public}@", errorString)
return
}
vc.present(self, animated: true, completion: nil)
}
private func getViewController() -> UIViewController? {
return UIApplication.shared.topMostViewController()
}
}
extension UIApplication {
func topMostViewController() -> UIViewController? {
return self.keyWindow?.rootViewController?.topMostViewController()
}
}
extension UIViewController {
func topMostViewController() -> UIViewController {
guard presentedViewController != nil else { return self }
switch presentedViewController {
case let navigation as UINavigationController:
return navigation.visibleViewController!.topMostViewController()
case let tab as UITabBarController:
guard let selectedTab = tab.selectedViewController else {
return tab.topMostViewController()
}
return selectedTab.topMostViewController()
default:
return presentedViewController!.topMostViewController()
}
}
func askAreYouSure(_ actionToPeform: String?, _ handleIfYes: @escaping ActionHandler, _ handleIfNo: ActionHandler?) {
let alert = UIAlertController(title: "Are You Sure", message: actionToPeform, preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .destructive) { (action) in
handleIfYes(action)
}
let noAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
if let handleIfNo = handleIfNo {
handleIfNo(action)
}
}
alert.addAction(yesAction)
alert.addAction(noAction)
present(alert, animated: true, completion: nil)
}
}
| 33.567164 | 155 | 0.644731 |
0357a38c38f78b628fce18dee05b5ea09c2318da | 2,562 | //
// StorageConfiguration.swift
// StorageKit
//
// Copyright © 2020 E-SOFT. All rights reserved.
//
import Realm
import RealmSwift
public final class StorageConfiguration {
private var storageType: StorageType
public lazy var configuration: Realm.Configuration = {
var configuration = Realm.Configuration()
let bundlePath = Bundle.main.url(forResource: "com.esoft", withExtension: "storage")
configuration.fileURL = configuration
.fileURL?
.deletingLastPathComponent()
.appendingPathComponent("client")
.appendingPathExtension("realm")
// Setup Realm Bundle from prepopulated file if exist
// which located in $PROJECT_DIR/Resourses/Realm/
// @see https://realm.io/docs/swift/latest/#configuring-a-realm
if bundlePath != nil && !realmFileExists(url: configuration.fileURL) {
copyStaticRealm(bundlePath: bundlePath!, realmFilePath: configuration.fileURL)
}
if storageType == .inmemory {
configuration.inMemoryIdentifier = "EsoftClientInMemoryStorage"
}
configuration.schemaVersion = 1
// TotalBytes refers to the size of the file on disk in bytes (data + free space)
// UsedBytes refers to the number of bytes used by data in the file
// Compact if the file is over 50MB in size and less than 50% 'used'
// @see https://realm.io/docs/objc/latest/#limitations-file-size
configuration.shouldCompactOnLaunch = { totalBytes, usedBytes in
let fiftyMB = 50 * 1024 * 1024
return (totalBytes > fiftyMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
}
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
// @see https://realm.io/docs/objc/latest/#limitations-file-size
configuration.migrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
// Nothing to do, yet
}
}
return configuration
}()
public init(type: StorageType = .persistent) {
storageType = type
}
private func copyStaticRealm(bundlePath: URL?, realmFilePath: URL?) {
guard bundlePath != nil && realmFilePath != nil else { return }
do {
try FileManager.default.copyItem(atPath: bundlePath!.path, toPath: realmFilePath!.path)
} catch let error as NSError {
print(error)
}
}
private func realmFileExists(url: URL?) -> Bool {
guard let realmURL = url else { return false }
return FileManager.default.fileExists(atPath: realmURL.path)
}
}
| 32.846154 | 93 | 0.684231 |
f91bc391d70282ffc60f12cff8379f0de71beed4 | 1,614 | //
// WindowsClass+ControlFunctionable.swift
// The App
//
// Created by Mikk Rätsep on 27/09/2017.
// Copyright © 2017 High-Mobility GmbH. All rights reserved.
//
import Foundation
extension WindowsCommand: ControlFunctionable {
var boolValue: (ControlFunction.Kind) -> Bool? {
return {
guard $0 == .windows else {
return nil
}
return self.open
}
}
var controlFunctions: [ControlFunction] {
let mainActions = ControlAction(name: "open", iconName: "WindowDOWN") { errorHandler in
Car.shared.sendWindowsCommand(open: true) {
if let error = $0 { errorHandler?(error) }
}
}
let oppositeAction = ControlAction(name: "close", iconName: "WindowUP") { errorHandler in
Car.shared.sendWindowsCommand(open: false) {
if let error = $0 { errorHandler?(error) }
}
}
return [DualControlFunction(kind: .windows, mainAction: mainActions, oppositeAction: oppositeAction, isMainTrue: true)]
}
var stringValue: (ControlFunction.Kind) -> String? {
return { _ in nil }
}
}
extension WindowsStatusCommand: ControlFunctionable {
var boolValue: (ControlFunction.Kind) -> Bool? {
return { _ in nil }
}
var controlFunctions: [ControlFunction] {
return [FullScreenControlFunction(kind: .windowsStatus, iconName: "WindowUP", viewControllerID: "WindowsStatusViewControllerID")]
}
var stringValue: (ControlFunction.Kind) -> String? {
return { _ in nil }
}
}
| 26.9 | 137 | 0.614622 |
ef09631ba8ef7e03c249492c1abae3aca0d76604 | 2,535 | //
// SolarizedDark.swift
// Pyto
//
// Created by Emma Labbé on 1/17/19.
// Copyright © 2018-2021 Emma Labbé. All rights reserved.
//
import SavannaKit
import SourceEditor
// MARK: - Source code theme
/// The Solarized Dark source code theme.
struct SolarizedDarkSourceCodeTheme: SourceCodeTheme {
let defaultTheme = DefaultSourceCodeTheme()
var lineNumbersStyle: LineNumbersStyle? {
return LineNumbersStyle(font: defaultTheme.font.withSize(font.pointSize), textColor: defaultTheme.lineNumbersStyle?.textColor ?? color(for: .plain))
}
var gutterStyle: GutterStyle {
return GutterStyle(backgroundColor: backgroundColor, minimumWidth: defaultTheme.gutterStyle.minimumWidth)
}
var font: Font {
return EditorViewController.font.withSize(CGFloat(ThemeFontSize))
}
let backgroundColor = Color(displayP3Red: 0/255, green: 43/255, blue: 54/255, alpha: 1)
func color(for syntaxColorType: SourceCodeTokenType) -> Color {
switch syntaxColorType {
case .comment:
return Color(red: 88/255, green: 110/255, blue: 117/255, alpha: 1)
case .editorPlaceholder:
return defaultTheme.color(for: syntaxColorType)
case .identifier:
return Color(red: 38/255, green: 139/255, blue: 210/255, alpha: 1)
case .builtin:
return Color(red: 37/255, green: 146/255, blue: 134/255, alpha: 1)
case .keyword:
return Color(red: 211/255, green: 54/255, blue: 130/255, alpha: 1)
case .number:
return Color(red: 220/255, green: 50/255, blue: 47/255, alpha: 1)
case .plain:
return Color(red: 147/255, green: 161/255, blue: 161/255, alpha: 1)
case .string:
return Color(red: 203/255, green: 75/255, blue: 22/255, alpha: 1)
}
}
func globalAttributes() -> [NSAttributedString.Key : Any] {
var attributes = [NSAttributedString.Key: Any]()
attributes[.font] = font
attributes[.foregroundColor] = color(for: .plain)
return attributes
}
}
// MARK: - Theme
/// The Cool Glow theme.
struct SolarizedDarkTheme: Theme {
let keyboardAppearance: UIKeyboardAppearance = .dark
let barStyle: UIBarStyle = .black
var userInterfaceStyle: UIUserInterfaceStyle {
return .dark
}
let sourceCodeTheme: SourceCodeTheme = SolarizedDarkSourceCodeTheme()
let name: String? = "Solarized Dark"
}
| 30.914634 | 156 | 0.637475 |
75f15d7bd84fa7a8aae124d439692402b25b77be | 2,219 | //
// studentLifeController.swift
// #RHS
//
// Created by Mitchell Sweet on 11/18/15.
// Copyright © 2015 Mitchell Sweet. All rights reserved.
//
import UIKit
class studentLifeController: UIViewController {
@IBOutlet weak var clocklabel:UILabel!
@IBOutlet weak var tabselector:UISegmentedControl!
@IBOutlet weak var topimageall:UIImageView!
@IBOutlet weak var bottomimageall:UIImageView!
@IBOutlet weak var topimageipad:UIImageView!
@IBOutlet weak var bottomimageipad:UIImageView!
@IBOutlet weak var toplabelall:UILabel!
@IBOutlet weak var bottomlabelall:UILabel!
@IBOutlet weak var toplabelipad:UILabel!
@IBOutlet weak var bottomlabelipad:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setclock()
clockrepeat()
}
func clockrepeat() {
NSTimer .scheduledTimerWithTimeInterval(5, target: self, selector: #selector(studentLifeController.setclock), userInfo: nil, repeats: true)
}
func setclock() {
let date = NSDate()
let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm a"
clocklabel.text = dateFormatter.stringFromDate(date)
}
@IBAction func tabchanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex
{
case 0:
print("hello")
case 1:
print("hello")
case 2:
print("hello")
case 3:
print("hello")
default:
print("hello")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27.060976 | 147 | 0.638576 |
1a28ba3598587c766641eb76de82a4f2fc70e3da | 1,203 | //
// AudioPlayerMode.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 19/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
/// Represents the mode in which the player should play. Modes can be used as masks so that you can play in `.shuffle`
/// mode and still `.repeatAll`.
public struct AudioPlayerMode: OptionSet {
/// The raw value describing the mode.
public let rawValue: UInt
/// Initializes an `AudioPlayerMode` from a `rawValue`.
///
/// - Parameter rawValue: The raw value describing the mode.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// In this mode, player's queue will be played as given.
public static let normal = AudioPlayerMode(rawValue: 0)
/// In this mode, player's queue is shuffled randomly.
public static let shuffle = AudioPlayerMode(rawValue: 0b001)
/// In this mode, the player will continuously play the same item over and over.
public static let `repeat` = AudioPlayerMode(rawValue: 0b010)
/// In this mode, the player will continuously play the same queue over and over.
public static let repeatAll = AudioPlayerMode(rawValue: 0b100)
}
| 33.416667 | 118 | 0.700748 |
e906ae55090abc5f34fd1ff6d91598c980812cfb | 1,417 | // ===----------------------------------------------------------------------===
//
// This source file is part of the CosmosSwift open source project.
//
// Tree.swift last updated 02/06/2020
//
// Copyright © 2020 Katalysis B.V. and the CosmosSwift project authors.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of CosmosSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
// ===----------------------------------------------------------------------===
import Foundation
public protocol Tree {
associatedtype Hash
var size: Int { get }
var height: Int8 { get }
func has(key: Data) -> Bool
// swiftlint:disable large_tuple
func proof(key: Data) -> (value: Data, proof: Data, exists: Bool) // TODO: make it return an index
// swiftlint:disable large_tuple
func get(key: Data) -> (index: Int, value: Data, exists: Bool)
func get(index: Int) -> (key: Data, value: Data)
func set(key: Data, value: Data) -> Bool
func remove(key: Data) -> (value: Data, remove: Bool)
func hashWithCount() -> (hash: Data, count: Int)
func hash() -> Hash
func save() -> Hash
func load(_ hash: Hash)
func copy() -> Self
func iterate(_ fx: (Data, Data) -> Bool) -> Bool
func iterate(start: Data, end: Data, ascending: Bool, _ fx: (Data, Data) -> Bool) -> Bool
}
| 28.918367 | 102 | 0.573747 |
ffbf8a984c4b2d9f69ca8a9e0baafdd51898caa0 | 2,355 | import Foundation
import Signals
import TSCBasic
import TuistGenerator
import TuistSupport
enum EditServiceError: FatalError {
case xcodeNotSelected
var description: String {
switch self {
case .xcodeNotSelected:
return "Couldn't determine the Xcode version to open the project. Make sure your Xcode installation is selected with 'xcode-select -s'."
}
}
var type: ErrorType {
switch self {
case .xcodeNotSelected:
return .abort
}
}
}
final class EditService {
private let projectEditor: ProjectEditing
private let opener: Opening
init(projectEditor: ProjectEditing = ProjectEditor(),
opener: Opening = Opener()) {
self.projectEditor = projectEditor
self.opener = opener
}
func run(path: String?,
permanent: Bool) throws {
let path = self.path(path)
if !permanent {
try withTemporaryDirectory { generationDirectory in
EditService.temporaryDirectory = generationDirectory
Signals.trap(signals: [.int, .abrt]) { _ in
// swiftlint:disable:next force_try
try! EditService.temporaryDirectory.map(FileHandler.shared.delete)
exit(0)
}
guard let selectedXcode = try XcodeController.shared.selected() else {
throw EditServiceError.xcodeNotSelected
}
let xcodeprojPath = try projectEditor.edit(at: path, in: generationDirectory)
logger.pretty("Opening Xcode to edit the project. Press \(.keystroke("CTRL + C")) once you are done editing")
try opener.open(path: xcodeprojPath, application: selectedXcode.path)
}
} else {
let xcodeprojPath = try projectEditor.edit(at: path, in: path)
logger.notice("Xcode project generated at \(xcodeprojPath.pathString)", metadata: .success)
}
}
// MARK: - Helpers
private func path(_ path: String?) -> AbsolutePath {
if let path = path {
return AbsolutePath(path, relativeTo: FileHandler.shared.currentPath)
} else {
return FileHandler.shared.currentPath
}
}
private static var temporaryDirectory: AbsolutePath?
}
| 31.824324 | 148 | 0.612314 |
62a477c7fe05576cd052554b34b4513bcdfeb998 | 408 | //
// NSColorExtension.swift
// Slack001
//
// Created by Ankit Kumar Bharti on 06/09/18.
// Copyright © 2018 Exilant. All rights reserved.
//
import Cocoa
extension NSColor {
static let darkPurple = NSColor(calibratedRed: 61.0/255.0, green: 7.0/255.0, blue: 57.0/255.0, alpha: 1.0)
static let darkGreen = NSColor(calibratedRed: 33.0/255.0, green: 102.0/255.0, blue: 132.0/255.0, alpha: 1.0)
}
| 27.2 | 112 | 0.681373 |
71c62ca696dbc18e310ff245f1725047f74e6568 | 1,817 | //
// MIT License
//
// Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Combine
public struct AnyAtomToExecutedActionMapper: BaseAtomToUserActionMapper {
private let _mapAtomSomeUserActions: (Atom) -> AnyPublisher<[UserAction], AtomToTransactionMapperError>
public init<Concrete>(any concrete: Concrete) where Concrete: BaseAtomToUserActionMapper {
self._mapAtomSomeUserActions = {
return concrete.mapAtomSomeUserActions($0)
}
}
}
public extension AnyAtomToExecutedActionMapper {
func mapAtomSomeUserActions(_ atom: Atom) -> AnyPublisher<[UserAction], AtomToTransactionMapperError> {
return self._mapAtomSomeUserActions(atom)
}
}
| 41.295455 | 107 | 0.752339 |
71d4a01f24c9fb311eff5bd7974f2b5981ab1acb | 3,718 | import JSONUtilities
extension Operation : Encodable {
enum CodingKeys: String, CodingKey {
case summary
case operationId
case tags
case parameters
case responses
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// print(self)
try container.encode(summary, forKey: .summary)
try container.encode(identifier, forKey: .operationId)
try container.encode(tags, forKey: .tags)
try container.encode(parameters, forKey: .parameters)
var responsesDict:Dictionary<String,OperationResponse> = [:]
for response in responses {
if let statusCode = response.statusCode {
responsesDict["\(statusCode)"] = response
}
else {
responsesDict["default"] = response
}
}
try container.encode(responsesDict, forKey: .responses)
}
}
public struct Operation {
public let json: [String: Any]
public var path: String
public var method: Method
public let summary: String?
public let description: String?
public let requestBody: PossibleReference<RequestBody>?
public let pathParameters: [PossibleReference<Parameter>]
public var operationParameters: [PossibleReference<Parameter>]
public var parameters: [PossibleReference<Parameter>] {
return pathParameters.filter { pathParam in
!operationParameters.contains { $0.value.name == pathParam.value.name }
} + operationParameters
}
public var responses: [OperationResponse]
public var defaultResponse: PossibleReference<Response>?
public let deprecated: Bool
public let identifier: String?
public let tags: [String]
public let securityRequirements: [SecurityRequirement]?
public var generatedIdentifier: String {
return identifier ?? "\(method)\(path)"
}
public enum Method: String {
case get
case put
case post
case delete
case options
case head
case patch
}
}
extension Operation {
public init(path: String, method: Method, pathParameters: [PossibleReference<Parameter>], jsonDictionary: JSONDictionary) throws {
json = jsonDictionary
self.path = path
self.method = method
self.pathParameters = pathParameters
if jsonDictionary["parameters"] != nil {
operationParameters = try jsonDictionary.json(atKeyPath: "parameters")
} else {
operationParameters = []
}
summary = jsonDictionary.json(atKeyPath: "summary")
description = jsonDictionary.json(atKeyPath: "description")
requestBody = jsonDictionary.json(atKeyPath: "requestBody")
identifier = jsonDictionary.json(atKeyPath: "operationId")
tags = (jsonDictionary.json(atKeyPath: "tags")) ?? []
securityRequirements = jsonDictionary.json(atKeyPath: "security")
let allResponses: [String: PossibleReference<Response>] = try jsonDictionary.json(atKeyPath: "responses")
var mappedResponses: [OperationResponse] = []
for (key, response) in allResponses {
if let statusCode = Int(key) {
let response = OperationResponse(statusCode: statusCode, response: response)
mappedResponses.append(response)
}
}
if let defaultResponse = allResponses["default"] {
self.defaultResponse = defaultResponse
mappedResponses.append(OperationResponse(statusCode: nil, response: defaultResponse))
} else {
defaultResponse = nil
}
responses = mappedResponses.sorted {
let code1 = $0.statusCode
let code2 = $1.statusCode
switch (code1, code2) {
case let (.some(code1), .some(code2)): return code1 < code2
case (.some, .none): return true
case (.none, .some): return false
default: return false
}
}
deprecated = (jsonDictionary.json(atKeyPath: "deprecated")) ?? false
}
}
| 29.744 | 131 | 0.711135 |
646182a9567584ef80539dcc611baabd40173b3f | 1,060 | import SwiftFormatRules
final class NeverUseForceTryTests: LintOrFormatRuleTestCase {
func testInvalidTryExpression() {
let input =
"""
let document = try! Document(path: "important.data")
let document = try Document(path: "important.data")
let x = try! someThrowingFunction()
let x = try? someThrowingFunction(
try! someThrowingFunction()
)
let x = try someThrowingFunction(
try! someThrowingFunction()
)
if let data = try? fetchDataFromDisk() { return data }
"""
performLint(NeverUseForceTry.self, input: input)
XCTAssertDiagnosed(.doNotForceTry)
XCTAssertDiagnosed(.doNotForceTry)
XCTAssertDiagnosed(.doNotForceTry)
XCTAssertDiagnosed(.doNotForceTry)
XCTAssertNotDiagnosed(.doNotForceTry)
}
func testAllowForceTryInTestCode() {
let input =
"""
import XCTest
let document = try! Document(path: "important.data")
"""
performLint(NeverUseForceTry.self, input: input)
XCTAssertNotDiagnosed(.doNotForceTry)
}
}
| 28.648649 | 61 | 0.680189 |
fb002315bde63bdf1dcf0d769b202fe16c67fa5a | 4,285 | //
// Canonical.swift
// Asclepius
// Module: R4
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import AsclepiusCore
/**
A URI that referes to a resource by its canonical URL (resources with a url property). The canonical type
differes from a URI in that it has special meaning in this specification and in that it may have a version
appended, separated by a vertical bar "|".
- Note: The type canonical is not used for actual canonical URLs that are the target of these references,
but for the URIs that refer to them and may have the version suffix in them. Like other URIs, elements of this
type may have `#fragment` references
http://hl7.org/fhir/datatypes.html#canonical
*/
public struct Canonical: AsclepiusPrimitiveType {
public var url: URL
public var version: String?
public init(_ url: URL, version: String? = nil) {
self.url = url
self.version = version
}
fileprivate static func parseParts(from string: String) -> (url: URL?, version: String?) {
let parts = string.split(separator: "|", maxSplits: 1)
if let urlPart = parts.first, let url = URL(string: String(urlPart)) {
return (url, parts.count > 1 ? String(parts[1]) : nil)
}
return (nil, parts.count > 1 ? String(parts[1]): nil)
}
}
extension Canonical: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
let (url, version) = Self.parseParts(from: value)
self.init(url ?? URL(string: "invalfhirId:uri")!, version: version)
}
}
// MARK: - Codable
extension Canonical: Codable {
public init(from decoder: Decoder) throws {
let codingKeyContainer = try decoder.singleValueContainer()
let string = try codingKeyContainer.decode(String.self)
let parts = string.split(separator: "|", maxSplits: 1)
guard let urlPart = parts.first, let urlInstance = URL(string: String(urlPart)) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingKeyContainer.codingPath, debugDescription: "Invalid URL in canonical \"\(string)\""))
}
self.url = urlInstance
self.version = parts.count > 1 ? String(parts[1]) : nil
}
public func encode(to encoder: Encoder) throws {
var codingKeyContainer = encoder.singleValueContainer()
if let version = version {
try codingKeyContainer.encode("\(url.absoluteString)|\(version)")
} else {
try codingKeyContainer.encode(url)
}
}
}
// MARK: - CustomStringConvertible
extension Canonical: CustomStringConvertible {
public var description: String {
if let version = version, !version.isEmpty {
return "\(url.absoluteString)|\(version)"
}
return url.absoluteString
}
}
// MARK: - Equatable
extension Canonical: Equatable {
public static func == (leftSide: Canonical, rightSide: Canonical) -> Bool {
if leftSide.url != rightSide.url {
return false
}
if leftSide.version != rightSide.version {
return false
}
return true
}
public static func == (leftSide: String, rightSide: Canonical) -> Bool {
return leftSide == rightSide.description
}
public static func == (leftSide: Canonical, rightSide: String) -> Bool {
return leftSide.description == rightSide
}
}
// MARK: -
extension String {
public func asAsclepiusCanonical() -> Canonical? {
let (parsedURL, version) = Canonical.parseParts(from: self)
guard let url = parsedURL else {
return nil
}
return Canonical(url, version: version)
}
public func asAsclepiusCanonicalPrimitive() -> AsclepiusPrimitive<Canonical>? {
guard let uri = asAsclepiusCanonical() else {
return nil
}
return AsclepiusPrimitive(uri)
}
}
| 31.507353 | 165 | 0.693582 |
1451b429477ee1ff507419da8956284dd35a9af5 | 5,796 | import XCTest
import Alloy
@available(iOS 11, macOS 10.15, *)
class PerformanceTests: XCTestCase {
var context: MTLContext!
var evenInitState: MTLComputePipelineState!
var evenOptimizedInitState: MTLComputePipelineState!
var exactInitState: MTLComputePipelineState!
var evenProcessState: MTLComputePipelineState!
var evenOptimizedProcessState: MTLComputePipelineState!
var exactProcessState: MTLComputePipelineState!
let textureBaseWidth = 1024
let textureBaseHeight = 1024
let gpuIterations = 4
override func setUpWithError() throws {
self.context = try MTLContext()
let library = try self.context.library(for: .module)
self.evenInitState = try library.computePipelineState(function: "initialize_even")
let computeStateDescriptor = MTLComputePipelineDescriptor()
computeStateDescriptor.computeFunction = library.makeFunction(name: "initialize_even")!
computeStateDescriptor.threadGroupSizeIsMultipleOfThreadExecutionWidth = true
self.evenOptimizedInitState = try self.context
.computePipelineState(descriptor: computeStateDescriptor,
options: [],
reflection: nil)
self.exactInitState = try library.computePipelineState(function: "initialize_exact")
self.evenProcessState = try library.computePipelineState(function: "process_even")
let processComputeStateDescriptor = MTLComputePipelineDescriptor()
processComputeStateDescriptor.computeFunction = library.makeFunction(name: "process_even")!
processComputeStateDescriptor.threadGroupSizeIsMultipleOfThreadExecutionWidth = true
self.evenOptimizedProcessState = try self.context
.computePipelineState(descriptor: processComputeStateDescriptor,
options: [],
reflection: nil)
self.exactProcessState = try library.computePipelineState(function: "process_exact")
}
func testEvenPerformance() {
self.measure {
self.runGPUWork { (encoder, texture, output) in
encoder.setTexture(texture, index: 0)
encoder.dispatch2d(state: self.evenInitState, covering: texture.size)
encoder.setTexture(output, index: 1)
encoder.dispatch2d(state: self.evenProcessState, covering: texture.size)
}
}
}
func testEvenOptimizedPerformance() {
self.measure {
self.runGPUWork { (encoder, texture, output) in
encoder.setTexture(texture, index: 0)
encoder.dispatch2d(state: self.evenOptimizedInitState, covering: texture.size)
encoder.setTexture(output, index: 1)
encoder.dispatch2d(state: self.evenOptimizedProcessState, covering: texture.size)
}
}
}
func testExactPerformance() {
self.measure {
self.runGPUWork { (encoder, texture, output) in
encoder.setTexture(texture, index: 0)
encoder.dispatch2d(state: self.exactInitState, exactly: texture.size)
encoder.setTexture(output, index: 1)
encoder.dispatch2d(state: self.exactProcessState, exactly: texture.size)
}
}
}
func runGPUWork(encoding: (MTLComputeCommandEncoder, MTLTexture, MTLTexture) -> Void) {
do {
let maximumThreadgroupSize = evenInitState.max2dThreadgroupSize
var totalGPUTime: CFTimeInterval = 0
var iterations = 0
for wd in 0..<maximumThreadgroupSize.width {
for ht in 0..<maximumThreadgroupSize.height {
var texture = try self.context.texture(width: self.textureBaseWidth + wd,
height: self.textureBaseHeight + ht,
pixelFormat: .rgba8Unorm)
var output = try self.context.texture(width: self.textureBaseWidth + wd,
height: self.textureBaseHeight + ht,
pixelFormat: .rgba8Unorm)
try self.context.scheduleAndWait { buffer in
buffer.compute { encoder in
for _ in 0...self.gpuIterations {
encoding(encoder, texture, output)
swap(&texture, &output)
}
}
buffer.addCompletedHandler { buffer in
iterations += 1
totalGPUTime += buffer.gpuExecutionTime
}
}
}
}
try self.attach(totalGPUTime / CFTimeInterval(iterations),
name: "\(#function) average GPU Time")
}
catch { fatalError(error.localizedDescription) }
}
func attach<T: Codable>(_ value: T,
name: String,
lifetime: XCTAttachment.Lifetime = .keepAlways) throws {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let resultAttachment = try XCTAttachment(data: encoder.encode(value))
resultAttachment.name = name
resultAttachment.lifetime = lifetime
self.add(resultAttachment)
}
}
| 40.531469 | 113 | 0.566598 |
3a5307fb647a60c3cbcda9a5fbd04b6425493434 | 1,896 | // Copyright (c) 2015 Neil Pankey. All rights reserved.
/// Track line and column number in a string. Negative values represent offset
/// from the end of lines and columns rather than the start.
public struct Position : Comparable {
/// 1-based line number in a string
public let line: Int
/// 0-based offset into the current `line`
public let offset: Int
/// Construct a `Position` at the start of a string
public init() {
self.init(1, 1)
}
/// Construct a `Position` at the given line and column
public init(_ line: Int, _ offset: Int) {
precondition(line != 0, "1-based line numbers")
self.line = line
self.offset = offset
}
/// Advances `Position` by `character`
public func successor(character: Character) -> Position {
return character.isNewline ? Position(line + 1, 1) : Position(line, offset + 1)
}
/// Retracts `Position` relative to `previous` character
public func predecessor(previous: Character) -> Position {
return previous.isNewline ? Position(line - 1, -1) : Position(line, offset - 1)
}
}
/// Compares two positions for exact equality.
///
/// Note for a given string there are semantically equivalent positions if
/// measuring offset from the end of lines that this won't consider equal.
public func ==(lhs: Position, rhs: Position) -> Bool {
return lhs.line == rhs.line && lhs.offset == rhs.offset
}
/// Determines if `lhs` position is less than `rhs` position.
///
/// Note that this assumes both positions are measured relative to the same
/// starting offset. In other words don't try to compare a negative based
/// position from a positive one.
public func <(lhs: Position, rhs: Position) -> Bool {
// TODO The above requirement sucks, can we do better.
return lhs.line < rhs.line || (lhs.line == rhs.line && lhs.offset < rhs.offset)
}
| 36.461538 | 87 | 0.669304 |
627553b174a6c760a6efda35f66747fdd1d29a77 | 2,185 | //
// AppDelegate.swift
// joepublic
//
// Created by yousefahmedarafa on 01/01/2020.
// Copyright (c) 2020 yousefahmedarafa. 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.489362 | 285 | 0.756064 |
4ba0ceb707f5bb3020a65061ced8141af30e7dce | 845 | import Foundation
extension Singular {
/// Always eight bytes.
///
/// More efficient than `uint64` if values are often greater than 2^56.
@propertyWrapper
public final class Fixed64 {
public let fieldNumber: Swift.UInt32
public internal(set) var rawValue: Swift.UInt64?
public var wrappedValue: Swift.UInt64 {
get { self.rawValue ?? 0 }
set { self.rawValue = newValue }
}
public init(_ fieldNumber: Swift.UInt32) {
self.fieldNumber = fieldNumber
}
}
}
extension Singular.Fixed64: _DecodingKey {
func decode(from reader: _ByteBufferReader) throws {
guard let bit64 = reader.mapBit64.removeValue(forKey: self.fieldNumber) else { return }
self.rawValue = bit64
}
}
| 24.142857 | 95 | 0.597633 |
6a4896e85460476554616b55297bc07fe8b19696 | 1,870 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Combine
enum RemoteSyncEngineEvent {
case storageAdapterAvailable
case subscriptionsPaused
case mutationsPaused
case clearedStateOutgoingMutations
case subscriptionsInitialized
case performedInitialSync
case subscriptionsActivated
case mutationQueueStarted
case syncStarted
case cleanedUp
case cleanedUpForTermination
case mutationEvent(MutationEvent)
}
/// Behavior to sync mutation events to the remote API, and to subscribe to mutations from the remote API
protocol RemoteSyncEngineBehavior: class {
/// Start the sync process with a "delta sync" merge
///
/// The order of the startup sequence is important:
/// 1. Subscription and Mutation processing to the network are paused
/// 1. Subscription connections are established and incoming messages are written to a queue
/// 1. Queries are run and objects applied to the Datastore
/// 1. Subscription processing runs off the queue and flows as normal, reconciling any items against
/// the updates in the Datastore
/// 1. Mutation processor drains messages off the queue in serial and sends to the service, invoking
/// any local callbacks on error if necessary
func start(api: APICategoryGraphQLBehavior, auth: AuthCategoryBehavior?)
func stop(completion: @escaping DataStoreCallback<Void>)
/// Submits a new mutation for synchronization to the remote API. The response will be handled by the appropriate
/// reconciliation queue
@available(iOS 13.0, *)
func submit(_ mutationEvent: MutationEvent) -> Future<MutationEvent, DataStoreError>
@available(iOS 13.0, *)
var publisher: AnyPublisher<RemoteSyncEngineEvent, DataStoreError> { get }
}
| 36.666667 | 117 | 0.74492 |
e6b741c8ee2def080a561875d9655955ea365be4 | 2,018 | // RUN: %target-swift-frontend -module-name main -typecheck -verify -swift-version 4 %s
struct S: P {}
protocol P {}
let _: S.Type = type(of: S())
let _ = type(of: S())
let _: P.Type = type(of: S() as P)
let _ = type(of: S() as P)
let _: P.Protocol = type(of: S() as P) // expected-error{{}}
let _: S.Type = Swift.type(of: S())
let _ = Swift.type(of: S())
let _: P.Type = Swift.type(of: S() as P)
let _ = Swift.type(of: S() as P)
let _: P.Protocol = Swift.type(of: S() as P) // expected-error{{}}
let _: (S) -> S.Type = type(of:) // expected-error{{}}
func type(_: S) -> S {}
func type(kinda _: S) -> Any.Type {}
let _ = type(S())
let _: S = type(S())
let _ = type(kinda: S())
let _: Any.Type = type(kinda: S())
struct Q {}
struct R {}
func type(of: Q) -> R {}
let _: R = type(of: Q())
let _: Q.Type = type(of: Q())
let _: Q.Type = Swift.type(of: Q())
let _: R = Swift.type(of: Q()) // expected-error{{}}
let _: Q.Type = main.type(of: Q()) // expected-error{{}}
let _: R = main.type(of: Q())
// Let's make sure that binding of the left-hand side
// of the dynamic-type-of constraint is not attempted.
class C {
typealias T = Int
}
// We need at least 4 classes here because type(of:)
// has 3 declarations in this file, and we need to
// try and make it so type(of:) picked as first overload.
class D : C {
typealias T = Float
}
class E : D {
typealias T = Double
}
class F : E {
typealias T = UInt
}
class G : F {
typealias T = Float
}
func foo(_: Any...) {}
// It's imperative for bar() to have more overloads
// the that of type(of:) to make sure that latter is
// picked first.
func bar() -> Int {} // expected-note {{found this candidate}}
func bar() -> Float {} // expected-note {{found this candidate}}
func bar() -> String {} // expected-note {{found this candidate}}
func bar() -> UInt {} // expected-note {{found this candidate}}
foo(type(of: G.T.self)) // Ok
let _: Any = type(of: G.T.self) // Ok
foo(type(of: bar())) // expected-error {{ambiguous use of 'bar()'}}
| 24.91358 | 87 | 0.603072 |
cc3178a6b22e3e2e67a312d7d9f696c5f7705720 | 738 | //
// CheckoutFlowController.swift
// NavigationEngineDemo
//
// Created by Alberto De Bortoli on 23/11/2018.
// Copyright © 2018 Just Eat. All rights reserved.
//
import UIKit
import Promis
public protocol CheckoutFlowControllerProtocol {
var parentFlowController: RestaurantsFlowControllerProtocol! { get }
@discardableResult func beginFlow(from viewController: UIViewController, animated: Bool) -> Future<Bool>
@discardableResult func proceedToPayment(animated: Bool) -> Future<Bool>
@discardableResult func goToOrderConfirmation(orderId: OrderId) -> Future<Bool>
@discardableResult func leaveFlow(animated: Bool) -> Future<Bool>
@discardableResult func leaveFlowAndGoBackToSERP() -> Future<Bool>
}
| 33.545455 | 108 | 0.762873 |
dd7b0e358043995b28fb2fb7ab935569d03c895f | 19,447 | //
// PhotoPreviewViewController.swift
// HXPHPickerExample
//
// Created by Silence on 2020/11/13.
// Copyright © 2020 Silence. All rights reserved.
//
import UIKit
import Photos
protocol PhotoPreviewViewControllerDelegate: AnyObject {
func previewViewController(
_ previewController: PhotoPreviewViewController,
didOriginalButton isOriginal: Bool
)
func previewViewController(
_ previewController: PhotoPreviewViewController,
didSelectBox photoAsset: PhotoAsset,
isSelected: Bool,
updateCell: Bool
)
func previewViewController(
_ previewController: PhotoPreviewViewController,
editAssetFinished photoAsset: PhotoAsset
)
func previewViewController(
_ previewController: PhotoPreviewViewController,
networkImagedownloadSuccess photoAsset: PhotoAsset
)
}
public class PhotoPreviewViewController: BaseViewController {
weak var delegate: PhotoPreviewViewControllerDelegate?
public let config: PreviewViewConfiguration
/// 当前预览的位置索引
public var currentPreviewIndex: Int = 0
/// 预览的资源数组
public var previewAssets: [PhotoAsset] = []
/// 是否是外部预览
public var isExternalPreview: Bool = false
var orientationDidChange: Bool = false
var statusBarShouldBeHidden: Bool = false
var videoLoadSingleCell = false
var viewDidAppear: Bool = false
var firstLayoutSubviews: Bool = true
var interactiveTransition: PickerInteractiveTransition?
lazy var selectBoxControl: SelectBoxView = {
let boxControl = SelectBoxView(
frame: CGRect(
origin: .zero,
size: config.selectBox.size
)
)
boxControl.backgroundColor = .clear
boxControl.config = config.selectBox
boxControl.addTarget(self, action: #selector(didSelectBoxControlClick), for: UIControl.Event.touchUpInside)
return boxControl
}()
lazy var collectionViewLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout.init()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
return layout
}()
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: collectionViewLayout)
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = true
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
self.automaticallyAdjustsScrollViewInsets = false
}
collectionView.register(
PreviewPhotoViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(PreviewPhotoViewCell.self)
)
collectionView.register(
PreviewLivePhotoViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(PreviewLivePhotoViewCell.self)
)
if let customVideoCell = config.customVideoCellClass {
collectionView.register(
customVideoCell,
forCellWithReuseIdentifier: NSStringFromClass(PreviewVideoViewCell.self)
)
}else {
collectionView.register(
PreviewVideoViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(PreviewVideoViewCell.self)
)
}
return collectionView
}()
var isMultipleSelect: Bool = false
var allowLoadPhotoLibrary: Bool = true
lazy var bottomView: PhotoPickerBottomView = {
let bottomView = PhotoPickerBottomView(
config: config.bottomView,
allowLoadPhotoLibrary: allowLoadPhotoLibrary,
isMultipleSelect: isMultipleSelect,
isPreview: true,
isExternalPreview: isExternalPreview
)
bottomView.hx_delegate = self
if config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) {
bottomView.selectedView.reloadData(
photoAssets: pickerController!.selectedAssetArray
)
}
if !isExternalPreview {
bottomView.boxControl.isSelected = pickerController!.isOriginal
bottomView.requestAssetBytes()
}
return bottomView
}()
var requestPreviewTimer: Timer?
init(config: PreviewViewConfiguration) {
self.config = config
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let margin: CGFloat = 20
let itemWidth = view.width + margin
collectionViewLayout.minimumLineSpacing = margin
collectionViewLayout.itemSize = view.size
let contentWidth = (view.width + itemWidth) * CGFloat(previewAssets.count)
collectionView.frame = CGRect(x: -(margin * 0.5), y: 0, width: itemWidth, height: view.height)
collectionView.contentSize = CGSize(width: contentWidth, height: view.height)
collectionView.setContentOffset(CGPoint(x: CGFloat(currentPreviewIndex) * itemWidth, y: 0), animated: false)
DispatchQueue.main.async {
if self.orientationDidChange {
let cell = self.getCell(for: self.currentPreviewIndex)
cell?.setupScrollViewContentSize()
self.orientationDidChange = false
}
}
configBottomViewFrame()
if firstLayoutSubviews {
if !previewAssets.isEmpty &&
config.bottomView.showSelectedView &&
(isMultipleSelect || isExternalPreview) &&
config.showBottomView {
DispatchQueue.main.async {
self.bottomView.selectedView.scrollTo(
photoAsset: self.previewAssets[self.currentPreviewIndex],
isAnimated: false
)
}
}
firstLayoutSubviews = false
}
}
public override func viewDidLoad() {
super.viewDidLoad()
title = ""
isMultipleSelect = pickerController?.config.selectMode == .multiple
allowLoadPhotoLibrary = pickerController?.config.allowLoadPhotoLibrary ?? true
extendedLayoutIncludesOpaqueBars = true
edgesForExtendedLayout = .all
view.clipsToBounds = true
initView()
}
public override func deviceOrientationDidChanged(notify: Notification) {
orientationDidChange = true
let cell = getCell(for: currentPreviewIndex)
if cell?.photoAsset.mediaSubType == .livePhoto {
if #available(iOS 9.1, *) {
cell?.scrollContentView.livePhotoView.stopPlayback()
}
}
if config.bottomView.showSelectedView && (isMultipleSelect || isExternalPreview) && config.showBottomView {
bottomView.selectedView.reloadSectionInset()
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
pickerController?.viewControllersWillAppear(self)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewDidAppear = true
DispatchQueue.main.async {
let cell = self.getCell(for: self.currentPreviewIndex)
cell?.requestPreviewAsset()
}
pickerController?.viewControllersDidAppear(self)
guard let picker = pickerController else {
return
}
if (picker.modalPresentationStyle == .fullScreen && interactiveTransition == nil) ||
(!UIDevice.isPortrait && !UIDevice.isPad) && !isExternalPreview {
interactiveTransition = PickerInteractiveTransition(
panGestureRecognizerFor: self,
type: .pop
)
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pickerController?.viewControllersWillDisappear(self)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
pickerController?.viewControllersDidDisappear(self)
}
public override var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
if PhotoManager.isDark {
return .lightContent
}
return pickerController?.config.statusBarStyle ?? .default
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) && viewDidAppear {
configColor()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: Function
extension PhotoPreviewViewController {
private func initView() {
view.addSubview(collectionView)
if config.showBottomView {
view.addSubview(bottomView)
bottomView.updateFinishButtonTitle()
}
if let pickerController = pickerController, isExternalPreview {
// statusBarShouldBeHidden = pickerController.config.prefersStatusBarHidden
if pickerController.modalPresentationStyle != .custom {
configColor()
}
}
if isMultipleSelect || isExternalPreview {
videoLoadSingleCell = pickerController!.singleVideo
if !isExternalPreview {
navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: selectBoxControl)
}else {
var cancelItem: UIBarButtonItem
if config.cancelType == .image {
let isDark = PhotoManager.isDark
cancelItem = UIBarButtonItem(
image: UIImage.image(
for: isDark ? config.cancelDarkImageName : config.cancelImageName
),
style: .done,
target: self,
action: #selector(didCancelItemClick)
)
}else {
cancelItem = UIBarButtonItem(
title: "取消".localized,
style: .done,
target: self,
action: #selector(didCancelItemClick)
)
}
if config.cancelPosition == .left {
navigationItem.leftBarButtonItem = cancelItem
} else {
navigationItem.rightBarButtonItem = cancelItem
}
}
if !previewAssets.isEmpty {
if currentPreviewIndex == 0 {
let photoAsset = previewAssets.first!
if config.bottomView.showSelectedView && config.showBottomView {
bottomView.selectedView.scrollTo(photoAsset: photoAsset)
}
if !isExternalPreview {
if photoAsset.mediaType == .video && videoLoadSingleCell {
selectBoxControl.isHidden = true
} else {
updateSelectBox(photoAsset.isSelected, photoAsset: photoAsset)
selectBoxControl.isSelected = photoAsset.isSelected
}
}
#if HXPICKER_ENABLE_EDITOR
if let pickerController = pickerController, !config.bottomView.editButtonHidden,
config.showBottomView {
if photoAsset.mediaType == .photo {
bottomView.editBtn.isEnabled = pickerController.config.editorOptions.isPhoto
}else if photoAsset.mediaType == .video {
bottomView.editBtn.isEnabled = pickerController.config.editorOptions.contains(.video)
}
}
#endif
pickerController?.previewUpdateCurrentlyDisplayedAsset(
photoAsset: photoAsset,
index: currentPreviewIndex
)
}
}
}else if !isMultipleSelect {
if !previewAssets.isEmpty {
if currentPreviewIndex == 0 {
let photoAsset = previewAssets.first!
#if HXPICKER_ENABLE_EDITOR
if let pickerController = pickerController, !config.bottomView.editButtonHidden,
config.showBottomView {
if photoAsset.mediaType == .photo {
bottomView.editBtn.isEnabled = pickerController.config.editorOptions.isPhoto
}else if photoAsset.mediaType == .video {
bottomView.editBtn.isEnabled = pickerController.config.editorOptions.contains(.video)
}
}
#endif
pickerController?.previewUpdateCurrentlyDisplayedAsset(
photoAsset: photoAsset,
index: currentPreviewIndex
)
}
}
}
}
func configBottomViewFrame() {
if !config.showBottomView {
return
}
var bottomHeight: CGFloat = 0
if isExternalPreview {
bottomHeight = (pickerController?.selectedAssetArray.isEmpty ?? true) ? 0 : UIDevice.bottomMargin + 70
#if HXPICKER_ENABLE_EDITOR
if !config.bottomView.showSelectedView && config.bottomView.editButtonHidden {
if config.bottomView.editButtonHidden {
bottomHeight = 0
}else {
bottomHeight = UIDevice.bottomMargin + 50
}
}
#endif
}else {
if let picker = pickerController {
bottomHeight = picker.selectedAssetArray.isEmpty ?
50 + UIDevice.bottomMargin : 50 + UIDevice.bottomMargin + 70
}
if !config.bottomView.showSelectedView || !isMultipleSelect {
bottomHeight = 50 + UIDevice.bottomMargin
}
}
bottomView.frame = CGRect(
x: 0,
y: view.height - bottomHeight,
width: view.width,
height: bottomHeight
)
}
func configColor() {
view.backgroundColor = PhotoManager.isDark ?
config.backgroundDarkColor :
config.backgroundColor
}
func reloadCell(for photoAsset: PhotoAsset) {
guard let item = previewAssets.firstIndex(of: photoAsset),
!previewAssets.isEmpty else {
return
}
let indexPath = IndexPath(item: item, section: 0)
collectionView.reloadItems(at: [indexPath])
if config.showBottomView {
bottomView.selectedView.reloadData(photoAsset: photoAsset)
bottomView.requestAssetBytes()
}
}
func getCell(for item: Int) -> PhotoPreviewViewCell? {
if previewAssets.isEmpty {
return nil
}
let cell = collectionView.cellForItem(
at: IndexPath(
item: item,
section: 0
)
) as? PhotoPreviewViewCell
return cell
}
func setCurrentCellImage(image: UIImage?) {
guard let image = image,
let cell = getCell(for: currentPreviewIndex) else {
return
}
if !cell.photoAsset.mediaSubType.isGif {
cell.cancelRequest()
cell.scrollContentView.imageView.image = image
}
}
func deleteCurrentPhotoAsset() {
if previewAssets.isEmpty || !isExternalPreview {
return
}
let photoAsset = previewAssets[currentPreviewIndex]
if let shouldDelete = pickerController?.previewShouldDeleteAsset(
photoAsset: photoAsset,
index: currentPreviewIndex
), !shouldDelete {
return
}
#if HXPICKER_ENABLE_EDITOR
photoAsset.photoEdit = nil
photoAsset.videoEdit = nil
#endif
previewAssets.remove(
at: currentPreviewIndex
)
collectionView.deleteItems(
at: [
IndexPath(
item: currentPreviewIndex,
section: 0
)
]
)
if config.showBottomView {
bottomView.selectedView.removePhotoAsset(photoAsset: photoAsset)
}
pickerController?.previewDidDeleteAsset(
photoAsset: photoAsset,
index: currentPreviewIndex
)
if previewAssets.isEmpty {
didCancelItemClick()
return
}
scrollViewDidScroll(collectionView)
setupRequestPreviewTimer()
}
func replacePhotoAsset(at index: Int, with photoAsset: PhotoAsset) {
previewAssets[index] = photoAsset
reloadCell(for: photoAsset)
// collectionView.reloadItems(at: [IndexPath.init(item: index, section: 0)])
}
func addedCameraPhotoAsset(_ photoAsset: PhotoAsset) {
guard let picker = pickerController else { return }
if config.bottomView.showSelectedView &&
(isMultipleSelect || isExternalPreview) &&
config.showBottomView {
bottomView.selectedView.reloadData(
photoAssets: picker.selectedAssetArray
)
configBottomViewFrame()
bottomView.layoutSubviews()
bottomView.updateFinishButtonTitle()
}
getCell(for: currentPreviewIndex)?.cancelRequest()
previewAssets.insert(
photoAsset,
at: currentPreviewIndex
)
collectionView.insertItems(
at: [
IndexPath(
item: currentPreviewIndex,
section: 0
)
]
)
collectionView.scrollToItem(
at: IndexPath(
item: currentPreviewIndex,
section: 0
),
at: .centeredHorizontally,
animated: false
)
scrollViewDidScroll(collectionView)
setupRequestPreviewTimer()
}
@objc func didCancelItemClick() {
pickerController?.cancelCallback()
dismiss(animated: true, completion: nil)
}
}
| 38.357002 | 116 | 0.591608 |
e8a8d2e3d61560d2ce44f2a2a42feb955216ce05 | 158 | import Foundation
protocol TagChartModuleOutput: class {
var dataSource: [RuuviMeasurement] { get }
var lastMeasurement: RuuviMeasurement? { get }
}
| 22.571429 | 50 | 0.746835 |
fe231f1b608db34398bbd4664806650148b70051 | 3,978 | // This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let removeFromCartBeacon = try RemoveFromCartBeacon(json)
//
// Hashable or Equatable:
// The compiler will not be able to synthesize the implementation of Hashable or Equatable
// for types that require the use of JSONAny, nor will the implementation of Hashable be
// synthesized for types that have collections (such as arrays or dictionaries).
import Foundation
/// A removeFromCart event for the native app client type (as opposed to other client types
/// like web browsers) sent directly from the client (as opposed to sent from a server
/// serving the client). This event is used when the shopper removes a product from their
/// cart. Note that the only client officially supported for sending GroupBy this data is the
/// official GroupBy native app SDK for the respective platform (Android, iOS, etc). A
/// backwards incompatible change may be made to a major version of this schema if the change
/// would not be backwards incompatible with respect to correct usage of the corresponding
/// major version of the native app SDK.
// MARK: - RemoveFromCartBeacon
public class RemoveFromCartBeacon: Codable {
var client: NativeAppClient
var customer: Customer
public var event: RemoveFromCartEvent
public var experiments: [Experiments]?
public var metadata: [Metadata]?
var shopper: ShopperTracking
var time: Date
init(client: NativeAppClient, customer: Customer, event: RemoveFromCartEvent, experiments: [Experiments]?, metadata: [Metadata]?, shopper: ShopperTracking, time: Date) {
self.client = client
self.customer = customer
self.event = event
self.experiments = experiments
self.metadata = metadata
self.shopper = shopper
self.time = time
}
public init(event: RemoveFromCartEvent, experiments: [Experiments]?, metadata: [Metadata]?) {
self.client = NativeAppClient()
self.customer = Customer()
self.event = event
self.experiments = experiments
self.metadata = metadata
self.shopper = ShopperTracking()
self.time = Date()
}
}
// MARK: RemoveFromCartBeacon convenience initializers and mutators
extension RemoveFromCartBeacon {
convenience init(data: Data) throws {
let me = try newJSONDecoder().decode(RemoveFromCartBeacon.self, from: data)
self.init(client: me.client, customer: me.customer, event: me.event, experiments: me.experiments, metadata: me.metadata, shopper: me.shopper, time: me.time)
}
convenience init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
convenience init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
client: NativeAppClient? = nil,
customer: Customer? = nil,
event: RemoveFromCartEvent? = nil,
experiments: [Experiments]?? = nil,
metadata: [Metadata]?? = nil,
shopper: ShopperTracking? = nil,
time: Date? = nil
) -> RemoveFromCartBeacon {
return RemoveFromCartBeacon(
client: client ?? self.client,
customer: customer ?? self.customer,
event: event ?? self.event,
experiments: experiments ?? self.experiments,
metadata: metadata ?? self.metadata,
shopper: shopper ?? self.shopper,
time: time ?? self.time
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
| 40.181818 | 173 | 0.677476 |
4b215e326b7d5a2f2e1c9160d6db8ff86adf6d37 | 1,814 | //
// String+Extension.swift
// DebugDemo
//
// Created by Vince Davis on 8/26/19.
// Copyright © 2019 Vince Davis. All rights reserved.
//
import Foundation
import UIKit
struct DDString {
static let allStrings = [
("Main", String.main),
("Debug", String.debug),
("Main View Description", String.mainViewDescription),
("Main App Controllers", String.mainAppControllers),
("Table View Cells", String.tableViewCells),
("None", String.none),
("Red Background", String.redBackground),
("Style Guide", String.styleGuide),
("Colors", String.colors),
("Fonts", String.fonts),
("Hidden Debug", String.hiddenDebug),
("Strings", String.strings),
("Debug Views", String.debugViews),
]
}
extension String {
var localized: String {
return localized(comment: "")
}
func localized(comment: String = "") -> String {
let translatedString = NSLocalizedString(self, comment: comment)
return translatedString
}
}
// MARK: - Static Text Strings
public extension String {
static let main = "Main".localized
static let debug = "Debug".localized
static let mainViewDescription = "This Controller is the main controller of the app".localized
static let mainAppControllers = "Main App Controllers".localized
static let tableViewCells = "Table View Cells".localized
static let none = "None".localized
static let redBackground = "Red Background".localized
static let styleGuide = "Style Guide".localized
static let colors = "Colors".localized
static let fonts = "Fonts".localized
static let hiddenDebug = "Hidden Debug".localized
static let strings = "Strings".localized
static let debugViews = "Debug Views".localized
}
| 31.824561 | 98 | 0.660419 |
01470da7bdb8b8ff8ed0b436c90462d7660026f5 | 1,210 | import Color
public struct NamedColors {
// public static var black: Color { return Color(white: 0) }
// public static var darkGray: Color { return Color(white: 0.333) }
// public static var lightGray: Color { return Color(white: 0.667) }
// public static var white: Color { return Color(white: 1) }
// public static var gray: Color { return Color(white: 0.5) }
// public static var red: Color { return Color(red: 1, green: 0, blue: 0) }
// public static var green: Color { return Color(red: 0, green: 1, blue: 0) }
// public static var blue: Color { return Color(red: 0, green: 0, blue: 1) }
// public static var cyan: Color { return Color(red: 0, green: 1, blue: 1) }
// public static var yellow: Color { return Color(red: 1, green: 1, blue: 0) }
// public static var magenta: Color { return Color(red: 1, green: 0, blue: 1) }
// public static var orange: Color { return Color(red: 1, green: 0.5, blue: 0) }
public static var purple: Color { return Color(red: 0.5, green: 0, blue: 0.5) }
// public static var brown: Color { return Color(red: 0.6, green: 0.4, blue: 0.2) }
// public static var clear: Color { return Color(white: 0, alpha: 0) }
}
| 60.5 | 87 | 0.63719 |
0ebb38bca26421df641faa8a32ba45e6baf69005 | 102 | // MIT license. Copyright (c) 2021 TriangleDraw. All rights reserved.
class TriangleDrawLibrary {
}
| 17 | 69 | 0.754902 |
e624fd8723470304c5b543684681c17d0d23a877 | 10,133 | //
// Lyrics3Tag.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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
fileprivate func ~=<T: Equatable> (left: [T], right: [T]) -> Bool {
return (left == right)
}
public class Lyrics3Tag {
// MARK: Type Properties
static let dataMarker: [UInt8] = [76, 89, 82, 73, 67, 83, 66, 69, 71, 73, 78]
static let dataSignatureV1: [UInt8] = [76, 89, 82, 73, 67, 83, 69, 78, 68]
static let dataSignatureV2: [UInt8] = [76, 89, 82, 73, 67, 83, 50, 48, 48]
static let maxSignatureLength: Int = 15
static let maxDataLengthV1: Int = 5100
static let maxDataLengthV2: Int = 1000014
static let minDataLength: Int = 20
// MARK: Instance Properties
public var version: Lyrics3Version
// MARK:
private var fieldKeys: [Lyrics3FieldID: Int]
public private(set) var fieldList: [Lyrics3Field]
// MARK:
public var isEmpty: Bool {
return self.fieldList.isEmpty
}
// MARK: Initializers
private init?(bodyData: [UInt8], version: Lyrics3Version) {
assert(bodyData.starts(with: Lyrics3Tag.dataMarker), "Invalid data")
self.version = version
self.fieldKeys = [:]
self.fieldList = []
var offset = Lyrics3Tag.dataMarker.count
while offset < bodyData.count {
if let field = Lyrics3Field(fromBodyData: bodyData, offset: &offset, version: self.version) {
if let index = self.fieldKeys[field.identifier] {
self.fieldList[index] = field
} else {
self.fieldKeys.updateValue(self.fieldList.count, forKey: field.identifier)
self.fieldList.append(field)
}
} else {
break
}
}
}
// MARK:
public init(version: Lyrics3Version = Lyrics3Version.v2) {
self.version = version
self.fieldKeys = [:]
self.fieldList = []
}
public convenience init?(fromData data: [UInt8]) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
var range = Range<UInt64>(0..<UInt64(data.count))
self.init(fromStream: stream, range: &range)
}
public convenience init?(fromStream stream: Stream, range: inout Range<UInt64>) {
assert(stream.isOpen && stream.isReadable && (stream.length >= range.upperBound), "Invalid stream")
guard range.lowerBound < range.upperBound else {
return nil
}
let minDataLength = UInt64(Lyrics3Tag.minDataLength)
let maxDataLength = UInt64(range.count)
guard minDataLength <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.upperBound - UInt64(Lyrics3Tag.maxSignatureLength)) else {
return nil
}
let signature = stream.read(maxLength: Lyrics3Tag.maxSignatureLength)
guard signature.count == Lyrics3Tag.maxSignatureLength else {
return nil
}
switch [UInt8](signature.suffix(Lyrics3Tag.dataSignatureV1.count)) {
case Lyrics3Tag.dataSignatureV1:
let dataLength = min(maxDataLength, UInt64(Lyrics3Tag.maxDataLengthV1))
let dataStart = range.upperBound - dataLength
guard stream.seek(offset: dataStart) else {
return nil
}
let data = stream.read(maxLength: Int(dataLength))
guard data.count == Int(dataLength) else {
return nil
}
let bodyEnd = data.count - Lyrics3Tag.dataSignatureV1.count
guard let bodyStart = data.lastOccurrence(of: Lyrics3Tag.dataMarker) else {
return nil
}
self.init(bodyData: [UInt8](data[bodyStart..<bodyEnd]), version: Lyrics3Version.v1)
range = (dataStart + UInt64(bodyStart))..<range.upperBound
case Lyrics3Tag.dataSignatureV2:
guard let bodyLength = Int(ID3v1Latin1TextEncoding.regular.decode(signature.prefix(6)) ?? "") else {
return nil
}
let dataLength = UInt64(bodyLength + Lyrics3Tag.maxSignatureLength)
guard dataLength <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.upperBound - dataLength) else {
return nil
}
let bodyData = stream.read(maxLength: bodyLength)
guard bodyData.count == bodyLength else {
return nil
}
guard bodyData.starts(with: Lyrics3Tag.dataMarker) else {
return nil
}
self.init(bodyData: bodyData, version: Lyrics3Version.v2)
range = (range.upperBound - dataLength)..<range.upperBound
default:
return nil
}
}
// MARK: Instance Methods
public func toData() -> [UInt8]? {
guard !self.isEmpty else {
return nil
}
var data = Lyrics3Tag.dataMarker
switch self.version {
case Lyrics3Version.v1:
let maxBodyLength = Lyrics3Tag.maxDataLengthV1 - Lyrics3Tag.dataSignatureV1.count
for field in self.fieldList {
if let fieldData = field.toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
guard data.count > Lyrics3Tag.dataMarker.count else {
return nil
}
data.append(contentsOf: Lyrics3Tag.dataSignatureV1)
case Lyrics3Version.v2:
let maxBodyLength = Lyrics3Tag.maxDataLengthV2 - Lyrics3Tag.maxSignatureLength
if let index = self.fieldKeys[Lyrics3FieldID.ind] {
if let fieldData = self.fieldList[index].toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
for field in self.fieldList {
if field.identifier != Lyrics3FieldID.ind {
if let fieldData = field.toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
}
guard data.count > Lyrics3Tag.dataMarker.count else {
return nil
}
data.append(contentsOf: ID3v1Latin1TextEncoding.regular.encode(String(format: "%06d", data.count)))
data.append(contentsOf: Lyrics3Tag.dataSignatureV2)
}
return data
}
@discardableResult
public func appendField(_ identifier: Lyrics3FieldID) -> Lyrics3Field {
if let index = self.fieldKeys[identifier] {
return self.fieldList[index]
} else {
let field = Lyrics3Field(identifier: identifier)
self.fieldKeys.updateValue(self.fieldList.count, forKey: identifier)
self.fieldList.append(field)
return field
}
}
@discardableResult
public func resetField(_ identifier: Lyrics3FieldID) -> Lyrics3Field {
if let index = self.fieldKeys[identifier] {
let field = self.fieldList[index]
field.reset()
return field
} else {
let field = Lyrics3Field(identifier: identifier)
self.fieldKeys.updateValue(self.fieldList.count, forKey: identifier)
self.fieldList.append(field)
return field
}
}
@discardableResult
public func removeField(_ identifier: Lyrics3FieldID) -> Bool {
guard let index = self.fieldKeys.removeValue(forKey: identifier) else {
return false
}
for i in (index + 1)..<self.fieldList.count {
self.fieldKeys.updateValue(i - 1, forKey: self.fieldList[i].identifier)
}
self.fieldList.remove(at: index)
return true
}
public func revise() {
for field in self.fieldList {
if field.isEmpty {
if let index = self.fieldKeys.removeValue(forKey: field.identifier) {
for i in index..<(self.fieldList.count - 1) {
self.fieldKeys.updateValue(i, forKey: self.fieldList[i + 1].identifier)
}
self.fieldList.remove(at: index)
}
}
}
}
public func clear() {
self.fieldKeys.removeAll()
self.fieldList.removeAll()
}
// MARK: Subscripts
public subscript(identifier: Lyrics3FieldID) -> Lyrics3Field? {
guard let index = self.fieldKeys[identifier] else {
return nil
}
return self.fieldList[index]
}
}
| 30.799392 | 112 | 0.590546 |
8ac2b15b589b5a83971e17f4be1062929ba66990 | 3,590 | import Foundation
import MongoSwift
import StitchCore
import StitchCoreRemoteMongoDBService
/**
* Represents a `find` or `aggregate` operation against a MongoDB collection. Use the methods in this class to execute
* the operation and retrieve the results.
*/
public class RemoteMongoReadOperation<T: Codable> {
private let proxy: CoreRemoteMongoReadOperation<T>
private let dispatcher: OperationDispatcher
internal init(withOperations operations: CoreRemoteMongoReadOperation<T>,
withDispatcher dispatcher: OperationDispatcher) {
self.proxy = operations
self.dispatcher = dispatcher
}
/**
* Executes the operation and returns the first document in the result.
*
* - parameters:
* - completionHandler: The completion handler to call when the operation is completed or if the operation fails.
* This handler is executed on a non-main global `DispatchQueue`. If the operation is
* successful, the result will contain an optional `T` indicating the first document in the
* result. the document will be `nil` if the result was empty.
*/
public func first(_ completionHandler: @escaping (StitchResult<T?>) -> Void) {
self.dispatcher.run(withCompletionHandler: completionHandler) {
return try self.proxy.first()
}
}
/**
* Executes the operation and returns the result as an array.
*
* - parameters:
* - completionHandler: The completion handler to call when the operation is completed or if the operation fails.
* This handler is executed on a non-main global `DispatchQueue`. If the operation is
* successful, the result will contain the documents in the result as an array.
*/
public func toArray(_ completionHandler: @escaping (StitchResult<[T]>) -> Void) {
self.dispatcher.run(withCompletionHandler: completionHandler) {
return try self.proxy.toArray()
}
}
/**
* Executes the operation and returns the result as an array. Deprecated in favor of toArray.
*
* - parameters:
* - completionHandler: The completion handler to call when the operation is completed or if the operation fails.
* This handler is executed on a non-main global `DispatchQueue`. If the operation is
* successful, the result will contain the documents in the result as an array.
*/
@available(*, deprecated, message: "use toArray instead")
public func asArray(_ completionHandler: @escaping (StitchResult<[T]>) -> Void) {
self.toArray(completionHandler)
}
/**
* Executes the operation and returns a cursor to its resulting documents.
*
* - parameters:
* - completionHandler: The completion handler to call when the operation is completed or if the operation fails.
* This handler is executed on a non-main global `DispatchQueue`. If the operation is
* successful, the result will contain an asynchronously iterating cursor to the documents
* in the result.
*/
public func iterator(_ completionHandler: @escaping (StitchResult<RemoteMongoCursor<T>>) -> Void) {
self.dispatcher.run(withCompletionHandler: completionHandler) {
return try RemoteMongoCursor.init(withCursor: self.proxy.iterator(), withDispatcher: self.dispatcher)
}
}
}
| 46.623377 | 119 | 0.653482 |
4bf3ce36d9e20f4fb7788deffe754eca44dc82d8 | 216 | import Foundation
@testable import githubuser
enum MockResult {
case success
case failure(error: ServiceError)
case failureUnknowError(error: MockError)
}
enum MockError: Error {
case unknowError
}
| 16.615385 | 45 | 0.75 |
f8bed1e2716ade79230ffa75208000c8b7cf15a5 | 4,672 | //
// JSONAPIError.swift
// Kakapo
//
// Created by Alex Manzella on 08/07/16.
// Copyright © 2016 devlucky. All rights reserved.
//
import Foundation
/// A convenience error object that conform to JSON API
public struct JSONAPIError: ResponseFieldsProvider {
/// An object containing references to the source of the error, optionally including any of the following members
public struct Source: Serializable {
/// A JSON `Pointer` ([RFC6901](https://tools.ietf.org/html/rfc6901)) to the associated entity in the request document [e.g. `/data` for a primary data object, or `/data/attributes/title` for a specific attribute].
public let pointer: String?
/// A string indicating which URI query parameter caused the error.
public let parameter: String?
/**
Initialize `Source` with the given parameters
- parameter pointer: A JSON `Pointer` ([RFC6901](https://tools.ietf.org/html/rfc6901)) to the associated entity in the request document [e.g. `/data` for a primary data object, or `/data/attributes/title` for a specific attribute].
- parameter parameter: A string indicating which URI query parameter caused the error.
- returns: An initialized `Source` representing the source of the `JSONAPIError`.
*/
public init(pointer: String?, parameter: String?) {
self.pointer = pointer
self.parameter = parameter
}
}
/// A builder for JSONAPIError
public class Builder: Serializable {
/// A unique identifier for this particular occurrence of the problem.
public var id: String?
/// A link object that leads to further details about this particular occurrence of the problem.
public var about: JSONAPILink?
/// The HTTP status code applicable to this problem, expressed as a string value.
public var status: Int
/// An application-specific error code, expressed as a string value
public var code: String?
/// A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization
public var title: String?
/// A human-readable explanation specific to this occurrence of the problem. Like title, this field’s value can be localized.
public var detail: String?
/**
An object containing references to the source of the error, optionally including any of the following members:
- pointer: a JSON `Pointer` ([RFC6901](https://tools.ietf.org/html/rfc6901)) to the associated entity in the request document [e.g. `/data` for a primary data object, or `/data/attributes/title` for a specific attribute].
- parameter: a string indicating which URI query parameter caused the error.
*/
public var source: Source?
/// A meta object containing non-standard meta-information about the error.
public var meta: Serializable?
fileprivate init(statusCode: Int) {
status = statusCode
}
}
private let builder: Builder
// MARK: ResponseFieldsProvider
/// The status code that will be used to affect the HTTP request status code.
public var statusCode: Int {
return builder.status
}
/// A `JSONAPIError.Builder` instance contains all the fields.
public var body: Serializable {
return builder
}
/// The headerFields that will be returned by the HTTP response.
public let headerFields: [String : String]?
public let error: Error?
/**
Initialize a `JSONAPIError` and build it with `JSONAPIError.Builder`
- parameter statusCode: The status code of the response, will be used also to provide a statusCode for your request
- parameter headerFields: The headerFields that will be returned by the HTTP response.
- parameter errorBuilder: A builder that can be used to fill the error objects, it contains all you need to provide an error object confiorming to JSON API (**see `JSONAPIError.Builder`**)
- returns: An error that conforms to JSON API specifications and it's ready to be serialized
*/
public init(statusCode: Int, headerFields: [String: String]? = nil, errorBuilder: (_ error: Builder) -> ()) {
let builder = Builder(statusCode: statusCode)
errorBuilder(builder)
self.builder = builder
self.headerFields = headerFields
self.error = nil
}
}
| 42.472727 | 242 | 0.659247 |
e2dd7c6e2a114c7262a445ed0dabf6ee927c90ff | 637 | //
// GIDSignInViewController.swift
// GmailDemo
//
// Created by 41nyaa on 2021/10/16.
//
import UIKit
import GoogleSignIn
class GIDSignInViewController: UIViewController {
var signInMgr: GIDSignInManager?
override func viewDidLoad() {
let button = GIDSignInButton()
button.addTarget(self, action: #selector(login), for: .touchUpInside)
view.bounds = CGRect(x: 0, y: 0, width: 100, height: 10)
view.addSubview(button)
}
@objc func login() {
guard let signInMgr = signInMgr else {
return
}
signInMgr.signIn(viewController: self)
}
}
| 21.965517 | 77 | 0.631083 |
1d5423b0a33a7445497be9f9f869842e3398ee56 | 15,470 | import Foundation
import UIKit
///
/// MacawView is a main class used to embed Macaw scene into your Cocoa UI.
/// You could create your own view extended from MacawView with predefined scene.
///
open class MacawView: UIView, UIGestureRecognizerDelegate {
/// Scene root node
open var node: Node = Group() {
willSet {
nodesMap.remove(node)
}
didSet {
nodesMap.add(node, view: self)
self.renderer?.dispose()
if let cache = animationCache {
self.renderer = RenderUtils.createNodeRenderer(node, context: context, animationCache: cache)
}
if let _ = superview {
animationProducer.addStoredAnimations(node)
}
self.setNeedsDisplay()
}
}
override open var frame: CGRect {
didSet {
super.frame = frame
frameSetFirstTime = true
guard let _ = superview else {
return
}
animationProducer.addStoredAnimations(node)
}
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
if !frameSetFirstTime {
return
}
animationProducer.addStoredAnimations(node)
}
var touchesMap = [UITouch: [Node]]()
var touchesOfNode = [Node: [UITouch]]()
var recognizersMap = [UIGestureRecognizer: [Node]]()
var context: RenderContext!
var renderer: NodeRenderer?
var toRender = true
var frameSetFirstTime = false
internal var animationCache: AnimationCache?
public init?(node: Node, coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeView()
self.node = node
nodesMap.add(node, view: self)
if let cache = self.animationCache {
self.renderer = RenderUtils.createNodeRenderer(node, context: context, animationCache: cache)
}
}
public convenience init(node: Node, frame: CGRect) {
self.init(frame:frame)
self.node = node
nodesMap.add(node, view: self)
if let cache = self.animationCache {
self.renderer = RenderUtils.createNodeRenderer(node, context: context, animationCache: cache)
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
initializeView()
}
public convenience required init?(coder aDecoder: NSCoder) {
self.init(node: Group(), coder: aDecoder)
}
fileprivate func initializeView() {
self.context = RenderContext(view: self)
self.animationCache = AnimationCache(sceneLayer: self.layer)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MacawView.handleTap))
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(MacawView.handlePan))
let rotationRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(MacawView.handleRotation))
let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(MacawView.handlePinch))
tapRecognizer.delegate = self
panRecognizer.delegate = self
rotationRecognizer.delegate = self
pinchRecognizer.delegate = self
tapRecognizer.cancelsTouchesInView = false
panRecognizer.cancelsTouchesInView = false
rotationRecognizer.cancelsTouchesInView = false
pinchRecognizer.cancelsTouchesInView = false
self.addGestureRecognizer(tapRecognizer)
self.addGestureRecognizer(panRecognizer)
self.addGestureRecognizer(rotationRecognizer)
self.addGestureRecognizer(pinchRecognizer)
}
override open func draw(_ rect: CGRect) {
self.context.cgContext = UIGraphicsGetCurrentContext()
renderer?.render(force: false, opacity: node.opacity)
}
private func localContext( _ callback: (CGContext) -> ()) {
UIGraphicsBeginImageContext(self.bounds.size)
if let ctx = UIGraphicsGetCurrentContext() {
callback(ctx)
}
UIGraphicsEndImageContext()
}
// MARK: - Touches
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if !self.node.shouldCheckForPressed() &&
!self.node.shouldCheckForMoved() &&
!self.node.shouldCheckForReleased (){
return
}
guard let renderer = renderer else {
return
}
for touch in touches {
let location = touch.location(in: self)
var foundNode: Node? = .none
localContext { ctx in
foundNode = renderer.findNodeAt(location: location, ctx: ctx)
}
if let node = foundNode {
if touchesMap[touch] == nil {
touchesMap[touch] = [Node]()
}
let inverted = node.place.invert()!
let loc = location.applying(RenderUtils.mapTransform(inverted))
let id = unsafeBitCast(Unmanaged.passUnretained(touch).toOpaque(), to: Int.self)
let point = TouchPoint(id: id, location: Point(x: Double(loc.x), y: Double(loc.y)))
let touchEvent = TouchEvent(node: node, points: [point])
var parent: Node? = node
while parent != .none {
let currentNode = parent!
if touchesOfNode[currentNode] == nil {
touchesOfNode[currentNode] = [UITouch]()
}
touchesMap[touch]?.append(currentNode)
touchesOfNode[currentNode]?.append(touch)
parent!.handleTouchPressed(touchEvent)
parent = nodesMap.parents(parent!).first
}
}
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if !self.node.shouldCheckForMoved() {
return
}
guard let renderer = renderer else {
return
}
touchesOfNode.keys.forEach { currentNode in
guard let touches = touchesOfNode[currentNode] else {
return
}
var points = [TouchPoint]()
for touch in touches {
let location = touch.location(in: self)
let inverted = currentNode.place.invert()!
let loc = location.applying(RenderUtils.mapTransform(inverted))
let id = unsafeBitCast(Unmanaged.passUnretained(touch).toOpaque(), to: Int.self)
let point = TouchPoint(id: id, location: Point(x: Double(loc.x), y: Double(loc.y)))
points.append(point)
}
let touchEvent = TouchEvent(node: currentNode, points: points)
currentNode.handleTouchMoved(touchEvent)
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesEnded(touches: touches, event: event)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesEnded(touches: touches, event: event)
}
private func touchesEnded(touches: Set<UITouch>, event: UIEvent?) {
guard let renderer = renderer else {
return
}
for touch in touches {
let location = touch.location(in: self)
touchesMap[touch]?.forEach { node in
let inverted = node.place.invert()!
let loc = location.applying(RenderUtils.mapTransform(inverted))
var id = unsafeBitCast(Unmanaged.passUnretained(touch).toOpaque(), to: Int.self)
let point = TouchPoint(id: id, location: Point(x: Double(loc.x), y: Double(loc.y)))
let touchEvent = TouchEvent(node: node, points: [point])
node.handleTouchReleased(touchEvent)
if let index = touchesOfNode[node]?.index(of: touch) {
touchesOfNode[node]?.remove(at: index)
if let count = touchesOfNode[node]?.count, count == 0 {
touchesOfNode.removeValue(forKey: node)
}
}
}
touchesMap.removeValue(forKey: touch)
}
}
// MARK: - Pan
func handleTap(recognizer: UITapGestureRecognizer) {
if !self.node.shouldCheckForTap() {
return
}
guard let renderer = renderer else {
return
}
let location = recognizer.location(in: self)
var foundNodes = [Node]()
localContext { ctx in
guard let foundNode = renderer.findNodeAt(location: location, ctx: ctx) else {
return
}
var parent: Node? = foundNode
while parent != .none {
if parent!.shouldCheckForTap() {
foundNodes.append(parent!)
}
parent = nodesMap.parents(parent!).first
}
}
foundNodes.forEach { node in
let inverted = node.place.invert()!
let loc = location.applying(RenderUtils.mapTransform(inverted))
let event = TapEvent(node: node, location: Point(x: Double(loc.x), y: Double(loc.y)))
node.handleTap(event)
}
}
func handlePan(recognizer: UIPanGestureRecognizer) {
if !self.node.shouldCheckForPan() {
return
}
guard let renderer = renderer else {
return
}
if recognizer.state == .began {
let location = recognizer.location(in: self)
localContext { ctx in
guard let foundNode = renderer.findNodeAt(location: location, ctx: ctx) else {
return
}
if self.recognizersMap[recognizer] == nil {
self.recognizersMap[recognizer] = [Node]()
}
var parent: Node? = foundNode
while parent != .none {
if parent!.shouldCheckForPan() {
self.recognizersMap[recognizer]?.append(parent!)
}
parent = nodesMap.parents(parent!).first
}
}
}
// get the rotation and scale of the shape and apply to the translation
let translation = recognizer.translation(in: self)
recognizer.setTranslation(CGPoint.zero, in: self)
let transform = node.place
let rotation = -CGFloat(atan2f(Float(transform.m12), Float(transform.m11)))
let scale = CGFloat(sqrt(transform.m11 * transform.m11 + transform.m21 * transform.m21))
let translatedLocation = translation.applying(CGAffineTransform(rotationAngle: rotation))
recognizersMap[recognizer]?.forEach { node in
let event = PanEvent(node: node, dx: Double(translatedLocation.x / scale), dy: Double(translatedLocation.y / scale),
count: recognizer.numberOfTouches)
node.handlePan(event)
}
if recognizer.state == .ended || recognizer.state == .cancelled {
recognizersMap.removeValue(forKey: recognizer)
}
}
// MARK: - Rotation
func handleRotation(_ recognizer: UIRotationGestureRecognizer) {
if !self.node.shouldCheckForRotate() {
return
}
guard let renderer = renderer else {
return
}
if recognizer.state == .began {
let location = recognizer.location(in: self)
localContext { ctx in
guard let foundNode = renderer.findNodeAt(location: location, ctx: ctx) else {
return
}
if self.recognizersMap[recognizer] == nil {
self.recognizersMap[recognizer] = [Node]()
}
var parent: Node? = foundNode
while parent != .none {
if parent!.shouldCheckForRotate() {
self.recognizersMap[recognizer]?.append(parent!)
}
parent = nodesMap.parents(parent!).first
}
}
}
let rotation = Double(recognizer.rotation)
recognizer.rotation = 0
recognizersMap[recognizer]?.forEach { node in
let event = RotateEvent(node: node, angle: rotation)
node.handleRotate(event)
}
if recognizer.state == .ended || recognizer.state == .cancelled {
recognizersMap.removeValue(forKey: recognizer)
}
}
// MARK: - Pinch
func handlePinch(_ recognizer: UIPinchGestureRecognizer) {
if !self.node.shouldCheckForPinch() {
return
}
guard let renderer = renderer else {
return
}
if recognizer.state == .began {
let location = recognizer.location(in: self)
localContext { ctx in
guard let foundNode = renderer.findNodeAt(location: location, ctx: ctx) else {
return
}
if self.recognizersMap[recognizer] == nil {
self.recognizersMap[recognizer] = [Node]()
}
var parent: Node? = foundNode
while parent != .none {
if parent!.shouldCheckForPinch() {
self.recognizersMap[recognizer]?.append(parent!)
}
parent = nodesMap.parents(parent!).first
}
}
}
let scale = Double(recognizer.scale)
recognizer.scale = 1
recognizersMap[recognizer]?.forEach { node in
let event = PinchEvent(node: node, scale: scale)
node.handlePinch(event)
}
if recognizer.state == .ended || recognizer.state == .cancelled {
recognizersMap.removeValue(forKey: recognizer)
}
}
deinit {
nodesMap.remove(node)
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 33.412527 | 164 | 0.535553 |
de7d2f37e17efd4a4a8aed9bb2fe26cfc363ea90 | 1,261 | //
// ViewController.swift
// TipCalculator
//
// Created by Nick Pappas on 1/9/19.
// Copyright © 2019 Nick Pappas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
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.
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
override func viewDidAppear(_ animated: Bool) {
billField.becomeFirstResponder()
}
@IBAction func calculateTip(_ sender: Any) {
let tipPercentages = [0.18, 0.2, 0.25]
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 26.829787 | 80 | 0.641554 |
1888d4ed5bd48db67b014e1e47dd369cf3152db3 | 238 | ////
/// ElloCollectionView.swift
//
// Even when this is just an empty class, it can be handy for debugging, i.e.
// override func setContentOffset(_ offset: CGPoint, animated: Bool)
//
class ElloCollectionView: UICollectionView {
}
| 23.8 | 78 | 0.722689 |
69d052e12eeb09fe1b22261832e98ccf872136ca | 279 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
struct WalletNewTransactionInserted: EventProtocol {
func accept(visitor: EventVisitorProtocol) {
visitor.processNewTransaction(event: self)
}
}
| 21.461538 | 52 | 0.738351 |
64774f15bac73bd156c110a1ea204ac10fa4b322 | 947 | //
// PreworkTests.swift
// PreworkTests
//
// Created by Rishi Sheth on 1/24/21.
// Copyright © 2021 Rishi Sheth. All rights reserved.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.057143 | 111 | 0.665259 |
e660744237883c1292dc2ffa3a898ae7d16f225d | 36,763 | //
// CheckoutViewModel.swift
// MercadoPagoSDK
//
// Created by Demian Tejo on 1/23/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import UIKit
internal enum CheckoutStep: String {
case START
case ACTION_FINISH
case SERVICE_GET_IDENTIFICATION_TYPES
case SCREEN_PAYMENT_METHOD_SELECTION
case SCREEN_CARD_FORM
case SCREEN_SECURITY_CODE
case SERVICE_GET_ISSUERS
case SCREEN_ISSUERS
case SERVICE_CREATE_CARD_TOKEN
case SCREEN_IDENTIFICATION
case SCREEN_ENTITY_TYPE
case SCREEN_FINANCIAL_INSTITUTIONS
case SERVICE_GET_PAYER_COSTS
case SCREEN_PAYER_INFO_FLOW
case SCREEN_PAYER_COST
case SCREEN_REVIEW_AND_CONFIRM
case SERVICE_POST_PAYMENT
case SCREEN_PAYMENT_RESULT
case SCREEN_ERROR
case SCREEN_HOOK_BEFORE_PAYMENT_METHOD_CONFIG
case SCREEN_HOOK_AFTER_PAYMENT_METHOD_CONFIG
case SCREEN_HOOK_BEFORE_PAYMENT
case SCREEN_PAYMENT_METHOD_PLUGIN_CONFIG
case FLOW_ONE_TAP
}
internal class MercadoPagoCheckoutViewModel: NSObject, NSCopying {
var hookService: HookService = HookService()
private var advancedConfig: PXAdvancedConfiguration = PXAdvancedConfiguration()
internal var trackingConfig: PXTrackingConfiguration?
internal var publicKey: String
internal var privateKey: String?
var lifecycleProtocol: PXLifeCycleProtocol?
// In order to ensure data updated create new instance for every usage
var amountHelper: PXAmountHelper {
guard let paymentData = self.paymentData.copy() as? PXPaymentData else {
fatalError("Cannot find payment data")
}
return PXAmountHelper(preference: self.checkoutPreference, paymentData: paymentData, chargeRules: self.chargeRules, paymentConfigurationService: self.paymentConfigurationService, splitAccountMoney: splitAccountMoney)
}
var checkoutPreference: PXCheckoutPreference!
let mercadoPagoServicesAdapter: MercadoPagoServicesAdapter
// var paymentMethods: [PaymentMethod]?
var cardToken: PXCardToken?
var customerId: String?
// Payment methods disponibles en selección de medio de pago
var paymentMethodOptions: [PaymentMethodOption]?
var paymentOptionSelected: PaymentMethodOption?
// Payment method disponibles correspondientes a las opciones que se muestran en selección de medio de pago
var availablePaymentMethods: [PXPaymentMethod]?
var rootPaymentMethodOptions: [PaymentMethodOption]?
var customPaymentOptions: [CustomerPaymentMethod]?
var identificationTypes: [PXIdentificationType]?
var search: PXInitDTO?
var rootVC = true
internal var paymentData = PXPaymentData()
internal var splitAccountMoney: PXPaymentData?
var payment: PXPayment?
internal var paymentResult: PaymentResult?
var disabledOption: PXDisabledOption?
var businessResult: PXBusinessResult?
open var payerCosts: [PXPayerCost]?
open var issuers: [PXIssuer]?
open var entityTypes: [EntityType]?
open var financialInstitutions: [PXFinancialInstitution]?
open var instructionsInfo: PXInstructions?
open var pointsAndDiscounts: PXPointsAndDiscounts?
static var error: MPSDKError?
var errorCallback: (() -> Void)?
var readyToPay: Bool = false
var initWithPaymentData = false
var savedESCCardToken: PXSavedESCCardToken?
private var checkoutComplete = false
var paymentMethodConfigPluginShowed = false
var escManager: MercadoPagoESC?
var invalidESC: Bool = false
// Discounts bussines service.
var paymentConfigurationService = PXPaymentConfigurationServices()
// Plugins payment method.
var paymentMethodPlugins = [PXPaymentMethodPlugin]()
var paymentMethodPluginsToShow = [PXPaymentMethodPlugin]()
// Payment plugin
var paymentPlugin: PXSplitPaymentProcessor?
var paymentFlow: PXPaymentFlow?
// Discount and charges
var chargeRules: [PXPaymentTypeChargeRule]?
// Init Flow
var initFlow: InitFlow?
weak var initFlowProtocol: InitFlowProtocol?
// OneTap Flow
var onetapFlow: OneTapFlow?
lazy var pxNavigationHandler: PXNavigationHandler = PXNavigationHandler.getDefault()
init(checkoutPreference: PXCheckoutPreference, publicKey: String, privateKey: String?, advancedConfig: PXAdvancedConfiguration? = nil, trackingConfig: PXTrackingConfiguration? = nil) {
self.publicKey = publicKey
self.privateKey = privateKey
self.checkoutPreference = checkoutPreference
if let advancedConfig = advancedConfig {
self.advancedConfig = advancedConfig
}
self.trackingConfig = trackingConfig
//let branchId = checkoutPreference.branchId
mercadoPagoServicesAdapter = MercadoPagoServicesAdapter(publicKey: publicKey, privateKey: privateKey)
super.init()
if !isPreferenceLoaded() {
self.paymentData.payer = self.checkoutPreference.getPayer()
}
// Create Init Flow
createInitFlow()
}
public func copy(with zone: NSZone? = nil) -> Any {
let copyObj = MercadoPagoCheckoutViewModel(checkoutPreference: self.checkoutPreference, publicKey: publicKey, privateKey: privateKey)
copyObj.setNavigationHandler(handler: pxNavigationHandler)
return copyObj
}
func setNavigationHandler(handler: PXNavigationHandler) {
pxNavigationHandler = handler
}
func hasError() -> Bool {
return MercadoPagoCheckoutViewModel.error != nil
}
func applyDefaultDiscountOrClear() {
if let defaultDiscountConfiguration = search?.selectedDiscountConfiguration {
attemptToApplyDiscount(defaultDiscountConfiguration)
} else {
clearDiscount()
}
}
func attemptToApplyDiscount(_ discountConfiguration: PXDiscountConfiguration?) {
guard let discountConfiguration = discountConfiguration else {
clearDiscount()
return
}
guard let campaign = discountConfiguration.getDiscountConfiguration().campaign, shouldApplyDiscount() else {
clearDiscount()
return
}
let discount = discountConfiguration.getDiscountConfiguration().discount
let consumedDiscount = discountConfiguration.getDiscountConfiguration().isNotAvailable
self.paymentData.setDiscount(discount, withCampaign: campaign, consumedDiscount: consumedDiscount)
}
func clearDiscount() {
self.paymentData.clearDiscount()
}
func shouldApplyDiscount() -> Bool {
return paymentPlugin != nil
}
public func getPaymentPreferences() -> PXPaymentPreference? {
return self.checkoutPreference.paymentPreference
}
public func cardFormManager() -> CardFormViewModel {
return CardFormViewModel(paymentMethods: getPaymentMethodsForSelection(), mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, bankDealsEnabled: advancedConfig.bankDealsEnabled)
}
public func getPaymentMethodsForSelection() -> [PXPaymentMethod] {
let filteredPaymentMethods = search?.availablePaymentMethods.filter {
return $0.conformsPaymentPreferences(self.getPaymentPreferences()) && $0.paymentTypeId == self.paymentOptionSelected?.getId()
}
guard let paymentMethods = filteredPaymentMethods else {
return []
}
return paymentMethods
}
func payerInfoFlow() -> PayerInfoViewModel {
let viewModel = PayerInfoViewModel(identificationTypes: self.identificationTypes!, payer: self.paymentData.payer!, amountHelper: amountHelper)
return viewModel
}
func getPluginPaymentMethodToShow() -> [PXPaymentMethodPlugin] {
populateCheckoutStore()
return paymentMethodPlugins.filter { $0.mustShowPaymentMethodPlugin(PXCheckoutStore.sharedInstance) == true }
}
// Returns list with all cards ids with esc
func getCardsIdsWithESC() -> [String] {
var cardIdsWithESC: [String] = []
if let customPaymentOptions = customPaymentOptions {
for customCard in customPaymentOptions {
if escManager?.getESC(cardId: customCard.getCardId(), firstSixDigits: customCard.getFirstSixDigits(), lastFourDigits: customCard.getCardLastForDigits()) != nil {
cardIdsWithESC.append(customCard.getCardId())
}
}
}
return cardIdsWithESC
}
func paymentVaultViewModel() -> PaymentVaultViewModel {
var groupName: String?
if let optionSelected = paymentOptionSelected {
groupName = optionSelected.getId()
}
populateCheckoutStore()
var customerOptions: [CustomerPaymentMethod]?
if inRootGroupSelection() { // Solo se muestran las opciones custom y los plugines en root
customerOptions = self.customPaymentOptions
}
return PaymentVaultViewModel(amountHelper: self.amountHelper, paymentMethodOptions: self.paymentMethodOptions!, customerPaymentOptions: customerOptions, paymentMethods: search?.availablePaymentMethods ?? [], groupName: groupName, isRoot: rootVC, email: self.checkoutPreference.payer.email, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, advancedConfiguration: advancedConfig, disabledOption: disabledOption)
}
public func entityTypeViewModel() -> AdditionalStepViewModel {
return EntityTypeViewModel(amountHelper: self.amountHelper, token: self.cardToken, paymentMethod: self.paymentData.getPaymentMethod()!, dataSource: self.entityTypes!, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, advancedConfiguration: advancedConfig)
}
public func financialInstitutionViewModel() -> AdditionalStepViewModel {
return FinancialInstitutionViewModel(amountHelper: self.amountHelper, token: self.cardToken, paymentMethod: self.paymentData.getPaymentMethod()!, dataSource: self.financialInstitutions!, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, advancedConfiguration: advancedConfig)
}
public func issuerViewModel() -> AdditionalStepViewModel {
guard let paymentMethod = self.paymentData.getPaymentMethod() else {
fatalError("Cannot find payment method")
}
return IssuerAdditionalStepViewModel(amountHelper: self.amountHelper, token: self.cardToken, paymentMethod: paymentMethod, dataSource: self.issuers!, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, advancedConfiguration: advancedConfig)
}
public func payerCostViewModel() -> AdditionalStepViewModel {
guard let paymentMethod = self.paymentData.getPaymentMethod() else {
fatalError("Cannot find payment method")
}
var cardInformation: PXCardInformationForm? = self.cardToken
if cardInformation == nil {
if let token = paymentOptionSelected as? PXCardInformationForm {
cardInformation = token
}
}
return PayerCostAdditionalStepViewModel(amountHelper: self.amountHelper, token: cardInformation, paymentMethod: paymentMethod, dataSource: payerCosts!, email: self.checkoutPreference.payer.email, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, advancedConfiguration: advancedConfig)
}
public func savedCardSecurityCodeViewModel() -> SecurityCodeViewModel {
guard let cardInformation = self.paymentOptionSelected as? PXCardInformation else {
fatalError("Cannot conver payment option selected to CardInformation")
}
var reason: SecurityCodeViewModel.Reason
if paymentResult != nil && paymentResult!.isInvalidESC() || invalidESC {
reason = SecurityCodeViewModel.Reason.INVALID_ESC
} else {
reason = SecurityCodeViewModel.Reason.SAVED_CARD
}
return SecurityCodeViewModel(paymentMethod: self.paymentData.paymentMethod!, cardInfo: cardInformation, reason: reason)
}
public func cloneTokenSecurityCodeViewModel() -> SecurityCodeViewModel {
let cardInformation = self.paymentData.token
let reason = SecurityCodeViewModel.Reason.CALL_FOR_AUTH
return SecurityCodeViewModel(paymentMethod: self.paymentData.paymentMethod!, cardInfo: cardInformation!, reason: reason)
}
func reviewConfirmViewModel() -> PXReviewViewModel {
disableChangePaymentMethodIfNeed()
return PXReviewViewModel(amountHelper: self.amountHelper, paymentOptionSelected: self.paymentOptionSelected!, advancedConfig: advancedConfig, userLogged: !String.isNullOrEmpty(privateKey), escProtocol: self.escManager)
}
func resultViewModel() -> PXResultViewModel {
return PXResultViewModel(amountHelper: self.amountHelper, paymentResult: self.paymentResult!, instructionsInfo: self.instructionsInfo, pointsAndDiscounts: self.pointsAndDiscounts, resultConfiguration: self.advancedConfig.paymentResultConfiguration)
}
//SEARCH_PAYMENT_METHODS
public func updateCheckoutModel(paymentMethods: [PXPaymentMethod], cardToken: PXCardToken?) {
self.cleanPayerCostSearch()
self.cleanIssuerSearch()
self.cleanIdentificationTypesSearch()
self.paymentData.updatePaymentDataWith(paymentMethod: paymentMethods[0])
self.cardToken = cardToken
// Sets if esc is enabled to card token
self.cardToken?.setRequireESC(escEnabled: advancedConfig.escEnabled)
}
//CREDIT_DEBIT
public func updateCheckoutModel(paymentMethod: PXPaymentMethod?) {
if let paymentMethod = paymentMethod {
self.paymentData.updatePaymentDataWith(paymentMethod: paymentMethod)
}
}
public func updateCheckoutModel(financialInstitution: PXFinancialInstitution) {
if let TDs = self.paymentData.transactionDetails {
TDs.financialInstitution = financialInstitution.id
} else {
let transactionDetails = PXTransactionDetails(externalResourceUrl: nil, financialInstitution: financialInstitution.id, installmentAmount: nil, netReivedAmount: nil, overpaidAmount: nil, totalPaidAmount: nil, paymentMethodReferenceId: nil)
self.paymentData.transactionDetails = transactionDetails
}
}
public func updateCheckoutModel(issuer: PXIssuer) {
self.cleanPayerCostSearch()
self.paymentData.updatePaymentDataWith(issuer: issuer)
}
public func updateCheckoutModel(payer: PXPayer) {
self.paymentData.updatePaymentDataWith(payer: payer)
}
public func updateCheckoutModel(identificationTypes: [PXIdentificationType]) {
self.identificationTypes = identificationTypes
}
public func cardFlowSupportedIdentificationTypes() -> [PXIdentificationType]? {
return IdentificationTypeValidator().filterSupported(identificationTypes: self.identificationTypes)
}
public func updateCheckoutModel(identification: PXIdentification) {
self.paymentData.cleanToken()
self.paymentData.cleanIssuer()
self.paymentData.cleanPayerCost()
self.cleanPayerCostSearch()
self.cleanIssuerSearch()
if paymentData.hasPaymentMethod() && paymentData.getPaymentMethod()!.isCard {
self.cardToken!.cardholder!.identification = identification
} else {
paymentData.payer?.identification = identification
}
}
public func updateCheckoutModel(payerCost: PXPayerCost) {
self.paymentData.updatePaymentDataWith(payerCost: payerCost)
if let paymentOptionSelected = paymentOptionSelected {
if paymentOptionSelected.isCustomerPaymentMethod() {
self.paymentData.cleanToken()
}
}
}
public func updateCheckoutModel(entityType: EntityType) {
self.paymentData.payer?.entityType = entityType.entityTypeId
}
// MARK: PAYMENT METHOD OPTION SELECTION
public func updateCheckoutModel(paymentOptionSelected: PaymentMethodOption) {
if !self.initWithPaymentData {
resetInFormationOnNewPaymentMethodOptionSelected()
}
resetPaymentOptionSelectedWith(newPaymentOptionSelected: paymentOptionSelected)
}
public func resetPaymentOptionSelectedWith(newPaymentOptionSelected: PaymentMethodOption) {
self.paymentOptionSelected = newPaymentOptionSelected
if let targetPlugin = paymentOptionSelected as? PXPaymentMethodPlugin {
self.paymentMethodPluginToPaymentMethod(plugin: targetPlugin)
return
}
if newPaymentOptionSelected.hasChildren() {
self.paymentMethodOptions = newPaymentOptionSelected.getChildren()
}
if self.paymentOptionSelected!.isCustomerPaymentMethod() {
self.findAndCompletePaymentMethodFor(paymentMethodId: newPaymentOptionSelected.getId())
} else if !newPaymentOptionSelected.isCard() && !newPaymentOptionSelected.hasChildren() {
self.paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(self.availablePaymentMethods!, paymentMethodId: newPaymentOptionSelected.getId()))
}
}
public func nextStep() -> CheckoutStep {
if needToInitFlow() {
return .START
}
if hasError() {
return .SCREEN_ERROR
}
if shouldExitCheckout() {
return .ACTION_FINISH
}
if shouldShowCongrats() {
return .SCREEN_PAYMENT_RESULT
}
if needOneTapFlow() {
return .FLOW_ONE_TAP
}
if !isPaymentTypeSelected() {
return .SCREEN_PAYMENT_METHOD_SELECTION
}
if shouldShowHook(hookStep: .BEFORE_PAYMENT_METHOD_CONFIG) {
return .SCREEN_HOOK_BEFORE_PAYMENT_METHOD_CONFIG
}
if needToShowPaymentMethodConfigPlugin() {
willShowPaymentMethodConfigPlugin()
return .SCREEN_PAYMENT_METHOD_PLUGIN_CONFIG
}
if shouldShowHook(hookStep: .AFTER_PAYMENT_METHOD_CONFIG) {
return .SCREEN_HOOK_AFTER_PAYMENT_METHOD_CONFIG
}
if shouldShowHook(hookStep: .BEFORE_PAYMENT) {
return .SCREEN_HOOK_BEFORE_PAYMENT
}
if needToCreatePayment() || shouldSkipReviewAndConfirm() {
readyToPay = false
return .SERVICE_POST_PAYMENT
}
if needReviewAndConfirm() {
return .SCREEN_REVIEW_AND_CONFIRM
}
if needCompleteCard() {
return .SCREEN_CARD_FORM
}
if needToGetIdentificationTypes() {
return .SERVICE_GET_IDENTIFICATION_TYPES
}
if needToGetPayerInfo() {
return .SCREEN_PAYER_INFO_FLOW
}
if needGetIdentification() {
return .SCREEN_IDENTIFICATION
}
if needSecurityCode() {
return .SCREEN_SECURITY_CODE
}
if needCreateToken() {
return .SERVICE_CREATE_CARD_TOKEN
}
if needGetEntityTypes() {
return .SCREEN_ENTITY_TYPE
}
if needGetFinancialInstitutions() {
return .SCREEN_FINANCIAL_INSTITUTIONS
}
if needGetIssuers() {
return .SERVICE_GET_ISSUERS
}
if needIssuerSelectionScreen() {
return .SCREEN_ISSUERS
}
if needChosePayerCost() {
return .SERVICE_GET_PAYER_COSTS
}
if needPayerCostSelectionScreen() {
return .SCREEN_PAYER_COST
}
return .ACTION_FINISH
}
fileprivate func autoselectOnlyPaymentMethod() {
guard let search = self.search else {
return
}
var paymentOptionSelected: PaymentMethodOption?
if !Array.isNullOrEmpty(search.groups) && search.groups.count == 1 {
paymentOptionSelected = search.groups.first
} else if !Array.isNullOrEmpty(search.payerPaymentMethods) && search.payerPaymentMethods.count == 1 {
paymentOptionSelected = search.payerPaymentMethods.first
} else if !Array.isNullOrEmpty(paymentMethodPluginsToShow) && paymentMethodPluginsToShow.count == 1 {
paymentOptionSelected = paymentMethodPluginsToShow.first
}
if let paymentOptionSelected = paymentOptionSelected {
self.updateCheckoutModel(paymentOptionSelected: paymentOptionSelected)
}
}
func getPaymentOptionConfigurations(paymentMethodSearch: PXInitDTO) -> Set<PXPaymentMethodConfiguration> {
let discountConfigurationsKeys = paymentMethodSearch.coupons.keys
var configurations = Set<PXPaymentMethodConfiguration>()
for customOption in paymentMethodSearch.payerPaymentMethods {
var paymentOptionConfigurations = [PXPaymentOptionConfiguration]()
for key in discountConfigurationsKeys {
guard let discountConfiguration = paymentMethodSearch.coupons[key], let payerCostConfiguration = customOption.paymentOptions?[key] else {
continue
}
let paymentOptionConfiguration = PXPaymentOptionConfiguration(id: key, discountConfiguration: discountConfiguration, payerCostConfiguration: payerCostConfiguration)
paymentOptionConfigurations.append(paymentOptionConfiguration)
}
let paymentMethodConfiguration = PXPaymentMethodConfiguration(paymentOptionID: customOption.id, discountInfo: customOption.discountInfo, creditsInfo: customOption.comment, paymentOptionsConfigurations: paymentOptionConfigurations, selectedAmountConfiguration: customOption.couponToApply)
configurations.insert(paymentMethodConfiguration)
}
return configurations
}
public func updateCheckoutModel(paymentMethodSearch: PXInitDTO) {
let configurations = getPaymentOptionConfigurations(paymentMethodSearch: paymentMethodSearch)
self.paymentConfigurationService.setConfigurations(configurations)
self.paymentConfigurationService.setDefaultDiscountConfiguration(paymentMethodSearch.selectedDiscountConfiguration)
self.search = paymentMethodSearch
guard let search = self.search else {
return
}
self.rootPaymentMethodOptions = paymentMethodSearch.groups
self.paymentMethodOptions = self.rootPaymentMethodOptions
self.availablePaymentMethods = paymentMethodSearch.availablePaymentMethods
customPaymentOptions?.removeAll()
for pxCustomOptionSearchItem in search.payerPaymentMethods {
let customerPaymentMethod = pxCustomOptionSearchItem.getCustomerPaymentMethod()
customPaymentOptions = Array.safeAppend(customPaymentOptions, customerPaymentMethod)
}
let totalPaymentMethodSearchCount = search.getPaymentOptionsCount()
self.paymentMethodPluginsToShow = getPluginPaymentMethodToShow()
let totalPaymentMethodsToShow = totalPaymentMethodSearchCount + paymentMethodPluginsToShow.count
if totalPaymentMethodsToShow == 0 {
self.errorInputs(error: MPSDKError(message: "Hubo un error".localized, errorDetail: "No se ha podido obtener los métodos de pago con esta preferencia".localized, retry: false), errorCallback: { () in
})
} else if totalPaymentMethodsToShow == 1 {
autoselectOnlyPaymentMethod()
}
// MoneyIn "ChoExpress"
if let defaultPM = getPreferenceDefaultPaymentOption() {
updateCheckoutModel(paymentOptionSelected: defaultPM)
}
}
public func updateCheckoutModel(token: PXToken) {
if !token.cardId.isEmpty {
if let esc = token.esc {
escManager?.saveESC(cardId: token.cardId, esc: esc)
} else {
escManager?.deleteESC(cardId: token.cardId)
}
} else {
if let esc = token.esc {
escManager?.saveESC(firstSixDigits: token.firstSixDigits, lastFourDigits: token.lastFourDigits, esc: esc)
} else {
escManager?.deleteESC(firstSixDigits: token.firstSixDigits, lastFourDigits: token.lastFourDigits)
}
}
self.paymentData.updatePaymentDataWith(token: token)
}
public func updateCheckoutModel(paymentMethodOptions: [PaymentMethodOption]) {
if self.rootPaymentMethodOptions != nil {
self.rootPaymentMethodOptions!.insert(contentsOf: paymentMethodOptions, at: 0)
} else {
self.rootPaymentMethodOptions = paymentMethodOptions
}
self.paymentMethodOptions = self.rootPaymentMethodOptions
}
func updateCheckoutModel(paymentData: PXPaymentData) {
self.paymentData = paymentData
if paymentData.getPaymentMethod() == nil {
prepareForNewSelection()
self.initWithPaymentData = false
} else {
self.readyToPay = !self.needToCompletePayerInfo()
}
}
func needToCompletePayerInfo() -> Bool {
if let paymentMethod = self.paymentData.getPaymentMethod() {
if paymentMethod.isPayerInfoRequired {
return !self.isPayerSetted()
}
}
return false
}
public func updateCheckoutModel(payment: PXPayment) {
self.payment = payment
self.paymentResult = PaymentResult(payment: self.payment!, paymentData: self.paymentData)
}
public func isCheckoutComplete() -> Bool {
return checkoutComplete
}
public func setIsCheckoutComplete(isCheckoutComplete: Bool) {
self.checkoutComplete = isCheckoutComplete
}
internal func findAndCompletePaymentMethodFor(paymentMethodId: String) {
guard let availablePaymentMethods = availablePaymentMethods else {
fatalError("availablePaymentMethods cannot be nil")
}
if paymentMethodId == PXPaymentTypes.ACCOUNT_MONEY.rawValue {
paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: paymentMethodId))
} else if let paymentOptionSelected = paymentOptionSelected as? PXCardInformation {
let cardInformation = paymentOptionSelected
let paymentMethod = Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: cardInformation.getPaymentMethodId())
cardInformation.setupPaymentMethodSettings(paymentMethod.settings)
cardInformation.setupPaymentMethod(paymentMethod)
paymentData.updatePaymentDataWith(paymentMethod: cardInformation.getPaymentMethod())
paymentData.updatePaymentDataWith(issuer: cardInformation.getIssuer())
}
}
func hasCustomPaymentOptions() -> Bool {
return !Array.isNullOrEmpty(self.customPaymentOptions)
}
internal func handleCustomerPaymentMethod() {
guard let availablePaymentMethods = availablePaymentMethods else {
fatalError("availablePaymentMethods cannot be nil")
}
if let paymentMethodId = self.paymentOptionSelected?.getId(), paymentMethodId == PXPaymentTypes.ACCOUNT_MONEY.rawValue {
paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: paymentMethodId))
} else {
// Se necesita completar información faltante de settings y pm para custom payment options
guard let cardInformation = paymentOptionSelected as? PXCardInformation else {
fatalError("Cannot convert paymentOptionSelected to CardInformation")
}
let paymentMethod = Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: cardInformation.getPaymentMethodId())
cardInformation.setupPaymentMethodSettings(paymentMethod.settings)
cardInformation.setupPaymentMethod(paymentMethod)
paymentData.updatePaymentDataWith(paymentMethod: cardInformation.getPaymentMethod())
}
}
func entityTypesFinder(inDict: NSDictionary, forKey: String) -> [EntityType]? {
if let siteETsDictionary = inDict.value(forKey: forKey) as? NSDictionary {
let entityTypesKeys = siteETsDictionary.allKeys
var entityTypes = [EntityType]()
for ET in entityTypesKeys {
let entityType = EntityType()
if let etKey = ET as? String, let etValue = siteETsDictionary.value(forKey: etKey) as? String {
entityType.entityTypeId = etKey
entityType.name = etValue.localized
entityTypes.append(entityType)
}
}
return entityTypes
}
return nil
}
func getEntityTypes() -> [EntityType] {
let dictET = ResourceManager.shared.getDictionaryForResource(named: "EntityTypes")
let site = SiteManager.shared.getSiteId()
if let siteETs = entityTypesFinder(inDict: dictET!, forKey: site) {
return siteETs
} else {
let siteETs = entityTypesFinder(inDict: dictET!, forKey: "default")
return siteETs!
}
}
func errorInputs(error: MPSDKError, errorCallback: (() -> Void)?) {
MercadoPagoCheckoutViewModel.error = error
self.errorCallback = errorCallback
}
func saveOrDeleteESC() -> Bool {
guard let token = paymentData.getToken() else {
return false
}
var isApprovedPayment: Bool = true
if self.paymentResult != nil {
isApprovedPayment = self.paymentResult!.isApproved()
} else if self.businessResult != nil {
isApprovedPayment = self.businessResult!.isApproved()
} else {
return false
}
if token.hasCardId() {
if !isApprovedPayment {
escManager?.deleteESC(cardId: token.cardId)
return false
}
}
return false
}
func populateCheckoutStore() {
PXCheckoutStore.sharedInstance.paymentDatas = [self.paymentData]
if let splitAccountMoney = amountHelper.splitAccountMoney {
PXCheckoutStore.sharedInstance.paymentDatas.append(splitAccountMoney)
}
PXCheckoutStore.sharedInstance.checkoutPreference = self.checkoutPreference
}
func isPreferenceLoaded() -> Bool {
return !String.isNullOrEmpty(self.checkoutPreference.id)
}
func getResult() -> PXResult? {
if let ourPayment = payment {
return ourPayment
} else {
return getGenericPayment()
}
}
func getGenericPayment() -> PXGenericPayment? {
if let paymentResponse = paymentResult {
return PXGenericPayment(status: paymentResponse.status, statusDetail: paymentResponse.statusDetail, paymentId: paymentResponse.paymentId)
} else if let businessResultResponse = businessResult {
return PXGenericPayment(status: businessResultResponse.paymentStatus, statusDetail: businessResultResponse.paymentStatusDetail, paymentId: businessResultResponse.getReceiptId())
}
return nil
}
func getOurPayment() -> PXPayment? {
return payment
}
}
extension MercadoPagoCheckoutViewModel {
func resetGroupSelection() {
self.paymentOptionSelected = nil
guard let search = self.search else {
return
}
self.updateCheckoutModel(paymentMethodSearch: search)
}
func resetInFormationOnNewPaymentMethodOptionSelected() {
resetInformation()
hookService.resetHooksToShow()
}
func resetInformation() {
self.clearCollectedData()
self.cardToken = nil
self.entityTypes = nil
self.financialInstitutions = nil
cleanPayerCostSearch()
cleanIssuerSearch()
cleanIdentificationTypesSearch()
resetPaymentMethodConfigPlugin()
}
func clearCollectedData() {
self.paymentData.clearPaymentMethodData()
self.paymentData.clearPayerData()
// Se setea nuevamente el payer que tenemos en la preferencia para no perder los datos
self.paymentData.payer = self.checkoutPreference.payer
}
func isPayerSetted() -> Bool {
if let payerData = self.paymentData.getPayer(),
let payerIdentification = payerData.identification,
let type = payerIdentification.type,
let boletoType = BoletoType(rawValue: type) {
//cpf type requires first name and last name to be a valid payer
let cpfCase = payerData.firstName != nil && payerData.lastName != nil && boletoType == .cpf
//cnpj type requires legal name to be a valid payer
let cnpjCase = payerData.legalName != nil && boletoType == .cnpj
let validDetail = cpfCase || cnpjCase
// identification value is required for both scenarios
let validIdentification = payerIdentification.number != nil
let validPayer = validDetail && validIdentification
return validPayer
}
return false
}
func cleanPayerCostSearch() {
self.payerCosts = nil
}
func cleanIssuerSearch() {
self.issuers = nil
}
func cleanIdentificationTypesSearch() {
self.identificationTypes = nil
}
func cleanPaymentResult() {
self.payment = nil
self.paymentResult = nil
self.readyToPay = false
self.setIsCheckoutComplete(isCheckoutComplete: false)
self.paymentFlow?.cleanPayment()
}
func prepareForClone() {
self.setIsCheckoutComplete(isCheckoutComplete: false)
self.cleanPaymentResult()
self.wentBackFrom(hook: .BEFORE_PAYMENT)
}
func prepareForNewSelection() {
self.setIsCheckoutComplete(isCheckoutComplete: false)
self.keepDisabledOptionIfNeeded()
self.cleanPaymentResult()
self.resetInformation()
self.resetGroupSelection()
self.applyDefaultDiscountOrClear()
self.rootVC = true
hookService.resetHooksToShow()
}
func prepareForInvalidPaymentWithESC() {
if self.paymentData.isComplete() {
readyToPay = true
self.savedESCCardToken = PXSavedESCCardToken(cardId: self.paymentData.getToken()!.cardId, esc: nil, requireESC: advancedConfig.escEnabled)
escManager?.deleteESC(cardId: self.paymentData.getToken()!.cardId)
}
self.paymentData.cleanToken()
}
static internal func clearEnviroment() {
MercadoPagoCheckoutViewModel.error = nil
}
func inRootGroupSelection() -> Bool {
guard let root = rootPaymentMethodOptions, let actual = paymentMethodOptions else {
return true
}
if let hashableSet = NSSet(array: actual) as? Set<AnyHashable> {
return NSSet(array: root).isEqual(to: hashableSet)
}
return true
}
}
// MARK: Advanced Config
extension MercadoPagoCheckoutViewModel {
func getAdvancedConfiguration() -> PXAdvancedConfiguration {
return advancedConfig
}
private func disableChangePaymentMethodIfNeed() {
if let pmSearch = search, let firsPm = pmSearch.availablePaymentMethods.first {
if pmSearch.getPaymentOptionsCount() + paymentMethodPluginsToShow.count == 1 && !firsPm.isCard {
advancedConfig.reviewConfirmConfiguration.disableChangeMethodOption()
}
} else {
advancedConfig.reviewConfirmConfiguration.disableChangeMethodOption()
}
}
}
// MARK: Payment Flow
extension MercadoPagoCheckoutViewModel {
func createPaymentFlow(paymentErrorHandler: PXPaymentErrorHandlerProtocol) -> PXPaymentFlow {
guard let paymentFlow = paymentFlow else {
let paymentFlow = PXPaymentFlow(paymentPlugin: paymentPlugin, mercadoPagoServicesAdapter: mercadoPagoServicesAdapter, paymentErrorHandler: paymentErrorHandler, navigationHandler: pxNavigationHandler, amountHelper: amountHelper, checkoutPreference: checkoutPreference, escManager: escManager)
if let productId = advancedConfig.productId {
paymentFlow.setProductIdForPayment(productId)
}
self.paymentFlow = paymentFlow
return paymentFlow
}
paymentFlow.model.amountHelper = amountHelper
paymentFlow.model.checkoutPreference = checkoutPreference
return paymentFlow
}
}
extension MercadoPagoCheckoutViewModel {
func keepDisabledOptionIfNeeded() {
disabledOption = PXDisabledOption(paymentResult: self.paymentResult)
}
func clean() {
paymentFlow = nil
initFlow = nil
onetapFlow = nil
}
}
| 40.443344 | 424 | 0.697114 |
abe0346a88b40a052d219bfd67bbddd032d25ac6 | 1,641 | //
// Curve.swift
// SwiftECC
//
// Created by Leif Ibsen on 18/02/2020.
//
///
/// Built-in elliptic curves
///
public enum ECCurve: CaseIterable {
/// brainpoolP160r1 curve
case BP160r1
/// brainpoolP160t1 curve
case BP160t1
/// brainpoolP192r1 curve
case BP192r1
/// brainpoolP192t1 curve
case BP192t1
/// brainpoolP224r1 curve
case BP224r1
/// brainpoolP224t1 curve
case BP224t1
/// brainpoolP256r1 curve
case BP256r1
/// brainpoolP256t1 curve
case BP256t1
/// brainpoolP320r1 curve
case BP320r1
/// brainpoolP320t1 curve
case BP320t1
/// brainpoolP384r1 curve
case BP384r1
/// brainpoolP384t1 curve
case BP384t1
/// brainpoolP512r1 curve
case BP512r1
/// brainpoolP512t1 curve
case BP512t1
/// NIST sect163k1 curve
case EC163k1
/// NIST sect163r2 curve
case EC163r2
/// NIST sect192k1 curve
case EC192k1
/// NIST sect192r1 curve
case EC192r1
/// NIST sect224k1 curve
case EC224k1
/// NIST sect224r1 curve
case EC224r1
/// NIST sect233k1 curve
case EC233k1
/// NIST sect233r1 curve
case EC233r1
/// NIST sect256k1 curve
case EC256k1
/// NIST sect256r1 curve
case EC256r1
/// NIST sect283k1 curve
case EC283k1
/// NIST sect283r1 curve
case EC283r1
/// NIST sect384r1 curve
case EC384r1
/// NIST sect409k1 curve
case EC409k1
/// NIST sect409r1 curve
case EC409r1
/// NIST sect521r1 curve
case EC521r1
/// NIST sect571k1 curve
case EC571k1
/// NIST sect571r1 curve
case EC571r1
}
| 21.311688 | 40 | 0.641073 |
f4b60c2cffc3b6e4a7b282835b66528c31ae3462 | 2,244 | //
// MyLovcationViewController.swift
// Yanolja
//
// Created by Chunsu Kim on 06/07/2019.
// Copyright © 2019 Chunsu Kim. All rights reserved.
//
import UIKit
class MyLocationViewController: UIViewController {
var topNaviView = TopNaviView()
var listCollectionView = ListCollectionView()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
configureViewComponents()
}
private func configureViewComponents() {
view.addSubview(topNaviView)
view.addSubview(listCollectionView)
listCollectionView.menuTitles = listMenuTitles
listCollectionView.customMenuBar.menuCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally)
topNaviView.delegate = self
topNaviView.translatesAutoresizingMaskIntoConstraints = false
listCollectionView.translatesAutoresizingMaskIntoConstraints = false
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
topNaviView.topAnchor.constraint(equalTo: guide.topAnchor),
topNaviView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
topNaviView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
listCollectionView.topAnchor.constraint(equalTo: topNaviView.bottomAnchor),
listCollectionView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
listCollectionView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
listCollectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
])
}
}
extension MyLocationViewController: checkBoxDelegate {
func possibleChkButton() {
if topNaviView.possibleChkButton.isSelected == false {
topNaviView.possibleChkButton.isSelected = true
} else {
topNaviView.possibleChkButton.isSelected = false
}
}
func searchButton() {
let vc = SearchController()
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)
}
}
| 33.492537 | 161 | 0.689394 |
f4b6739e1a0265b0751b0859e29d31e9067827f1 | 4,974 | //
// BehaviorSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a value that changes over time.
///
/// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
public final class BehaviorSubject<Element>: Observable<Element>, SubjectType, ObserverType, SynchronizedUnsubscribeType, Cancelable {
public typealias SubjectObserverType = BehaviorSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let value = self._observers.count > 0
self._lock.unlock()
return value
}
let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _element: Element
private var _observers = Observers()
private var _stoppedEvent: Event<Element>?
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
/// Indicates whether the subject has been disposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// Initializes a new instance of the subject that caches its last value and starts with the specified value.
///
/// - parameter value: Initial value sent to observers when no other value has been received by the subject yet.
public init(value: Element) {
self._element = value
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
/// Gets the current value or throws an error.
///
/// - returns: Latest value.
public func value() throws -> Element {
self._lock.lock(); defer { self._lock.unlock() } // {
if self._isDisposed {
throw RxError.disposed(object: self)
}
if let error = self._stoppedEvent?.error {
// intentionally throw exception
throw error
} else {
return self._element
}
//}
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<Element>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
if self._stoppedEvent != nil || self._isDisposed {
return Observers()
}
switch event {
case .next(let element):
self._element = element
case .error, .completed:
self._stoppedEvent = event
}
return self._observers
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
let key = self._observers.insert(observer.on)
observer.on(.next(self._element))
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if self._isDisposed {
return
}
_ = self._observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> BehaviorSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
self._lock.lock()
self._isDisposed = true
self._observers.removeAll()
self._stoppedEvent = nil
self._lock.unlock()
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
| 30.89441 | 134 | 0.633293 |
e92f43a856e16ea1ba8ac4b2abf3cc594010b6a9 | 3,110 | //
// TestRegex.swift
// BebopLib
//
// Copyright 2020 Bebop Authors
// Licensed under MIT (https://github.com/johnfairh/Bebop/blob/master/LICENSE)
//
import XCTest
@testable import BebopLib
class TestRegex: XCTestCase {
func testSplitNone() {
let str = "123"
XCTAssertEqual(["123"], str.re_split(","))
let str2 = ""
XCTAssertEqual([], str2.re_split(","))
}
func testSplit() {
let str = "1,2,3"
XCTAssertEqual(["1", "2", "3"], str.re_split(","))
}
func testSplitEnds() {
let str = "1,2,"
XCTAssertEqual(["1", "2"], str.re_split(","))
let str2 = ",1,2"
XCTAssertEqual(["1", "2"], str2.re_split(","))
let str3 = ",1,2,"
XCTAssertEqual(["1", "2"], str3.re_split(","))
}
func testSplitEmpty() {
let str = "foo,,bar"
XCTAssertEqual(["foo", "bar"], str.re_split(","))
let str2 = ",,"
XCTAssertEqual([], str2.re_split(","))
}
func testSplitOptions() {
let str = "foobarFOObar"
XCTAssertEqual(["barFOObar"], str.re_split("foo"))
XCTAssertEqual(["bar", "bar"], str.re_split("foo", options: .i))
}
func testSub() {
let str = "foofoo"
XCTAssertEqual(str, str.re_sub("boo", with: "baa"))
XCTAssertEqual("booboo", str.re_sub("f", with: "b"))
XCTAssertEqual("foofoofoofoo", str.re_sub("foo", with: "$0$0"))
}
func testIsMatch() {
let str = "cookie"
XCTAssertTrue(str.re_isMatch("ook"))
XCTAssertTrue(str.re_isMatch("ook"))
XCTAssertTrue(str.re_isMatch("ie$"))
XCTAssertTrue(!str.re_isMatch("COOK"))
XCTAssertTrue(str.re_isMatch("COOK", options: .i))
}
func testMatchGroups() {
let str = "Fish or beef"
guard let matches = str.re_match(#"(.sh)(?: )(?<join>\w\w)\s"#) else {
XCTFail("No match")
return
}
XCTAssertEqual("ish or ", matches[0])
XCTAssertEqual("or", matches["join"])
}
func testMultiMatch() {
let str = "Fish or FISH"
let matches = str.re_matches("fish", options: .i)
XCTAssertEqual(2, matches.count)
XCTAssertEqual("Fish", matches[0][0])
XCTAssertEqual("FISH", matches[1][0])
}
func testCheck() {
initResources()
AssertThrows(try "a(".re_check(), .errCfgRegexp)
}
func testInteractiveSub() {
let str = "abc"
XCTAssertEqual("aBc", str.re_sub("b", replacer: { _ in "B"}))
XCTAssertEqual("BBB", str.re_sub(".", replacer: { _ in "B"}))
}
func testEscaped() {
XCTAssertEqual(#"\*"#, "*".re_escapedPattern)
}
func testOptionalMatch() {
let imgRe = #"^(.*?)\|(\d+)x(\d+)(?:,(\d+)%)?$"#
guard let match = "abc|123x456,20%".re_match(imgRe) else {
XCTFail()
return
}
XCTAssertEqual("20", match[4])
guard let match2 = "abc|123x456".re_match(imgRe) else {
XCTFail()
return
}
XCTAssertEqual("", match2[4])
}
}
| 27.043478 | 79 | 0.533119 |
56e5fab7831f627da272f30092d7e5a185f3b09b | 2,990 | //
// PacketTunnelProvider.swift
// EduVPNTunnelExtension-macOS
//
import TunnelKit
import NetworkExtension
#if os(macOS)
enum PacketTunnelProviderError: Error {
case connectionAttemptFromOSNotAllowed
}
#endif
class PacketTunnelProvider: OpenVPNTunnelProvider {
#if os(macOS)
override var reasserting: Bool {
didSet {
if reasserting {
if let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol {
if tunnelProtocol.shouldPreventAutomaticConnections {
stopTunnel(with: .none, completionHandler: {})
}
}
}
}
}
override func startTunnel(options: [String: NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {
let startTunnelOptions = StartTunnelOptions(options: options ?? [:])
if !startTunnelOptions.isStartedByApp {
if let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol {
if tunnelProtocol.shouldPreventAutomaticConnections {
Darwin.sleep(3) // Prevent rapid connect-disconnect cycles
completionHandler(PacketTunnelProviderError.connectionAttemptFromOSNotAllowed)
return
}
}
}
super.startTunnel(options: options, completionHandler: completionHandler)
}
#endif
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
// Convert TunnelKit's response to our response
guard messageData.count == 1, let code = TunnelMessageCode(rawValue: messageData[0]) else {
completionHandler?(nil)
return
}
let encoder = JSONEncoder()
switch code {
case .getTransferredByteCount:
super.handleAppMessage(
OpenVPNTunnelProvider.Message.dataCount.data,
completionHandler: completionHandler)
case .getNetworkAddresses:
super.handleAppMessage(OpenVPNTunnelProvider.Message.serverConfiguration.data) { data in
guard let data = data else {
completionHandler?(nil)
return
}
var addresses: [String] = []
if let config = try? JSONDecoder().decode(OpenVPN.Configuration.self, from: data) {
if let ipv4Address = config.ipv4?.address {
addresses.append(ipv4Address)
}
if let ipv6Address = config.ipv6?.address {
addresses.append(ipv6Address)
}
}
completionHandler?(try? encoder.encode(addresses))
}
case .getLog:
super.handleAppMessage(
OpenVPNTunnelProvider.Message.requestLog.data,
completionHandler: completionHandler)
}
}
}
| 36.024096 | 114 | 0.58796 |
ff34cf658b485785d71cd244d9c0c5eda3d54333 | 2,249 | //
// TableViewDeleteable.swift
// Flix
//
// Created by DianQK on 22/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
public protocol _TableViewDeleteable {
func _tableView(_ tableView: UITableView, itemDeletedForRowAt indexPath: IndexPath, node: _Node)
func _tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath, node: _Node) -> String?
}
public protocol TableViewDeleteable: TableViewEditable, _TableViewDeleteable {
func tableView(_ tableView: UITableView, itemDeletedForRowAt indexPath: IndexPath, value: Value)
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath, value: Value) -> String?
}
extension TableViewDeleteable where Self: TableViewMultiNodeProvider {
public func tableView(_ tableView: UITableView, itemDeletedForRowAt indexPath: IndexPath, value: Self.Value) { }
public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath, value: Self.Value) -> String? {
return nil
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath, value: Self.Value) -> UITableViewCell.EditingStyle {
return .delete
}
public func _tableView(_ tableView: UITableView, itemDeletedForRowAt indexPath: IndexPath, node: _Node) {
self.tableView(tableView, itemDeletedForRowAt: indexPath, value: node._unwarp())
self.event._itemDeleted.onNext((tableView: tableView, indexPath: indexPath, value: node._unwarp()))
}
public func _tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath, node: _Node) -> String? {
return self.tableView(tableView, titleForDeleteConfirmationButtonForRowAt: indexPath, value: node._unwarp())
}
}
extension TableViewEvent where Provider: TableViewDeleteable {
public var modelDeleted: ControlEvent<Value> {
return ControlEvent(events: self._itemDeleted.map { $0.value })
}
public var itemDeleted: ControlEvent<EventValue> {
return ControlEvent(events: self._itemDeleted)
}
}
| 36.868852 | 147 | 0.748333 |
69a8e26d8913659f86f50d6f58aed32501177adb | 536 | //
// UIViewController.swift
// Zakkuri
//
// Created by mironal on 2019/10/11.
// Copyright © 2019 mironal. All rights reserved.
//
import UIKit
extension UIViewController {
private static func loadFromStoryboard<T>(withClass name: T.Type) -> T? where T: UIViewController {
let sb = UIStoryboard(name: String(describing: name), bundle: .main)
return sb.instantiateInitialViewController()
}
static func instantiateFromStoryboard() -> Self? {
return loadFromStoryboard(withClass: self)
}
}
| 25.52381 | 103 | 0.692164 |
e8ebcdddbcfe8b34b01da7ca678b44109016a2a0 | 1,192 | import Toml
import FootlessParser
public typealias PluginConfig = Plugin
public struct Plugin {
private let global: Toml
private let plugin: Toml?
public init(global: Toml, plugin: Toml? = nil) {
self.global = global
self.plugin = plugin
}
public var name: String? {
return get(.name)
}
public var cycleInterval: Double {
return get(.cycleInterval, 10.0)
}
public var isEnabled: Bool {
return get(.enabled, true)
}
public var fontFamily: String? {
return get(.fontFamily)
}
public var fontSize: Int? {
return get(.fontSize)
}
public var args: [String] {
return get(.args, [])
}
public var env: [String: String] {
switch (plugin?.get(.env), global.get(.env)) {
case let (.some(pEnv), .some(gEnv)):
return gEnv + pEnv
case let (.none, .some(gEnv)):
return gEnv
case let (.some(pEnv), .none):
return pEnv
default:
return [:]
}
}
private func get<In, Out>(_ param: Param<In, Out>, _ otherwise: Out) -> Out {
return get(param) ?? otherwise
}
private func get<In, Out>(_ param: Param<In, Out>) -> Out? {
return plugin?.get(param) ?? global.get(param)
}
}
| 20.20339 | 79 | 0.615772 |
90a3d85799de6fe13e49b46dadb5a5423e949264 | 544 | //
// Config.swift
// Whitelabel
//
// Created by Martin Eberl on 10.06.17.
// Copyright © 2017 Martin Eberl. All rights reserved.
//
import Foundation
final class Config {
static var configDictionary: [String: Any]? {
return Bundle.main.infoDictionary?["CONFIG"] as? [String: Any]
}
static var primaryAppColorHex: String? {
return configDictionary?["PRIMARY_APP_COLOR"] as? String
}
static var apiBasePath: String? {
return configDictionary?["API_BASE_PATH"] as? String
}
}
| 21.76 | 70 | 0.647059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.