import Foundation

struct APIDefaults {
    private static let baseURL = URL(string: "http://localhost:9000")!

    static func enhanceRequest(_ request: Request) -> Request {
        guard var components = URLComponents(url: request.url, resolvingAgainstBaseURL: true) else {
            fatalError("Attempt to enhance malformed Request: \(request)")
        }

        components.scheme = baseURL.scheme
        components.host = baseURL.host
        components.port = baseURL.port

        return Request(
            url: components.url!,
            method: request.method,
            parameters: request.parameters,
            headers: request.headers,
            parameterEncoding: request.parameterEncoding
        )
    }
}

Use hosted API backend as base URL

import Foundation

struct APIDefaults {
    private static let baseURL = URL(string: "https://democracy-api.herokuapp.com")!

    static func enhanceRequest(_ request: Request) -> Request {
        guard var components = URLComponents(url: request.url, resolvingAgainstBaseURL: true) else {
            fatalError("Attempt to enhance malformed Request: \(request)")
        }

        components.scheme = baseURL.scheme
        components.host = baseURL.host
        components.port = baseURL.port

        return Request(
            url: components.url!,
            method: request.method,
            parameters: request.parameters,
            headers: request.headers,
            parameterEncoding: request.parameterEncoding
        )
    }
}


//
//  MapViewControllerUITests.swift
//  MapViewControllerUITests
//
//  Created by Peng Wang on 8/3/15.
//  Copyright © 2015 pengxwang. All rights reserved.
//

import XCTest

class MapViewControllerUITests: XCTestCase {

    let existsPredicate = NSPredicate(format: "exists == 1")

    override func setUp() {
        super.setUp()

        self.continueAfterFailure = false
        XCUIApplication().launch()
    }

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

    func testBasicUserFlow() {
        let app = XCUIApplication()
        let presentButton = app.buttons["Show Map"]

        presentButton.tap()

        let locationAnnotation = app.otherElements["Current Location"]

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: locationAnnotation, handler: nil)
        self.waitForExpectationsWithTimeout(5.0, handler: nil)

        let searchField = app.navigationBars["Select Nearby Location"].searchFields["Search for place or address"]
        searchField.tap()
        searchField.typeText("Apple Inc., Cupertino")
        app.tables["Search results"].staticTexts["Apple Inc., 1 Infinite Loop, Cupertino, CA 95014-2083, United States"].tap()

        app.buttons["Select address in callout view"].tap()

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: presentButton, handler: nil)
        self.waitForExpectationsWithTimeout(2.0, handler: nil)
    }

}

Refactor basic-user-flow UI test to separate element queries

//
//  MapViewControllerUITests.swift
//  MapViewControllerUITests
//
//  Created by Peng Wang on 8/3/15.
//  Copyright © 2015 pengxwang. All rights reserved.
//

import XCTest

class MapViewControllerUITests: XCTestCase {

    let existsPredicate = NSPredicate(format: "exists == 1")

    override func setUp() {
        super.setUp()

        self.continueAfterFailure = false
        XCUIApplication().launch()
    }

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

    func testBasicUserFlow() {
        let app = XCUIApplication()
        let presentButton = app.buttons["Show Map"]
        let locationAnnotation = app.otherElements["Current Location"]
        let searchField = app.navigationBars["Select Nearby Location"].searchFields["Search for place or address"]
        let searchResult = app.tables["Search results"].staticTexts["Apple Inc., 1 Infinite Loop, Cupertino, CA 95014-2083, United States"]
        let selectButton = app.buttons["Select address in callout view"]

        presentButton.tap()

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: locationAnnotation, handler: nil)
        self.waitForExpectationsWithTimeout(5.0, handler: nil)

        searchField.tap()
        searchField.typeText("Apple Inc., Cupertino")
        searchResult.tap()
        selectButton.tap()

        self.expectationForPredicate(self.existsPredicate, evaluatedWithObject: presentButton, handler: nil)
        self.waitForExpectationsWithTimeout(2.0, handler: nil)
    }

}


//
//  MDWebViewController.swift
//  Markdown
//
//  Created by Boris Bügling on 01/12/15.
//  Copyright © 2015 Contentful GmbH. All rights reserved.
//

import MMMarkdown
import WebKit

class MDWebViewController: UIViewController {
    convenience init() {
        self.init(nibName: nil, bundle: nil)

        self.tabBarItem = UITabBarItem(title: "WebView", image: UIImage(named: "webView"), tag: 0)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: view.bounds)
        view.addSubview(webView)

        client.fetchEntry("4bJdF7zhwkwcWq202gmkuM").1.next { (entry) in
            if let markdown = entry.fields["body"] as? String {
                do {
                    let html = try MMMarkdown.HTMLStringWithMarkdown(markdown)
                    webView.loadHTMLString(html, baseURL: nil)
                } catch let error {
                    showError(error, self)
                }
            }
        }.error { (error) in
            showError(error, self)
        }
    }
}

Use GH flavoured MD extensions for web view

//
//  MDWebViewController.swift
//  Markdown
//
//  Created by Boris Bügling on 01/12/15.
//  Copyright © 2015 Contentful GmbH. All rights reserved.
//

import MMMarkdown
import WebKit

class MDWebViewController: UIViewController {
    convenience init() {
        self.init(nibName: nil, bundle: nil)

        self.tabBarItem = UITabBarItem(title: "WebView", image: UIImage(named: "webView"), tag: 0)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: view.bounds)
        view.addSubview(webView)

        webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: tabBarController?.tabBar.frame.size.height ?? 0, right: 0)
        webView.scrollView.scrollIndicatorInsets = webView.scrollView.contentInset

        client.fetchEntry("4bJdF7zhwkwcWq202gmkuM").1.next { (entry) in
            if let markdown = entry.fields["body"] as? String {
                do {
                    let html = try MMMarkdown.HTMLStringWithMarkdown(markdown, extensions: MMMarkdownExtensions.GitHubFlavored)
                    webView.loadHTMLString(html, baseURL: nil)
                } catch let error {
                    showError(error, self)
                }
            }
        }.error { (error) in
            showError(error, self)
        }
    }
}


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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(type(Graph()), ==, .Unit)
	}

	func testGraphsWithOneReturnHaveVariableType() {
		assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))])), ==, .function(0, .Unit))
	}

	func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))])), ==, .function(1, 0))
	}
}

private func type(graph: Graph<Node>) -> Term {
	return simplify(constraints(graph).0)
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest

Test b -> a -> ()

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

final class InferenceTests: XCTestCase {
	func testGraphsWithoutReturnsHaveUnitType() {
		assert(type(Graph()), ==, .Unit)
	}

	func testGraphsWithOneReturnHaveVariableType() {
		assert(type(Graph(nodes: [Identifier(): .Return((0, .Unit))])), ==, 0)
	}

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionTypeReturningUnit() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit))])), ==, .function(0, .Unit))
	}

	func testGraphsWithOneParameterAndOneReturnHaveFunctionTypeFromVariableToDifferentVariable() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Return((0, .Unit))])), ==, .function(1, 0))
	}

	func testGraphsWithMultipleParametersHaveCurriedFunctionType() {
		assert(type(Graph(nodes: [Identifier(): .Parameter((0, .Unit)), Identifier(): .Parameter((0, .Unit))])), ==, .function(1, .function(0, .Unit)))
	}
}

private func type(graph: Graph<Node>) -> Term {
	return simplify(constraints(graph).0)
}

private func simplify(type: Term) -> Term {
	return Substitution(lazy(enumerate(type.freeVariables |> (flip(sorted) <| { $0.value < $1.value }))).map { ($1, Term(integerLiteral: $0)) }).apply(type)
}

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest


//
//  ActivityIndicatorPlugin.swift
//  RxHttpClient
//
//  Created by Anton Efimenko on 28.01.17.
//  Copyright © 2017 RxSwiftCommunity. All rights reserved.
//

import Foundation
import UIKit

protocol UIApplicationType : class {
	var isNetworkActivityIndicatorVisible: Bool { get set }
}

extension UIApplication : UIApplicationType { }

/// Plugin that shows Network activity indicator if there is active network request
public final class NetworkActivityIndicatorPlugin : RequestPluginType {
	let application: UIApplicationType

	var counter = 0 {
		didSet { application.isNetworkActivityIndicatorVisible = counter != 0 }
	}

	convenience public init(application: UIApplication = UIApplication.shared) {
		self.init(applicationType: application)
	}

	init(applicationType: UIApplicationType) {
		self.application = applicationType
	}

	public func prepare(request: URLRequest) -> URLRequest {
		return request
	}

	public func beforeSend(request: URLRequest) {
		counter += 1
	}

	public func afterFailure(response: URLResponse?, error: Error, data: Data?) {
		counter -= 1
	}

	public func afterSuccess(response: URLResponse?, data: Data?) {
		counter -= 1
	}
}

Set isNetworkActivityIndicatorVisible in Main thread

//
//  ActivityIndicatorPlugin.swift
//  RxHttpClient
//
//  Created by Anton Efimenko on 28.01.17.
//  Copyright © 2017 RxSwiftCommunity. All rights reserved.
//

import Foundation
import UIKit

protocol UIApplicationType : class {
	var isNetworkActivityIndicatorVisible: Bool { get set }
}

extension UIApplication : UIApplicationType { }

/// Plugin that shows Network activity indicator if there is active network request
public final class NetworkActivityIndicatorPlugin : RequestPluginType {
	let application: UIApplicationType

	var counter = 0 {
		didSet {
			DispatchQueue.main.async {
				self.application.isNetworkActivityIndicatorVisible = self.counter != 0
			}
		}
	}

	convenience public init(application: UIApplication = UIApplication.shared) {
		self.init(applicationType: application)
	}

	init(applicationType: UIApplicationType) {
		self.application = applicationType
	}

	public func prepare(request: URLRequest) -> URLRequest {
		return request
	}

	public func beforeSend(request: URLRequest) {
		counter += 1
	}

	public func afterFailure(response: URLResponse?, error: Error, data: Data?) {
		counter -= 1
	}

	public func afterSuccess(response: URLResponse?, data: Data?) {
		counter -= 1
	}
}


import UIKit

final class VSettingsMemoryListFooter:UICollectionReusableView
{
    weak var labelSize:UILabel!
    weak var buttonClean:UIButton!
    weak var labelEmpty:UILabel!

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.white

        factoryViews()
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    //MARK: internal

    func config(controller:CSettingsMemory)
    {

    }
}

Update and show size on footer

import UIKit

final class VSettingsMemoryListFooter:UICollectionReusableView
{
    weak var labelSize:UILabel!
    weak var buttonClean:UIButton!
    weak var labelEmpty:UILabel!

    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.white

        factoryViews()
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    //MARK: private

    private func updateSize(
        model:MSettingsMemory,
        garbage:MSettingsMemoryProjects)
    {
        guard

            let megas:String = model.bytesAsMB(bytes:garbage.size)

        else
        {
            return
        }

        labelEmpty.isHidden = true
        labelSize.text = megas
        labelSize.isHidden = false
        buttonClean.isHidden = false
    }

    //MARK: internal

    func config(controller:CSettingsMemory)
    {
        guard

            let model:MSettingsMemory = controller.model,
            let garbage:MSettingsMemoryProjects = model.garbage,
            garbage.size > 0

        else
        {
            return
        }

        updateSize(
            model:model,
            garbage:garbage)
    }
}


//
//  BeerTests.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/3/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import XCTest
@testable import BreweryDB

class BeerTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

}

Test object allocation and deallocation

//
//  BeerTests.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/3/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import XCTest
@testable import BreweryDB

class BeerTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testBeerCanBeInitialized() {
        let beer: Beer? = Beer()
        XCTAssertNotNil(beer)
    }

    func testBeerCanBeDeinitialized() {
        var beer: Beer? = Beer()
        beer = nil
        XCTAssertNil(beer)
    }

}


//
//  shim.swift
//  Yams
//
//  Created by Norio Nomura 1/27/18.
//  Copyright (c) 2018 Yams. All rights reserved.
//

#if !swift(>=4.1)

    extension Array {
        public func compactMap(_ transform: (Element) throws -> String?) rethrows -> [String] {
            return try flatMap(transform)
        }
    }

    extension LazyMapCollection {
        public func compactMap(_ transform: (Element) throws -> String?) rethrows -> [String] {
            return try flatMap(transform)
        }
    }

    extension Sequence {
        public func compactMap<ElementOfResult>(
            _ transform: (Self.Element
            ) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
            return try flatMap(transform)
        }
    }

#endif

Change access level of `compactMap()` from `public` to `internal`

//
//  shim.swift
//  Yams
//
//  Created by Norio Nomura 1/27/18.
//  Copyright (c) 2018 Yams. All rights reserved.
//

#if !swift(>=4.1)

    extension Array {
        func compactMap(_ transform: (Element) throws -> String?) rethrows -> [String] {
            return try flatMap(transform)
        }
    }

    extension LazyMapCollection {
        func compactMap(_ transform: (Element) throws -> String?) rethrows -> [String] {
            return try flatMap(transform)
        }
    }

    extension Sequence {
        func compactMap<ElementOfResult>(
            _ transform: (Self.Element
            ) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
            return try flatMap(transform)
        }
    }

#endif


//
//  AppDelegate.swift
//  KeyboardKitDemo
//
//  Created by Daniel Saidi on 2019-10-01.
//  Copyright © 2019 Daniel Saidi. All rights reserved.
//

import UIKit
import KeyboardKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print(isKeyboardEnabled("com.danielsaidi.KeyboardKitDemo.KeyboardKitDemoKeyboard"))
        return true
    }

    // MARK: UISceneSession Lifecycle

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
}

Adjust enabled print to be more readable

//
//  AppDelegate.swift
//  KeyboardKitDemo
//
//  Created by Daniel Saidi on 2019-10-01.
//  Copyright © 2019 Daniel Saidi. All rights reserved.
//

import UIKit
import KeyboardKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let isEnabled = isKeyboardEnabled("com.danielsaidi.KeyboardKitDemo.KeyboardKitDemoKeyboard")
        print(isEnabled ? "Keyboard is enabled" : "Keyboard is disabled")
        return true
    }

    // MARK: UISceneSession Lifecycle

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
}


// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s

// Ensure that the superclass's generid argument canonicalizes to
// Sequence.Element.

// CHECK: @"symbolic _____y7ElementSTQzG

public protocol ElementTypeProtocol: RandomAccessCollection {
    typealias ElementType = Element
}
extension Array: ElementTypeProtocol {}

private class WrapperBase<T> {}
private final class WrapperDerived<C: ElementTypeProtocol>: WrapperBase<C.ElementType> {
    init(base: C) {
        let _ = base
    }
}

Fix typo in test case

// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s

// Ensure that the superclass's generic argument canonicalizes to
// Sequence.Element.

// CHECK: @"symbolic _____y7ElementSTQzG

public protocol ElementTypeProtocol: RandomAccessCollection {
    typealias ElementType = Element
}
extension Array: ElementTypeProtocol {}

private class WrapperBase<T> {}
private final class WrapperDerived<C: ElementTypeProtocol>: WrapperBase<C.ElementType> {
    init(base: C) {
        let _ = base
    }
}


import Vapor
import HTTP
import Node
import Foundation

final class Sighting: Model {
    var id: Node?
    var bird: String
    var time: Int
    var exists: Bool = false

    init(bird: String, time: Double) {
        self.bird = bird
        self.time = Int(time)
    }

    convenience init(bird: String) {
        self.init(bird: bird, time: NSDate().timeIntervalSince1970.doubleValue)
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        bird = try node.extract("bird")
        time = try node.extract("time")
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "bird": bird,
            "time": time
            ])
    }

    static func prepare(_ database: Database) throws {
        try database.create("Sightings") { sightings in
            sightings.id()
            sightings.string("bird", optional: false)
            sightings.int("time")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete("Sightings")
    }
}

Use readable date in sightings

import Vapor
import HTTP
import Node
import Foundation

final class Sighting: Model {
    var id: Node?
    var bird: String
    var time: Int
    var exists: Bool = false

    init(bird: String, time: Double) {
        self.bird = bird
        self.time = Int(time)
    }

    convenience init(bird: String) {
        self.init(bird: bird, time: NSDate().timeIntervalSince1970.doubleValue)
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        bird = try node.extract("bird")
        time = try node.extract("time")
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "bird": bird,
            "time": time,
            "date": DateFormatter.localizedString(from: NSDate(timeIntervalSince1970:TimeInterval(time)) as Date, dateStyle: .short, timeStyle: .short)
            ])
    }

    static func prepare(_ database: Database) throws {
        try database.create("Sightings") { sightings in
            sightings.id()
            sightings.string("bird", optional: false)
            sightings.int("time")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete("Sightings")
    }
}


// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -emit-ir
([-.f\n{}{$0(n&[]{

Mark a recent compiler crasher as non-deterministic

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// REQUIRES: deterministic-behavior
// Type checking causes a use-after-free.
// RUN: not --crash %target-swift-frontend %s -emit-ir
([-.f\n{}{$0(n&[]{


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

extension Module {
	public static var churchPair: Module {
		let Pair = Declaration("Pair",
			type: Recur.lambda(.Type, .Type, .Type) { A, B, Result in Recur.lambda(A, B, Recur.FunctionType(A, B, Result), const(Result)) },
			value: Recur.lambda(.Type, .Type, .Type) { A, B, Result in Recur.lambda(A, B, .FunctionType(A, B, Result)) { a, b, f in f[a, b] } })
		return Module([ churchBoolean ], [ Pair ])
	}
}

import Prelude

Rename Pair to pair, since it’s the constructor, not the type.

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

extension Module {
	public static var churchPair: Module {
		let pair = Declaration("pair",
			type: Recur.lambda(.Type, .Type, .Type) { A, B, Result in Recur.lambda(A, B, Recur.FunctionType(A, B, Result), const(Result)) },
			value: Recur.lambda(.Type, .Type, .Type) { A, B, Result in Recur.lambda(A, B, .FunctionType(A, B, Result)) { a, b, f in f[a, b] } })
		return Module([ churchBoolean ], [ pair ])
	}
}

import Prelude


import UIKit

public protocol Reusable { }

extension Reusable {

    public static var reuseIdentifier: String {
        return NSStringFromClass(self as! AnyObject.Type)
    }

}

extension UITableViewCell: Reusable { }
extension UICollectionReusableView: Reusable { }

extension UITableView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UITableViewCell {
        register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

extension UICollectionView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UICollectionViewCell {
        register(T.classForCoder(), forCellWithReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

Add UITableView and UICollectionView dequeue extensions for headers/footers

import UIKit

public protocol Reusable { }

extension Reusable {
    public static var reuseIdentifier: String {
        return NSStringFromClass(self as! AnyObject.Type)
    }
}

extension UITableViewCell: Reusable { }
extension UITableViewHeaderFooterView: Reusable { }
extension UICollectionReusableView: Reusable { }

extension UITableView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UITableViewCell {
        register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }

    public func dequeueHeaderFooterView<T>() -> T where T: UITableViewHeaderFooterView {
        register(T.classForCoder(), forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as! T
    }
}

extension UICollectionView {
    public func dequeueCell<T>(for indexPath: IndexPath) -> T where T: UICollectionViewCell {
        register(T.classForCoder(), forCellWithReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }

    public func dequeueSupplementaryView<T>(ofKind kind: String, for indexPath: IndexPath) -> T where T: UICollectionReusableView {
        register(T.classForCoder(), forSupplementaryViewOfKind: kind, withReuseIdentifier: T.reuseIdentifier)
        return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}


.Package(url: "https://github.com/tfrank64/MongoKitten.git", majorVersion: 3),

Set specific tfrank64 MongoKitten version


//
//  ETCornerRadiusAction.swift
//  EasyTransitioning
//
//  Created by Jerry Yu on 2016-11-12.
//  Copyright © 2016 Jerry Yu. All rights reserved.
//

import UIKit

public struct ETCornerRadiusAction: ETAction {
	public let toCornerRadius: CGFloat
	public let fromCornerRadius: CGFloat

	public init(toCornerRadius: CGFloat, fromCornerRadius: CGFloat) {
		self.toCornerRadius = toCornerRadius
		self.fromCornerRadius = fromCornerRadius
	}

	public func setup(snapshotView: UIView?, in containerView: UIView) {
		guard let snapshotView = snapshotView else { return }
		snapshotView.layer.cornerRadius = fromCornerRadius
	}

	public func animate(snapshotView: UIView?, in containerView: UIView, animationDuration: NSTimeInterval) {
		guard let snapshotView = snapshotView else { return }
		snapshotView.layer.masksToBounds = true
		let animation = CABasicAnimation(keyPath: "cornerRadius")
		animation.toValue = toCornerRadius
		animation.duration = animationDuration
		snapshotView.layer.addAnimation(animation, forKey: "cornerRadius")
	}

	public func reversed() -> ETAction {
		return ETCornerRadiusAction(toCornerRadius: fromCornerRadius, fromCornerRadius: toCornerRadius)
	}
}

Fix jumpiness issue with cornerRadius

//
//  ETCornerRadiusAction.swift
//  EasyTransitioning
//
//  Created by Jerry Yu on 2016-11-12.
//  Copyright © 2016 Jerry Yu. All rights reserved.
//

import UIKit

public struct ETCornerRadiusAction: ETAction {
	public let toCornerRadius: CGFloat
	public let fromCornerRadius: CGFloat

	public init(toCornerRadius: CGFloat, fromCornerRadius: CGFloat) {
		self.toCornerRadius = toCornerRadius
		self.fromCornerRadius = fromCornerRadius
	}

	public func setup(snapshotView: UIView?, in containerView: UIView) {
		guard let snapshotView = snapshotView else { return }
		snapshotView.layer.cornerRadius = fromCornerRadius
	}

	public func animate(snapshotView: UIView?, in containerView: UIView, animationDuration: NSTimeInterval) {
		guard let snapshotView = snapshotView else { return }
		snapshotView.layer.masksToBounds = true
		let animation = CABasicAnimation(keyPath: "cornerRadius")
		animation.fromValue = snapshotView.layer.cornerRadius
		animation.duration = animationDuration
		snapshotView.layer.cornerRadius = toCornerRadius
		snapshotView.layer.addAnimation(animation, forKey: "cornerRadius")
	}

	public func reversed() -> ETAction {
		return ETCornerRadiusAction(toCornerRadius: fromCornerRadius, fromCornerRadius: toCornerRadius)
	}
}


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

extension Term {
	public static func equate(left: Term, _ right: Term, _ environment: [Name:Term]) -> Term? {
		let normalize: Term -> Term = { term in
			term.weakHeadNormalForm(environment, shouldRecur: false)
		}

		let left = normalize(left)
		let right = normalize(right)

		if left == right { return right }

		switch (left.out, right.out) {
		case (.Implicit, _):
			return right

		case (_, .Implicit):
			return left

		case (.Type, .Type):
			return right

		case let (.Application(a1, a2), .Application(b1, b2)):
			guard let first = equate(a1, b1, environment), second = equate(a2, b2, environment) else { return nil }
			return .Application(first, second)

		case let (.Lambda(_, a1, a2), .Lambda(i, b1, b2)):
			guard let type = equate(a1, b1, environment), body = equate(a2, b2, environment) else { return nil }
			return .Lambda(i, type, body)

		default:
			return nil
		}
	}
}

Rename the normalized variables in definitional equality.

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

extension Term {
	public static func equate(left: Term, _ right: Term, _ environment: [Name:Term]) -> Term? {
		let normalize: Term -> Term = { term in
			term.weakHeadNormalForm(environment, shouldRecur: false)
		}

		let leftʹ = normalize(left)
		let rightʹ = normalize(right)

		if leftʹ == rightʹ { return rightʹ }

		switch (leftʹ.out, rightʹ.out) {
		case (.Implicit, _):
			return rightʹ

		case (_, .Implicit):
			return leftʹ

		case (.Type, .Type):
			return rightʹ

		case let (.Application(a1, a2), .Application(b1, b2)):
			guard let first = equate(a1, b1, environment), second = equate(a2, b2, environment) else { return nil }
			return .Application(first, second)

		case let (.Lambda(_, a1, a2), .Lambda(i, b1, b2)):
			guard let type = equate(a1, b1, environment), body = equate(a2, b2, environment) else { return nil }
			return .Lambda(i, type, body)

		default:
			return nil
		}
	}
}


//
//  PusherClientOptions.swift
//  PusherSwift
//
//  Created by Hamilton Chapman on 01/04/2016.
//
//

public enum PusherHost {
    case host(String)
    case cluster(String)

    public var stringValue: String {
        switch self {
            case .host(let host): return host
            case .cluster(let cluster): return "ws-\(cluster).pusher.com"
        }
    }
}

@objc public protocol AuthRequestBuilderProtocol {
    func requestFor(socketID: String, channel: PusherChannel) -> NSMutableURLRequest?
}

public enum AuthMethod {
    case endpoint(authEndpoint: String)
    case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
    case inline(secret: String)
    case noMethod
}

@objc public class PusherClientOptions: NSObject {
    public var authMethod: AuthMethod
    public let attemptToReturnJSONObject: Bool
    public let autoReconnect: Bool
    public let host: String
    public let port: Int
    public let encrypted: Bool

    public init(
        authMethod: AuthMethod = .noMethod,
        attemptToReturnJSONObject: Bool = true,
        autoReconnect: Bool = true,
        host: PusherHost = .host("ws.pusherapp.com"),
        port: Int? = nil,
        encrypted: Bool = true) {
            self.authMethod = authMethod
            self.attemptToReturnJSONObject = attemptToReturnJSONObject
            self.autoReconnect = autoReconnect
            self.host = host.stringValue
            self.port = port ?? (encrypted ? 443 : 80)
            self.encrypted = encrypted
    }
}

Mark function not for objc usage as @nonobjc

//
//  PusherClientOptions.swift
//  PusherSwift
//
//  Created by Hamilton Chapman on 01/04/2016.
//
//

public enum PusherHost {
    case host(String)
    case cluster(String)

    public var stringValue: String {
        switch self {
            case .host(let host): return host
            case .cluster(let cluster): return "ws-\(cluster).pusher.com"
        }
    }
}

@objc public protocol AuthRequestBuilderProtocol {
    func requestFor(socketID: String, channel: PusherChannel) -> NSMutableURLRequest?
}

public enum AuthMethod {
    case endpoint(authEndpoint: String)
    case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
    case inline(secret: String)
    case noMethod
}

@objc public class PusherClientOptions: NSObject {
    public var authMethod: AuthMethod
    public let attemptToReturnJSONObject: Bool
    public let autoReconnect: Bool
    public let host: String
    public let port: Int
    public let encrypted: Bool

    @nonobjc public init(
        authMethod: AuthMethod = .noMethod,
        attemptToReturnJSONObject: Bool = true,
        autoReconnect: Bool = true,
        host: PusherHost = .host("ws.pusherapp.com"),
        port: Int? = nil,
        encrypted: Bool = true) {
            self.authMethod = authMethod
            self.attemptToReturnJSONObject = attemptToReturnJSONObject
            self.autoReconnect = autoReconnect
            self.host = host.stringValue
            self.port = port ?? (encrypted ? 443 : 80)
            self.encrypted = encrypted
    }
}


import UIKit

class ControllerList:UIViewController
{
    let model:ModelList
    private weak var viewListBar:ViewListBar!

    init()
    {
        model = ModelList()

        super.init(nibName:nil, bundle:nil)

        let viewListBar:ViewListBar = ViewListBar()
        self.viewListBar = viewListBar
        navigationItem.titleView = viewListBar
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    override func loadView()
    {
        let view:ViewList = ViewList(controller:self)
        self.view = view
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        model.loadItems
        {
            DispatchQueue.main.async
            { [weak self] in

                self?.itemsLoaded()
            }
        }
    }

    //MARK: private

    private func itemsLoaded()
    {
        viewListBar.isHidden = false

        guard

            let view:ViewList = self.view as? ViewList

        else
        {
            return
        }

        view.itemsLoaded()
    }
}

Add delegate to search bar

import UIKit

class ControllerList:UIViewController
{
    let model:ModelList
    private weak var viewListBar:ViewListBar!

    init()
    {
        model = ModelList()

        super.init(nibName:nil, bundle:nil)

        let viewListBar:ViewListBar = ViewListBar()
        viewListBar.delegate = self
        self.viewListBar = viewListBar
        navigationItem.titleView = viewListBar
    }

    required init?(coder:NSCoder)
    {
        return nil
    }

    override func loadView()
    {
        let view:ViewList = ViewList(controller:self)
        self.view = view
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        model.loadItems
        {
            DispatchQueue.main.async
            { [weak self] in

                self?.itemsLoaded()
            }
        }
    }

    //MARK: private

    private func itemsLoaded()
    {
        viewListBar.isHidden = false

        guard

            let view:ViewList = self.view as? ViewList

        else
        {
            return
        }

        view.itemsLoaded()
    }
}


import XCTest
@testable import RocksDB

class RocksDBTests: XCTestCase {
  func testExample() {
    do {
      let db = try Database(path: "/tmp/test")
      try db.put("foo", value: "bar")
      let val = try db.get("foo")
      XCTAssertEqual(val, "bar")
    } catch {
      XCTFail("\(error)")
    }
  }

  static var allTests : [(String, (RocksDBTests) -> () throws -> Void)] {
    return [
      ("testExample", testExample)
    ]
  }
}

Add a couple more tests

import XCTest
@testable import RocksDB

class RocksDBTests: XCTestCase {
  func testGetAndPut() {
    do {
      let db = try Database(path: "/tmp/test")
      try db.put("foo", value: "bar")
      let val = try db.get("foo")
      XCTAssertEqual(val!, "bar")
    } catch {
      XCTFail("\(error)")
    }
  }

  func testNilGet() {
    do {
      let db = try Database(path: "/tmp/test")
      let val = try db.get("baz")
      XCTAssertEqual(val, nil)
    } catch {
      XCTFail("\(error)")
    }
  }

  func testPutOverwrite() {
    do {
      let db = try Database(path: "/tmp/test")
      try db.put("foo", value: "bar")
      try db.put("foo", value: "baz")
      let val = try db.get("foo")
      XCTAssertEqual(val!, "baz")
    } catch {
      XCTFail("\(error)")
    }
  }

  static var allTests : [(String, (RocksDBTests) -> () throws -> Void)] {
    return [
      ("testGetAndPut", testGetAndPut),
      ("testNilGet", testNilGet),
      ("testPutOverwrite", testPutOverwrite)
    ]
  }
}


// LoginKit.h
//
// Copyright (c) 2016 Kieran Andrews
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import UIKit

public class LoginKit {

    public class func loginScreenController() -> UIViewController {
        return LoginController()
    }

    public class func getBundle() -> NSBundle {
        return NSBundle(forClass: LoginKit.self)
    }

}

Add documentation and easy access Appearance controller

// LoginKit.h
//
// Copyright (c) 2016 Kieran Andrews
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import UIKit

public class LoginKit {

    /**
     This method returns a UIView controller that will display your
     login screen.

     It can be configured using LoginKitConfig

     - returns: UIViewController generated by LoginKit
     */
    public class func loginScreenController() -> UIViewController {
        return LoginController()
    }

    public class func getBundle() -> NSBundle {
        return NSBundle(forClass: LoginKit.self)
    }

    public class func Appearance() -> AppearanceController {
        return AppearanceController.sharedInstance
    }

}


//
//  MainViewController.swift
//  Take
//
//  Created by Roopesh Chander on 15/07/14.
//  Copyright (c) 2014 Roopesh Chander. All rights reserved.
//

import UIKit

class MainViewController: UIViewController {

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func loadView() {
        var view = UIView()
        self.view = view

        var navigationBar = UINavigationBar()
        navigationBar.delegate = self
        var navigationItem = UINavigationItem(title: "Take")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .Plain,
            target: self, action: "openButtonTapped:")
        navigationBar.items = [ navigationItem ]

        view.addSubviewsWithConstraints(
            (navigationBar, [
                .FillHorizontallyIn(view),
                .Anchor(.Top, self.bottomOfTopLayoutGuide())
                ])
        )

    }

    func openButtonTapped(sender: UIBarButtonItem!) {
        println("Tapped")
    }
}

extension MainViewController: UINavigationBarDelegate {
    func positionForBar(bar: UIBarPositioning!) -> UIBarPosition {
        return .TopAttached
    }
}

Change the 'Open' button to a '+' button

//
//  MainViewController.swift
//  Take
//
//  Created by Roopesh Chander on 15/07/14.
//  Copyright (c) 2014 Roopesh Chander. All rights reserved.
//

import UIKit

class MainViewController: UIViewController {

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func loadView() {
        var view = UIView()
        self.view = view

        var navigationBar = UINavigationBar()
        navigationBar.delegate = self
        var navigationItem = UINavigationItem(title: "Take")
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add,
            target: self, action: "addButtonTapped:")
        navigationBar.items = [ navigationItem ]

        view.addSubviewsWithConstraints(
            (navigationBar, [
                .FillHorizontallyIn(view),
                .Anchor(.Top, self.bottomOfTopLayoutGuide())
                ])
        )

    }

    func addButtonTapped(sender: UIBarButtonItem!) {
        println("Tapped")
    }
}

extension MainViewController: UINavigationBarDelegate {
    func positionForBar(bar: UIBarPositioning!) -> UIBarPosition {
        return .TopAttached
    }
}


//
//  WebStack.swift
//  BartlebyKit
//
//  Created by Benoit Pereira da silva on 28/07/2016.
//
//

import Cocoa
import WebKit

class WebStack: NSViewController,RegistryDependent {

    @IBOutlet weak var webView: WebView!

    private var URL:NSURL?

    private var _loadingAttempted:Bool=false

    var registryDelegate: RegistryDelegate?{
        didSet{
            if let document=self.registryDelegate?.getRegistry(){
                self.URL=NSURL(string: document.baseURL.absoluteString.stringByReplacingOccurrencesOfString("/api/v1", withString: "")+"/signIn?spaceUID=\(document.spaceUID)&userUID=\(document.registryMetadata.currentUser!.UID)&password=\(document.registryMetadata.currentUser!.password)");
            }
        }
    }

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

    override func viewDidAppear() {
        super.viewDidAppear()
        if !self._loadingAttempted {
            if let URL=self.URL {
                let r=NSURLRequest(URL:URL)
                self.webView.mainFrame.loadRequest(r)
                self._loadingAttempted=true
            }
        }
    }

}

Allow url reloading in web stack in case of failure

//
//  WebStack.swift
//  BartlebyKit
//
//  Created by Benoit Pereira da silva on 28/07/2016.
//
//

import Cocoa
import WebKit

class WebStack: NSViewController,RegistryDependent,WebFrameLoadDelegate {

    @IBOutlet weak var webView: WebView!{
        didSet{
            webView.frameLoadDelegate=self
        }
    }

    private var URL:NSURL?

    private var _loadingAttempted:Bool=false

    var registryDelegate: RegistryDelegate?{
        didSet{
            if let document=self.registryDelegate?.getRegistry(){
                self.URL=NSURL(string: document.baseURL.absoluteString.stringByReplacingOccurrencesOfString("/api/v1", withString: "")+"/signIn?spaceUID=\(document.spaceUID)&userUID=\(document.registryMetadata.currentUser!.UID)&password=\(document.registryMetadata.currentUser!.password)");
            }
        }
    }

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

    override func viewDidAppear() {
        super.viewDidAppear()
        if !self._loadingAttempted {
            if let URL=self.URL {
                let r=NSURLRequest(URL:URL)
                self.webView.mainFrame.loadRequest(r)
                self._loadingAttempted=true
            }
        }
    }

    // Mark: WebFrameLoadDelegate

    public func webView(sender: WebView!, didFailLoadWithError error: NSError!, forFrame frame: WebFrame!){
        self._loadingAttempted=false
    }

}


//
//  NSLayoutConstraint+SwifPlusPlus.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 11/11/15.
//  Copyright © 2015 Drewag LLC. All rights reserved.
//

import Foundation

extension NSLayoutConstraint {
    @available(iOS 8.0, *)
    func setMultiplier(multiplier:CGFloat) {

        let newConstraint = NSLayoutConstraint(
            item: firstItem,
            attribute: firstAttribute,
            relatedBy: relation,
            toItem: secondItem,
            attribute: secondAttribute,
            multiplier: multiplier,
            constant: constant)

        newConstraint.priority = self.priority
        newConstraint.shouldBeArchived = self.shouldBeArchived
        newConstraint.identifier = self.identifier
        newConstraint.active = self.active

        NSLayoutConstraint.deactivateConstraints([self])
        NSLayoutConstraint.activateConstraints([newConstraint])
    }
}

Clear priority of changed multiple constraint

//
//  NSLayoutConstraint+SwifPlusPlus.swift
//  SwiftPlusPlus
//
//  Created by Andrew J Wagner on 11/11/15.
//  Copyright © 2015 Drewag LLC. All rights reserved.
//

import Foundation

extension NSLayoutConstraint {
    @available(iOS 8.0, *)
    func setMultiplier(multiplier:CGFloat) {

        let newConstraint = NSLayoutConstraint(
            item: firstItem,
            attribute: firstAttribute,
            relatedBy: relation,
            toItem: secondItem,
            attribute: secondAttribute,
            multiplier: multiplier,
            constant: constant)

        newConstraint.priority = self.priority
        newConstraint.shouldBeArchived = self.shouldBeArchived
        newConstraint.identifier = self.identifier
        newConstraint.active = self.active
        self.priority = 1

        NSLayoutConstraint.deactivateConstraints([self])
        NSLayoutConstraint.activateConstraints([newConstraint])
    }
}


//
// ActivityResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//

import Foundation

/** The model that defines the actions that can be taken for a given Activity entry */
public class ActivityResponse: JSONEncodable {
    public enum ActivityResponseType: String {
        case ConnectionRequestAccept = "connection_request_accept"
        case ConnectionRequestDecline = "connection_request_decline"
        case ConnectionAcceptedView = "connection_accepted_view"
        case MatchSuggestedAccept = "match_suggested_accept"
        case MatchSuggestedDecline = "match_suggested_decline"
        case MatchAcceptedView = "match_accepted_view"
        case DateSuggestedAccept = "date_suggested_accept"
        case DateSuggestedSuggest = "date_suggested_suggest"
        case DateAcceptedView = "date_accepted_view"
        case MessageReceivedView = "message_received_view"
    }
    /** The text to show when presenting the response */
    public var text: String?
    /** The different types of responses to activities */
    public var activityResponseType: ActivityResponseType?

    public init() {}

    // MARK: JSONEncodable
    func encodeToJSON() -> AnyObject {
        var nillableDictionary = [String:AnyObject?]()
        nillableDictionary["text"] = self.text
        nillableDictionary["activity_response_type"] = self.activityResponseType?.rawValue
        let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
        return dictionary
    }
}

Remove unnecessary activity response types

//
// ActivityResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//

import Foundation

/** The model that defines the actions that can be taken for a given Activity entry */
public class ActivityResponse: JSONEncodable {
    public enum ActivityResponseType: String {
        case ConnectionRequestAccept = "connection_request_accept"
        case ConnectionRequestDecline = "connection_request_decline"
        case MatchSuggestedAccept = "match_suggested_accept"
        case MatchSuggestedDecline = "match_suggested_decline"
        case DateSuggestedAccept = "date_suggested_accept"
        case DateSuggestedSuggest = "date_suggested_suggest"
        case MessageReceivedView = "message_received_view"
    }
    /** The text to show when presenting the response */
    public var text: String?
    /** The different types of responses to activities */
    public var activityResponseType: ActivityResponseType?

    public init() {}

    // MARK: JSONEncodable
    func encodeToJSON() -> AnyObject {
        var nillableDictionary = [String:AnyObject?]()
        nillableDictionary["text"] = self.text
        nillableDictionary["activity_response_type"] = self.activityResponseType?.rawValue
        let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
        return dictionary
    }
}


import MapKit

extension MCreateSaveRenderSliceRect
{
    private static let kMaxSize:Double = 2560

    //MARK: internal

    static func factoryRects(
        tileRange:MCreateSaveTileRange) -> [MCreateSaveRenderSliceRect]
    {
        var rects:[MCreateSaveRenderSliceRect] = []
        var tileY:Double = tileRange.minY
        let maxX:Double = tileRange.maxX + 1
        let maxY:Double = tileRange.maxY + 1

        while tileY < maxY
        {
            var tileX:Double = tileRange.minX
            var deltaY:Double = maxY - tileY

            if deltaY > kMaxSize
            {
                deltaY = kMaxSize
            }

            while tileX < maxX
            {
                var deltaX:Double = maxX - tileX

                if deltaX > kMaxSize
                {
                    deltaX = kMaxSize
                }

                let rect:MCreateSaveRenderSliceRect = MCreateSaveRenderSliceRect(
                    tileX:tileX,
                    tileY:tileY,
                    tileWidth:deltaX,
                    tileHeight:deltaY)

                rects.append(rect)

                tileX += deltaX
            }

            tileY += deltaY
        }

        return rects
    }
}

Update max size to tiles

import MapKit

extension MCreateSaveRenderSliceRect
{
    private static let kMaxSize:Double = 10

    //MARK: internal

    static func factoryRects(
        tileRange:MCreateSaveTileRange) -> [MCreateSaveRenderSliceRect]
    {
        var rects:[MCreateSaveRenderSliceRect] = []
        var tileY:Double = tileRange.minY
        let maxX:Double = tileRange.maxX + 1
        let maxY:Double = tileRange.maxY + 1

        while tileY < maxY
        {
            var tileX:Double = tileRange.minX
            var deltaY:Double = maxY - tileY

            if deltaY > kMaxSize
            {
                deltaY = kMaxSize
            }

            while tileX < maxX
            {
                var deltaX:Double = maxX - tileX

                if deltaX > kMaxSize
                {
                    deltaX = kMaxSize
                }

                let rect:MCreateSaveRenderSliceRect = MCreateSaveRenderSliceRect(
                    tileX:tileX,
                    tileY:tileY,
                    tileWidth:deltaX,
                    tileHeight:deltaY)

                rects.append(rect)

                tileX += deltaX
            }

            tileY += deltaY
        }

        return rects
    }
}


import UIKit
import DateToolsSwift

open class DayViewController: UIViewController, DayViewDelegate {

  public lazy var dayView: DayView = DayView()

  override open func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge()
    view.addSubview(dayView)
    view.tintColor = UIColor.red

    dayView.dataSource = self
    dayView.delegate = self
    dayView.reloadData()
  }

  open override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }

  open func reloadData() {
    dayView.reloadData()
  }

  public func updateStyle(_ newStyle: CalendarStyle) {
    dayView.updateStyle(newStyle)
  }
}

extension DayViewController: DayViewDataSource {
  open func eventViewsForDate(_ date: Date) -> [EventView] {
    return [EventView]()
  }

  // MARK: DayViewDelegate

  open func dayViewDidSelectEventView(_ eventview: EventView) {

  }

  open func dayViewDidLongPressEventView(_ eventView: EventView) {

  }

  public func dayViewDidLongPressTimelineAtHour(_ hour: Int) {

  }

  public func dayView(dayView: DayView, willMoveTo date: Date) {
    print("DayView = \(dayView) will move to: \(date)")
  }

  public func dayView(dayView: DayView, didMoveTo date: Date) {
    print("DayView = \(dayView) did move to: \(date)")
  }
}

Make all the DayViewDelegate functions open instead of public

import UIKit
import DateToolsSwift

open class DayViewController: UIViewController, DayViewDelegate {

  public lazy var dayView: DayView = DayView()

  override open func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge()
    view.addSubview(dayView)
    view.tintColor = UIColor.red

    dayView.dataSource = self
    dayView.delegate = self
    dayView.reloadData()
  }

  open override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }

  open func reloadData() {
    dayView.reloadData()
  }

  public func updateStyle(_ newStyle: CalendarStyle) {
    dayView.updateStyle(newStyle)
  }
}

extension DayViewController: DayViewDataSource {
  open func eventViewsForDate(_ date: Date) -> [EventView] {
    return [EventView]()
  }

  // MARK: DayViewDelegate

  open func dayViewDidSelectEventView(_ eventview: EventView) {

  }

  open func dayViewDidLongPressEventView(_ eventView: EventView) {

  }

  open func dayViewDidLongPressTimelineAtHour(_ hour: Int) {

  }

  open func dayView(dayView: DayView, willMoveTo date: Date) {
    print("DayView = \(dayView) will move to: \(date)")
  }

  open func dayView(dayView: DayView, didMoveTo date: Date) {
    print("DayView = \(dayView) did move to: \(date)")
  }
}


import Foundation
import CoreData

extension NSManagedObjectContext {

    public var childBackgroundContext: NSManagedObjectContext {

        get {

            let childContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)

            childContext.parent = self

            return childContext
        }
    }
}

Add automatically merge to parent context for child context

import Foundation
import CoreData

extension NSManagedObjectContext {

    public var childBackgroundContext: NSManagedObjectContext {

        get {

            let childContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)

            childContext.parent = self
            childContext.automaticallyMergesChangesFromParent = true

            return childContext
        }
    }
}


//
//  APITokenTests.swift
//  NetworkingServiceKit
//
//  Created by Phillipe Casorla Sagot on 4/4/17.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import Quick
import Nimble
import NetworkingServiceKit

class APITokenTests: QuickSpec {

    override func spec() {
    }
}

Add unit test for APITokens

//
//  APITokenTests.swift
//  NetworkingServiceKit
//
//  Created by Phillipe Casorla Sagot on 4/4/17.
//  Copyright © 2017 CocoaPods. All rights reserved.
//

import Quick
import Nimble
import NetworkingServiceKit

class APITokenTests: QuickSpec {

    override func spec() {

        describe("when setting up access token information") {
            let userEmail = "email1@email.com"
            context("if we have an access token") {
                it("should return the appropiate information for the given email") {
                    let dataResponse = ["refresh_token" : "DWALI",
                               "token_type" : "access",
                               "access_token" : "KWALI",
                               "expires_in" : 100,
                               "scope" : "mobile"] as [String : Any]
                    let apiToken = APITokenManager.store(tokenInfo: dataResponse, for: userEmail)
                    expect(apiToken).toNot(beNil())

                    let accessToken = APITokenManager.accessToken(for: userEmail)
                    expect(accessToken).to(equal("KWALI"))

                    let refreshToken = APITokenManager.refreshToken(for: userEmail)
                    expect(refreshToken).to(equal("DWALI"))
                }
            }

            context("if we have clear the token info") {
                let dataResponse = ["refresh_token" : "DWALI",
                                    "token_type" : "access",
                                    "access_token" : "KWALI",
                                    "expires_in" : 100,
                                    "scope" : "mobile"] as [String : Any]
                let apiToken = APITokenManager.store(tokenInfo: dataResponse, for: userEmail)
                expect(apiToken).toNot(beNil())
                APITokenManager.clearAuthentication()

                let accessToken = APITokenManager.accessToken(for: userEmail)
                expect(accessToken).to(beNil())

                let refreshToken = APITokenManager.refreshToken(for: userEmail)
                expect(refreshToken).to(beNil())
            }
        }
    }
}


// swift-tools-version:4.0

import PackageDescription

// Version number can be found in Source/Danger/Danger.swift

let package = Package(
    name: "danger-swift",
    products: [
        .library(name: "Danger", type: .dynamic, targets: ["Danger"]),
        .executable(name: "danger-swift", targets: ["Runner"])
    ],
    dependencies: [
        .package(url: "https://github.com/JohnSundell/Marathon.git", from: "2.0.2"),
    ],
    targets: [
        .target(name: "Danger", dependencies: []),
        .target(name: "Runner", dependencies: ["Danger", "MarathonCore"]),
        .testTarget(name: "DangerTests", dependencies: ["Danger"]),
    ],
    swiftLanguageVersions: [4]
)

Update minimum Marathon version to 2.1.0 (SPM fix)

// swift-tools-version:4.0

import PackageDescription

// Version number can be found in Source/Danger/Danger.swift

let package = Package(
    name: "danger-swift",
    products: [
        .library(name: "Danger", type: .dynamic, targets: ["Danger"]),
        .executable(name: "danger-swift", targets: ["Runner"])
    ],
    dependencies: [
        .package(url: "https://github.com/JohnSundell/Marathon.git", from: "2.1.0"),
    ],
    targets: [
        .target(name: "Danger", dependencies: []),
        .target(name: "Runner", dependencies: ["Danger", "MarathonCore"]),
        .testTarget(name: "DangerTests", dependencies: ["Danger"]),
    ],
    swiftLanguageVersions: [4]
)


import PackageDescription

let package = Package(
    name: "FuntastyKit"
)

Add products and platform to SPM

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "FuntastyKit",
    platforms: [.iOS(.v9)],
    products: [
        .library(
            name: "FuntastyKit",
            targets: ["FuntastyKit"])
    ],
    targets: [
        .target(
            name: "FuntastyKit",
            dependencies: []),
        .testTarget(
            name: "FuntastyKitTests",
            dependencies: ["FuntastyKit"])
    ]
)


//
//  WebSocketTransportSpec.swift
//  WebSocketTransportSpec
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Quick
import Nimble
import WebSocketTransport
import JSONLib

class WebSocketTransportSpec: QuickSpec {

    override func spec() {

        describe("WebSocket transport") {

            describe("when receiving a message") {

                it("should be received in the runtime") {
                    let transport = WebSocketTransport()

                    let transportChannel = "channel"
                    let transportTopic = "topic"
                    let transportPayload = "{\"key\":\"value\"}"
                    let transportData = "{\"protocol\":\"\(transportChannel)\",\"command\":\"\(transportTopic)\",\"payload\":\(transportPayload)}"

                    var runtimeChannel: String!
                    var runtimeTopic: String!
                    var runtimePayload: JSON!

                    let runtime = FakeRuntime(transport) { (channel, topic, payload) in
                        runtimeChannel = channel
                        runtimeTopic = topic
                        runtimePayload = payload
                    }

                    // TODO: Receive a message in the transport

                    expect(runtimeChannel).to(equal(transportChannel))
                    expect(runtimeTopic).to(equal(transportTopic))

                    let json = JSON.parse(transportPayload).value
                    expect(runtimePayload).to(equal(json))
                }
            }

            describe("when sent a message by the runtime") {

                pending("should send a message") {

                }
            }
        }
    }
}

Send a message to the transport.

//
//  WebSocketTransportSpec.swift
//  WebSocketTransportSpec
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Quick
import Nimble
import WebSocketTransport
import JSONLib

class WebSocketTransportSpec: QuickSpec {

    override func spec() {

        describe("WebSocket transport") {

            describe("when receiving a message") {

                it("should be received in the runtime") {
                    let transport = WebSocketTransport()

                    let transportChannel = "channel"
                    let transportTopic = "topic"
                    let transportPayload = "{\"key\":\"value\"}"
                    let transportData = "{\"protocol\":\"\(transportChannel)\",\"command\":\"\(transportTopic)\",\"payload\":\(transportPayload)}"

                    var runtimeChannel: String!
                    var runtimeTopic: String!
                    var runtimePayload: JSON!

                    let runtime = FakeRuntime(transport) { (channel, topic, payload) in
                        runtimeChannel = channel
                        runtimeTopic = topic
                        runtimePayload = payload
                    }

                    expect(runtimeChannel).to(equal(transportChannel))
                    expect(runtimeTopic).to(equal(transportTopic))
                    let fakeWebSocketClient = FakeWebSocketClient { webSocket in
                        webSocket.send(transportData)
                    }

                    let json = JSON.parse(transportPayload).value
                    expect(runtimePayload).to(equal(json))
                }
            }

            describe("when sent a message by the runtime") {

                pending("should send a message") {

                }
            }
        }
    }
}


import WidgetKit

struct EventsTimelineProvider: IntentTimelineProvider {

    func placeholder(in context: Context) -> EventsTimelineEntry {
        EventsTimelineEntry(date: Date(), filter: .upcoming, events: [])
    }

    func getSnapshot(
        for configuration: ViewEventsIntent,
        in context: Context,
        completion: @escaping (EventsTimelineEntry) -> ()
    ) {
        let entry = EventsTimelineEntry(date: Date(), filter: .upcoming, events: [])
        completion(entry)
    }

    func getTimeline(
        for configuration: ViewEventsIntent,
        in context: Context,
        completion: @escaping (Timeline<EventsTimelineEntry>) -> ()
    ) {
        var entries: [EventsTimelineEntry] = []

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = EventsTimelineEntry(date: entryDate, filter: .upcoming, events: [])
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }

}

Add sample data for testing

import WidgetKit

struct EventsTimelineProvider: IntentTimelineProvider {

    func placeholder(in context: Context) -> EventsTimelineEntry {
        EventsTimelineEntry(date: Date(), filter: .upcoming, events: [])
    }

    func getSnapshot(
        for configuration: ViewEventsIntent,
        in context: Context,
        completion: @escaping (EventsTimelineEntry) -> ()
    ) {
        let entry = EventsTimelineEntry(date: Date(), filter: .upcoming, events: [])
        completion(entry)
    }

    func getTimeline(
        for configuration: ViewEventsIntent,
        in context: Context,
        completion: @escaping (Timeline<EventsTimelineEntry>) -> ()
    ) {
        let events: [EventViewModel] = [
            EventViewModel(
                formattedStartTime: "13:00",
                formattedEndTime: "14:30",
                eventTitle: "Trans Meet-Up",
                eventLocation: "Nizza"
            ),

            EventViewModel(
                formattedStartTime: "13:30",
                formattedEndTime: "15:00",
                eventTitle: "Dealer's Den",
                eventLocation: "Dealer's Den - Convention Center Foyer 3"
            ),

            EventViewModel(
                formattedStartTime: "17:30",
                formattedEndTime: "18:30",
                eventTitle: "Funny Animals and Amerimanga in Sonic the Hedgehog Archie Series",
                eventLocation: "Nizza"
            )
        ]

        let entry = EventsTimelineEntry(
            date: Date(),
            filter: .upcoming,
            events: events
        )

        let timeline = Timeline(entries: [entry], policy: .atEnd)
        completion(timeline)
    }

}


//  Created by dasdom on 12.04.20.
//  Copyright © 2020 dasdom. All rights reserved.
//

import Foundation

public struct BirthdayCountdown : Hashable {
  public let name: String
  public let remainingDays: Int
  let birthday: Birthday

  public init(birthday: Birthday) {

    // https://stackoverflow.com/a/31132581/498796
    let calendar = Calendar(identifier: .gregorian)
    let today = calendar.startOfDay(for: Date())
    let birthdayComponents = calendar.dateComponents([.day, .month], from: birthday.date)
    let nextBirthday = calendar.nextDate(after: today, matching: birthdayComponents, matchingPolicy: .nextTimePreservingSmallerComponents)

    guard let daysCount = calendar.dateComponents([.day], from: today, to: nextBirthday!).day else {
      fatalError()
    }

    name = birthday.name
    remainingDays = daysCount
    self.birthday = birthday
  }
}

Make birthday in count down public

//  Created by dasdom on 12.04.20.
//  Copyright © 2020 dasdom. All rights reserved.
//

import Foundation

public struct BirthdayCountdown : Hashable {
  public let name: String
  public let remainingDays: Int
  public let birthday: Birthday

  public init(birthday: Birthday) {

    // https://stackoverflow.com/a/31132581/498796
    let calendar = Calendar(identifier: .gregorian)
    let today = calendar.startOfDay(for: Date())
    let birthdayComponents = calendar.dateComponents([.day, .month], from: birthday.date)
    let nextBirthday = calendar.nextDate(after: today, matching: birthdayComponents, matchingPolicy: .nextTimePreservingSmallerComponents)

    guard let daysCount = calendar.dateComponents([.day], from: today, to: nextBirthday!).day else {
      fatalError()
    }

    name = birthday.name
    remainingDays = daysCount
    self.birthday = birthday
  }
}


/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import CloudKit
import Reactor

public struct CheckCloudKitStatus<U: State>: Command {

    public init() { }

    public func execute(state: U, core: Core<U>) {
        CKContainer.default().accountStatus { status, error in
            core.fire(event: CloudKitStatusRetrieved(status: status, error: error))
        }
    }

}

Add callback to status check

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import Foundation
import CloudKit
import Reactor

public struct CheckCloudKitStatus<U: State>: Command {

    let completion: (() -> Void)

    public init(completion: @escaping (() -> Void) = { }) {
        self.completion = completion
    }

    public func execute(state: U, core: Core<U>) {
        CKContainer.default().accountStatus { status, error in
            core.fire(event: CloudKitStatusRetrieved(status: status, error: error))
            self.completion()
        }
    }

}


//
//  ClearContainerView.swift
//  SlideOutable
//
//  Created by Domas Nutautas on 20/05/16.
//  Copyright © 2016 Domas Nutautas. All rights reserved.
//

import UIKit

// MARK: - ContainterView

///
/// Passes touches if background is clear and point is not inside one of its subviews
///
open class ClearContainerView: UIView {

    open weak var viewForClearTouches: UIView?

    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let superHit = super.hitTest(point, with: event)
        guard backgroundColor == nil || backgroundColor == .clear else { return superHit }

        return self == superHit ? viewForClearTouches?.hitTest(point, with: event) : superHit
    }
}

Convert hit point to viewForClearTouches coordinate system

//
//  ClearContainerView.swift
//  SlideOutable
//
//  Created by Domas Nutautas on 20/05/16.
//  Copyright © 2016 Domas Nutautas. All rights reserved.
//

import UIKit

// MARK: - ContainterView

///
/// Passes touches if background is clear and point is not inside one of its subviews
///
open class ClearContainerView: UIView {

    open weak var viewForClearTouches: UIView?

    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let superHit = super.hitTest(point, with: event)
        guard
            backgroundColor == nil || backgroundColor == .clear,
            self == superHit
        else { return superHit }

        return viewForClearTouches?.hitTest(convert(point, to: viewForClearTouches), with: event)
    }
}


//
//  CharactersNavigationControllerTests.swift
//  Example
//
//  Created by Pedro Vicente Gomez on 26/11/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation
import KIF
import Nimble
@testable import Example

class CharactersViewControllerTests: AcceptanceTestCase {

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

    func testShowsSpiderManAndIronManByDefaultSuperHeroes() {
        openCharactersViewController()

        let spiderManRowLabel = tester().waitForViewWithAccessibilityLabel("SpiderMan") as! UILabel
        let ironManRowLabel = tester().waitForViewWithAccessibilityLabel("IronMan") as! UILabel

        expect(spiderManRowLabel.text).to(equal("SpiderMan"))
        expect(ironManRowLabel.text).to(equal("IronMan"))
    }

    private func openCharactersViewController() {
        let charactersViewController = ServiceLocator().provideCharactersViewController()
        presentViewController(charactersViewController)
    }

}

Remove not needed tearDown method

//
//  CharactersNavigationControllerTests.swift
//  Example
//
//  Created by Pedro Vicente Gomez on 26/11/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation
import KIF
import Nimble
@testable import Example

class CharactersViewControllerTests: AcceptanceTestCase {

    func testShowsSpiderManAndIronManByDefaultSuperHeroes() {
        openCharactersViewController()

        let spiderManRowLabel = tester().waitForViewWithAccessibilityLabel("SpiderMan") as! UILabel
        let ironManRowLabel = tester().waitForViewWithAccessibilityLabel("IronMan") as! UILabel

        expect(spiderManRowLabel.text).to(equal("SpiderMan"))
        expect(ironManRowLabel.text).to(equal("IronMan"))
    }

    private func openCharactersViewController() {
        let charactersViewController = ServiceLocator().provideCharactersViewController()
        presentViewController(charactersViewController)
    }

}


print("Hello, world!")

Add list and select subcommand

import TextInputSources
import Commander

let main = Group {
    $0.command("list", description: "List enabled input sources") {
        for inputSource in TextInputSources.find() {
            print(inputSource.id)
        }
    }

    $0.command("select", description: "Select an input source") { (id: String) in
        guard let inputSource = TextInputSources.find(filtering: [.id: id]).first else {
            return
        }
        try TextInputSources.select(inputSource)
    }
}

main.run()


// swift-tools-version:4.2

import PackageDescription

let package = Package(
	name: "FootlessParser",
	products: [
		.library(name: "FootlessParser",	targets: ["FootlessParser"]),
		],
	targets: [
		.target(name: "FootlessParser"),
		.testTarget(name: "FootlessParserTests", dependencies: ["FootlessParser"]),
		],
	swiftLanguageVersions: [.v4_2]
)

Enable compiling with both Swift 4.1 and 4.2.

// swift-tools-version:4.1

import PackageDescription

let package = Package(
	name: "FootlessParser",
	products: [
		.library(name: "FootlessParser",	targets: ["FootlessParser"]),
		],
	targets: [
		.target(name: "FootlessParser"),
		.testTarget(name: "FootlessParserTests", dependencies: ["FootlessParser"]),
		]
)


//
//  AppDelegate.swift
//  Bluetility
//
//  Created by Joseph Ross on 11/9/15.
//  Copyright © 2015 Joseph Ross. 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
    }

    func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
        return true
    }

}

Disable tooltip wrapping by default

//
//  AppDelegate.swift
//  Bluetility
//
//  Created by Joseph Ross on 11/9/15.
//  Copyright © 2015 Joseph Ross. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        let defaults = ["NSToolTipAutoWrappingDisabled" : NSNumber(bool: true)]
        NSUserDefaults.standardUserDefaults().registerDefaults(defaults)
    }

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

    func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
        return true
    }

}


//
//  ContentView.swift
//  NaviLinkProg
//
//  Created by Alexander Farber on 31.10.21.
//

import SwiftUI

struct ContentView: View {
    @StateObject private var vm:GamesViewModel = GamesViewModel()

    var body: some View {
        NavigationView {
            VStack {

                // the NavigationLink/EmptyView should stay visible onscreen for the isActive to work
                NavigationLink(
                        destination: GameView(gameNumber: vm.displayedGame),
                        isActive: vm.navigationBinding()
                ) {
                    EmptyView()
                }

                List {
                    ForEach(vm.currentGames, id: \.self) { gameNumber in
                        NavigationLink(
                                destination: GameView(gameNumber: gameNumber)
                            ) {
                            Text("Game #\(gameNumber)")
                        }
                    }
                }
                Button(
                    action: { vm.updateCurrentGames() },
                    label: { Text("Update games") }
                ).padding(4)

                Button(
                    action: { vm.updateDisplayedGame() },
                    label: { Text("Join a random game") }
                ).padding(4)
          }.navigationBarTitle("Select a game")
       }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Create a List from binding, without ForEach

//
//  ContentView.swift
//  NaviLinkProg
//
//  Created by Alexander Farber on 31.10.21.
//

import SwiftUI

struct ContentView: View {
    @StateObject private var vm:GamesViewModel = GamesViewModel()

    var body: some View {
        NavigationView {
            VStack {

                // the NavigationLink/EmptyView should stay visible onscreen for the isActive to work
                NavigationLink(
                        destination: GameView(gameNumber: vm.displayedGame),
                        isActive: vm.navigationBinding()
                ) {
                    EmptyView()
                }

                // iOS 15 feature: create a List from binding
                List($vm.currentGames, id: \.self) { $gameNumber in
                    NavigationLink(
                            destination: GameView(gameNumber: gameNumber)
                        ) {
                        Text("Game #\(gameNumber)")
                    }
                }
                Button(
                    action: { vm.updateCurrentGames() },
                    label: { Text("Update games") }
                ).padding(4)

                Button(
                    action: { vm.updateDisplayedGame() },
                    label: { Text("Join a random game") }
                ).padding(4)
          }.navigationBarTitle("Select a game")
       }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


//
//  FAQViewTests.swift
//  FAQViewTests
//
//  Created by Mukesh Thawani on 12/11/16.
//  Copyright © 2016 Mukesh Thawani. All rights reserved.
//

import XCTest
@testable import FAQView

class FAQViewTests: XCTestCase {

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

  override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    super.tearDown()
  }

}

Add tests for title label properties

//
//  FAQViewTests.swift
//  FAQViewTests
//
//  Created by Mukesh Thawani on 12/11/16.
//  Copyright © 2016 Mukesh Thawani. All rights reserved.
//

import XCTest
@testable import FAQView

class FAQViewTests: XCTestCase {

  var faqView: FAQView!

  override func setUp() {
    super.setUp()
    let item = FAQItem(question: "Question", answer: "Answer")
    faqView = FAQView(frame: CGRect.zero, items: [item])
  }

  override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    super.tearDown()
  }

  func test_TitleLabelProperties_WhenSetToDefault() {
    let titleLabel = faqView.titleLabel
    let configuration = faqView.configuration
    XCTAssertEqual(titleLabel?.backgroundColor, configuration.titleLabelBackgroundColor)
    XCTAssertEqual(titleLabel?.textColor, configuration.titleTextColor)
    XCTAssertEqual(titleLabel?.font, configuration.titleTextFont)
  }

  func test_TitleLabelProperties_WhenCustomized() {
    let titleLabel = faqView.titleLabel
    faqView.titleLabelBackgroundColor = UIColor.blue
    faqView.titleLabelTextColor = UIColor.blue
    faqView.titleLabelTextFont = UIFont.systemFont(ofSize: 20)
    XCTAssertEqual(titleLabel?.backgroundColor, UIColor.blue)
    XCTAssertEqual(titleLabel?.textColor, UIColor.blue)
    XCTAssertEqual(titleLabel?.font, UIFont.systemFont(ofSize: 20))
  }

}


//
//  MixedColor.swift
//  Pods
//
//  Created by Draveness on 6/30/16.
//
//

import UIKit

public class MixedColor {
    public let normalColor: UIColor
    public let nightColor: UIColor

    public init(normal: UIColor, night: UIColor) {
        normalColor = normal
        nightColor = night;
    }

    public init(normal: Int, night: Int) {
        normalColor = UIColor(rgb: normal)
        nightColor = UIColor(rgb: night);
    }

    func unfold() -> UIColor? {
        switch NightNight.theme {
        case .NORMAL: return normalColor
        case .NIGHT:  return nightColor
        default:      return normalColor
        }
    }
}

extension UIColor {
    convenience init(rgb: Int) {
        let red = CGFloat(rgb >> 16) / 255.0
        let green = CGFloat(rgb >> 8 & 0xff) / 255.0
        let blue = CGFloat(rgb >> 0 & 0xff) / 255.0

        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

Add UIColor convience method with alpha param

//
//  MixedColor.swift
//  Pods
//
//  Created by Draveness on 6/30/16.
//
//

import UIKit

public class MixedColor {
    public let normalColor: UIColor
    public let nightColor: UIColor

    public init(normal: UIColor, night: UIColor) {
        normalColor = normal
        nightColor = night;
    }

    public init(normal: Int, night: Int) {
        normalColor = UIColor(rgb: normal)
        nightColor = UIColor(rgb: night);
    }

    func unfold() -> UIColor? {
        switch NightNight.theme {
        case .NORMAL: return normalColor
        case .NIGHT:  return nightColor
        default:      return normalColor
        }
    }
}

extension UIColor {
    convenience init(rgb: Int) {
        self.init(rgb: rgb, alpha: 1.0)
    }

    convenience init(rgb: Int, alpha: CGFloat) {
        let red = CGFloat(rgb >> 16) / 255.0
        let green = CGFloat(rgb >> 8 & 0xff) / 255.0
        let blue = CGFloat(rgb >> 0 & 0xff) / 255.0

        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}


//
//  MessageBroker.swift
//  MessageBroker
//
//  Created by Paul Young on 02/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

public final class MessageBroker: MessageSenderWithReceiver, MessageReceiverWithSender {

    public var messageSender: MessageSender?
    public var messageReceiver: MessageReceiver?

    public init() {}

    public func send(channel: String, _ topic: String, _ payload: JSON) {
        if let maybeMessageSender = self.messageSender {
            maybeMessageSender.send(channel, topic, payload)
        }
    }

    public func receive(channel: String, _ topic: String, _ payload: JSON) {
        if let maybeMessageReceiver = self.messageReceiver {
            maybeMessageReceiver.receive(channel, topic, payload)
        }
    }
}

Switch final and public keywords.

//
//  MessageBroker.swift
//  MessageBroker
//
//  Created by Paul Young on 02/09/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Foundation
import MessageTransfer
import JSONLib

final public class MessageBroker: MessageSenderWithReceiver, MessageReceiverWithSender {

    public var messageSender: MessageSender?
    public var messageReceiver: MessageReceiver?

    public init() {}

    public func send(channel: String, _ topic: String, _ payload: JSON) {
        if let maybeMessageSender = self.messageSender {
            maybeMessageSender.send(channel, topic, payload)
        }
    }

    public func receive(channel: String, _ topic: String, _ payload: JSON) {
        if let maybeMessageReceiver = self.messageReceiver {
            maybeMessageReceiver.receive(channel, topic, payload)
        }
    }
}


//
// Created by zen on 31/01/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var name: String?

    public var image: UIImage
    public var highlightedImage: UIImage?
}

Add background color for menu item

//
// Created by zen on 31/01/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var name: String?

    public var image: UIImage
    public var highlightedImage: UIImage?

    public var backgroundColor = UIColor.blackColor()
    public var highlightedBackgroundColor = UIColor.redColor()
}


//
//  Config.swift
//  TableTennisAPI
//
//  Created by David Bireta on 12/7/16.
//  Copyright © 2016 David Bireta. All rights reserved.
//

import Foundation

Add placeholder config value for API key.

//
//  Config.swift
//  TableTennisAPI
//
//  Created by David Bireta on 12/7/16.
//  Copyright © 2016 David Bireta. All rights reserved.
//

struct Config {
    static let apiKey = "<API_KEY>"
}


//
//  EndpointsTestCase.swift
//  FlingChallengeKit
//
//  Created by Alexander Kolov on 5/9/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

@testable import FlingChallengeKit
import XCTest

class EndpointsTestCase: XCTestCase {

  func testBaseURL() {
    var components = NSURLComponents(URL: FlingChallengeKit.baseURL, resolvingAgainstBaseURL: false)
    XCTAssertNotNil(components)
    XCTAssertEqual(components?.scheme, "https")

    FlingChallengeKit.secure = false
    components = NSURLComponents(URL: FlingChallengeKit.baseURL, resolvingAgainstBaseURL: false)
    XCTAssertNotNil(components)
    XCTAssertEqual(components?.scheme, "http")
  }

  func testFeedURL() {
    do {
      let URL = try Endpoints.Feed.URL()
      XCTAssertNotNil(URL)
    }
    catch {
      XCTFail()
    }
  }

  func testPhotosURL() {
    do {
      let photoID = "5"
      let components = NSURLComponents(URL: try Endpoints.Photos.URL(["id": photoID]), resolvingAgainstBaseURL: false)
      XCTAssertNotNil(components)
      XCTAssertNotNil(components?.path)
      XCTAssertEqual((components!.path! as NSString).lastPathComponent, photoID)
    }
    catch {
      XCTFail()
    }
  }

}

Add explicit secure base URL test case

//
//  EndpointsTestCase.swift
//  FlingChallengeKit
//
//  Created by Alexander Kolov on 5/9/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

@testable import FlingChallengeKit
import XCTest

class EndpointsTestCase: XCTestCase {

  func testBaseURL() {
    var components = NSURLComponents(URL: FlingChallengeKit.baseURL, resolvingAgainstBaseURL: false)
    XCTAssertNotNil(components)
    XCTAssertEqual(components?.scheme, "https")

    FlingChallengeKit.secure = false
    components = NSURLComponents(URL: FlingChallengeKit.baseURL, resolvingAgainstBaseURL: false)
    XCTAssertNotNil(components)
    XCTAssertEqual(components?.scheme, "http")

    FlingChallengeKit.secure = true
    components = NSURLComponents(URL: FlingChallengeKit.baseURL, resolvingAgainstBaseURL: false)
    XCTAssertNotNil(components)
    XCTAssertEqual(components?.scheme, "https")
  }

  func testFeedURL() {
    do {
      let URL = try Endpoints.Feed.URL()
      XCTAssertNotNil(URL)
    }
    catch {
      XCTFail()
    }
  }

  func testPhotosURL() {
    do {
      let photoID = "5"
      let components = NSURLComponents(URL: try Endpoints.Photos.URL(["id": photoID]), resolvingAgainstBaseURL: false)
      XCTAssertNotNil(components)
      XCTAssertNotNil(components?.path)
      XCTAssertEqual((components!.path! as NSString).lastPathComponent, photoID)
    }
    catch {
      XCTFail()
    }
  }

}


//  Copyright © 2017 Steve Brambilla. All rights reserved.

import AVKit

extension Anchors where Base: AVPlayerViewController {
	/// A layout area representing the view's `unobscuredContentGuide`.
	@available(tvOS 11.0, *)
	public var unobstructed: LayoutAreaAnchors {
		return LayoutAreaAnchors(guide: base.unobscuredContentGuide)
	}
}

Correct naming of unobstructed -> unobscured

//  Copyright © 2017 Steve Brambilla. All rights reserved.

import AVKit

extension Anchors where Base: AVPlayerViewController {
	/// A layout area representing the view's `unobscuredContentGuide`.
	@available(tvOS 11.0, *)
	public var unobscured: LayoutAreaAnchors {
		return LayoutAreaAnchors(guide: base.unobscuredContentGuide)
	}
}


#!/usr/bin/env swift

import Foundation

var num_steps: Int = 1000000000

#if swift(>=3)
if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}
#else
if Process.arguments.count == 2 {
    num_steps = Int(Process.arguments[1])!;
}
#endif

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// Get time.
let start = Date()

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time again.
let stop = Date()
let interval = stop.timeIntervalSince(start)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(interval) + " seconds")

Revert "Use preprocessor directives to support Swift 2.x"

#!/usr/bin/env swift

import Foundation

var num_steps: Int = 1000000000

if CommandLine.arguments.count == 2 {
    num_steps = Int(CommandLine.arguments[1])!;
}

print("Calculating PI with:")
print("  " + String(num_steps) + " slices")
print("  1 process")

var total_sim: Double = 0.0
var step: Double = 1.0/Double(num_steps)

// Get time.
let start = Date()

for i in 1...num_steps {
    var x: Double = (Double(i) - 0.5) * step
    total_sim += 4.0/(1.0+(x*x))
}

var pi: Double = total_sim * step

// Get time again.
let stop = Date()
let interval = stop.timeIntervalSince(start)

print("Obtained value of PI: " + String(pi))
print("Time taken: " + String(interval) + " seconds")


//
//  PersonalizationCommandTests.swift
//
//
//  Created by Vladislav Fitc on 27/05/2020.
//

import Foundation
import XCTest
@testable import AlgoliaSearchClient

class PersonalizationCommandTests: XCTestCase, AlgoliaCommandTest {

  func testGet() {
    let command = Command.Personalization.Get(requestOptions: test.requestOptions)
    check(command: command,
          callType: .read,
          method: .get,
          urlPath: "/1/strategies/personalization",
          queryItems: [
              .init(name: "testParameter", value: "testParameterValue"),
          ],
          body: nil,
          requestOptions: test.requestOptions)
  }

  func testSet() {
    let command = Command.Personalization.Set(strategy: test.personalizationStrategy, requestOptions: test.requestOptions)
    check(command: command,
          callType: .write,
          method: .post,
          urlPath: "/1/strategies/personalization",
          queryItems: [
              .init(name: "testParameter", value: "testParameterValue"),
          ],
          body: test.personalizationStrategy.httpBody,
          requestOptions: test.requestOptions)
  }

}

Fix Personalization set command unit test

//
//  PersonalizationCommandTests.swift
//
//
//  Created by Vladislav Fitc on 27/05/2020.
//

import Foundation
import XCTest
@testable import AlgoliaSearchClient

class PersonalizationCommandTests: XCTestCase, AlgoliaCommandTest {

  func testGet() {
    let command = Command.Personalization.Get(requestOptions: test.requestOptions)
    check(command: command,
          callType: .read,
          method: .get,
          urlPath: "/1/strategies/personalization",
          queryItems: [
              .init(name: "testParameter", value: "testParameterValue"),
          ],
          body: nil,
          requestOptions: test.requestOptions)
  }

  func testSet() {
    let command = Command.Personalization.Set(strategy: test.personalizationStrategy, requestOptions: test.requestOptions)
    check(command: command,
          callType: .write,
          method: .post,
          urlPath: "/1/strategies/personalization",
          queryItems: [
              .init(name: "testParameter", value: "testParameterValue"),
          ],
          body: test.personalizationStrategy.httpBody,
          additionalHeaders: ["Content-Type": "application/json"],
          requestOptions: test.requestOptions)
  }

}


//
//  ANFullScreenViewController.swift
//  Pods
//
//  Created by Sergey Demchenko on 6/30/16.
//
//

import UIKit

class ANFullScreenViewController: UIViewController
{
    @IBOutlet var fullScreenView: ANFullScreenView!
    var player: ANPlayerController?

    var onCloseButtonTapped : (() -> Void) = { () -> Void in }

    init()
    {
        super.init(nibName: "ANFullScreenViewController", bundle: NSBundle(forClass: self.dynamicType))
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    // MARK: - IBAction

    @IBAction func onCloseButtonTapped(sender: AnyObject)
    {
        onCloseButtonTapped()
    }
}

Hide status bar for full screen.

//
//  ANFullScreenViewController.swift
//  Pods
//
//  Created by Sergey Demchenko on 6/30/16.
//
//

import UIKit

class ANFullScreenViewController: UIViewController
{
    @IBOutlet var fullScreenView: ANFullScreenView!
    var player: ANPlayerController?

    var onCloseButtonTapped : (() -> Void) = { () -> Void in }

    init()
    {
        super.init(nibName: "ANFullScreenViewController", bundle: NSBundle(forClass: self.dynamicType))
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    override func prefersStatusBarHidden() -> Bool { return true }

    // MARK: - IBAction

    @IBAction func onCloseButtonTapped(sender: AnyObject)
    {
        onCloseButtonTapped()
    }
}


//: Creational Pattern

import UIKit

Implement Creational pattern : Prototype pattern

//: Creational Pattern
/*
    - Prototype
    - Factory method
    - Abstract factory
    - Singleton
    - Builder
*/

//: Prototype Pattern
/*
This pattern will help you create new object by duplicating and cloning capability.
*/

//: Implementation
class SmartPhonePrototype {
    var name: String
    var price: Int
    var brand: String

    init(name: String, price: Int, brand: String) {
        self.name = name
        self.price = price
        self.brand = brand
    }

    func clone() -> SmartPhonePrototype {
        return SmartPhonePrototype(name: self.name, price: self.price, brand: self.brand)
    }
}

class SmartPhone: SmartPhonePrototype {
    override init(name: String, price: Int, brand: String) {
        super.init(name: name, price: price, brand: brand)
    }
}

//: Usage
let iPhone6 = SmartPhone(name: "iPhone 6", price: 649, brand: "Apple")

let aaaiPhone6 = iPhone6.clone()

aaaiPhone6.name
aaaiPhone6.price
aaaiPhone6.brand


//
//  Created by Christopher Trott on 10/22/15.
//  Copyright © 2015 twocentstudios. All rights reserved.
//

import Foundation

public enum EventError : ErrorType {
    case UnderlyingError(error: NSError)
    case InvalidResponse
    case ImageURLMissing
    case StreamURLMissing
    case UnknownError

    func localizedDescription() -> String {
        switch self {
        case .InvalidResponse:
            return "The server returned an invalid response.".l10()
        case .StreamURLMissing:
            return "The stream's URL could not be found.".l10()
        case .ImageURLMissing:
            return "The stream's image URL could not be found.".l10()
        case .UnderlyingError(let e):
            return e.localizedDescription
        default:
            return "An unknown error occurred. Please try again.".l10()
        }
    }
}

Make error message more user friendly

//
//  Created by Christopher Trott on 10/22/15.
//  Copyright © 2015 twocentstudios. All rights reserved.
//

import Foundation

public enum EventError : ErrorType {
    case UnderlyingError(error: NSError)
    case InvalidResponse
    case ImageURLMissing
    case StreamURLMissing
    case UnknownError

    func localizedDescription() -> String {
        switch self {
        case .InvalidResponse:
            return "The server returned an invalid response.".l10()
        case .StreamURLMissing:
            return "This stream is currently offline. Please try again later.".l10()
        case .ImageURLMissing:
            return "The stream's image URL could not be found.".l10()
        case .UnderlyingError(let e):
            return e.localizedDescription
        default:
            return "An unknown error occurred. Please try again.".l10()
        }
    }
}