//
//  ImageCacheTests.swift
//  ImageCacheTests
//
//  Created by Julian Grosshauser on 26/06/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import XCTest
import ImageCache

class ImageCacheTests: XCTestCase {

    override func setUp() {
        super.setUp()
    }

    func testDiskCachePathGetsCorrectlySet() {
        let identifier = "TestImageCache"
        let imageCache = ImageCache(identifier: identifier)

        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let cachePath = paths.first!
        let diskCachePath: String

        if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier {
            diskCachePath = cachePath.stringByAppendingPathComponent("\(bundleIdentifier).\(identifier)")
        } else {
            diskCachePath = cachePath.stringByAppendingPathComponent("DiskCache.\(identifier)")
        }

        XCTAssertEqual(diskCachePath, imageCache.diskCachePath, "diskCachePath wasn't correctly set")
    }
}

Make image cache and it's identifier global

//
//  ImageCacheTests.swift
//  ImageCacheTests
//
//  Created by Julian Grosshauser on 26/06/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import XCTest
import ImageCache

let imageCacheIdentifier = "TestImageCache"
let imageCache = ImageCache(identifier: imageCacheIdentifier)

class ImageCacheTests: XCTestCase {

    override func setUp() {
        super.setUp()
    }

    func testDiskCachePathGetsCorrectlySet() {
        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let cachePath = paths.first!
        let diskCachePath: String

        if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier {
            diskCachePath = cachePath.stringByAppendingPathComponent("\(bundleIdentifier).\(imageCacheIdentifier)")
        } else {
            diskCachePath = cachePath.stringByAppendingPathComponent("DiskCache.\(imageCacheIdentifier)")
        }

        XCTAssertEqual(diskCachePath, imageCache.diskCachePath, "diskCachePath wasn't correctly set")
    }
}


//
// UIImage+.swift
// MyKit
//
// Created by Hai Nguyen on 12/26/16.
// Copyright (c) 2016 Hai Nguyen.
//

import UIKit

public extension UIImage {

    static func render(_ attributedString: NSAttributedString) -> UIImage? {
        let size = attributedString.size()
        let image: UIImage?

        UIGraphicsBeginImageContext(size)
        attributedString.draw(in: .init(origin: .zero, size: size))
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

Fix the issue of rendering pixelated images

//
// UIImage+.swift
// MyKit
//
// Created by Hai Nguyen on 12/26/16.
// Copyright (c) 2016 Hai Nguyen.
//

import UIKit

public extension UIImage {

    static func render(_ attributedString: NSAttributedString) -> UIImage? {
        let size = attributedString.size()
        let image: UIImage?

        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        attributedString.draw(in: .init(origin: .zero, size: size))
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}


//  Copyright © 2015 Rob Rix. All rights reserved.

final class ListTests: XCTestCase {
	func testListTypechecksAsAHigherOrderType() {
		let kind = Expression<Term>.Variable("List").typecheck(context)
		assert(kind.left, ==, nil)
		assert(kind.right, ==, Expression<Term>.lambda(.Type(0), const(.Type(0))))
	}

	func testEmptyListEliminatesWithSecondArgumentToUncons() {
		let eliminated = uncons[Term(.UnitType), Term(.BooleanType), Term.lambda(Term(.UnitType), const(Term.lambda(List[Term(.UnitType)], const(Term(false))))), Term.lambda(Term(.UnitType), const(Term(true))), empty]
		assert(eliminated.out.evaluate(environment), ==, true)
	}
}

private let context = Expression<Term>.list.context
private let environment = Expression<Term>.list.environment

private let List = Term("List")
private let uncons = Term("uncons")
private let empty = Term("[]")

import Assertions
@testable import Manifold
import Prelude
import XCTest

Test elimination of unary lists.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class ListTests: XCTestCase {
	func testListTypechecksAsAHigherOrderType() {
		let kind = Expression<Term>.Variable("List").typecheck(context)
		assert(kind.left, ==, nil)
		assert(kind.right, ==, Expression<Term>.lambda(.Type(0), const(.Type(0))))
	}

	func testEmptyListEliminatesWithSecondArgumentToUncons() {
		let eliminated = uncons[Term(.UnitType), Term(.BooleanType), Term.lambda(Term(.UnitType), const(Term.lambda(List[Term(.UnitType)], const(Term(false))))), Term.lambda(Term(.UnitType), const(Term(true))), empty]
		assert(eliminated.out.evaluate(environment), ==, true)
	}

	func testNonEmptyListsEliminateWithFirstArgumentToUncons() {
		let eliminated = uncons[Term(.UnitType), Term(.BooleanType), Term.lambda(Term(.UnitType), const(Term.lambda(List[Term(.UnitType)], const(Term(true))))), Term.lambda(Term(.UnitType), const(Term(false))), unary]
		assert(eliminated.out.evaluate(environment), ==, true)
	}
}

private let context = Expression<Term>.list.context
private let environment = Expression<Term>.list.environment

private let List = Term("List")
private let cons = Term("::")
private let uncons = Term("uncons")
private let empty = Term("[]")
private let unary = cons[Term(.UnitType), Term(.Unit), empty]

import Assertions
@testable import Manifold
import Prelude
import XCTest


//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class TypeTests: XCTestCase {
	func testVariableTypesHaveOneFreeVariable() {
		let variable = Variable()
		assertEqual(Type(variable).freeVariables, Set(variable))
	}
}

// MARK: - Imports

import Manifold
import Set
import XCTest

Test the free type variables in function types.

//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class TypeTests: XCTestCase {
	func testVariableTypesHaveOneFreeVariable() {
		let variable = Variable()
		assertEqual(Type(variable).freeVariables, Set(variable))
	}

	func testFunctionTypesDistributeFreeVariables() {
		let variable = Variable()
		assertEqual(Type(function: Type(variable), Type(variable)).freeVariables, Set(variable))
	}
}

// MARK: - Imports

import Manifold
import Set
import XCTest


//
//  GetContentType.swift
//  KenticoCloud
//
//  Created by Martin Makarsky on 13/10/2017.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import Quick
import Nimble
import KenticoCloud

class GetContentTypeSpec: QuickSpec {
    override func spec() {
        describe("Get content type request") {

            let client = DeliveryClient.init(projectId: TestConstants.projectId)

            //MARK: Get some content types

            context("getting content type using content type name", {

                it("returns content type with correct name and codename") {

                    waitUntil(timeout: 5) { done in
                        client.getContentType(name: "coffee", completionHandler: { (isSuccess, contentType, error) in
                            if !isSuccess {
                                fail("Response is not successful. Error: \(String(describing: error))")
                            }

                            if let type = contentType {
                                let expectedName = "Coffee"
                                let expecedCodename = "coffee"
                                expect(type.name) == expectedName
                                expect(type.codename) == expecedCodename
                                done()
                            }
                        })
                    }
                }
            })
        }
    }
}

Add tests for content type's elements

//
//  GetContentType.swift
//  KenticoCloud
//
//  Created by Martin Makarsky on 13/10/2017.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import Quick
import Nimble
import KenticoCloud

class GetContentTypeSpec: QuickSpec {
    override func spec() {
        describe("Get content type request") {

            let client = DeliveryClient.init(projectId: TestConstants.projectId)

            //MARK: Get some content types

            context("getting content type using content type name", {

                it("returns content type with correct name codename and elements") {

                    waitUntil(timeout: 5) { done in
                        client.getContentType(name: "coffee", completionHandler: { (isSuccess, contentType, error) in
                            if !isSuccess {
                                fail("Response is not successful. Error: \(String(describing: error))")
                            }

                            if let type = contentType {
                                let expectedName = "Coffee"
                                let expecedCodename = "coffee"
                                let expectedElementName = "Farm"
                                let expectedElementType = "text"
                                let expectedElementsCount = 13
                                expect(type.name) == expectedName
                                expect(type.codename) == expecedCodename
                                expect(type.elements?.count) == expectedElementsCount
                                expect(type.elements?["farm"]?.type) == expectedElementType
                                expect(type.elements?["farm"]?.name) == expectedElementName
                                done()
                            }
                        })
                    }
                }
            })
        }
    }
}


//
//  DataViewable.swift
//  ZamzamKit iOS
//
//  Created by Basem Emara on 2018-02-04.
//  Copyright © 2018 Zamzam. All rights reserved.
//

import UIKit

public protocol DataViewable {
    func reloadData()
}

// Align API's for table and collections views
// http://basememara.com/protocol-oriented-tableview-collectionview/

extension UITableView: DataViewable {}
extension UICollectionView: DataViewable {}

Consolidate collection and table view API's for backgroundView

//
//  DataViewable.swift
//  ZamzamKit iOS
//
//  Created by Basem Emara on 2018-02-04.
//  Copyright © 2018 Zamzam. All rights reserved.
//

import UIKit

public protocol DataViewable {
    var backgroundView: UIView? { get set }
    func reloadData()
}

// Align API's for table and collections views
// http://basememara.com/protocol-oriented-tableview-collectionview/

extension UITableView: DataViewable {}
extension UICollectionView: DataViewable {}


//
//  Extensions.swift
//  ZhihuDaily
//
//  Created by syxc on 16/2/20.
//  Copyright © 2016年 syxc. All rights reserved.
//

import Foundation
import UIKit
import Hue

// MARK: - UIColor

extension UIColor {

  static func themeColor() -> UIColor {
    return UIColor.hex(FYColors.theme)
  }

  static func hudBackgroundColor() -> UIColor {
    return UIColor.hex("#000000").alpha(0.80)
  }

}

// MARK: - UINavigationController

extension UINavigationController {

  public override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return (self.topViewController?.preferredStatusBarStyle())!
  }

  public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
    return (self.topViewController?.preferredStatusBarUpdateAnimation())!
  }

  public override func prefersStatusBarHidden() -> Bool {
    return (self.topViewController?.prefersStatusBarHidden())!
  }

}

// MARK: - String

extension String {
  var ns: NSString {
    return self as NSString
  }

  var pathExtension: String? {
    return ns.pathExtension
  }

  var lastPathComponent: String? {
    return ns.lastPathComponent
  }
}

Solve the MBProgressHud behind the UITableView divider (seperator).

//
//  Extensions.swift
//  ZhihuDaily
//
//  Created by syxc on 16/2/20.
//  Copyright © 2016年 syxc. All rights reserved.
//

import Foundation
import UIKit
import Hue
import MBProgressHUD

// MARK: - UIColor

extension UIColor {
  static func themeColor() -> UIColor {
    return UIColor.hex(FYColors.theme)
  }

  static func hudBackgroundColor() -> UIColor {
    return UIColor.hex("#000000").alpha(0.80)
  }
}

// MARK: - UINavigationController

extension UINavigationController {
  public override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return (self.topViewController?.preferredStatusBarStyle())!
  }

  public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
    return (self.topViewController?.preferredStatusBarUpdateAnimation())!
  }

  public override func prefersStatusBarHidden() -> Bool {
    return (self.topViewController?.prefersStatusBarHidden())!
  }
}

// MARK: - UITableView

extension UITableView {
  /* Solve the MBProgressHud behind the UITableView divider (seperator). */
  public override func didAddSubview(subview: UIView) {
    for view in self.subviews {
      if view.isKindOfClass(MBProgressHUD.classForCoder()) {
        self.bringSubviewToFront(view)
        break
      }
    }
  }
}

// MARK: - String

extension String {
  var ns: NSString {
    return self as NSString
  }

  var pathExtension: String? {
    return ns.pathExtension
  }

  var lastPathComponent: String? {
    return ns.lastPathComponent
  }
}


/**
 *  Marathon
 *  Copyright (c) John Sundell 2017
 *  Licensed under the MIT license. See LICENSE file.
 */

import PackageDescription

let package = Package(
    name: "Marathon",
    targets: [
        Target(name: "Marathon", dependencies: ["MarathonCore"]),
        Target(name: "MarathonCore")
    ],
    dependencies: [
        .Package(url: "git@github.com:johnsundell/files.git", majorVersion: 1),
        .Package(url: "git@github.com:johnsundell/unbox.git", majorVersion: 2),
        .Package(url: "git@github.com:johnsundell/wrap.git", majorVersion: 2),
        .Package(url: "git@github.com:johnsundell/shellout.git", majorVersion: 1),
        .Package(url: "git@github.com:johnsundell/require.git", majorVersion: 1),
        .Package(url: "git@github.com:johnsundell/releases.git", majorVersion: 1)
    ]
)

Use HTTPS instead of SSH to clone all dependencies

/**
 *  Marathon
 *  Copyright (c) John Sundell 2017
 *  Licensed under the MIT license. See LICENSE file.
 */

import PackageDescription

let package = Package(
    name: "Marathon",
    targets: [
        Target(name: "Marathon", dependencies: ["MarathonCore"]),
        Target(name: "MarathonCore")
    ],
    dependencies: [
        .Package(url: "https://github.com/JohnSundell/Files.git", majorVersion: 1),
        .Package(url: "https://github.com/JohnSundell/Unbox.git", majorVersion: 2),
        .Package(url: "https://github.com/JohnSundell/Wrap.git", majorVersion: 2),
        .Package(url: "https://github.com/JohnSundell/ShellOut.git", majorVersion: 1),
        .Package(url: "https://github.com/JohnSundell/Require.git", majorVersion: 1),
        .Package(url: "https://github.com/JohnSundell/Releases.git", majorVersion: 1)
    ]
)


import PackageDescription

let package = Package(
    name: "UDP",
    dependencies: [
        .Package(url: "https://github.com/VeniceX/IP.git", majorVersion: 0, minor: 5),
    ]
)

Update IP dependency to 0.7

import PackageDescription

let package = Package(
    name: "UDP",
    dependencies: [
        .Package(url: "https://github.com/VeniceX/IP.git", majorVersion: 0, minor: 7),
    ]
)


//
//  NSString+IDNA.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-18.
//

import Foundation

@objc public extension NSString {
	@objc(IDNAEncoded) var idnaEncoded: String? { (self as String).idnaEncoded }
	@objc(IDNADecoded) var idnaDecoded: String? { (self as String).idnaDecoded }
	var encodedURLString: String? { (self as String).encodedURLString}
	var decodedURLString: String? { (self as String).encodedURLString }
}

@objc public extension NSURL {
	@objc(URLWithUnicodeString:) static func urlWithUnicodeString(_ unicodeString: String) -> URL? {
		return URL(unicodeString: unicodeString)
	}

	var decodedURLString: String? {
		return (self as URL).decodedURLString
	}

	@objc(URLWithUnicodeString:relativeToURL:) static func urlWithUnicodeString(_ unicodeString: String, relativeTo url: URL) -> URL? {
		return URL(unicodeString: unicodeString, relativeTo: url)
	}
}

Append "String" to applicable NSString method names

//
//  NSString+IDNA.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-18.
//

import Foundation

@objc public extension NSString {
	@objc(IDNAEncodedString) var idnaEncoded: String? { (self as String).idnaEncoded }
	@objc(IDNADecodedString) var idnaDecoded: String? { (self as String).idnaDecoded }
	var encodedURLString: String? { (self as String).encodedURLString}
	var decodedURLString: String? { (self as String).encodedURLString }
}

@objc public extension NSURL {
	@objc(URLWithUnicodeString:) static func urlWithUnicodeString(_ unicodeString: String) -> URL? {
		return URL(unicodeString: unicodeString)
	}

	var decodedURLString: String? {
		return (self as URL).decodedURLString
	}

	@objc(URLWithUnicodeString:relativeToURL:) static func urlWithUnicodeString(_ unicodeString: String, relativeTo url: URL) -> URL? {
		return URL(unicodeString: unicodeString, relativeTo: url)
	}
}


//
//  Operators.swift
//  swiftz_core
//
//  Created by Maxwell Swadling on 28/06/2014.
//  Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//

// Operators
infix operator • {
associativity right
}

infix operator § {
associativity right
precedence 0
}

infix operator |> {
associativity left
precedence 0
}

infix operator <| {
associativity right
precedence 0
}

// "fmap" like
infix operator <^> {
associativity left
}

// "imap" like
infix operator <^^> {
associativity left
}

// "contramap" like
infix operator <!> {
associativity left
}

// "ap" like
infix operator <*> {
associativity left
}

// "extend" like
infix operator ->> {
associativity left
}

/// Monadic bind operator, because >>= is already in the standard lib.
infix operator >>- {
associativity left
}

/// "From" for Results.
infix operator !! {
associativity none
}

Remove unnecessary operators from core

//
//  Operators.swift
//  swiftz_core
//
//  Created by Maxwell Swadling on 28/06/2014.
//  Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//

/// Compose |
infix operator • {
associativity right
}

infix operator § {
associativity right
precedence 0
}

infix operator |> {
associativity left
precedence 0
}

infix operator <| {
associativity right
precedence 0
}

// "fmap" like
infix operator <^> {
associativity left
}

// "ap" like
infix operator <*> {
associativity left
}

/// Monadic bind operator, because >>= is already in the standard lib.
infix operator >>- {
associativity left
}

/// "From" for Results.
infix operator !! {
associativity none
}


import Foundation
import Kitura
import DotEnv
import SwiftyJSON
import LoggerAPI
import HeliumLogger
import HaCTML
import Fluent
import PostgreSQLDriver

func getWebsiteRouter() -> Router {
  let router = Router()

  router.all("/", middleware: RedirectsMiddleware(redirects: [
    "/intro-to-programming": "https://github.com/hackersatcambridge/workshops/blob/master/workshops/introduction_to_programming/session_1/description.md"
  ]))

  router.all("/static", middleware: StaticFileServer(path: "./static/dist"))
  router.all("/", middleware: NotFoundHandler())

  /// Intended for use by GitHub webhooks
  router.post("/api/refresh_workshops", handler: GitHubWebhookController.handler)

  router.get("/", handler: LandingPageController.handler)
  router.get("/workshops", handler: WorkshopsController.handler)

  // MARK: Features in progress
  router.get("/beta/landing-update-feed", handler: LandingUpdateFeedController.handler)

  return router
}

public func serveWebsite() {
  testDatabase()
  // Helium logger provides logging for Kitura processes
  HeliumLogger.use()
  // This speaks to Kitura's 'LoggerAPI' to set the default logger to HeliumLogger.
  // Kitura calls this API to log things

  Kitura.addHTTPServer(onPort: Config.listeningPort, with: getWebsiteRouter())
  Kitura.run() // This call never returns
}

Move not found handler to later position

import Foundation
import Kitura
import DotEnv
import SwiftyJSON
import LoggerAPI
import HeliumLogger
import HaCTML
import Fluent
import PostgreSQLDriver

func getWebsiteRouter() -> Router {
  let router = Router()

  router.all("/", middleware: RedirectsMiddleware(redirects: [
    "/intro-to-programming": "https://github.com/hackersatcambridge/workshops/blob/master/workshops/introduction_to_programming/session_1/description.md"
  ]))

  router.all("/static", middleware: StaticFileServer(path: "./static/dist"))

  /// Intended for use by GitHub webhooks
  router.post("/api/refresh_workshops", handler: GitHubWebhookController.handler)

  router.get("/", handler: LandingPageController.handler)
  router.get("/workshops", handler: WorkshopsController.handler)

  // MARK: Features in progress
  router.get("/beta/landing-update-feed", handler: LandingUpdateFeedController.handler)

  router.all("/", middleware: NotFoundHandler())

  return router
}

public func serveWebsite() {
  testDatabase()
  // Helium logger provides logging for Kitura processes
  HeliumLogger.use()
  // This speaks to Kitura's 'LoggerAPI' to set the default logger to HeliumLogger.
  // Kitura calls this API to log things

  Kitura.addHTTPServer(onPort: Config.listeningPort, with: getWebsiteRouter())
  Kitura.run() // This call never returns
}


/**
 * Question Link: https://leetcode.com/problems/palindrome-permutation/
 * Primary idea: Use a dictionary to track each character's frequency
 * Time Complexity: O(n), Space Complexity: O(n)
 */

class PalindromePermutation {
    func canPermutePalindrome(s: String) -> Bool {
        let sChars = [Character](s.characters)
        var oddNum = 0
        var charFrequency = [Character: Int]()

        for char in sChars {
            if charFrequency[char] != nil {
                charFrequency[char]! += 1
            } else {
                charFrequency[char] = 1
            }
        }

        for char in charFrequency.keys {
            let fre = charFrequency[char]!
            if fre % 2 == 1 {
                oddNum += 1
            }
            if oddNum >= 2 {
                return false
            }
        }

        return true
    }
}

Update Palindrome Permutation Solution to a more Swift way

/**
 * Question Link: https://leetcode.com/problems/palindrome-permutation/
 * Primary idea: Use a dictionary to track each character's frequency
 * Time Complexity: O(n), Space Complexity: O(n)
 */

class PalindromePermutation {
  func canPermutePalindrome(_ s: String) -> Bool {
    var oddNum = 0

    for (_, value) in s.frequencies where value % 2 == 1 {
      oddNum += 1

      if oddNum >= 2 {
        return false
      }
    }

    return true
  }
}

extension Sequence where Element: Hashable {
  var frequencies: [Element: Int] {
    return Dictionary(self.map{ ($0, 1)}, uniquingKeysWith: +)
  }
}


//  Copyright (c) 2015 Rob Rix. All rights reserved.

import TesseractCore
import XCTest

final class NodeTests: XCTestCase {
	func node(symbolName: String) -> Node {
		return .Symbolic(Prelude[symbolName]!.0)
	}

	func testConstantSymbolsHaveNoInputs() {
		let a = Identifier()
		let n = node("unit")
		let graph = Graph(nodes: [ a: n ])
		assertEqual(n.inputs(a, graph).count, 0)
	}
}

Test unary functions have an input.

//  Copyright (c) 2015 Rob Rix. All rights reserved.

import TesseractCore
import XCTest

final class NodeTests: XCTestCase {
	func node(symbolName: String) -> Node {
		return .Symbolic(Prelude[symbolName]!.0)
	}

	func testConstantSymbolsHaveNoInputs() {
		let a = Identifier()
		let n = node("unit")
		let graph = Graph(nodes: [ a: n ])
		assertEqual(n.inputs(a, graph).count, 0)
	}

	func testUnaryFunctionSymbolsHaveOneInput() {
		let a = Identifier()
		let n = node("identity")
		let graph = Graph(nodes: [ a: n ])
		assertEqual(n.inputs(a, graph).count, 1)
	}
}


import PackageDescription

let package = Package(
    name: "Bond",
    dependencies: [
        .Package(url: "https://github.com/ReactiveKit/ReactiveKit.git", versions: Version(3, 0, 0, prereleaseIdentifiers: ["beta"])..<Version(4, 0, 0))
    ]
)

Add Diff.swift to Swift PM dependencies

import PackageDescription

let package = Package(
    name: "Bond",
    dependencies: [
        .Package(url: "https://github.com/ReactiveKit/ReactiveKit.git", versions: Version(3, 0, 0, prereleaseIdentifiers: ["beta"])..<Version(4, 0, 0))
        .Package(url: "https://github.com/wokalski/Diff.swift.git", versions: Version(0, 4, 1)..<Version(1, 0, 0))
    ]
)


//
//  SearchFieldToolbarItem.swift
//  Helium
//
//  Created by Jaden Geller on 5/14/20.
//  Copyright © 2020 Jaden Geller. All rights reserved.
//

import Cocoa

class SearchFieldToolbarItem: NSToolbarItem, NSSearchFieldDelegate {
    struct Model {
        var navigateWithSearchTerm: (String) -> Void
    }

    let model: Model
    init(model: Model) {
        self.model = model
        super.init(itemIdentifier: .searchField)
        let searchField = NSSearchField()
        searchField.delegate = self
        searchField.target = self
        searchField.action = #selector(navigate)
        searchField.placeholderString = "Search or enter website name"
        searchField.sendsWholeSearchString = true // Send action only on enter, not unfocus
        view = searchField
    }

    @objc func navigate(_ searchField: NSSearchField) {
        model.navigateWithSearchTerm(searchField.stringValue)
    }
}

extension NSToolbarItem.Identifier {
    static var searchField = NSToolbarItem.Identifier("searchField")
}

Hide cancel button in search field

//
//  SearchFieldToolbarItem.swift
//  Helium
//
//  Created by Jaden Geller on 5/14/20.
//  Copyright © 2020 Jaden Geller. All rights reserved.
//

import Cocoa

class SearchFieldToolbarItem: NSToolbarItem, NSSearchFieldDelegate {
    struct Model {
        var navigateWithSearchTerm: (String) -> Void
    }

    let model: Model
    init(model: Model) {
        self.model = model
        super.init(itemIdentifier: .searchField)
        let searchField = NSSearchField()
        searchField.delegate = self
        searchField.target = self
        searchField.action = #selector(navigate)
        searchField.placeholderString = "Search or enter website name"
        searchField.sendsWholeSearchString = true // Send action only on enter, not unfocus

        let searchFieldCell = searchField.cell as! NSSearchFieldCell
        searchFieldCell.cancelButtonCell = nil

        view = searchField
    }

    @objc func navigate(_ searchField: NSSearchField) {
        model.navigateWithSearchTerm(searchField.stringValue)
    }
}

extension NSToolbarItem.Identifier {
    static var searchField = NSToolbarItem.Identifier("searchField")
}


//
//  _RecursiveLock.swift
//  SwiftTask
//
//  Created by Yasuhiro Inami on 2015/05/18.
//  Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//

import Darwin

internal final class _RecursiveLock
{
    private let mutex: UnsafeMutablePointer<pthread_mutex_t>
    private let attribute: UnsafeMutablePointer<pthread_mutexattr_t>

    internal init()
    {
        self.mutex = UnsafeMutablePointer<pthread_mutex_t>(allocatingCapacity: 1)
        self.attribute = UnsafeMutablePointer<pthread_mutexattr_t>(allocatingCapacity: 1)

        pthread_mutexattr_init(self.attribute)
        pthread_mutexattr_settype(self.attribute, PTHREAD_MUTEX_RECURSIVE)
        pthread_mutex_init(self.mutex, self.attribute)
    }

    deinit
    {
        pthread_mutexattr_destroy(self.attribute)
        pthread_mutex_destroy(self.mutex)

        self.attribute.deallocateCapacity(1)
        self.mutex.deallocateCapacity(1)
    }

    internal func lock()
    {
        pthread_mutex_lock(self.mutex)
    }

    internal func unlock()
    {
        pthread_mutex_unlock(self.mutex)
    }
}

Update for Xcode 8 beta 4

//
//  _RecursiveLock.swift
//  SwiftTask
//
//  Created by Yasuhiro Inami on 2015/05/18.
//  Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//

import Darwin

internal final class _RecursiveLock
{
    private let mutex: UnsafeMutablePointer<pthread_mutex_t>
    private let attribute: UnsafeMutablePointer<pthread_mutexattr_t>

    internal init()
    {
        self.mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
        self.attribute = UnsafeMutablePointer<pthread_mutexattr_t>.allocate(capacity: 1)

        pthread_mutexattr_init(self.attribute)
        pthread_mutexattr_settype(self.attribute, PTHREAD_MUTEX_RECURSIVE)
        pthread_mutex_init(self.mutex, self.attribute)
    }

    deinit
    {
        pthread_mutexattr_destroy(self.attribute)
        pthread_mutex_destroy(self.mutex)

        self.attribute.deallocate(capacity: 1)
        self.mutex.deallocate(capacity: 1)
    }

    internal func lock()
    {
        pthread_mutex_lock(self.mutex)
    }

    internal func unlock()
    {
        pthread_mutex_unlock(self.mutex)
    }
}


// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "SmartDeviceLink",
    defaultLocalization: "en",
    platforms: [
        .iOS(.v10)
    ],
    products: [
        .library(name: "SmartDeviceLink", targets: ["SmartDeviceLink"]),
        .library(name: "SmartDeviceLinkSwift", targets: ["SmartDeviceLinkSwift"])
    ],
    targets: [
        .target(
            name: "SmartDeviceLink",
            path: "SmartDeviceLink",
            exclude: ["Info.plist"],
            publicHeadersPath: "public"
        ),
        .target(
            name: "SmartDeviceLinkSwift",
            dependencies: [
                "SmartDeviceLink"
            ],
            path: "SmartDeviceLinkSwift"
        ),
        .target(
            name: "BiSON",
            path: "bson_c_lib/src"
        )
    ]
)

Exclude swift info.plist as well

// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "SmartDeviceLink",
    defaultLocalization: "en",
    platforms: [
        .iOS(.v10)
    ],
    products: [
        .library(name: "SmartDeviceLink", targets: ["SmartDeviceLink"]),
        .library(name: "SmartDeviceLinkSwift", targets: ["SmartDeviceLinkSwift"])
    ],
    targets: [
        .target(
            name: "SmartDeviceLink",
            path: "SmartDeviceLink",
            exclude: ["Info.plist"],
            publicHeadersPath: "public"
        ),
        .target(
            name: "SmartDeviceLinkSwift",
            dependencies: [
                "SmartDeviceLink"
            ],
            path: "SmartDeviceLinkSwift",
            exclude: ["Info.plist"]
        ),
        .target(
            name: "BiSON",
            path: "bson_c_lib/src"
        )
    ]
)


import PackageDescription

let package = Package(
    name: "PostgreSQL",
    dependencies: [
   		 .Package(url: "https://github.com/vapor/cpostgresql.git", majorVersion: 0),
   		 .Package(url: "https://github.com/vapor/node.git", majorVersion: 0, minor: 6)
    ]
)

Add minor version number to `cpostgresql` package.

import PackageDescription

let package = Package(
    name: "PostgreSQL",
    dependencies: [
   		 .Package(url: "https://github.com/vapor/cpostgresql.git", majorVersion: 0, minor: 1),
   		 .Package(url: "https://github.com/vapor/node.git", majorVersion: 0, minor: 6)
    ]
)


// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Criollo",
    platforms: [
        .iOS(.v8),
        .macOS(.v10_10),
        .tvOS(.v9)
    ],
    products: [
        .library(
            name: "Criollo",
            type: .dynamic,
            targets: ["Criollo"]),
    ],
    dependencies: [
        .package(name:"CocoaAsyncSocket", url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.4"),
    ],
    targets: [
        .target(
            name: "Criollo",
            dependencies: ["CocoaAsyncSocket"],
            path: "Criollo/",
            publicHeadersPath: "Criollo",
            cSettings: [
                .headerSearchPath("CocoaAsyncSocket")]),

        .testTarget(name: "CriolloTests",
                    dependencies: ["Criollo"],
                    path: "CriolloTests"),
    ]
)

Update header search paths in Swift package manifest

// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Criollo",
    platforms: [
        .iOS(.v8),
        .macOS(.v10_10),
        .tvOS(.v9)
    ],
    products: [
        .library(
            name: "Criollo",
            type: .dynamic,
            targets: ["Criollo"]),
    ],
    dependencies: [
        .package(name:"CocoaAsyncSocket", url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.4"),
    ],
    targets: [
        .target(
            name: "Criollo",
            dependencies: ["CocoaAsyncSocket"],
            path: "Criollo/",
            publicHeadersPath: "Criollo",
            cSettings: [
                .headerSearchPath("Criollo/Sources/**"),
                .headerSearchPath("CocoaAsyncSocket")]),

        .testTarget(name: "CriolloTests",
                    dependencies: ["Criollo"],
                    path: "CriolloTests"),
    ]
)


import PackageDescription

let package = Package(
    name: "ValidationToolkit",
    exclude: ["Tests"]
)

Update the package manifest file

// swift-tools-version:4.2

import PackageDescription

let package = Package(
    name: "ValidationToolkit",
    products: [
        .library(
            name: "ValidationToolkit",
            targets: ["ValidationToolkit"])
    ],
    targets: [
        .target(
            name: "ValidationToolkit",
            path:"Sources"),
        .testTarget(
            name: "ValidationToolkitTests",
            dependencies: ["ValidationToolkit"],
            path:"Tests")
    ]
)


import PackageDescription

let package = Package(
    name: "SwiftFoundation",
    targets: [
        Target(
            name: "UnitTests",
            dependencies: [.Target(name: "SwiftFoundation")]),
        Target(
            name: "SwiftFoundation")
    ],
    dependencies: [
        .Package(url: "https://github.com/PureSwift/CUUID.git", majorVersion: 1),
        .Package(url: "https://github.com/PureSwift/CStatfs.git", majorVersion: 1),
        .Package(url: "https://github.com/PureSwift/CJSONC.git", majorVersion: 1)
    ],
    exclude: ["Xcode", "Carthage"]
)

Remove PureSwift/CUUID as a dependency

import PackageDescription

let package = Package(
    name: "SwiftFoundation",
    targets: [
        Target(
            name: "UnitTests",
            dependencies: [.Target(name: "SwiftFoundation")]),
        Target(
            name: "SwiftFoundation")
    ],
    dependencies: [
        .Package(url: "https://github.com/PureSwift/CStatfs.git", majorVersion: 1),
        .Package(url: "https://github.com/PureSwift/CJSONC.git", majorVersion: 1)
    ],
    exclude: ["Xcode", "Carthage"]
)


// swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Vandelay",
    platforms: [
        .iOS(.v9)
    ],
    products: [
        .library(
            name: "Vandelay",
            targets: ["Vandelay"])
    ],
    dependencies: [
        .package(url: "git@github.com:Quick/Quick.git", .upToNextMinor(from: "2.2.0")),
        .package(url: "git@github.com:Quick/Nimble.git", .exact("8.0.2"))
    ],
    targets: [
        .target(
            name: "Vandelay",
            dependencies: []),
        .testTarget(
            name: "VandelayTests",
            dependencies: ["Vandelay", "Quick", "Nimble"])
    ]
)

Use https instead of ssh for package dependencies

// swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "Vandelay",
    platforms: [
        .iOS(.v9)
    ],
    products: [
        .library(
            name: "Vandelay",
            targets: ["Vandelay"])
    ],
    dependencies: [
        .package(url: "https://github.com/Quick/Quick.git", .upToNextMinor(from: "2.2.0")),
        .package(url: "https://github.com/Quick/Nimble.git", .exact("8.0.2"))
    ],
    targets: [
        .target(
            name: "Vandelay",
            dependencies: []),
        .testTarget(
            name: "VandelayTests",
            dependencies: ["Vandelay", "Quick", "Nimble"])
    ]
)


import PackageDescription

let package = Package(
    name: "PostgreSQL",
    dependencies: [
   		 .Package(url: "https://github.com/vapor/cpostgresql.git", majorVersion: 1),
   		 .Package(url: "https://github.com/vapor/node.git", majorVersion: 1),
   		 .Package(url: "https://github.com/vapor/core.git", majorVersion: 1),
    ]
)

Update dependencies for beta release.

import PackageDescription

let package = Package(
    name: "PostgreSQL",
    dependencies: [
        // Module map for `libpq`
        .Package(url: "https://github.com/vapor/cpostgresql.git", Version(2,0,0, prereleaseIdentifiers: ["alpha"])),

        // Data structure for converting between multiple representations
        .Package(url: "https://github.com/vapor/node.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),

        // Core extensions, type-aliases, and functions that facilitate common tasks
        .Package(url: "https://github.com/vapor/core.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
    ]
)


import UIKit
import FanSabisuKit
import Photos

class PreviewViewController: UIViewController {

    var url: URL?
    @IBOutlet var imageView: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = String.localizedString(for: "PREVIEW")
        if let url = self.url {
            let image = UIImage.animatedImage(with: url)
            self.imageView?.image = image
        }
    }

    @IBAction func save(with sender: UIBarButtonItem) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: self.url!)
        }) { (success, error) in
            if let _ = error {
                self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "SAVE_FAILED"), actionHandler: nil)
            } else {
                DispatchQueue.main.async { self.performSegue(withIdentifier: "UnwindToMedia", sender: nil) }
            }
        }
    }

}

Delete temporary file after saving to photos library

import UIKit
import FanSabisuKit
import Photos

class PreviewViewController: UIViewController {

    var url: URL?
    @IBOutlet var imageView: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = String.localizedString(for: "PREVIEW")
        if let url = self.url {
            let image = UIImage.animatedImage(with: url)
            self.imageView?.image = image
        }
    }

    @IBAction func save(with sender: UIBarButtonItem) {
        if let url = self.url {
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
            }) { (success, error) in
                if let _ = error {
                    self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "SAVE_FAILED"), actionHandler: nil)
                } else {
                    let manager = FileManager.default
                    try? manager.removeItem(at: url)
                    DispatchQueue.main.async { self.performSegue(withIdentifier: "UnwindToMedia", sender: nil) }
                }
            }
        }
    }

}


//
//  GalleryDetailDataViewController.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class GalleryDetailDataViewController: UIViewController {

    @IBOutlet weak var dataImage: UIImageView!
    @IBOutlet weak var photoCaption: UILabel!

    var dataObject: UIImage = #imageLiteral(resourceName: "placeholder")
    var photoIndex: Int = 0
    var photosCount: Int = 0

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.dataImage!.image = dataObject
        self.photoCaption.text = "Zdjęcie \(photoIndex) / \(photosCount)"
    }
}

Remove strong reference to self in closure expression Change dataObject type to URL

//
//  GalleryDetailDataViewController.swift
//  TOZ_iOS
//
//  Copyright © 2017 intive. All rights reserved.
//

import UIKit

class GalleryDetailDataViewController: UIViewController {

    @IBOutlet weak var dataImage: UIImageView!
    @IBOutlet weak var photoCaption: UILabel!

    var dataObject: URL?
    var photoIndex: Int = 0
    var photosCount: Int = 0

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getAnimalPhoto()
        self.photoCaption.text = "Zdjęcie \(photoIndex) / \(photosCount)"
    }

    func getAnimalPhoto() {
            if let dataObject = self.dataObject {
                DispatchQueue.main.async {
                    PhotoManager.shared.getPhoto(from: dataObject, completion: { [weak self] (image) -> (Void) in
                    self?.dataImage.image = image
                })
                }
            } else {
        self.dataImage.image = #imageLiteral(resourceName: "placeholder")
        }
    }
}


//  Copyright (c) 2014 Rob Rix. All rights reserved.

/// Takes an unevaluated closure \c value and returns a lazily-evaluating wrapper for it.
func delay<T>(value: @auto_closure () -> T) -> Delay<T> {
	return Delay(value)
}

/// A lazily-provided value, convertible to its underlying type.
@final class Delay<T> {
	var _thunk: (() -> T)?
	var _value: Box<T?>

	var forced: T { return __conversion() }

	init(_ thunk: () -> T) {
		_thunk = thunk
		_value = box(nil)
	}

	@conversion func __conversion() -> T {
		if let thunk = _thunk {
			_value = box(thunk())
			_thunk = nil
		}
		return _value!
	}
}

func == <T : Equatable> (left: Delay<T>, right: Delay<T>) -> Bool {
	return ((left as T) == (right as T))
}

func == <T : Equatable> (left: Delay<T>, right: T) -> Bool {
	return (left as T) == right
}

func hash<Delayed : Hashable>(delay: Delay<Delayed>) -> Int {
	return (delay as Delayed).hashValue
}

Add a lazily-instantiated value property.

//  Copyright (c) 2014 Rob Rix. All rights reserved.

/// Takes an unevaluated closure \c value and returns a lazily-evaluating wrapper for it.
func delay<T>(value: @auto_closure () -> T) -> Delay<T> {
	return Delay(value)
}

/// A lazily-provided value, convertible to its underlying type.
@final class Delay<T> {
	var _thunk: (() -> T)?
	var _value: Box<T?>

	var forced: T { return __conversion() }
	@lazy var value: T = { self._thunk!() }()

	init(_ thunk: () -> T) {
		_thunk = thunk
		_value = box(nil)
	}

	@conversion func __conversion() -> T {
		if let thunk = _thunk {
			_value = box(thunk())
			_thunk = nil
		}
		return _value!
	}
}

func == <T : Equatable> (left: Delay<T>, right: Delay<T>) -> Bool {
	return ((left as T) == (right as T))
}

func == <T : Equatable> (left: Delay<T>, right: T) -> Bool {
	return (left as T) == right
}

func hash<Delayed : Hashable>(delay: Delay<Delayed>) -> Int {
	return (delay as Delayed).hashValue
}


//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class DTermTests: XCTestCase {
	func testHigherOrderConstruction() {
		let expected = DTerm(.Pi(Box(DTerm(.Variable(1, Box(.type)))), Box(DTerm(.Pi(Box(DTerm(.Variable(0, Box(DTerm(.Variable(1, Box(.type))))))), Box(DTerm(.Variable(0, Box(DTerm(.Variable(1, Box(.type))))))))))))
		assert(identity, ==, expected)
	}

	func testTypechecking() {
		assert(identity.typecheck().right, ==, .lambda(.type, const(.lambda(.type, const(.type)))))
	}

	func testFunctionTypesArePrintedWithAnArrow() {
		assert(identity.typecheck().right?.description, ==, "(Type) → (Type) → Type")
	}

	func testProductTypesArePrintedWithAnX() {
		assert(DTerm.pair(.type, const(.type)).typecheck().right?.description == "(Type ✕ Type)")
	}

	func testEvaluation() {
		let value = identity.typecheck().flatMap { DTerm.application(DTerm.application(identity, $0), identity).evaluate() }
		assert(value.right, ==, identity)
		assert(value.left, ==, nil)
	}
}

private let identity = DTerm.lambda(.type) { A in .lambda(A, id) }

import Assertions
import Box
import Manifold
import Prelude
import XCTest

Use the correct assertion function.

//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class DTermTests: XCTestCase {
	func testHigherOrderConstruction() {
		let expected = DTerm(.Pi(Box(DTerm(.Variable(1, Box(.type)))), Box(DTerm(.Pi(Box(DTerm(.Variable(0, Box(DTerm(.Variable(1, Box(.type))))))), Box(DTerm(.Variable(0, Box(DTerm(.Variable(1, Box(.type))))))))))))
		assert(identity, ==, expected)
	}

	func testTypechecking() {
		assert(identity.typecheck().right, ==, .lambda(.type, const(.lambda(.type, const(.type)))))
	}

	func testFunctionTypesArePrintedWithAnArrow() {
		assert(identity.typecheck().right?.description, ==, "(Type) → (Type) → Type")
	}

	func testProductTypesArePrintedWithAnX() {
		assert(DTerm.pair(.type, const(.type)).typecheck().right?.description, ==, "(Type ✕ Type)")
	}

	func testEvaluation() {
		let value = identity.typecheck().flatMap { DTerm.application(DTerm.application(identity, $0), identity).evaluate() }
		assert(value.right, ==, identity)
		assert(value.left, ==, nil)
	}
}

private let identity = DTerm.lambda(.type) { A in .lambda(A, id) }

import Assertions
import Box
import Manifold
import Prelude
import XCTest


//
//  ResolutionPool.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 7/28/15.
//  Copyright (c) 2015 Swinject Contributors. All rights reserved.
//

import Foundation

internal struct ResolutionPool {
    private static let maxDepth = 200

    private var pool = [ServiceKey: Any]()
    private var depth: Int = 0

    internal subscript(key: ServiceKey) -> Any? {
        get { return pool[key] }
        set { pool[key] = newValue }
    }

    internal mutating func incrementDepth() {
        guard depth < ResolutionPool.maxDepth else {
            fatalError("Infinite recursive call for circular dependency has been detected. " +
                       "To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.")
        }
        depth++
    }

    internal mutating func decrementDepth() {
        assert(depth > 0, "The depth cannot be negative.")

        depth--
        if depth == 0 {
            pool = [:]
        }
    }
}

Replace deprecated increment/decrement (++/--) operators.

//
//  ResolutionPool.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 7/28/15.
//  Copyright (c) 2015 Swinject Contributors. All rights reserved.
//

import Foundation

internal struct ResolutionPool {
    private static let maxDepth = 200

    private var pool = [ServiceKey: Any]()
    private var depth: Int = 0

    internal subscript(key: ServiceKey) -> Any? {
        get { return pool[key] }
        set { pool[key] = newValue }
    }

    internal mutating func incrementDepth() {
        guard depth < ResolutionPool.maxDepth else {
            fatalError("Infinite recursive call for circular dependency has been detected. " +
                       "To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.")
        }
        depth += 1
    }

    internal mutating func decrementDepth() {
        assert(depth > 0, "The depth cannot be negative.")

        depth -= 1
        if depth == 0 {
            pool = [:]
        }
    }
}


import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }
}

Create test for load data

import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    var modelList:ModelList?

    override func setUp()
    {
        super.setUp()
        modelList = ModelList()
    }

    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }

    func testLoadData()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl()

        else
        {
            return
        }

        let data:Data? = modelList?.loadData(url:url)
        XCTAssertNotNil(data, "failed loading data from url")
    }
}


// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }
        }
    }
}

Add temporary fail test for travis

// https://github.com/Quick/Quick

import Quick
import Nimble
import SwiftVersionUtils

class TableOfContentsSpec: QuickSpec {
    override func spec() {
        describe("Version Info file") {

            it("has build 'number'") {
                expect("1 Test") == SwiftVersionUtils.getBuildNumber()
            }

            it("has version name") {
                expect("1.0 Test") == SwiftVersionUtils.getVersion()
            }

            it("will fail and travis will throw error") {
                expect("ok") == "ko"
            }
        }
    }
}


//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String?
    var issuer: String?
    let type: TokenType
    let secret: NSData
    let algorithm: Algorithm
    let digits: Int

    init(type: TokenType, secret: NSData, algorithm: Algorithm = .SHA1, digits: Int = 6) {
        self.type = type
        self.secret = secret
        self.algorithm = algorithm
        self.digits = digits
    }

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}

Make name and issuer required properties

//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String
    var issuer: String
    let type: TokenType
    let secret: NSData
    let algorithm: Algorithm
    let digits: Int

    init(type: TokenType, secret: NSData, name: String = "", issuer: String = "", algorithm: Algorithm = .SHA1, digits: Int = 6) {
        self.type = type
        self.secret = secret
        self.name = name
        self.issuer = issuer
        self.algorithm = algorithm
        self.digits = digits
    }

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}


//
//  main.swift
//  R.swift
//
//  Created by Mathijs Kadijk on 11-12-14.
//  From: https://github.com/mac-cain13/R.swift
//  License: MIT License
//

import Foundation

do {
  let callInformation = try CallInformation(processInfo: NSProcessInfo.processInfo())

  let resourceURLs = try resourceURLsInXcodeproj(callInformation.xcodeprojPath, forTarget: callInformation.targetName, pathResolver: pathResolverWithSourceTreeToPathConverter(callInformation.pathFromSourceTreeFolder))
  print("\(resourceURLs)")

  let resources = Resources(resourceURLs: resourceURLs, fileManager: NSFileManager.defaultManager())

  let (internalStruct, externalStruct) = generateResourceStructsWithResources(resources)

  let fileContents = [
    Header, "",
    Imports, "",
    externalStruct.description, "",
    internalStruct.description, "",
    ReuseIdentifier.description, "",
    NibResourceProtocol.description, "",
    ReusableProtocol.description, "",
    ReuseIdentifierUITableViewExtension.description, "",
    ReuseIdentifierUICollectionViewExtension.description, "",
    NibUIViewControllerExtension.description,
    ].joinWithSeparator("\n")

  // Write file if we have changes
  let outputFolderURL = NSURL(fileURLWithPath: callInformation.outputFolderPath)
  if readResourceFile(outputFolderURL) != fileContents {
    writeResourceFile(fileContents, toFolderURL: outputFolderURL)
  }

} catch let error as InputParsingError {
  fail(error)
}

Make joining the final file a bit nicer

//
//  main.swift
//  R.swift
//
//  Created by Mathijs Kadijk on 11-12-14.
//  From: https://github.com/mac-cain13/R.swift
//  License: MIT License
//

import Foundation

do {
  let callInformation = try CallInformation(processInfo: NSProcessInfo.processInfo())

  let resourceURLs = try resourceURLsInXcodeproj(callInformation.xcodeprojPath, forTarget: callInformation.targetName, pathResolver: pathResolverWithSourceTreeToPathConverter(callInformation.pathFromSourceTreeFolder))
  print("\(resourceURLs)")

  let resources = Resources(resourceURLs: resourceURLs, fileManager: NSFileManager.defaultManager())

  let (internalStruct, externalStruct) = generateResourceStructsWithResources(resources)

  let fileContents = [
    Header,
    Imports,
    externalStruct.description,
    internalStruct.description,
    ReuseIdentifier.description,
    NibResourceProtocol.description,
    ReusableProtocol.description,
    ReuseIdentifierUITableViewExtension.description,
    ReuseIdentifierUICollectionViewExtension.description,
    NibUIViewControllerExtension.description,
    ].joinWithSeparator("\n\n")

  // Write file if we have changes
  let outputFolderURL = NSURL(fileURLWithPath: callInformation.outputFolderPath)
  if readResourceFile(outputFolderURL) != fileContents {
    writeResourceFile(fileContents, toFolderURL: outputFolderURL)
  }

} catch let error as InputParsingError {
  fail(error)
}


//
//  LoginViewController.swift
//  ReactiveCocoa-Swift-Demo
//
//  Created by Ash Furrow on 2014-10-27.
//  Copyright (c) 2014 Ash Furrow. All rights reserved.
//

import UIKit
import ReactiveCocoa

class LoginViewController: UIViewController {
    @IBOutlet weak var emailAddressTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var goButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        let validEmailSignal = emailAddressTextField.rac_textSignal().map { (object) -> AnyObject! in
            let string = object as NSString
            let range: NSRange! = string.rangeOfString("@")
            return range.location != NSNotFound
        }

        let validPasswordSignal = passwordTextField.rac_textSignal().map { (object) -> AnyObject! in
            let string = object as String
            return countElements(string) > 6
        }

        RAC(goButton, "enabled") <~ RACSignal.combineLatest([validEmailSignal, validPasswordSignal]).and()
    }
}

Use contains from the Swift standard library...

//
//  LoginViewController.swift
//  ReactiveCocoa-Swift-Demo
//
//  Created by Ash Furrow on 2014-10-27.
//  Copyright (c) 2014 Ash Furrow. All rights reserved.
//

import UIKit
import ReactiveCocoa

class LoginViewController: UIViewController {
    @IBOutlet weak var emailAddressTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var goButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        let validEmailSignal = emailAddressTextField.rac_textSignal().map { (object) -> AnyObject! in
            let string = object as String
            return contains(string, "@")
        }

        let validPasswordSignal = passwordTextField.rac_textSignal().map { (object) -> AnyObject! in
            let string = object as String
            return countElements(string) > 6
        }

        RAC(goButton, "enabled") <~ RACSignal.combineLatest([validEmailSignal, validPasswordSignal]).and()
    }
}


//  Copyright © 2015 Rob Rix. All rights reserved.

final class EvaluationTests: XCTestCase {
	func testUnitTermEvaluatesToItself() {
		assert(Term.unitTerm.evaluate().quote, ==, Term.unitTerm)
	}

	func testUnitTypeEvaluatesToItself() {
		assert(Term.unitType.evaluate().quote, ==, Term.unitType)
	}

	func testTypeEvaluatesToItself() {
		assert(Term.type.evaluate().quote, ==, Term.type)
	}

	func testApplicationOfIdentityAbstractionToUnitTermEvaluatesToUnitTerm() {
		let identity = Term.pi(.unitType, .bound(0))
		assert(Term.application(identity, Term.unitTerm).evaluate().quote, ==, Term.unitTerm)
	}

	func testSimpleAbstractionEvaluatesToItself() {
		let identity = Term.pi(.unitType, .bound(0))
		assert(identity.evaluate().quote, ==, identity)
	}
}

import Assertions
import Manifold
import XCTest

Test a more complex abstraction.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class EvaluationTests: XCTestCase {
	func testUnitTermEvaluatesToItself() {
		assert(Term.unitTerm.evaluate().quote, ==, Term.unitTerm)
	}

	func testUnitTypeEvaluatesToItself() {
		assert(Term.unitType.evaluate().quote, ==, Term.unitType)
	}

	func testTypeEvaluatesToItself() {
		assert(Term.type.evaluate().quote, ==, Term.type)
	}

	func testApplicationOfIdentityAbstractionToUnitTermEvaluatesToUnitTerm() {
		let identity = Term.pi(.unitType, .bound(0))
		assert(Term.application(identity, Term.unitTerm).evaluate().quote, ==, Term.unitTerm)
	}

	func testSimpleAbstractionEvaluatesToItself() {
		let identity = Term.pi(.unitType, .bound(0))
		assert(identity.evaluate().quote, ==, identity)
	}

	func testAbstractionsNormalizeByEvaluation() {
		let identity = Term.pi(.unitType, .application(.pi(.unitType, .bound(0)), .bound(0)))
		assert(identity.evaluate().quote, ==, Term.pi(.unitType, .bound(0)))
	}
}

import Assertions
import Manifold
import XCTest


import Foundation

class BkkCrypt {

    func BkkCrypt(_ input: String) -> String {
        return input
    }
}

Add encrypting function as a String extension

import Foundation

class BkkCrypt {

    func BkkCrypt(_ input: String) -> String {
        return input
    }
}

extension String {
    func BKKCrypt() -> String {
        return self
    }
}


//
//  DateFormatter+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 6/2/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import Foundation

extension DateFormatter {
    public static let shared: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.isLenient = true
        return formatter
    }()
}

Set date formatter time zone

//
//  DateFormatter+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 6/2/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import Foundation

extension DateFormatter {
    public static let shared: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.isLenient = true
        return formatter
    }()
}


//  Copyright © 2015 Outware Mobile. All rights reserved.

public typealias StepDefinitionFunc = () -> ()

public class StepDefinition: QuickSpec {

  // MARK: Step definition API

  public func Given(description: String, definition: () -> ()) {
    registerStepWithDescription(description, definition: definition)
  }

  public func Then(description: String, definition: () -> ()) {
    registerStepWithDescription(description, definition: definition)
  }

  // MARK: Matching step definitions

  internal static func lookup(description: String, forStepInFile filePath: String, atLine lineNumber: UInt) -> () -> StepDefinitionFunc? {
    let step = Step(name: description, inFile: filePath, atLine: lineNumber)

    return {
      guard let definition = stepDefinitions[description] else {
        return nil
      }

      return {
        executingStep = step
        definition()
        executingStep = nil
      }
    }
  }

  // MARK: Step definition hook

  public func steps() {}

  public override func spec() {
    super.spec()
    steps()
  }

  // MARK: Currently executing step

  internal private(set) static var executingStep: Step?

  // MARK: Registering step definitions

  private func registerStepWithDescription(description: String, definition: () -> ()) {
    self.dynamicType.stepDefinitions[description] = definition
  }

  private static var stepDefinitions: [String: () -> ()] = [:]

}

import Quick

Add ability to define steps with When

//  Copyright © 2015 Outware Mobile. All rights reserved.

public typealias StepDefinitionFunc = () -> ()

public class StepDefinition: QuickSpec {

  // MARK: Step definition API

  public func Given(description: String, definition: () -> ()) {
    registerStepWithDescription(description, definition: definition)
  }

  public func When(description: String, definition: () -> ()) {
    registerStepWithDescription(description, definition: definition)
  }

  public func Then(description: String, definition: () -> ()) {
    registerStepWithDescription(description, definition: definition)
  }

  // MARK: Matching step definitions

  internal static func lookup(description: String, forStepInFile filePath: String, atLine lineNumber: UInt) -> () -> StepDefinitionFunc? {
    let step = Step(name: description, inFile: filePath, atLine: lineNumber)

    return {
      guard let definition = stepDefinitions[description] else {
        return nil
      }

      return {
        executingStep = step
        definition()
        executingStep = nil
      }
    }
  }

  // MARK: Step definition hook

  public func steps() {}

  public override func spec() {
    super.spec()
    steps()
  }

  // MARK: Currently executing step

  internal private(set) static var executingStep: Step?

  // MARK: Registering step definitions

  private func registerStepWithDescription(description: String, definition: () -> ()) {
    self.dynamicType.stepDefinitions[description] = definition
  }

  private static var stepDefinitions: [String: () -> ()] = [:]

}

import Quick


//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest

Test that leaves are leaves.

//  Copyright (c) 2015 Rob Rix. All rights reserved.

final class BinaryTreeTests: XCTestCase {
	func testEmptyTreesAreNotLeaves() {
		XCTAssertFalse(BinaryTree<Int>().isLeaf)
	}

	func testLeavesAreLeaves() {
		XCTAssert(BinaryTree(0).isLeaf)
	}

	func testLeavesAreNonEmpty() {
		XCTAssertFalse(BinaryTree(0).isEmpty)
	}

	func testLeavesAreNotBranches() {
		XCTAssertFalse(BinaryTree(0).isBranch)
	}
}

import BinaryTree
import XCTest


//
//  ArgumentCaptorValues.swift
//  InstantMock
//
//  Created by Patrick on 21/05/2017.
//  Copyright © 2017 pirishd. All rights reserved.
//

/** Protocol for returning captured values */
protocol ArgumentCaptorValues {
    associatedtype Value
    var value: Value? { get }
    var allValues: [Value?] { get }
}

/** Main implementation for returning captured values */
public class ArgumentCaptorValuesImpl<T>: ArgumentCaptorValues {

    /// Argument capture instance
    private var arg: ArgumentCapture?

    /// Captured value
    public var value: T? {
        var ret: T?
        if let captureArg = self.arg {
            ret = captureArg.value as? T
        }
        return ret
    }

    /// All captured values
    public var allValues: [T?] {
        var ret = [T?]()
        if let captureArg = self.arg {
            ret = captureArg.allValues.map { $0 as? T }.flatMap { $0 }
        }
        return ret
    }

    /** Initializer */
    init(_ arg: ArgumentCapture?) {
        self.arg = arg
    }

}

Replace flatMap by compactMap, removing a warning

//
//  ArgumentCaptorValues.swift
//  InstantMock
//
//  Created by Patrick on 21/05/2017.
//  Copyright © 2017 pirishd. All rights reserved.
//

/** Protocol for returning captured values */
protocol ArgumentCaptorValues {
    associatedtype Value
    var value: Value? { get }
    var allValues: [Value?] { get }
}

/** Main implementation for returning captured values */
public class ArgumentCaptorValuesImpl<T>: ArgumentCaptorValues {

    /// Argument capture instance
    private var arg: ArgumentCapture?

    /// Captured value
    public var value: T? {
        var ret: T?
        if let captureArg = self.arg {
            ret = captureArg.value as? T
        }
        return ret
    }

    /// All captured values
    public var allValues: [T?] {
        var ret = [T?]()
        if let captureArg = self.arg {
            ret = captureArg.allValues.map { $0 as? T }.compactMap { $0 }
        }
        return ret
    }

    /** Initializer */
    init(_ arg: ArgumentCapture?) {
        self.arg = arg
    }

}


//
//  PageboyPropertyTests.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 22/03/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import XCTest
@testable import Pageboy

class PageboyPropertyTests: PageboyTests {

    /// Test that currentViewController property returns correct view controller.
    func testCorrectCurrentViewControllerReported() {
        self.dataSource.numberOfPages = 5
        self.pageboyViewController.dataSource = self.dataSource

        self.pageboyViewController.scrollToPage(.next, animated: false)

        let currentViewController = self.pageboyViewController.currentViewController

        XCTAssertTrue(currentViewController === self.dataSource.viewControllers[1],
                      "currentViewController property is incorrect following transitions.")
    }

    /// Test that setting isScrollEnabled updates internal scroll view correctly.
    func testIsScrollEnabledUpdates() {
        self.dataSource.numberOfPages = 5
        self.pageboyViewController.dataSource = self.dataSource

        self.pageboyViewController.isScrollEnabled = false

        XCTAssertTrue(self.pageboyViewController.pageViewController?.scrollView?.isScrollEnabled == false,
                      "isScrollEnabled does not update the internal scrollView correctly.")
    }
}

Add tests for page view controller options

//
//  PageboyPropertyTests.swift
//  Pageboy
//
//  Created by Merrick Sapsford on 22/03/2017.
//  Copyright © 2017 Merrick Sapsford. All rights reserved.
//

import XCTest
@testable import Pageboy

class PageboyPropertyTests: PageboyTests {

    /// Test that currentViewController property returns correct view controller.
    func testCorrectCurrentViewControllerReported() {
        self.dataSource.numberOfPages = 5
        self.pageboyViewController.dataSource = self.dataSource

        self.pageboyViewController.scrollToPage(.next, animated: false)

        let currentViewController = self.pageboyViewController.currentViewController

        XCTAssertTrue(currentViewController === self.dataSource.viewControllers[1],
                      "currentViewController property is incorrect following transitions.")
    }

    /// Test that setting isScrollEnabled updates internal scroll view correctly.
    func testIsScrollEnabledUpdates() {
        self.dataSource.numberOfPages = 5
        self.pageboyViewController.dataSource = self.dataSource

        self.pageboyViewController.isScrollEnabled = false

        XCTAssertTrue(self.pageboyViewController.pageViewController?.scrollView?.isScrollEnabled == false,
                      "isScrollEnabled does not update the internal scrollView correctly.")
    }

    func testPageViewControllerOptions() {
        self.dataSource.numberOfPages = 5
        self.pageboyViewController.dataSource = self.dataSource

        self.pageboyViewController.interPageSpacing = 12.0

        XCTAssert(self.pageboyViewController.pageViewControllerOptions?.count ?? 0 > 0,
                  "Custom UIPageViewController options are not being passed.")
    }
}


//
//  StringExtension.swift
//  SimpleXPath
//
//  Created by CHEN Xian’an on 2/21/15.
//  Copyright (c) 2015 lazyapps. All rights reserved.
//

import Foundation
import libxml2

extension String {

  var xmlCharPointer: UnsafePointer<xmlChar> {
    return unsafeBitCast((self as NSString).UTF8String, UnsafePointer<xmlChar>.self)
  }

  var namespacePrefixs: Set<String>? {
    if let regexp = NSRegularExpression(pattern: "(\\w+):[^\\W:]", options: nil, error: nil) {
      if let matches = regexp.matchesInString(self, options: nil, range: NSMakeRange(0, count(self.utf16))) as? [NSTextCheckingResult] {
        return Set(matches.map {
          let range = $0.rangeAtIndex(1)
          return (self as NSString).substringWithRange(range)
        })
      }

    }

    return nil
  }

}

Use Swift 1.2's new s in a String Extension

//
//  StringExtension.swift
//  SimpleXPath
//
//  Created by CHEN Xian’an on 2/21/15.
//  Copyright (c) 2015 lazyapps. All rights reserved.
//

import Foundation
import libxml2

extension String {

  var xmlCharPointer: UnsafePointer<xmlChar> {
    return unsafeBitCast((self as NSString).UTF8String, UnsafePointer<xmlChar>.self)
  }

  var namespacePrefixs: Set<String>? {
    if let regexp = NSRegularExpression(pattern: "(\\w+):[^\\W:]", options: nil, error: nil),
       let matches = regexp.matchesInString(self, options: nil, range: NSMakeRange(0, count(self.utf16))) as? [NSTextCheckingResult]
    {
      return Set(matches.map {
        let range = $0.rangeAtIndex(1)
        return (self as NSString).substringWithRange(range)
      })
    }

    return nil
  }

}


//
//  AppDelegate.swift
//  BaristaHelper
//
//  Created by Franz Greiling on 18.11.2014.
//  Copyright (c) 2014 Franz Greiling. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

}

Add code to launch main application from helper

//
//  AppDelegate.swift
//  BaristaHelper
//
//  Created by Franz Greiling on 18.11.2014.
//  Copyright (c) 2014 Franz Greiling. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationWillFinishLaunching(aNotification: NSNotification) {
        // Since Helper must reside in Bundle/Contents/Library/LoginItems
        // remove unnessesary path elements
        let appPath = NSBundle.mainBundle().bundlePath.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent

        NSWorkspace.sharedWorkspace().launchApplication(appPath)

        NSApplication.sharedApplication().terminate(nil)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

}


//
//  FontTests.swift
//  Silica
//
//  Created by Alsey Coleman Miller on 6/1/16.
//  Copyright © 2016 PureSwift. All rights reserved.
//

import XCTest
@testable import Silica

final class FontTests: XCTestCase {

    static let allTests = [("testCreateFont", testCreateFont)]

    func testCreateFont() {

        var fontNames = [
            ("TimesNewRoman", "Times New Roman"),
            ("TimesNewRoman-Bold", "Times New Roman")
        ]

        #if os(macOS)
        fontNames += [("MicrosoftSansSerif", "Microsoft Sans Serif"),
                      ("MicrosoftSansSerif-Bold", "Microsoft Sans Serif")]
        #endif

        for (fontName, expectedFullName) in fontNames {

            guard let font = Silica.CGFont(name: fontName)
                else { XCTFail("Could not create font"); return }

            XCTAssert(font.name == font.name)
            XCTAssert(expectedFullName == font.scaledFont.fullName, "\(expectedFullName) == \(font.scaledFont.fullName)")
        }
    }
}

Fix unit tests to work in Ubuntu linux environment

//
//  FontTests.swift
//  Silica
//
//  Created by Alsey Coleman Miller on 6/1/16.
//  Copyright © 2016 PureSwift. All rights reserved.
//

import XCTest
@testable import Silica

final class FontTests: XCTestCase {

    static let allTests = [("testCreateFont", testCreateFont)]

    func testCreateFont() {

        #if os(Linux)
        var fontNames = [
            ("LiberationSerif", "Liberation Serif"),
            ("LiberationSerif-Bold", "Liberation Serif")
        ]

        #else
        var fontNames = [
            ("TimesNewRoman", "Times New Roman"),
            ("TimesNewRoman-Bold", "Times New Roman")
        ]
        #endif

        #if os(macOS)
        fontNames += [("MicrosoftSansSerif", "Microsoft Sans Serif"),
                      ("MicrosoftSansSerif-Bold", "Microsoft Sans Serif")]
        #endif

        for (fontName, expectedFullName) in fontNames {

            guard let font = Silica.CGFont(name: fontName)
                else { XCTFail("Could not create font"); return }

            XCTAssert(font.name == font.name)
            XCTAssert(expectedFullName == font.scaledFont.fullName, "\(expectedFullName) == \(font.scaledFont.fullName)")
        }
    }
}


//
//  URLBuilder.swift
//  Yawp
//
//  Created by Paul Schifferer on 21/5/17.
//  Copyright © 2017 Pilgrimage Software. All rights reserved.
//

import Foundation

public struct URLHelper {

    public static func buildURL(from urlBase : String, isHTTPS : Bool) -> URL? {
        return URL(string: "http\(isHTTPS ? "s" : "")://\(urlBase)")
    }

    public static func trim(url : URL) -> (String, Bool) {
        let s = url.absoluteString

        if s.hasPrefix("https:") {
            return (s.substring(from: s.index(s.startIndex, offsetBy: 6)), true)
        }
        else if s.hasPrefix("http:") {
            return (s.substring(from: s.index(s.startIndex, offsetBy: 5)), false)
        }

        return (s, false)
    }

}

Make the URL helper a bit smarter to handle inconsistencies in canonical URLs.

//
//  URLBuilder.swift
//  Yawp
//
//  Created by Paul Schifferer on 21/5/17.
//  Copyright © 2017 Pilgrimage Software. All rights reserved.
//

import Foundation

public struct URLHelper {

    public static func buildURL(from urlBase : String, isHTTPS : Bool) -> URL? {
        if urlBase.hasPrefix("//"),
            let url = URL(string: "http\(isHTTPS ? "s" : ""):\(urlBase)") {
            return url
        }
        else if let url = URL(string: "http\(isHTTPS ? "s" : "")://\(urlBase)") {
            return url
        }

        return URL(string: urlBase)
    }

    public static func trim(url : URL) -> (String, Bool) {
        let s = url.absoluteString

        if s.hasPrefix("https:") {
            return (s.substring(from: s.index(s.startIndex, offsetBy: 6)), true)
        }
        else if s.hasPrefix("http:") {
            return (s.substring(from: s.index(s.startIndex, offsetBy: 5)), false)
        }

        return (s, false)
    }

}


//
//  main.swift
//  ParseCSV
//
//  Created by Alexander Farber on 27.06.21.
//

import Foundation

func process(string: String) throws {
    print("your code here")
}

func processFile(at url: URL) throws {
    let s = try String(contentsOf: url)
    try process(string: s)
}

func main() {
    guard CommandLine.arguments.count > 1 else {
        print("usage: \(CommandLine.arguments[0]) file...")
        return
    }
    for path in CommandLine.arguments[1...] {
        do {
            let u = URL(fileURLWithPath: path)
            try processFile(at: u)
        } catch {
            print("error processing: \(path): \(error)")
        }
    }
}

main()
exit(EXIT_SUCCESS)

Split lines by a pipe symbol

//
//  main.swift
//  ParseCSV
//
//  Created by Alexander Farber on 27.06.21.
//

import Foundation

func process(string: String) throws {
    let lines = string.split(separator: "\n")
    for line in lines {
        let columns = line.split(separator: "|", omittingEmptySubsequences: true)
        for column in columns {
            print("column: \(column)")
        }
    }
}

func processFile(at url: URL) throws {
    let s = try String(contentsOf: url)
    try process(string: s)
}

func main() {
    guard CommandLine.arguments.count > 1 else {
        print("usage: \(CommandLine.arguments[0]) file...")
        return
    }
    for path in CommandLine.arguments[1...] {
        do {
            let u = URL(fileURLWithPath: path)
            try processFile(at: u)
        } catch {
            print("error processing: \(path): \(error)")
        }
    }
}

main()
exit(EXIT_SUCCESS)


/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 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 swiftra

get("/abc") { req in
    return Response("/abc was requested with GET")
}

post("/abc") { req in
    return "/abc was requested with POST, body = \(req.body)"
}

get("/def") { req in
    return "/def was was requested with GET"
}

serve(8080)

Add importing Glibc for Linux platforms

/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 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 swiftra

#if os(Linux)
    import Glibc
#endif

get("/abc") { req in
    return Response("/abc was requested with GET")
}

post("/abc") { req in
    return "/abc was requested with POST, body = \(req.body)"
}

get("/def") { req in
    return "/def was was requested with GET"
}

serve(8080)


//
//  LinuxMain.swift
//  SwiftSoup
//
//  Created by Nabil Chatbi on 20/12/16.
//  Copyright © 2016 Nabil Chatbi. All rights reserved.
//

import XCTest
@testable import SwiftSoupTests

XCTMain([
	testCase(CssTest.allTests),
	testCase(ElementsTest.allTests),
	testCase(QueryParserTest.allTests),
	testCase(SelectorTest.allTests),
	testCase(AttributeParseTest.allTests),
	testCase(CharacterReaderTest.allTests),
	testCase(HtmlParserTest.allTests),
	testCase(ParseSettingsTest.allTests),
	testCase(TagTest.allTests),
	testCase(TokenQueueTest.allTests),
	testCase(XmlTreeBuilderTest.allTests),
	testCase(FormElementTest.allTests),
	testCase(EntitiesTest.allTests),
	testCase(DocumentTypeTest.allTests),
	testCase(TextNodeTest.allTests),
	testCase(DocumentTest.allTests),
	testCase(AttributesTest.allTests),
	testCase(NodeTest.allTests),
	testCase(AttributeTest.allTests),
	testCase(CleanerTest.allTests)
	])

Add missing tests to Linux

//
//  LinuxMain.swift
//  SwiftSoup
//
//  Created by Nabil Chatbi on 20/12/16.
//  Copyright © 2016 Nabil Chatbi. All rights reserved.
//

import XCTest
@testable import SwiftSoupTests

XCTMain([
	testCase(CssTest.allTests),
	testCase(ElementsTest.allTests),
	testCase(QueryParserTest.allTests),
	testCase(SelectorTest.allTests),
	testCase(AttributeParseTest.allTests),
	testCase(CharacterReaderTest.allTests),
	testCase(HtmlParserTest.allTests),
	testCase(ParseSettingsTest.allTests),
	testCase(TagTest.allTests),
	testCase(TokenQueueTest.allTests),
	testCase(XmlTreeBuilderTest.allTests),
	testCase(FormElementTest.allTests),
	testCase(ElementTest.allTests),
	testCase(EntitiesTest.allTests),
	testCase(DocumentTypeTest.allTests),
	testCase(TextNodeTest.allTests),
	testCase(DocumentTest.allTests),
	testCase(AttributesTest.allTests),
	testCase(NodeTest.allTests),
	testCase(AttributeTest.allTests),
	testCase(CleanerTest.allTests)
	])


import PackageDescription

let package = Package(
    name: "Smud"
)

Add CEvent and ConfigFile imports

import PackageDescription

let package = Package(
    name: "Smud",
    dependencies: [
	    .Package(url: "https://github.com/smud/CEvent.git", majorVersion: 0),
	    .Package(url: "https://github.com/smud/ConfigFile.git", majorVersion: 0),
    ]
)


// swift-tools-version:5.0
//
// Package.swift
// Thingy
//
// Created by Bojan Dimovski on 03.4.17.
// Copyright (c) 2017 Bojan Dimovski.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//                    Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
//  0. You just DO WHAT THE FUCK YOU WANT TO.
//
//

import PackageDescription

let package = Package(
    name: "Thingy",
    platforms: [
        .iOS(.v8),
        .tvOS(.v9),
        .watchOS(.v2)
    ],
    products: [
        .library(name: "Thingy", targets: ["Thingy"])
    ],
    dependencies: [],
    targets: [
        .target(
            name: "Thingy",
            path: "Sources")
    ]
)

Add the test target to the SPM manifest.

// swift-tools-version:5.0
//
// Package.swift
// Thingy
//
// Created by Bojan Dimovski on 03.4.17.
// Copyright (c) 2017 Bojan Dimovski.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//                    Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
//  0. You just DO WHAT THE FUCK YOU WANT TO.
//
//

import PackageDescription

let package = Package(
    name: "Thingy",
    platforms: [
        .iOS(.v8),
        .tvOS(.v9),
        .watchOS(.v2)
    ],
    products: [
        .library(name: "Thingy", targets: ["Thingy"])
    ],
    dependencies: [],
    targets: [
        .target(
            name: "Thingy",
            path: "Sources"),
		.testTarget(
				name: "ThingyTests",
				dependencies: ["Thingy"],
				path: "Tests"),
    ]
)


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "Song",
    products: [
        .executable(name: "song", targets: ["Sing"]),
        .library(name: "Song", targets: ["Song"])
    ],
    dependencies: [
        .package(url: "https://github.com/dcutting/Syft.git", .branch("develop")),
        .package(url: "https://github.com/apple/swift-package-manager.git", from: "0.1.0"),
        .package(url: "https://github.com/dcutting/linenoise-swift.git", .branch("master")),
    ],
    targets: [
        .target(
            name: "Sing",
            dependencies: ["Song", "Utility", "LineNoise"]),
        .target(
            name: "Song",
            dependencies: ["Syft", "Utility"]),
        .testTarget(
            name: "SongTests",
            dependencies: ["Song"]),
        .testTarget(
            name: "SongPerformanceTests",
            dependencies: ["Song"])
    ]
)

Update to Swift 4.1 tools.

// swift-tools-version:4.1

import PackageDescription

let package = Package(
    name: "Song",
    products: [
        .executable(name: "song", targets: ["Sing"]),
        .library(name: "Song", targets: ["Song"])
    ],
    dependencies: [
        .package(url: "https://github.com/dcutting/Syft.git", .branch("develop")),
        .package(url: "https://github.com/apple/swift-package-manager.git", from: "0.1.0"),
        .package(url: "https://github.com/dcutting/linenoise-swift.git", .branch("master")),
    ],
    targets: [
        .target(
            name: "Sing",
            dependencies: ["Song", "Utility", "LineNoise"]),
        .target(
            name: "Song",
            dependencies: ["Syft", "Utility"]),
        .testTarget(
            name: "SongTests",
            dependencies: ["Song"]),
        .testTarget(
            name: "SongPerformanceTests",
            dependencies: ["Song"])
    ]
)


//
//  main.swift
//  mas-cli
//
//  Created by Andrew Naylor on 11/07/2015.
//  Copyright © 2015 Andrew Naylor. All rights reserved.
//

import Foundation

var client = ISStoreClient(storeClientType: 0)

var downloadQueue = CKDownloadQueue.sharedDownloadQueue()
downloadQueue.addObserver(DownloadQueueObserver())

let registry = CommandRegistry<MASError>()
let helpCommand = HelpCommand(registry: registry)
registry.register(AccountCommand())
registry.register(InstallCommand())
registry.register(ListInstalledCommand())
registry.register(ListUpdatesCommand())
registry.register(helpCommand)

registry.main(defaultVerb: helpCommand.verb, errorHandler: { error in
    fputs(error.description + "\n", stderr)
})

Remove the unused store client

//
//  main.swift
//  mas-cli
//
//  Created by Andrew Naylor on 11/07/2015.
//  Copyright © 2015 Andrew Naylor. All rights reserved.
//

import Foundation

var downloadQueue = CKDownloadQueue.sharedDownloadQueue()
downloadQueue.addObserver(DownloadQueueObserver())

let registry = CommandRegistry<MASError>()
let helpCommand = HelpCommand(registry: registry)
registry.register(AccountCommand())
registry.register(InstallCommand())
registry.register(ListInstalledCommand())
registry.register(ListUpdatesCommand())
registry.register(helpCommand)

registry.main(defaultVerb: helpCommand.verb, errorHandler: { error in
    fputs(error.description + "\n", stderr)
})


// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "GABoardGameGeek",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "GABoardGameGeek",
            targets: ["GABoardGameGeek"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.5.0")),
        .package(url: "https://github.com/drmohundro/SWXMLHash.git", .upToNextMajor(from: "6.0.0"))
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "GABoardGameGeek",
            dependencies: ["Alamofire", "SWXMLHash"]),
        .testTarget(
            name: "GABoardGameGeekTests",
            dependencies: ["GABoardGameGeek"]),
    ]
)

Update list of supported platform versions

// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "GABoardGameGeek",
    platforms: [
        .macOS(.v10_12),
        .iOS(.v10),
        .tvOS(.v10),
        .watchOS(.v3)
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "GABoardGameGeek",
            targets: ["GABoardGameGeek"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.5.0")),
        .package(url: "https://github.com/drmohundro/SWXMLHash.git", .upToNextMajor(from: "6.0.0"))
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "GABoardGameGeek",
            dependencies: ["Alamofire", "SWXMLHash"]),
        .testTarget(
            name: "GABoardGameGeekTests",
            dependencies: ["GABoardGameGeek"]),
    ]
)


// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "ISEmojiView",
    platforms: [.iOS(.v13)],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "ISEmojiView",
            targets: ["ISEmojiView"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "ISEmojiView",
            dependencies: [],
            path: "Sources",
            resources: [
                .process("ISEmojiView/Assets"),
                .copy("ISEmojiView/Assets/Views/*.xib")
            ]
            ),
    ]
)

Reduce iOS deployment target to 12.0

// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "ISEmojiView",
    platforms: [.iOS(.v12)],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "ISEmojiView",
            targets: ["ISEmojiView"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "ISEmojiView",
            dependencies: [],
            path: "Sources",
            resources: [
                .process("ISEmojiView/Assets"),
                .copy("ISEmojiView/Assets/Views/*.xib")
            ]
            ),
    ]
)


import Foundation

class GradeSchool {
    var db = [Int: [String]]()

    func addStudent(name: String, grade: Int) {
        var students = studentsInGrade(grade)
        students.append(name)
        db[grade] = students
    }

    func studentsInGrade(grade: Int) -> [String] {
        return db[grade] ?? []
    }g

    func sortedRoster() -> [Int: [String]] {
        var sortedDb = db
        for (grade, students) in sortedDb {
            sortedDb[grade] = students.sorted { $0 < $1 }
        }
        return sortedDb
    }
}

Clean up a simple typo

import Foundation

class GradeSchool {
    var db = [Int: [String]]()

    func addStudent(name: String, grade: Int) {
        var students = studentsInGrade(grade)
        students.append(name)
        db[grade] = students
    }

    func studentsInGrade(grade: Int) -> [String] {
        return db[grade] ?? []
    }

    func sortedRoster() -> [Int: [String]] {
        var sortedDb = db
        for (grade, students) in sortedDb {
            sortedDb[grade] = students.sorted { $0 < $1 }
        }
        return sortedDb
    }
}


//
//  TextViewTableViewCell.swift
//  pass
//
//  Created by Mingshen Sun on 11/2/2017.
//  Copyright © 2017 Bob Sun. All rights reserved.
//

import UIKit

class TextViewTableViewCell: ContentTableViewCell {

    @IBOutlet weak var contentTextView: UITextView!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    override func getContent() -> String? {
        return contentTextView.text
    }

    override func setContent(content: String?) {
        contentTextView.text = content
    }
}

Fix UITextView inner margin to zero

//
//  TextViewTableViewCell.swift
//  pass
//
//  Created by Mingshen Sun on 11/2/2017.
//  Copyright © 2017 Bob Sun. All rights reserved.
//

import UIKit

class TextViewTableViewCell: ContentTableViewCell {

    @IBOutlet weak var contentTextView: UITextView!
    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentTextView.textContainer.lineFragmentPadding = 0
        self.contentTextView.textContainerInset = .zero
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    override func getContent() -> String? {
        return contentTextView.text
    }

    override func setContent(content: String?) {
        contentTextView.text = content
    }
}


import Foundation

typealias NotificationsCenterIconName = String

//Use if you need to make the system (SFSymbols) vs custom distinction
enum NotificationsCenterIconType: Equatable {
    case custom(NotificationsCenterIconName)
    case system(NotificationsCenterIconName)

    static var lock: NotificationsCenterIconType {
        return .system("lock")
    }

    static var link: NotificationsCenterIconType {
        return .system("link")
    }

    static var personFill: NotificationsCenterIconType {
        return .system("person.circle.fill")
    }

    static var person: NotificationsCenterIconType {
        return .system("person")
    }

    static var documentFill: NotificationsCenterIconType {
        if #available(iOS 14, *) {
            return .system("doc.plaintext.fill")
        }
        return .system("doc.text.fill")
    }

    static var document: NotificationsCenterIconType {
        if #available(iOS 14, *) {
            return .system("doc.plaintext")
        }
        return .system("doc.text")
    }

    static var photo: NotificationsCenterIconType {
        return .system("photo")
    }

    static var diff: NotificationsCenterIconType {
        return .custom("notifications-icon-diff") //TODO: Need to add icon to project
    }

    static var wikidata: NotificationsCenterIconType {
        return .custom("notifications-project-wikidata")
    }
}

Use SF Symbol based on OS availability for diff type.

import Foundation

typealias NotificationsCenterIconName = String

//Use if you need to make the system (SFSymbols) vs custom distinction
enum NotificationsCenterIconType: Equatable {
    case custom(NotificationsCenterIconName)
    case system(NotificationsCenterIconName)

    static var lock: NotificationsCenterIconType {
        return .system("lock")
    }

    static var link: NotificationsCenterIconType {
        return .system("link")
    }

    static var personFill: NotificationsCenterIconType {
        return .system("person.circle.fill")
    }

    static var person: NotificationsCenterIconType {
        return .system("person")
    }

    static var documentFill: NotificationsCenterIconType {
        if #available(iOS 14, *) {
            return .system("doc.plaintext.fill")
        }
        return .system("doc.text.fill")
    }

    static var document: NotificationsCenterIconType {
        if #available(iOS 14, *) {
            return .system("doc.plaintext")
        }
        return .system("doc.text")
    }

    static var photo: NotificationsCenterIconType {
        return .system("photo")
    }

    static var diff: NotificationsCenterIconType {
        if #available(iOS 15, *) {
            return .system("chevron.left.forwardslash.chevron.right")
        } else {
            return .system("chevron.left.slash.chevron.right")
        }
    }

    static var wikidata: NotificationsCenterIconType {
        return .custom("notifications-project-wikidata")
    }
}


import Foundation

class SecureHTTPAdapter: HTTPAdapter {
    override init(serverHost: String, serverPort: Int, auth: Authentication?) {
        super.init(serverHost: serverHost, serverPort: serverPort, auth: auth)
        secured = false
    }
}

Fix HTTP proxy over SSL

import Foundation

class SecureHTTPAdapter: HTTPAdapter {
    override init(serverHost: String, serverPort: Int, auth: Authentication?) {
        super.init(serverHost: serverHost, serverPort: serverPort, auth: auth)
        secured = true
    }
}