import HTTP
import Routing

@_exported import HTTPRouting
@_exported import TypeSafeRouting

extension Droplet: RouteBuilder {
    public typealias Value = Responder

    public func add(
        path: [String],
        value: Value
    ) {
        router.add(path: path, value: value)
    }
}

extension RouteBuilder where Value == Responder {
    public func group(_ middleware: Middleware ..., closure: (RouteGroup<Value, Self>) ->()) {
        group(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middleware.chain(to: handler).respond(to: request)
            }
        }, closure: closure)
    }

    public func grouped(_ middleware: Middleware ...) -> RouteGroup<Value, Self> {
        return grouped(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middleware.chain(to: handler).respond(to: request)
            }
        })
    }
}

extension RouteBuilder {
    public func collection<
        C: RouteCollection>(_ collectionType: C.Type)
        where C.Wrapped == Value,
        C: EmptyInitializable
    {
        let collection = collectionType.init()
        self.collection(collection)
    }
}

Support for [Middleware] in route groups

import HTTP
import Routing

@_exported import HTTPRouting
@_exported import TypeSafeRouting

extension Droplet: RouteBuilder {
    public typealias Value = Responder

    public func add(
        path: [String],
        value: Value
    ) {
        router.add(path: path, value: value)
    }
}

extension RouteBuilder where Value == Responder {
    public func group(_ middleware: Middleware ..., closure: (RouteGroup<Value, Self>) ->()) {
        group(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middleware.chain(to: handler).respond(to: request)
            }
        }, closure: closure)
    }

    public func grouped(_ middleware: Middleware ...) -> RouteGroup<Value, Self> {
        return grouped(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middleware.chain(to: handler).respond(to: request)
            }
        })
    }

    public func group(_ middlewares: [Middleware], closure: (RouteGroup<Value, Self>) ->()) {
        group(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middlewares.chain(to: handler).respond(to: request)
            }
        }, closure: closure)
    }

    public func grouped(_ middlewares: [Middleware]) -> RouteGroup<Value, Self> {
        return grouped(prefix: [nil, nil], path: [], map: { handler in
            return Request.Handler { request in
                return try middlewares.chain(to: handler).respond(to: request)
            }
        })
    }
}

extension RouteBuilder {
    public func collection<
        C: RouteCollection>(_ collectionType: C.Type)
        where C.Wrapped == Value,
        C: EmptyInitializable
    {
        let collection = collectionType.init()
        self.collection(collection)
    }
}


//
//  Bundle+Helper.swift
//  OpalImagePicker
//
//  Created by Kris Katsanevas on 1/15/17.
//  Copyright © 2017 Opal Orange LLC. All rights reserved.
//

import Foundation

extension Bundle {
    static func podBundle(forClass: AnyClass) -> Bundle? {

        let bundleForClass = Bundle(for: forClass)

        if let bundleURL = bundleForClass.url(forResource: "OpalImagePickerResources", withExtension: "bundle") {
            if let bundle = Bundle(url: bundleURL) {
                return bundle
            } else {
                assertionFailure("Could not load the bundle")
            }
        } else {
            assertionFailure("Could not create a path to the bundle")
        }
        return nil
    }
}

Remove assertions that break non-Cocoapods installations

//
//  Bundle+Helper.swift
//  OpalImagePicker
//
//  Created by Kris Katsanevas on 1/15/17.
//  Copyright © 2017 Opal Orange LLC. All rights reserved.
//

import Foundation

extension Bundle {
    static func podBundle(forClass: AnyClass) -> Bundle? {

        let bundleForClass = Bundle(for: forClass)

        if let bundleURL = bundleForClass.url(forResource: "OpalImagePickerResources", withExtension: "bundle"),
            let bundle = Bundle(url: bundleURL) {
                return bundle
            }
        return nil
    }
}


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

public func find<C: CollectionType>(domain: C, predicate: C.Generator.Element -> Bool) -> C.Index? {
	for index in domain.startIndex..<domain.endIndex {
		if predicate(domain[index]) { return index }
	}
	return nil
}

Mark find’s predicate as noescape.

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

public func find<C: CollectionType>(domain: C, @noescape predicate: C.Generator.Element -> Bool) -> C.Index? {
	for index in domain.startIndex..<domain.endIndex {
		if predicate(domain[index]) { return index }
	}
	return nil
}


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

final class IntExtensionTests: XCTestCase {
	func testThereIsOneDigitInZero() {
		assert(0.digits, ==, [0])
	}

	func testThereIsOneDigitInNine() {
		assert(9.digits, ==, [9])
	}

	func testThereAreTwoDigitsInTen() {
		assert(10.digits, ==, [1, 0])
	}

	func testThereAreTwoDigitsInNinetyNine() {
		assert(99.digits, ==, [9, 9])
	}

	func testThereAreThreeDigitsInOneHundredAndTwentyThree() {
		assert(123.digits, ==, [1, 2, 3])
	}
}

import Assertions
@testable import Manifold
import XCTest

Test integer digits in various bases.

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

final class IntExtensionTests: XCTestCase {
	func testThereIsOneDigitInZero() {
		assert(0.digits, ==, [0])
	}

	func testThereIsOneDigitInNine() {
		assert(9.digits, ==, [9])
	}

	func testThereAreTwoDigitsInTen() {
		assert(10.digits, ==, [1, 0])
	}

	func testThereAreTwoDigitsInNinetyNine() {
		assert(99.digits, ==, [9, 9])
	}

	func testThereAreThreeDigitsInOneHundredAndTwentyThree() {
		assert(123.digits, ==, [1, 2, 3])
	}

	func testBinaryDigits() {
		assert(4.digits(2), ==, [ 1, 0, 0 ])
		assert(7.digits(2), ==, [ 1, 1, 1 ])
	}

	func testHexDigits() {
		assert(0.digits(16), ==, [ 0 ])
		assert(255.digits(16), ==, [ 15, 15 ])
		assert(65535.digits(16), ==, [ 15, 15, 15, 15 ])
	}
}

import Assertions
@testable import Manifold
import XCTest


// swift-tools-version:5.2

import PackageDescription

let pkgName = "gir2swift"
let libTarget = "lib\(pkgName)"

let package = Package(
    name: pkgName,
    products: [
        .executable(name: pkgName, targets: [pkgName]),
        .library(name: libTarget, targets: [libTarget]),
    ],
    dependencies: [
        .package(url: "https://github.com/jpsim/Yams.git", from: "4.0.6"),
        .package(url: "https://github.com/rhx/SwiftLibXML.git", .branch("manual")),
        .package(url: "https://github.com/apple/swift-argument-parser", from: "0.4.0")
    ],
    targets: [
        .target(
            name: pkgName,
            dependencies: [
                .init(stringLiteral: libTarget)
            ]
        ),
        .target(
            name: libTarget,
            dependencies: [
                "SwiftLibXML",
                .product(name: "ArgumentParser", package: "swift-argument-parser"),
                "Yams"
            ]
        ),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.init(stringLiteral: libTarget)]),
    ]
)

Revert back to main branch of SwiftLibXML

// swift-tools-version:5.2

import PackageDescription

let pkgName = "gir2swift"
let libTarget = "lib\(pkgName)"

let package = Package(
    name: pkgName,
    products: [
        .executable(name: pkgName, targets: [pkgName]),
        .library(name: libTarget, targets: [libTarget]),
    ],
    dependencies: [
        .package(url: "https://github.com/jpsim/Yams.git", from: "4.0.6"),
        .package(url: "https://github.com/rhx/SwiftLibXML.git", .branch("main")),
        .package(url: "https://github.com/apple/swift-argument-parser", from: "0.4.0")
    ],
    targets: [
        .target(
            name: pkgName,
            dependencies: [
                .init(stringLiteral: libTarget)
            ]
        ),
        .target(
            name: libTarget,
            dependencies: [
                "SwiftLibXML",
                .product(name: "ArgumentParser", package: "swift-argument-parser"),
                "Yams"
            ]
        ),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.init(stringLiteral: libTarget)]),
    ]
)


#include <builtins.swift>
// THIS-TEST-SHOULD-NOT-RUN

// CHeck that double writes are caught

main {
    int A[];
    A[id(1)] = 1;
    A[id(1)] = 2;
}

(int o) id (int i) {
    o = i;
}

Fix 312 to prevent array being optimized out

#include <builtins.swift>
// THIS-TEST-SHOULD-NOT-RUN

// CHeck that double writes are caught

main {
    int A[];
    A[id(1)] = 1;
    A[id(1)] = 2;
    // Prevent A getting optimized out
    trace(A[1]);
}

(int o) id (int i) {
    o = i;
}


import Mockingjay

func api(method: HTTPMethod, _ uri: String, token: String)(request: NSURLRequest) -> Bool {
    guard let headers = request.allHTTPHeaderFields,
        authorization = headers["Authorization"] where
        authorization == "Bearer \(token)"
    else {
        return false
    }

    return api(method, uri)(request: request)
}

func api(method: HTTPMethod, _ uri: String)(request: NSURLRequest) -> Bool {
    guard let headers = request.allHTTPHeaderFields,
        accept = headers["Accept"],
        acceptEncoding = headers["Accept-Encoding"],
        contentType = headers["Content-Type"] where
        accept == "application/json" &&
        contentType == "application/json" &&
        acceptEncoding == "gzip;q=1.0,compress;q=0.5"
    else {
        return false
    }

    return http(method, uri: uri)(request: request)
}

func api(method: HTTPMethod, _ uri: String, body: [String: AnyObject])(request: NSURLRequest) -> Bool {
    let bodyJson = try? NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions())
    guard bodyJson == request.HTTPBody else { return false }
    return api(method, uri)(request: request)
}

Fix Mockingjay matcher to workaround issue with HTTPBody.

import Mockingjay

func api(method: HTTPMethod, _ uri: String, token: String)(request: NSURLRequest) -> Bool {
    guard let headers = request.allHTTPHeaderFields,
        authorization = headers["Authorization"] where
        authorization == "Bearer \(token)"
    else {
        return false
    }

    return api(method, uri)(request: request)
}

func api(method: HTTPMethod, _ uri: String)(request: NSURLRequest) -> Bool {
    guard let headers = request.allHTTPHeaderFields,
        accept = headers["Accept"],
        acceptEncoding = headers["Accept-Encoding"],
        contentType = headers["Content-Type"] where
        accept == "application/json" &&
        contentType == "application/json" &&
        acceptEncoding == "gzip;q=1.0,compress;q=0.5"
    else {
        return false
    }

    return http(method, uri: uri)(request: request)
}

func api(method: HTTPMethod, _ uri: String, body: [String: AnyObject])(request: NSURLRequest) -> Bool {
    guard let bodyStream = request.HTTPBodyStream else { return false }

    bodyStream.open()

    guard let bodyStreamJsonObject = try? NSJSONSerialization.JSONObjectWithStream(bodyStream, options: NSJSONReadingOptions()) else {
        return false
    }

    let bodyStreamJsonData = try? NSJSONSerialization.dataWithJSONObject(bodyStreamJsonObject, options: NSJSONWritingOptions())
    let bodyJsonData = try? NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions())

    guard bodyStreamJsonData == bodyJsonData else { return false }

    return api(method, uri)(request: request)
}


//
//  ParserProtocol.swift
//
//
//  Created by 1024jp on 2017/03/04.
//
//

import Foundation

struct Heading {

    let string: String
    let level: Int
}

enum Chunk {
    case heading(string: String, level: Int)
    case nonHeading(string: String)
}

protocol Parsable {

    var langauge: String { get }

    func parse(string: String) -> Document

    func makeBlocks(lines: [String]) -> [Block]
    func makeStyledString(string: String) -> StyledString
    func headingLevel(string: String) -> Int?
}

Change `language` property to static

//
//  ParserProtocol.swift
//
//
//  Created by 1024jp on 2017/03/04.
//
//

import Foundation

struct Heading {

    let string: String
    let level: Int
}

enum Chunk {
    case heading(string: String, level: Int)
    case nonHeading(string: String)
}

protocol Parsable {

    static var langauge: String { get }

    func parse(string: String) -> Document

    func makeBlocks(lines: [String]) -> [Block]
    func makeStyledString(string: String) -> StyledString
    func headingLevel(string: String) -> Int?
}


import UIKit

struct TextFactory {

    private static let dateFormatter = DateFormatter()
    private static let numberFormatter = NumberFormatter()

    static func makeLastUpdateDateText(updateDate: Date, timeZone: TimeZone? = nil) -> String {
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .short

        if let timeZone = timeZone {
            dateFormatter.timeZone = timeZone
        }

        return "\(NSLocalizedString("last.updated.on", comment: "")) \(dateFormatter.string(from: updateDate))"
    }

    static func makeFormattedCurrencyValueString(for value: Double?, isFiat: Bool) -> String {
        numberFormatter.locale = .current
        numberFormatter.numberStyle = .decimal
        numberFormatter.generatesDecimalNumbers = true

        if isFiat {
            numberFormatter.minimumFractionDigits = 2
            numberFormatter.maximumFractionDigits = 2
        } else {
            numberFormatter.minimumFractionDigits = 0
            numberFormatter.maximumFractionDigits = 100
        }

        let valueString: String

        if let value = value, let string = numberFormatter.string(for: value) {
            valueString = string
        } else {
            valueString = "-"
        }

        return valueString
    }

}

Fix rounding double value in makeFormattedCurrencyValueString()

import UIKit

struct TextFactory {

    private static let dateFormatter = DateFormatter()
    private static let numberFormatter = NumberFormatter()

    static func makeLastUpdateDateText(updateDate: Date, timeZone: TimeZone? = nil) -> String {
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .short

        if let timeZone = timeZone {
            dateFormatter.timeZone = timeZone
        }

        return "\(NSLocalizedString("last.updated.on", comment: "")) \(dateFormatter.string(from: updateDate))"
    }

    static func makeFormattedCurrencyValueString(for value: Double?, isFiat: Bool) -> String {
        numberFormatter.locale = .current
        numberFormatter.numberStyle = .decimal
        numberFormatter.generatesDecimalNumbers = true

        if isFiat {
            numberFormatter.minimumFractionDigits = 2
            numberFormatter.maximumFractionDigits = 2
        } else {
            numberFormatter.minimumFractionDigits = 0
            numberFormatter.maximumFractionDigits = 10
        }

        let valueString: String

        if let value = value, let string = numberFormatter.string(for: value) {
            valueString = string
        } else {
            valueString = "-"
        }

        return valueString
    }

}


import Cocoa
import FlutterMacOS
import os

private let CALLBACK_HANDLE = "callback"
private let BG_CALLBACK_HANDLE = "background_callback"

private func _log(_ args: CVarArg...) {
  if #available(macOS 10.12, *) {
    os_log("TaqoTimePlugin: %s", args)
  }
}

public class TaqoTimePlugin: NSObject, FlutterPlugin {
  private static let channelName = "taqo_time_plugin"
  private static let initialize = "initialize"
  private static let cancel = "cancel"

  private static let bgCallbackMethod = "backgroundIsolateCallback"

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger)
    let instance = TaqoTimePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  @objc private func timeChanged(notification: NSNotification) {
    _log("timeChanged")
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case TaqoTimePlugin.initialize:
        NotificationCenter.default.addObserver(self, selector: #selector(self.timeChanged), name: NSNotification.Name.NSSystemClockDidChange, object: nil)

        result(true)
      case TaqoTimePlugin.cancel:
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSSystemClockDidChange, object: nil)

        result(true)
      default:
        result(FlutterMethodNotImplemented)
    }
  }
}

Fix incorrect params to os_log in macOS time plugin

import Cocoa
import FlutterMacOS
import os

private let CALLBACK_HANDLE = "callback"
private let BG_CALLBACK_HANDLE = "background_callback"

public class TaqoTimePlugin: NSObject, FlutterPlugin {
  private static let channelName = "taqo_time_plugin"
  private static let initialize = "initialize"
  private static let cancel = "cancel"

  private static let bgCallbackMethod = "backgroundIsolateCallback"

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger)
    let instance = TaqoTimePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  @objc private func timeChanged(notification: NSNotification) {
    if #available(macOS 10.12, *) {
      os_log("TaqoTimePlugin: timeChanged")
    }
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case TaqoTimePlugin.initialize:
        NotificationCenter.default.addObserver(self, selector: #selector(self.timeChanged), name: NSNotification.Name.NSSystemClockDidChange, object: nil)

        result(true)
      case TaqoTimePlugin.cancel:
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSSystemClockDidChange, object: nil)

        result(true)
      default:
        result(FlutterMethodNotImplemented)
    }
  }
}


//
//  DateTimeManipulation.swift
//  Noted
//
//  Created by Michael Andrew Auer on 3/19/16.
//  Copyright © 2016 Usonia LLC. All rights reserved.
//

import Foundation

struct DateTime {

    let df: NSDateFormatter = NSDateFormatter()

    init() {
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
    }
    func fmtDate(noteDate: String) -> String {
        if (noteDate == "") {
            return ""
        }

        let noteNSD: NSDate = df.dateFromString(noteDate)!
        let difference = -(noteNSD.timeIntervalSinceNow)
        let oneday: Double = 86400

        if (difference < oneday) {
            return "Today"
        } else if (difference < (oneday * 2)) {
            return "Yesterday"
        } else {
            df.dateFormat = "mm/dd/yy"
            return df.stringFromDate(df.dateFromString(noteDate)!)
        }
    }
    func setDate() -> String {
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return df.stringFromDate(NSDate())
    }
}

Fix date formatting on unwrap bug

//
//  DateTimeManipulation.swift
//  Noted
//
//  Created by Michael Andrew Auer on 3/19/16.
//  Copyright © 2016 Usonia LLC. All rights reserved.
//

import Foundation

struct DateTime {

    let df: NSDateFormatter = NSDateFormatter()

    init() {
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
    }
    func fmtDate(noteDate: String) -> String {
        if (noteDate == "") {
            return ""
        }

        let noteNSD: NSDate = df.dateFromString(noteDate)!
        let difference = -(noteNSD.timeIntervalSinceNow)
        let oneday: Double = 86400

        if (difference < oneday) {
            return "Today"
        } else if (difference < (oneday * 2)) {
            return "Yesterday"
        } else {
            let noteDateObject = df.dateFromString(noteDate)
            df.dateFormat = "MM/dd/yy"
            return df.stringFromDate(noteDateObject!)
        }
    }
    func setDate() -> String {
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return df.stringFromDate(NSDate())
    }
}


public extension Sequence where Element: Hashable {
  /// Returns a `Dictionary` containing the occurrence of each value.
  ///
  ///     print([0, 1, 1, 2, 2, 2].occurrences)
  ///     // [0: 1, 1: 2, 2: 3]
  var occurrences: [Element: Int] {
    return self.reduce(into: [:]) { $0[$1, default: 0] += 1 }
  }
}

public extension Sequence where Element: Equatable {
  /// Returns an `Array` containing all unique values.
  ///
  ///     print([0, 1, 1, 2, 2, 2].uniques)
  ///     // [0, 1, 2]
  var uniques: [Element] {
    return self.reduce(into: []) {
      if !$0.contains($1) {
        $0.append($1)
      }
    }
  }

  /// Returns an `Array` containing all duplicate values.
  ///
  ///     print([0, 1, 1, 2, 2, 2].duplicates)
  ///     // [1, 2, 2]
  ///
  /// - Note: To get unique duplicate values call `duplicates.uniques`.
  var duplicates: [Element] {
    var uniques = [Element]()

    return self.reduce(into: []) {
      if uniques.contains($1) {
        $0.append($1)
      } else {
        uniques.append($1)
      }
    }
  }
}

Sort declarations by alphabetical order

public extension Sequence where Element: Equatable {
  /// Returns an `Array` containing all duplicate values.
  ///
  ///     print([0, 1, 1, 2, 2, 2].duplicates)
  ///     // [1, 2, 2]
  ///
  /// - Note: To get unique duplicate values call `duplicates.uniques`.
  var duplicates: [Element] {
    var uniques = [Element]()

    return self.reduce(into: []) {
      if uniques.contains($1) {
        $0.append($1)
      } else {
        uniques.append($1)
      }
    }
  }

  /// Returns an `Array` containing all unique values.
  ///
  ///     print([0, 1, 1, 2, 2, 2].uniques)
  ///     // [0, 1, 2]
  var uniques: [Element] {
    return self.reduce(into: []) {
      if !$0.contains($1) {
        $0.append($1)
      }
    }
  }
}

public extension Sequence where Element: Hashable {
  /// Returns a `Dictionary` containing the occurrence of each value.
  ///
  ///     print([0, 1, 1, 2, 2, 2].occurrences)
  ///     // [0: 1, 1: 2, 2: 3]
  var occurrences: [Element: Int] {
    return self.reduce(into: [:]) { $0[$1, default: 0] += 1 }
  }
}


// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "EurofurenceComponents",
    products: [
        .library(
            name: "EurofurenceComponents",
            targets: ["EurofurenceComponents"]
        )
    ],
    dependencies: [

    ],
    targets: [
        .target(
            name: "EurofurenceComponents",
            dependencies: []
        ),
        .testTarget(
            name: "EurofurenceComponentsTests",
            dependencies: ["EurofurenceComponents"]
        )
    ]
)

Define base target for components

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "EurofurenceComponents",
    products: [
        .library(
            name: "EurofurenceComponents",
            targets: ["EurofurenceComponents"]
        )
    ],
    dependencies: [

    ],
    targets: [
        .target(name: "EurofurenceComponentBase", dependencies: []),
        .testTarget(name: "EurofurenceComponentBaseTests", dependencies: [
            .target(name: "EurofurenceComponentBase")
        ]),

        .target(name: "EurofurenceComponents", dependencies: [
            .target(name: "EurofurenceComponentBase")
        ]),

        .testTarget(name: "EurofurenceComponentsTests", dependencies: [
            .target(name: "EurofurenceComponents")
        ]),
    ]
)


//
//  AspectRatioConstrainedImageView.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class AspectRatioConstrainedImageView: UIImageView {

    override var image: UIImage? {
        didSet {
            if let size = image?.size {
                applyAspectRatioImageConstraints(size: size)
            }
        }
    }

    private func applyAspectRatioImageConstraints(size: CGSize) {
        let aspectRatio = size.width / size.height
        widthAnchor.constraint(equalTo: heightAnchor, multiplier: aspectRatio).isActive = true
    }

}

Reduce priority of aspect ratio constraints maringally

//
//  AspectRatioConstrainedImageView.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class AspectRatioConstrainedImageView: UIImageView {

    override var image: UIImage? {
        didSet {
            if let size = image?.size {
                applyAspectRatioImageConstraints(size: size)
            }
        }
    }

    private func applyAspectRatioImageConstraints(size: CGSize) {
        let aspectRatio = size.width / size.height
        let aspectRatioConstraint = widthAnchor.constraint(equalTo: heightAnchor, multiplier: aspectRatio)
        aspectRatioConstraint.priority = UILayoutPriority(999)
        aspectRatioConstraint.isActive = true
    }

}


/*
  Helper functions for dealing with locations
 */

@pure
(location loc) location_from_rank(int rank) "turbine" "0.1.1" [
  // Currently location is represented as an integer rank,
  // so this function just down-casts the type.
  // This may change in future.
  "set <<loc>> <<rank>>"
];

(location loc) random_worker() "turbine" "0.1.1" [
   "set <<loc>> [ ::turbine::random_worker ]"
];

(location loc) random_engine() "turbine" "0.1.1" [
   "set <<loc>> [ ::turbine::random_engine ]"
];

(location rank) hostmap_one(string name) "turbine" "0.0.2" [
    "set <<rank>> [ draw [ adlb::hostmap <<name>> ] ]"
];

(location rank) hostmap_one_worker(string name) "turbine" "0.0.2" [
    "set <<rank>> [ ::turbine::random_rank WORKER [ adlb::hostmap <<name>> ] ]"
];

(string results[]) hostmap_list() "turbine" "0.5.0" "hostmap_list";

Update header to reflect new hostmap function

/*
  Helper functions for dealing with locations
 */

@pure
(location loc) location_from_rank(int rank) "turbine" "0.1.1" [
  // Currently location is represented as an integer rank,
  // so this function just down-casts the type.
  // This may change in future.
  "set <<loc>> <<rank>>"
];

(location loc) random_worker() "turbine" "0.1.1" [
   "set <<loc>> [ ::turbine::random_worker ]"
];

(location loc) random_engine() "turbine" "0.1.1" [
   "set <<loc>> [ ::turbine::random_engine ]"
];

(location rank) hostmap_one(string name) "turbine" "0.0.2" [
    "set <<rank>> [ draw [ adlb::hostmap_lookup <<name>> ] ]"
];

(location rank) hostmap_one_worker(string name) "turbine" "0.0.2" [
    "set <<rank>> [ ::turbine::random_rank WORKER [ adlb::hostmap_lookup <<name>> ] ]"
];

(string results[]) hostmap_list() "turbine" "0.5.0" "hostmap_list";


//
//  AppCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import UIKit
import Dip

class AppCoordinator: Coordinator {

    override func start() {
        container.register(.singleton) { DataManager(backend: CoreDataDataManagerBackend(containerName: "Artikolo")) }

        let articleListCoordinator = ArticleListCoordinator(navigationController: navigationController, container: container)
        addChild(articleListCoordinator)
    }

}

Add argument to reset the database on app launch.

//
//  AppCoordinator.swift
//  Artikolo
//
//  Created by Grant Butler on 4/30/17.
//  Copyright © 2017 Grant Butler. All rights reserved.
//

import UIKit
import Dip

class AppCoordinator: Coordinator {

    override func start() {
        container.register(.singleton) { DataManager(backend: CoreDataDataManagerBackend(containerName: "Artikolo")) }

        setupForRunning()

        let articleListCoordinator = ArticleListCoordinator(navigationController: navigationController, container: container)
        addChild(articleListCoordinator)
    }

    func setupForRunning() {
        if CommandLine.arguments.contains("-ResetDatabase") {
            let dataManager = try! container.resolve() as DataManager
            try! dataManager.reset()
        }
    }

}


//
//  Store+Subscribe.swift
//  TDRedux
//
//  Created by Nicholas Tian on 18/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {
    public typealias StateSubscriber = (_ state: State) -> ()

    public func subscribe(with subscriber: @escaping StateSubscriber) {
        self.subscribe { store in
            subscriber(store.state)
        }
    }

    public func subscribe<SpecificState>(
        withConverter converter: @escaping (State) -> SpecificState,
        subscriber: @escaping (SpecificState) -> ()
    ) {
        self.subscribe { state in
            subscriber(converter(state))
        }
    }
}

Add docs for new `subscribe` methods

//
//  Store+Subscribe.swift
//  TDRedux
//
//  Created by Nicholas Tian on 18/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {
    public typealias StateSubscriber = (_ state: State) -> ()

    /// Subcribes a *StateSubscriber* (takes a *State* rather than a *Store*)
    /// to the changes of a *Store*'s *State*
    ///
    /// - parameter subscriber: A StateSubscriber function
    public func subscribe(with subscriber: @escaping StateSubscriber) {
        self.subscribe { store in
            subscriber(store.state)
        }
    }

    /// Subcribes a *SpecificStateSubscriber* (takes a *SpecificState*)
    /// to the changes of a *Store*'s *State*
    /// with the help of a `Converter`
    ///
    /// - parameter converter:  A function converts State to SpecificState
    /// - parameter subscriber: A SpecificStateSubscriber function
    public func subscribe<SpecificState>(
        withConverter converter: @escaping (State) -> SpecificState,
        subscriber: @escaping (SpecificState) -> ()
    ) {
        self.subscribe { state in
            subscriber(converter(state))
        }
    }
}


import SystemConfiguration

struct Interfaces {

  static func all(async: Bool) -> [Interface] {
    let interfaces = SCNetworkInterfaceCopyAll()
    var instances: [Interface] = []

    for interfaceRef in interfaces {
      guard let BSDName = SCNetworkInterfaceGetBSDName(interfaceRef as! SCNetworkInterface) else { continue }
      guard let displayName = SCNetworkInterfaceGetLocalizedDisplayName(interfaceRef as! SCNetworkInterface) else { continue }
      guard let hardMAC = SCNetworkInterfaceGetHardwareAddressString(interfaceRef as! SCNetworkInterface) else { continue }
      guard let type = SCNetworkInterfaceGetInterfaceType(interfaceRef as! SCNetworkInterface) else { continue }

      let interface = Interface(BSDName: BSDName as String, displayName: displayName as String, kind: type as String, hardMAC: hardMAC as String, async: async)
      if (interface.isSpoofable) { instances.append(interface) }
    }
    return instances
  }

}

Sort interfaces by BSD name

import SystemConfiguration

struct Interfaces {

  static func all(async: Bool) -> [Interface] {
    let interfaces = SCNetworkInterfaceCopyAll()
    var instances: [Interface] = []

    for interfaceRef in interfaces {
      guard let BSDName = SCNetworkInterfaceGetBSDName(interfaceRef as! SCNetworkInterface) else { continue }
      guard let displayName = SCNetworkInterfaceGetLocalizedDisplayName(interfaceRef as! SCNetworkInterface) else { continue }
      guard let hardMAC = SCNetworkInterfaceGetHardwareAddressString(interfaceRef as! SCNetworkInterface) else { continue }
      guard let type = SCNetworkInterfaceGetInterfaceType(interfaceRef as! SCNetworkInterface) else { continue }

      let interface = Interface(BSDName: BSDName as String, displayName: displayName as String, kind: type as String, hardMAC: hardMAC as String, async: async)
      if (interface.isSpoofable) { instances.append(interface) }
    }
    return instances.sorted { $0.BSDName < $1.BSDName }
  }

}


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

final class DatatypeTests: XCTestCase {
}

import Assertions
@testable import Manifold
import XCTest

Test that zero-constructor datatypes are unit.

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

final class DatatypeTests: XCTestCase {
	func testDatatypeWithZeroConstructorsIsUnitType() {
		assert(Datatype(constructors: []).value("A"), ==, .UnitType)
	}
}

import Assertions
@testable import Manifold
import XCTest


//
//  HotSignalSpec.swift
//  ReactiveCocoa
//
//  Created by Alan Rogers on 30/10/2014.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

import Nimble
import Quick
import ReactiveCocoa

class HotSignalSpec: QuickSpec {
	override func spec() {
		describe("replay") {
			var signal : HotSignal<Int>!
			var sink : SinkOf<Int>!
			var coldSignal : ColdSignal<Int>!

			beforeEach {
				let pipe = HotSignal<Int>.pipe()
				signal = pipe.0
				sink = pipe.1
				coldSignal = signal.replay(1)
			}

			it("should replay the first value to a subscriber") {
				sink.put(99)
				let result = coldSignal.first().value()
				expect(result).toNot(beNil())
				expect(result).to(equal(99))
			}
		}
	}
}

Rename some of the test vars.

//
//  HotSignalSpec.swift
//  ReactiveCocoa
//
//  Created by Alan Rogers on 30/10/2014.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

import Nimble
import Quick
import ReactiveCocoa

class HotSignalSpec: QuickSpec {
	override func spec() {
		describe("replay") {
			var signal : HotSignal<Int>!
			var sink : SinkOf<Int>!
			var replaySignal : ColdSignal<Int>!

			beforeEach {
				let pipe = HotSignal<Int>.pipe()
				signal = pipe.0
				sink = pipe.1
				replaySignal = signal.replay(1)
			}

			it("should replay the first value") {
				sink.put(99)

				let result = replaySignal.first().value()
				expect(result).toNot(beNil())
				expect(result).to(equal(99))
			}
		}
	}
}


// ------------------------------------------------------------------------------
// Copyright by Uwe Arzt mailto:mail@uwe-arzt.de, https://uwe-arzt.de
// under BSD License, see https://uwe-arzt.de/bsd-license
// ------------------------------------------------------------------------------
// Just some sample calls, the real demo is in the Unit Test cases
// ------------------------------------------------------------------------------
import Foundation

print("Swift-C-Interop")

print(ret_uint8(13))
print(ret_int8(27))
print(ret_uint64(1124))
print(ret_int64(-1124))

// This crashes the compiler:
//   Version 7.0 beta 6 (7A192o)
//   Version 7.0 (7A220)
//   Version 7.1 beta (7B60)
//   Version 7.1 beta (7B75)
//   Version 7.1 beta 3 (7B85)
//   Version 7.1 (7B91b)
//   Version 7.1.1 (7B1005)
//   Version 7.2 beta (7C62)
//   Version 7.2 (7C68)
//let myCallback : @convention(c) (i: Int) -> Int = {
// works
let myCallback : @convention(c) (Int) -> Int = {
    (i) -> Int in
    return i * 2
}

let x = call(myCallback, i: 5)
print (x)

Test with Version 7.2.1 (7C1002) --> crashes


//
//  PhoneAppFactory.swift
//  Peekazoo
//
//  Created by Thomas Sherwood on 14/05/2017.
//  Copyright © 2017 Peekazoo. All rights reserved.
//

import UIKit

public struct PhoneAppFactory: AppFactory {

    public func makeApplication(window: UIWindow) -> App {
        struct DummyTimeFormatter: TimeFormatter {
            func string(from date: Date) -> String { return "" }
        }

        let networkAdapter = URLSessionNetworkAdapter()
        let weasylAPI = WeasylAPI(networkAdapter: networkAdapter)
        let weasylAdapter = WeasylAPIAdapter(api: weasylAPI)
        let inkbunnyAPI = InkbunnyAPI(networkAdapter: networkAdapter)
        let inkbunnyAdapter = InkbunnyAPIAdapter(api: inkbunnyAPI)
        let service = PeekazooClient(feeds: [weasylAdapter, inkbunnyAdapter], delegateWorker: MainThreadWorker())
        let serviceAdapter = PeekazooHomepageAdapter(service: service)

        return PhoneApp(rootRouter: WindowRootRouter(window: window),
                        homepageService: serviceAdapter,
                        timeFormatter: DummyTimeFormatter())
    }

}

Use relative time formatter in factory

//
//  PhoneAppFactory.swift
//  Peekazoo
//
//  Created by Thomas Sherwood on 14/05/2017.
//  Copyright © 2017 Peekazoo. All rights reserved.
//

import UIKit

public struct PhoneAppFactory: AppFactory {

    public func makeApplication(window: UIWindow) -> App {
        let networkAdapter = URLSessionNetworkAdapter()
        let weasylAPI = WeasylAPI(networkAdapter: networkAdapter)
        let weasylAdapter = WeasylAPIAdapter(api: weasylAPI)
        let inkbunnyAPI = InkbunnyAPI(networkAdapter: networkAdapter)
        let inkbunnyAdapter = InkbunnyAPIAdapter(api: inkbunnyAPI)
        let service = PeekazooClient(feeds: [weasylAdapter, inkbunnyAdapter], delegateWorker: MainThreadWorker())
        let serviceAdapter = PeekazooHomepageAdapter(service: service)

        return PhoneApp(rootRouter: WindowRootRouter(window: window),
                        homepageService: serviceAdapter,
                        timeFormatter: RelativeTimeFormatter())
    }

}


//
//  NavigationItem.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 13/01/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import UIKit

class NavigationItem: UINavigationItem {

    //MARK: Style management

    override var title: String? {
        didSet {
            let label = (self.titleView as? UILabel) ?? UILabel()
            label.text = title ?? ""
            label.style = "pageTitle"
            label.sizeToFit()
            self.titleView = label
        }
    }

    //MARK: Localization

    override func awakeFromNib() {
        super.awakeFromNib()

        self.title = localizedString(self.title ?? "")
        self.leftBarButtonItem?.customView?.sizeToFit()
        self.rightBarButtonItem?.customView?.sizeToFit()
    }

}

Update navigation item title style

//
//  NavigationItem.swift
//  ledger-wallet-ios
//
//  Created by Nicolas Bigot on 13/01/2015.
//  Copyright (c) 2015 Ledger. All rights reserved.
//

import UIKit

class NavigationItem: UINavigationItem {

    //MARK: Style management

    override var title: String? {
        didSet {
            let label = (self.titleView as? UILabel) ?? UILabel()
            label.text = title ?? ""
            label.style = "navigationBar.title"
            label.sizeToFit()
            self.titleView = label
        }
    }

    //MARK: Localization

    override func awakeFromNib() {
        super.awakeFromNib()

        self.title = localizedString(self.title ?? "")
        self.leftBarButtonItem?.customView?.sizeToFit()
        self.rightBarButtonItem?.customView?.sizeToFit()
    }

}


//
//  NSMutableAttributedString+Extension.swift
//  KernLabel
//
//  Created by ikai on 2016/05/26.
//  Copyright © 2016年 Taishi Ikai. All rights reserved.
//

import UIKit

extension NSMutableAttributedString {
    func kerning(regexp: NSRegularExpression) -> Self {
        regexp.matchesInString(self.string, options: [], range: NSMakeRange(0, self.length)).enumerate().forEach { result in
            let (location, length) = (result.element.range.location, result.element.range.length)
            let curAttrs = self.attributesAtIndex(location, effectiveRange: nil)
            let font = curAttrs[NSFontAttributeName] as? UIFont ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
            self.addAttributes([
                NSKernAttributeName: font.pointSize * -0.5,
                NSBackgroundColorAttributeName: UIColor.blueColor()
            ], range: NSMakeRange(location, length - 1))
        }
        return self
    }

    override var attributes: [String : AnyObject]? {
        get {
            return super.attributes
        }
        set {
            guard let newValue = newValue else {
                return
            }
            self.addAttributes(newValue, range: NSMakeRange(0, self.length))
        }
    }
}

Remove unnecessary background color setting

//
//  NSMutableAttributedString+Extension.swift
//  KernLabel
//
//  Created by ikai on 2016/05/26.
//  Copyright © 2016年 Taishi Ikai. All rights reserved.
//

import UIKit

extension NSMutableAttributedString {
    func kerning(regexp: NSRegularExpression) -> Self {
        regexp.matchesInString(self.string, options: [], range: NSMakeRange(0, self.length)).enumerate().forEach { result in
            let (location, length) = (result.element.range.location, result.element.range.length)
            let curAttrs = self.attributesAtIndex(location, effectiveRange: nil)
            let font = curAttrs[NSFontAttributeName] as? UIFont ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
            self.addAttributes([
                NSKernAttributeName: font.pointSize * -0.5,
            ], range: NSMakeRange(location, length - 1))
        }
        return self
    }

    override var attributes: [String : AnyObject]? {
        get {
            return super.attributes
        }
        set {
            guard let newValue = newValue else {
                return
            }
            self.addAttributes(newValue, range: NSMakeRange(0, self.length))
        }
    }
}


//
//  SettingsViewController.swift
//  StaticCellsSwift
//
// http://derpturkey.com/create-a-static-uitableview-without-storyboards/

import Foundation
import UIKit

class SettingsViewController: UIViewController {

    var tableView: UITableView!
    let dataSource = SettingsViewDataSource()
    let delegate = SettingsViewDelegate()

    override func loadView() {
        super.loadView()

        // create Table view
        self.tableView = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
        self.tableView.dataSource = self.dataSource
        self.tableView.delegate = self.delegate
        self.view = self.tableView

        // set the view title
        self.title = "Settings"

        //self.tableView.setEditing(true, animated: false)

        self.tableView.register(VersionCell.self, forCellReuseIdentifier: "currVersion")
    }
}

Add Edit button to top.

//
//  SettingsViewController.swift
//  StaticCellsSwift
//
// http://derpturkey.com/create-a-static-uitableview-without-storyboards/

import Foundation
import UIKit

class SettingsViewController: UIViewController {

    var tableView: UITableView!
    let dataSource = SettingsViewDataSource()
    let delegate = SettingsViewDelegate()

    override func loadView() {
        super.loadView()

        // create Table view
        self.tableView = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
        self.view = self.tableView

        // set the view title
        self.title = "Settings"

        // set Top Bar items
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneHandler))
        self.saveHandler(sender: nil)

        self.tableView.register(VersionCell.self, forCellReuseIdentifier: "currVersion")

        self.tableView.dataSource = self.dataSource
        self.tableView.delegate = self.delegate
    }

    @objc func editHandler(sender: UIBarButtonItem?) {
        self.tableView.setEditing(true, animated: true)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self,
                                                                 action: #selector(saveHandler))
    }

    @objc func saveHandler(sender: UIBarButtonItem?) {
        self.tableView.setEditing(false, animated: true)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self,
                                                                 action: #selector(editHandler))
    }

    @objc func doneHandler(sender: UIBarButtonItem?) {
        print("Done button clicked")
    }
}

// why does auto rotation not work


//
//  FirstTDDemoTests.swift
//  FirstTDDemoTests
//
//  Created by Karsten Gresch on 11.02.17.
//  Copyright © 2017 Closure One. All rights reserved.
//

import XCTest
@testable import FirstTDDemo

class FirstTDDemoTests: 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 test_NumberOfVowels_WhenPassedKarsten_ReturnsTwo() {
    let viewController = ViewController()

    let string = "Karsten"

    let numberOfVowels = viewController.numberOfVowels(inString: string)

    XCTAssertEqual(numberOfVowels, 2,
                   "should find 2 vowels in 'Karsten'", file: "FirstTDDemoTests.swift", line: 24)
  }

  func test_MakeHeadline_ReturnsStringWithEachWordStartCapital() {

  }

}

Test implementation. Too bad you can't do a method creation from w/in the test case.

//
//  FirstTDDemoTests.swift
//  FirstTDDemoTests
//
//  Created by Karsten Gresch on 11.02.17.
//  Copyright © 2017 Closure One. All rights reserved.
//

import XCTest
@testable import FirstTDDemo

class FirstTDDemoTests: 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 test_NumberOfVowels_WhenPassedKarsten_ReturnsTwo() {
    let viewController = ViewController()

    let string = "Karsten"

    let numberOfVowels = viewController.numberOfVowels(inString: string)

    XCTAssertEqual(numberOfVowels, 2,
                   "should find 2 vowels in 'Karsten'", file: "FirstTDDemoTests.swift", line: 24)
  }

  func test_MakeHeadline_ReturnsStringWithEachWordStartCapital() {
    let viewController = ViewController()
    let string = "this is A test headline"
    let headline = viewController.makeHeadline(from: string)

  }

}


import SwiftUI

/// A `View` for rendering `Image` types from the EurofurenceKit package.
public struct EurofurenceKitImage: View {

    @ObservedObject private var image: EurofurenceKit.Image

    public init(image: EurofurenceKit.Image) {
        self.image = image
    }

    public var body: some View {
        AsyncImage(url: image.cachedImageURL) { image in
            image
                .resizable()
                .aspectRatio(contentMode: .fit)
                .cornerRadius(7)
        } placeholder: {
            Color.gray
        }
    }

}

Enable consistent previewing experience of images

import SwiftUI

/// A `View` for rendering `Image` types from the EurofurenceKit package.
public struct EurofurenceKitImage: View {

    @ObservedObject private var image: EurofurenceKit.Image

    public init(image: EurofurenceKit.Image) {
        self.image = image
    }

    public var body: some View {
        swiftUIImage
            .aspectRatio(contentMode: .fit)
            .cornerRadius(7)
    }

    @ViewBuilder
    private var swiftUIImage: some View {
        if let url = image.cachedImageURL {
            if let uiImage = UIImage(contentsOfFile: url.path) {
                SwiftUI.Image(uiImage: uiImage)
                    .resizable()
            }
        }
    }

}


//
//  Repl.swift
//  FlyingMonkey
//
//  Created by Ahmad Alhashemi on 2017-08-18.
//  Copyright © 2017 Ahmad Alhashemi. All rights reserved.
//

let prompt = ">> "

func start() {
    while true {
        print(prompt, terminator: "")
        guard let line = readLine() else { return }
        var l = Lexer(line)
        var tok = l.nextToken()
        while tok.type != .eof {
            print(tok)
            tok = l.nextToken()
        }
    }
}

Update REPL to parse input

//
//  Repl.swift
//  FlyingMonkey
//
//  Created by Ahmad Alhashemi on 2017-08-18.
//  Copyright © 2017 Ahmad Alhashemi. All rights reserved.
//

let prompt = ">> "

func start() {
    while true {
        print(prompt, terminator: "")
        guard let line = readLine() else { return }
        let l = Lexer(line)
        let p = Parser(l)

        let program = p.parseProgram()

        if p.errors.count != 0 {
            printParserErrors(p.errors)
        }

        print(program.string)
    }
}

func printParserErrors(_ errors: [String]) {
    for msg in errors {
        print("\t\(msg)\n")
    }
}


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

// MARK: Operators

infix operator |> {
	/// Associates to the left for consistency with F# and λ calculi.
	associativity left

	/// Minimal precedence means that everything else binds tighter.
	precedence 0
}

// MARK: Function application

/// Forward function application.
///
/// Applies the value on the left to the function on the right.
public func |> <T, U> (left: T, right: T -> U) -> U {
	return right(left)
}

Correct the forward function application docs.

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

// MARK: Operators

infix operator |> {
	/// Associates to the left for consistency with F# and λ calculi.
	associativity left

	/// Minimal precedence means that everything else binds tighter.
	precedence 0
}

// MARK: Function application

/// Forward function application.
///
/// Applies the function on the right to the value on the left.
public func |> <T, U> (left: T, right: T -> U) -> U {
	return right(left)
}


//
//  NSNotificationCenter+Rx.swift
//  RxCocoa
//
//  Created by Krunoslav Zaher on 5/2/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif

extension Reactive where Base: NotificationCenter {
    /**
    Transforms notifications posted to notification center to observable sequence of notifications.

    - parameter name: Filter notifications by name.
    - parameter object: Optional object used to filter notifications.
    - returns: Observable sequence of posted notifications.
    */
    public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable<Notification> {
        return Observable.create { [weak object] observer in
            let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in
                observer.on(.next(notification))
            }

            return Disposables.create {
                self.base.removeObserver(nsObserver)
            }
        }
    }
}

Update comment to match parameter.

//
//  NSNotificationCenter+Rx.swift
//  RxCocoa
//
//  Created by Krunoslav Zaher on 5/2/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//

import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif

extension Reactive where Base: NotificationCenter {
    /**
    Transforms notifications posted to notification center to observable sequence of notifications.

    - parameter name: Optional name used to filter notifications.
    - parameter object: Optional object used to filter notifications.
    - returns: Observable sequence of posted notifications.
    */
    public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable<Notification> {
        return Observable.create { [weak object] observer in
            let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in
                observer.on(.next(notification))
            }

            return Disposables.create {
                self.base.removeObserver(nsObserver)
            }
        }
    }
}


//
//  Created by Jake Lin on 12/5/15.
//  Copyright © 2015 IBAnimatable. All rights reserved.
//

import UIKit

extension UIBlurEffectStyle : IBEnum {
  /** initialize a UIBlurEffectStyle from string. `extraLight`, `light`, `dark`, `prominent` (iOS 10+), `extraLight` (iOS 10+)
  */
  public init?(string: String?) {
    guard let string = string?.lowercased() else {
      return nil
    }

    switch string {
    case "extralight":
      self = .extraLight
      return
    case "light":
      self = .light
      return
    case "dark":
      self = .dark
      return
    case "prominent":
      if #available(iOSApplicationExtension 10.0, *) {
        self = .prominent
        return
      }
    case "regular":
      if #available(iOSApplicationExtension 10.0, *) {
        self = .regular
        return
      }
    default: break
    }
    return nil
  }
}

Fix blur effect available for iOS10

//
//  Created by Jake Lin on 12/5/15.
//  Copyright © 2015 IBAnimatable. All rights reserved.
//

import UIKit

extension UIBlurEffectStyle : IBEnum {
  /** initialize a UIBlurEffectStyle from string. `extraLight`, `light`, `dark`, `prominent` (iOS 10+), `extraLight` (iOS 10+)
  */
  public init?(string: String?) {
    guard let string = string?.lowercased() else {
      return nil
    }

    switch string {
    case "extralight":
      self = .extraLight
      return
    case "light":
      self = .light
      return
    case "dark":
      self = .dark
      return
    case "prominent":
      if #available(iOS 10.0, *) {
        self = .prominent
        return
      }
    case "regular":
      if #available(iOS 10.0, *) {
        self = .regular
        return
      }
    default: break
    }
    return nil
  }
}


//
//  BundleUtil.swift
//  PasswordTextField
//
//  Created by Chris Jimenez on 2/12/16.
//  Copyright © 2016 Chris Jimenez. All rights reserved.
//

import Foundation

/// Get the Pod Bundle
public class BundleUtil:NSObject{

    /// Gets the bundle property for the pod
    public static var bundle:NSBundle{

        get{

            let bundle = NSBundle(forClass: self.classForCoder())

//            NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
//
//            let bundleURL = podBundle.URLForResource("PasswordTextField.bundle", withExtension: "bundle")!
//
//            let bundle = NSBundle(URL: bundleURL)!

            return bundle
        }
    }

}

Fix bundle loading for pod

//
//  BundleUtil.swift
//  PasswordTextField
//
//  Created by Chris Jimenez on 2/12/16.
//  Copyright © 2016 Chris Jimenez. All rights reserved.
//

import Foundation

/// Get the Pod Bundle
public class BundleUtil:NSObject{

    /// Gets the bundle property for the pod
    public static var bundle:NSBundle{

        get{

//            let podBundle = NSBundle(forClass: BundleUtil.self.classForCoder())

            let bundlePath:String = NSBundle.mainBundle().pathForResource("PasswordTextField", ofType: "bundle")!

            let bundle:NSBundle = NSBundle(path: bundlePath)!

//            NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
//
//            let bundleURL = podBundle.URLForResource("PasswordTextField.bundle", withExtension: "bundle")!
//
//            let bundle = NSBundle(URL: bundleURL)!

            return bundle
        }
    }

}


import Foundation

public struct RunError: LocalizedError, CustomStringConvertible {
    public var input: String
    public var position: String.Index
    public var underlyingErrors: [ParseError]

    public init(input: String, position: String.Index, underlyingErrors: [ParseError]) {
        self.input = input
        self.position = position
        self.underlyingErrors = underlyingErrors
    }

    public var errorDescription: String? {
        var buffer = ErrorOutputBuffer()

        ErrorMessageWriter(input: input, position: position, errors: underlyingErrors)
            .write(to: &buffer)

        return buffer.text
    }

    public var failureReason: String? {
        var buffer = ErrorOutputBuffer()

        ErrorMessageWriter(errors: underlyingErrors).write(to: &buffer)

        return buffer.text
    }

    public var description: String {
        return "line: \(textPosition.line), column: \(textPosition.column), "
            + "underlyingErrors: \(underlyingErrors)"
    }

    public var textPosition: TextPosition {
        return TextPosition(string: input, index: position)
    }
}

Fix minor typo in error description

import Foundation

public struct RunError: LocalizedError, CustomStringConvertible {
    public var input: String
    public var position: String.Index
    public var underlyingErrors: [ParseError]

    public init(input: String, position: String.Index, underlyingErrors: [ParseError]) {
        self.input = input
        self.position = position
        self.underlyingErrors = underlyingErrors
    }

    public var errorDescription: String? {
        var buffer = ErrorOutputBuffer()

        ErrorMessageWriter(input: input, position: position, errors: underlyingErrors)
            .write(to: &buffer)

        return buffer.text.trimmingCharacters(in: .newlines)
    }

    public var failureReason: String? {
        var buffer = ErrorOutputBuffer()

        ErrorMessageWriter(errors: underlyingErrors).write(to: &buffer)

        return buffer.text.trimmingCharacters(in: .newlines)
    }

    public var description: String {
        return "line: \(textPosition.line), column: \(textPosition.column), "
            + "underlyingErrors: \(underlyingErrors)"
    }

    public var textPosition: TextPosition {
        return TextPosition(string: input, index: position)
    }
}


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

final class ResultTests: XCTestCase {
	func testMapTransformsSuccesses() {
		XCTAssertEqual(success.map(count) ?? 0, 7)
	}

	func testMapRewrapsFailures() {
		XCTAssertEqual(failure.map(count) ?? 0, 0)
	}
}

let success = Result.success("success")
let failure = Result<String>.failure(NSError(domain: "com.antitypical.Result", code: 0xdeadbeef, userInfo: nil))

// MARK: - Imports

import Prelude
import Result
import XCTest

Test try for failure cases.

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

final class ResultTests: XCTestCase {
	func testMapTransformsSuccesses() {
		XCTAssertEqual(success.map(count) ?? 0, 7)
	}

	func testMapRewrapsFailures() {
		XCTAssertEqual(failure.map(count) ?? 0, 0)
	}

	// MARK: Cocoa API idioms

	func testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference() {
		let result = try { attempt(true, succeed: false, error: $0) }
		XCTAssertFalse(result ?? false)
		XCTAssertNotNil(result.failure)
	}

	func testTryProducesFailuresForObjectAPIWithErrorReturnedByReference() {
		let result = try { attempt(1, succeed: false, error: $0) }
		XCTAssertEqual(result ?? 0, 0)
		XCTAssertNotNil(result.failure)
	}
}

func attempt<T>(value: T, #succeed: Bool, #error: NSErrorPointer) -> T? {
	if succeed {
		return value
	} else {
		error.memory = Result<()>.error()
		return nil
	}
}

let success = Result.success("success")
let failure = Result<String>.failure(NSError(domain: "com.antitypical.Result", code: 0xdeadbeef, userInfo: nil))

// MARK: - Imports

import Prelude
import Result
import XCTest


import PackageDescription

let package = Package(
    name: "Moya",
    targets: [
        Target(
            name: "Moya"
        ),
        Target(
            name: "ReactiveMoya",
            dependencies: ["Moya"]
        ),
        Target(
            name: "RxMoya",
            dependencies: ["Moya"]
        )
    ],
    dependencies: [
        .Package(url: "https://github.com/Alamofire/Alamofire", majorVersion: 4),
        .Package(url: "https://github.com/ReactiveCocoa/ReactiveSwift", majorVersion: 1),
        .Package(url: "https://github.com/ReactiveX/RxSwift", majorVersion: 3)
    ],
    exclude: [
        "Tests"
    ]
)

Add Result as an explicit dependency in SwiftPM

import PackageDescription

let package = Package(
    name: "Moya",
    targets: [
        Target(
            name: "Moya"
        ),
        Target(
            name: "ReactiveMoya",
            dependencies: ["Moya"]
        ),
        Target(
            name: "RxMoya",
            dependencies: ["Moya"]
        )
    ],
    dependencies: [
        .Package(url: "https://github.com/Alamofire/Alamofire", majorVersion: 4),
        .Package(url: "https://github.com/ReactiveCocoa/ReactiveSwift", majorVersion: 1),
        .Package(url: "https://github.com/ReactiveX/RxSwift", majorVersion: 3),
        .Package(url: "https://github.com/antitypical/Result", majorVersion: 3)
    ],
    exclude: [
        "Tests"
    ]
)


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

extension Expression where Recur: FixpointType {
	public static var list: Module<Recur> {
		let List = Recur("List")

		// List : λ A : Type . Type
		// List = λ A : Type . λ tag : Boolean . if tag then (A, List A) else Unit
		let list = Binding("List",
			lambda(.Type) { A in Recur.lambda(.BooleanType) { .If($0, .Product(A, List[A]), .UnitType) } },
			lambda(.Type, const(.Type)))

		// nil : List
		// nil = (false, ()) : List
		let `nil` = Binding("[]",
			.Annotation(Recur.Product(.Boolean(false), .Unit), List),
			List.out)

		// cons : λ A : Type . λ _ : A . λ _ : List A . List A
		// cons = λ A : Type . λ first : A . λ rest : List A . (true, (first, rest)) : List A
		let cons = Binding("::",
			lambda(.Type) { A in Recur.lambda(A) { first in Recur.lambda(.Application(List, A)) { rest in .Annotation(.Product(.Boolean(true), .Product(first, rest)), List) } } },
			List.out)

		return Module([ list, `nil`, cons ])
	}
}

import Prelude

Correct the type of cons.

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

extension Expression where Recur: FixpointType {
	public static var list: Module<Recur> {
		let List = Recur("List")

		// List : λ A : Type . Type
		// List = λ A : Type . λ tag : Boolean . if tag then (A, List A) else Unit
		let list = Binding("List",
			lambda(.Type) { A in Recur.lambda(.BooleanType) { .If($0, .Product(A, List[A]), .UnitType) } },
			lambda(.Type, const(.Type)))

		// nil : List
		// nil = (false, ()) : List
		let `nil` = Binding("[]",
			.Annotation(Recur.Product(.Boolean(false), .Unit), List),
			List.out)

		// cons : λ A : Type . λ _ : A . λ _ : List A . List A
		// cons = λ A : Type . λ first : A . λ rest : List A . (true, (first, rest)) : List A
		let cons = Binding("::",
			lambda(.Type) { A in Recur.lambda(A) { first in Recur.lambda(.Application(List, A)) { rest in .Annotation(.Product(.Boolean(true), .Product(first, rest)), List) } } },
			lambda(.Type) { A in .lambda(A, const(.lambda(List[A], const(List[A])))) })

		return Module([ list, `nil`, cons ])
	}
}

import Prelude


/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import Foundation

extension MotionObservableConvertible where T: UIGestureRecognizer {

  /** Only forwards the gesture recognizer if its state matches the provided value. */
  public func onRecognitionState(_ state: UIGestureRecognizerState) -> MotionObservable<T> {
    return asStream()._filter { value in
      return value.state == state
    }
  }

  /** Only forwards the gesture recognizer if its state matches any of the provided values. */
  public func onRecognitionStates(_ states: [UIGestureRecognizerState]) -> MotionObservable<T> {
    return asStream()._filter { value in
      return states.contains(value.state)
    }
  }
}

Add active and atRest operators for gesture streams.

/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import Foundation

extension MotionObservableConvertible where T: UIGestureRecognizer {

  /** Only forwards the gesture recognizer if its state matches the provided value. */
  public func onRecognitionState(_ state: UIGestureRecognizerState) -> MotionObservable<T> {
    return asStream()._filter { value in
      return value.state == state
    }
  }

  /** Only forwards the gesture recognizer if its state matches any of the provided values. */
  public func onRecognitionStates(_ states: [UIGestureRecognizerState]) -> MotionObservable<T> {
    return asStream()._filter { value in
      return states.contains(value.state)
    }
  }

  public func active() -> MotionObservable<Bool> {
    return asStream()._map { value in
      return value.state == .began || value.state == .changed
    }
  }

  public func atRest() -> MotionObservable<Bool> {
    return asStream()._map { value in
      return value.state != .began && value.state != .changed
    }
  }
}


import Fluent
import Vapor

func routes(_ app: Application) throws {

    // MARK: Controllers
    let dataController = DataController()
    let homeController = HomeController()
    let addController = AddController()
    let facebookController = FacebookController()
    let statusController = StatusController()
    let avatarController = AvatarController()

    // MARK: Pages
    app.get(use: homeController.index)
    app.get("add", use: addController.index)
    app.get("status", ":avatarId", use: statusController.status)
    app.post("facebook", "process", use: facebookController.process)
    app.get("terms") { req -> EventLoopFuture<View> in
        return req.view.render("terms")
    }

    // MARK: API
    app.get("api", "data", use: dataController.index)
    app.get("api", "avatar.jpg", use: avatarController.index)

}

Add the legacy endpoint so we stop seeing 404's for those

import Fluent
import Vapor

func routes(_ app: Application) throws {

    // MARK: Controllers
    let dataController = DataController()
    let homeController = HomeController()
    let addController = AddController()
    let facebookController = FacebookController()
    let statusController = StatusController()
    let avatarController = AvatarController()

    // MARK: Pages
    app.get(use: homeController.index)
    app.get("add", use: addController.index)
    app.get("status", ":avatarId", use: statusController.status)
    app.post("facebook", "process", use: facebookController.process)
    app.get("terms") { req -> EventLoopFuture<View> in
        return req.view.render("terms")
    }

    // MARK: API
    app.get("api", "data", use: dataController.index)
    app.get("api", "avatar.jpg", use: avatarController.index)

    // MARK: API Legacy
    app.get("api", "users", use: dataController.index)

}


func toComponent(string: String) -> CGFloat {
  return CGFloat(strtol(string, nil, 16)) / 255
}

let digit = %("0"..."9")
let lower = %("a"..."f")
let upper = %("A"..."F")
let hex = digit | lower | upper
let hex2 = (hex ++ hex |> map { $0 + $1 })
let component1: Parser<String, CGFloat>.Function = hex |> map { toComponent($0 + $0) }
let component2: Parser<String, CGFloat>.Function = toComponent <^> hex2
let three: Parser<String, [CGFloat]>.Function = component1 * 3
let six: Parser<String, [CGFloat]>.Function = component2 * 3

let colour: Parser<String, NSColor>.Function = ignore("#") ++ (six | three) |> map {
	NSColor(calibratedRed: $0[0], green: $0[1], blue: $0[2], alpha: 1)
}

if let reddish = parse(colour, "#d52a41").right {
	reddish
}

if let greenish = parse(colour, "#5a2").right {
	greenish
}

if let blueish = parse(colour, "#5e8ca1").right {
	blueish
}

Fix up the colours playground.

func toComponent(string: String) -> CGFloat {
  return CGFloat(strtol(string, nil, 16)) / 255
}

let digit = %("0"..."9")
let lower = %("a"..."f")
let upper = %("A"..."F")
let hex = digit <|> lower <|> upper
let hex2 = hex <*> hex |> map { $0 + $1 }
let component1: Parser<String, CGFloat>.Function = hex |> map { toComponent($0 + $0) }
let component2: Parser<String, CGFloat>.Function = toComponent <^> hex2
let three: Parser<String, [CGFloat]>.Function = component1 * 3
let six: Parser<String, [CGFloat]>.Function = component2 * 3

let colour: Parser<String, NSColor>.Function = %"#" *> (six <|> three) |> map {
	NSColor(calibratedRed: $0[0], green: $0[1], blue: $0[2], alpha: 1)
}

if let reddish = parse(colour, "#d52a41").right {
	reddish
}

if let greenish = parse(colour, "#5a2").right {
	greenish
}

if let blueish = parse(colour, "#5e8ca1").right {
	blueish
}


//
// ImageBodyDeserializer.swift
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//

#if os(iOS) || os(tvOS) || os(watchOS)
	import UIKit
	private typealias PlatformImage = UIImage
#elseif os(OSX)
	import AppKit
	private typealias PlatformImage = NSImage
#else
	// Is this carOS? :trollface:
#endif

/// Deserializes image bodies.
@objc(RDTImageBodyDeserializer) public final class ImageBodyDeserializer: NSObject, BodyDeserializer {

	/// Deserializes image data into a pretty-printed string.
	public func deserializeBody(body: NSData) -> String? {
		return PlatformImage(data: body).map { "(\($0.size.width)px × \($0.size.height)px" }
	}

}

Move typealias to class declaration

//
// ImageBodyDeserializer.swift
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//

#if os(iOS) || os(tvOS) || os(watchOS)
	import UIKit
#elseif os(OSX)
	import AppKit
#endif

/// Deserializes image bodies.
@objc(RDTImageBodyDeserializer) public final class ImageBodyDeserializer: NSObject, BodyDeserializer {

	#if os(iOS) || os(tvOS) || os(watchOS)
		private typealias Image = UIImage
	#elseif os(OSX)
		private typealias Image = NSImage
	#endif

	/// Deserializes image data into a pretty-printed string.
	public func deserializeBody(body: NSData) -> String? {
		return Image(data: body).map { "(\($0.size.width)px × \($0.size.height)px" }
	}

}


/**
 * Question Link: https://leetcode.com/problems/validate-binary-search-tree/
 * Primary idea: Keep min to go right and keep max to go left
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */

class ValidateBinarySearchTree {
    func isValidBST(root: TreeNode?) -> Bool {
        return _helper(root, nil, nil)
    }

    private func _helper(node: TreeNode?, _ min: Int?, _ max: Int?) -> Bool {
        guard let node = node else {
            return true
        }

        if min != nil && node.val <= min {
            return false
        }
        if max != nil && node.val >= max {
            return false
        }

        return _helper(node.left, min, node.val) && _helper(node.right, node.val, max)
    }
}

Optimize solution to Validate Binary Search Tree

/**
 * Question Link: https://leetcode.com/problems/validate-binary-search-tree/
 * Primary idea: Keep min to go right and keep max to go left
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */

class ValidateBinarySearchTree {
    func isValidBST(root: TreeNode?) -> Bool {
        return _helper(root, nil, nil)
    }

    private func _helper(node: TreeNode?, _ min: Int?, _ max: Int?) -> Bool {
        guard let node = node else {
            return true
        }

        if let min = min, root.val <= min {
            return false
        }
        if let max = max, root.val >= max {
            return false
        }

        return _helper(node.left, min, node.val) && _helper(node.right, node.val, max)
    }
}


//
//  StripeStatus.swift
//  Stripe
//
//  Created by Anthony Castelli on 4/15/17.
//
//

import Foundation

public enum StripeStatus: String, Codable {
    case success
    case succeeded
    case failed
    case pending
    case canceled
    case chargeable
}

// https://stripe.com/docs/api/curl#subscription_object-status
public enum StripeSubscriptionStatus: String, Codable {
    case trailing
    case active
    case pastDue = "past_due"
    case canceled
    case unpaid
}

public enum LegalEntityVerificationStatus: String, Codable {
    case unverified
    case pending
    case verified
}

public enum LegalEntityVerificationState: String, Codable {
    case scanCorrupt = "scan_corrupt"
    case scanNotReadable = "scan_not_readable"
    case scanFailedGreyscale = "scan_failed_greyscale"
    case scanNotUploaded = "scan_not_uploaded"
    case scanIdTypeNotUploaded = "scan_id_type_not_supported"
    case scanIdCountryNotSupported = "scan_id_country_not_supported"
    case scanNameMismatch = "scan_name_mismatch"
    case scanFailedOther = "scan_failed_other"
    case failedKeyedIdentity = "failed_keyed_identity"
    case failedOther = "failed_other"
}

Fix a typo in StripeSubscriptionStatus.trialing name

//
//  StripeStatus.swift
//  Stripe
//
//  Created by Anthony Castelli on 4/15/17.
//
//

import Foundation

public enum StripeStatus: String, Codable {
    case success
    case succeeded
    case failed
    case pending
    case canceled
    case chargeable
}

// https://stripe.com/docs/api/curl#subscription_object-status
public enum StripeSubscriptionStatus: String, Codable {
    case trialing
    case active
    case pastDue = "past_due"
    case canceled
    case unpaid
}

public enum LegalEntityVerificationStatus: String, Codable {
    case unverified
    case pending
    case verified
}

public enum LegalEntityVerificationState: String, Codable {
    case scanCorrupt = "scan_corrupt"
    case scanNotReadable = "scan_not_readable"
    case scanFailedGreyscale = "scan_failed_greyscale"
    case scanNotUploaded = "scan_not_uploaded"
    case scanIdTypeNotUploaded = "scan_id_type_not_supported"
    case scanIdCountryNotSupported = "scan_id_country_not_supported"
    case scanNameMismatch = "scan_name_mismatch"
    case scanFailedOther = "scan_failed_other"
    case failedKeyedIdentity = "failed_keyed_identity"
    case failedOther = "failed_other"
}


import Foundation

// MARK: - File

/// A simple typealias for strings representing files
public typealias File = String

extension File {

    public var fileType: FileType? {
        return FileType(from: self)
    }

    public var name: String {
        return String(self)
    }

}

// MARK: - FileType

public enum FileType: String, Equatable, CaseIterable {
    case h, json, m, markdown = "md", mm, pbxproj, plist, storyboard, swift, xcscheme, yaml, yml
}

// MARK: - FileType extensions

extension FileType {

    public var `extension`: String {
        return rawValue
    }

    init?(from file: File) {
        let allCasesDelimited = FileType.allCases.map { $0.extension }.joined(separator: "|")

        guard
            let pattern = try? NSRegularExpression(pattern: "\\.(\(allCasesDelimited))$"),
            let match = pattern.firstMatchingString(in: file.name)
        else {
            return nil
        }

        let rawValue = match.replacingOccurrences(of: ".", with: "")
        self.init(rawValue: rawValue)
    }

}

Add compatibility for Swift 4.1 and below

import Foundation

// MARK: - File

/// A simple typealias for strings representing files
public typealias File = String

extension File {

    public var fileType: FileType? {
        return FileType(from: self)
    }

    public var name: String {
        return String(self)
    }

}

// MARK: - FileType

public enum FileType: String, Equatable {
    case h, json, m, markdown = "md", mm, pbxproj, plist, storyboard, swift, xcscheme, yaml, yml
}

#if swift(>=4.2)  // Use compiler-generated allCases when available
    extension FileType: CaseIterable {}
#else
    extension FileType {
        static var allCases: [FileType] {
            return [.h, .json, .m, .markdown, .mm, .pbxproj, .plist, .storyboard, .swift, .xcscheme, .yaml, .yml]
        }
    }
#endif

// MARK: - FileType extensions

extension FileType {

    public var `extension`: String {
        return rawValue
    }

    init?(from file: File) {
        let allCasesDelimited = FileType.allCases.map { $0.extension }.joined(separator: "|")

        guard
            let pattern = try? NSRegularExpression(pattern: "\\.(\(allCasesDelimited))$"),
            let match = pattern.firstMatchingString(in: file.name)
        else {
            return nil
        }

        let rawValue = match.replacingOccurrences(of: ".", with: "")
        self.init(rawValue: rawValue)
    }

}


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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.type, id).quote, ==, Value.pi(.type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.type) { Value.pi(.type, const($0)) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(1)))))))))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.pi(.type) { _ in Value.pi(.type, id) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(0)))))))))
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest

Test that the 0-ary product is the unit term.

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

final class ValueTests: XCTestCase {
	func testQuotation() {
		assert(Value.pi(.type, id).quote, ==, Value.pi(.type, id).quote)
	}

	func testNestedQuotation() {
		assert(Value.pi(.type) { Value.pi(.type, const($0)) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(1)))))))))
	}

	func testQuotationMapsNestedBoundVariablesToBoundVariables() {
		assert(Value.pi(.type) { _ in Value.pi(.type, id) }.quote, ==, Term(.Pi(Box(.type), Box(Term(.Pi(Box(.type), Box(Term(.Bound(0)))))))))
	}

	func testNullaryProductIsUnitTerm() {
		assert(Value.product([]).quote, ==, Term.unitTerm)
	}
}

import Assertions
import Box
import Either
import Manifold
import Prelude
import XCTest


//
//  UnavailableItems.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 11/30/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

// MARK: For auto migration from Swinject v1 to v2.
extension ObjectScope {
    @available(*, unavailable, renamed: "transient")
    public static let none = transient

    @available(*, unavailable, renamed: "container")
    public static let hierarchy = container
}

@available(*, unavailable, renamed: "Resolver")
public protocol ResolverType { }

Add unavailability annotations for renamed protocols

//
//  UnavailableItems.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 11/30/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

// MARK: For auto migration from Swinject v1 to v2.
extension ObjectScope {
    @available(*, unavailable, renamed: "transient")
    public static let none = transient

    @available(*, unavailable, renamed: "container")
    public static let hierarchy = container
}

@available(*, unavailable, renamed: "Resolver")
public protocol ResolverType { }

@available(*, unavailable, renamed: "Assembly")
public protocol AssemblyType { }

@available(*, unavailable, renamed: "ServiceKeyOption")
public protocol ServiceKeyOptionType { }


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

import UIKit

class GalleryDetailPhotoViewController: UIViewController, UIPageViewControllerDelegate {

    var galleryDetailPhotoURL: URL?
    var photos: [URL]?
    var pageViewController: UIPageViewController?

    lazy var modelController = GalleryDetailModelController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Configure the page view controller and add it as a child view controller.
        self.pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        self.pageViewController!.delegate = self

        if let photos = photos {
            self.modelController.pageData = photos
        } else {
            self.modelController.pageData = []
        }

        let startingViewController: GalleryDetailDataViewController = self.modelController.viewController(at: 0, storyboard: self.storyboard!)!
        let viewControllers = [startingViewController]
        self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: false)

        self.pageViewController!.dataSource = self.modelController

        self.addChildViewController(self.pageViewController!)
        self.view.addSubview(self.pageViewController!.view)

        self.pageViewController!.didMove(toParentViewController: self)
    }
}

Configure UIPageViewController when array of photos is set

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

import UIKit

class GalleryDetailPhotoViewController: UIViewController, UIPageViewControllerDelegate {

    var pageViewController: UIPageViewController?
    lazy var modelController = GalleryDetailModelController()

    var photos: [URL] = [] {
        didSet {
            // Configure the page view controller and add it as a child view controller.
            self.pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
            self.pageViewController!.delegate = self

            self.modelController.pageData = photos

            let startingViewController: GalleryDetailDataViewController = self.modelController.viewController(at: 0, storyboard: self.storyboard!)!
            let viewControllers = [startingViewController]
            self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: false)

            self.pageViewController!.dataSource = self.modelController

            self.addChildViewController(self.pageViewController!)
            self.view.addSubview(self.pageViewController!.view)

            self.pageViewController!.didMove(toParentViewController: self)
        }
    }
}


//
//  AppDelegate.swift
//  FlingChallenge
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    return true
  }

}

Disable strict SSL certificate checking

//
//  AppDelegate.swift
//  FlingChallenge
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import FlingChallengeKit
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FlingChallengeKit.strictSSL = false
    return true
  }

}


println("Song")

// [].length = 0
// [x|xs].length = 1 + xs.length

func integerList(values: [Int]) -> Expression {
    return values.reverse().reduce(Expression.UnitValue) {
        Expression.Pair(Expression.IntegerValue($1), $0)
    }
}

let listVar = Expression.Variable("list")
let isUnitValue = Expression.IsUnit(listVar)
let zero = Expression.IntegerValue(0)
let one = Expression.IntegerValue(1)
let second = Expression.Second(listVar)
let recursiveCall = Expression.Call(closure: Expression.Variable("length"), arguments: [second])
let otherwise = Expression.Plus(one, recursiveCall)
let lengthBody = Expression.Conditional(condition: isUnitValue, then: zero, otherwise: otherwise)
let lengthFunc = Expression.Function(name: "length", parameters: ["list"], body: lengthBody)
let list = integerList([1,2,3,4,3,2,1,2,2,4,4,1,2])
let lengthCall = Expression.Call(closure: lengthFunc, arguments: [list])
let result = lengthCall.evaluate()

println(lengthCall)
println(result)

Test that lambdas can be assigned to variables and called later.

println("Song")

// [].length = 0
// [x|xs].length = 1 + xs.length

func integerList(values: [Int]) -> Expression {
    return values.reverse().reduce(Expression.UnitValue) {
        Expression.Pair(Expression.IntegerValue($1), $0)
    }
}

let listVar = Expression.Variable("list")
let isUnitValue = Expression.IsUnit(listVar)
let zero = Expression.IntegerValue(0)
let one = Expression.IntegerValue(1)
let second = Expression.Second(listVar)
let recursiveCall = Expression.Call(closure: Expression.Variable("length"), arguments: [second])
let otherwise = Expression.Plus(one, recursiveCall)
let lengthBody = Expression.Conditional(condition: isUnitValue, then: zero, otherwise: otherwise)
let lengthFunc = Expression.Function(name: "length", parameters: ["list"], body: lengthBody)
let list = integerList([1,2,3,4,3,2,1,2,2,4,4,1,2])
let lengthCall = Expression.Call(closure: lengthFunc, arguments: [list])
let result = lengthCall.evaluate()

println(lengthCall)
println(result)

let lambda = Expression.Function(name: nil, parameters: [], body: Expression.IntegerValue(5))
let lambdaCall = Expression.Call(closure: Expression.Variable("x"), arguments: [])
let letExpr = Expression.Let(name: "x", binding: lambda, body: lambdaCall)
let lambdaResult = letExpr.evaluate();

println(letExpr)
println(lambdaResult)


//
//  User.swift
//  SpotifySessionManager
//
//  Created by Julian Grosshauser on 11/03/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

class User {

    //MARK: Properties

    static let sessionUpdatedNotification: String = "SessionUpdatedNotification"
    static let sessionRemovedNotification: String = "SessionRemovedNotification"

    static let sharedInstance: User = User(session: nil)

    var session: SPTSession? {
        didSet {
            let notificationCenter = NSNotificationCenter.defaultCenter()

            if let newSession = session {
                notificationCenter.postNotificationName(User.sessionUpdatedNotification, object: nil)
            } else {
                notificationCenter.postNotificationName(User.sessionRemovedNotification, object: nil)
            }
        }
    }

    //MARK: Initialization

    init(session: SPTSession?) {
        self.session = session
    }
}

Set default value of property `session` to `nil`

//
//  User.swift
//  SpotifySessionManager
//
//  Created by Julian Grosshauser on 11/03/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

class User {

    //MARK: Properties

    static let sessionUpdatedNotification: String = "SessionUpdatedNotification"
    static let sessionRemovedNotification: String = "SessionRemovedNotification"

    static let sharedInstance: User = User()

    var session: SPTSession? = nil {
        didSet {
            let notificationCenter = NSNotificationCenter.defaultCenter()

            if let newSession = session {
                notificationCenter.postNotificationName(User.sessionUpdatedNotification, object: nil)
            } else {
                notificationCenter.postNotificationName(User.sessionRemovedNotification, object: nil)
            }
        }
    }
}


import Foundation

extension Data
{
    func writeToTemporal() -> URL?
    {
        let randomName:String = UUID().uuidString
        let directoryUrl:URL = URL(fileURLWithPath:NSTemporaryDirectory())
        let fileUrl:URL = directoryUrl.appendingPathComponent(randomName)

        do
        {
            try write(to:fileUrl, options:Data.WritingOptions.atomicWrite)
        }
        catch
        {
            return nil
        }

        return fileUrl
    }
}

Add extension to temporal file

import Foundation

extension Data
{
    func writeToTemporal(withExtension:String?) -> URL?
    {
        var randomName:String = UUID().uuidString

        if let withExtension:String = withExtension
        {
            randomName.append(".")
            randomName.append(withExtension)
        }

        let directoryUrl:URL = URL(fileURLWithPath:NSTemporaryDirectory())
        let fileUrl:URL = directoryUrl.appendingPathComponent(randomName)

        do
        {
            try write(to:fileUrl, options:Data.WritingOptions.atomicWrite)
        }
        catch
        {
            return nil
        }

        return fileUrl
    }
}


//
//  ViewController.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

    fileprivate let pinpointKit = PinpointKit(feedbackRecipients: ["feedback@example.com"])

    override func viewDidLoad() {
        super.viewDidLoad()

        // Hides the infinite cells footer.
        tableView.tableFooterView = UIView()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        pinpointKit.show(from: self, screenshot: #imageLiteral(resourceName: "liberatore"))
    }
}

Revert "Adds test code for alternate image"

//
//  ViewController.swift
//  PinpointKitExample
//
//  Created by Paul Rehkugler on 2/7/16.
//  Copyright © 2016 Lickability. All rights reserved.
//

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

    fileprivate let pinpointKit = PinpointKit(feedbackRecipients: ["feedback@example.com"])

    override func viewDidLoad() {
        super.viewDidLoad()

        // Hides the infinite cells footer.
        tableView.tableFooterView = UIView()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        pinpointKit.show(from: self)
    }
}


import Vapor
import Fluent
import Sessions
import SteamPress
import Foundation
import VaporPostgreSQL

let drop = Droplet()
try drop.addProvider(VaporPostgreSQL.Provider.self)

let memory = MemorySessions()
let sessions = SessionsMiddleware(sessions: memory)
drop.middleware.append(sessions)

let steamPress = SteamPress(drop: drop, blogPath: "blog")

drop.get { req in
    drop.log.error("An Admin user been created for you - the username is admin and the password is password")

    var posts = try BlogPost.all()
    posts.sort { $0.created > $1.created }
    let newPosts = posts.prefix(3)

    var parameters: [String: Node] = [:]

    if newPosts.count > 0 {
        var postsNode = [Node]()
        for post in newPosts {
            postsNode.append(try post.makeNodeWithExtras())
        }
        parameters["posts"] = try postsNode.makeNode()
    }

    return try drop.view.make("index", parameters)
}

drop.get("about") { req in
    return try drop.view.make("about", ["aboutPage": true])
}

drop.run()

Revert "Attempting to get logs from Heroku"

import Vapor
import Fluent
import Sessions
import SteamPress
import Foundation
import VaporPostgreSQL

let drop = Droplet()
try drop.addProvider(VaporPostgreSQL.Provider.self)

let memory = MemorySessions()
let sessions = SessionsMiddleware(sessions: memory)
drop.middleware.append(sessions)

let steamPress = SteamPress(drop: drop, blogPath: "blog")

drop.get { req in
    var posts = try BlogPost.all()
    posts.sort { $0.created > $1.created }
    let newPosts = posts.prefix(3)

    var parameters: [String: Node] = [:]

    if newPosts.count > 0 {
        var postsNode = [Node]()
        for post in newPosts {
            postsNode.append(try post.makeNodeWithExtras())
        }
        parameters["posts"] = try postsNode.makeNode()
    }

    return try drop.view.make("index", parameters)
}

drop.get("about") { req in
    return try drop.view.make("about", ["aboutPage": true])
}

drop.run()


//
//  Request+Notifications.swift
//  Pods
//
//  Created by Lim, Jennifer on 1/18/17.
//
//

public extension Request
{
    private static var Path: String { return "/me/notifications/subscriptions" }

    /// Create a request that updates the push notification subscriptions
    ///
    /// - Parameter subscription: The subscription object contains the boolean values for each of those: comment, credit, like, reply, follow, video_available that defines what the user is subscripted to.
    /// - Returns: The result of the .PATCH is a SubscriptionCollection
    public static func updateNotificationSubscriptions(subscription: Subscription) -> Request
    {
        let parameters = [
                        "comment": subscription.comment,
                        "credit": subscription.credit,
                        "like": subscription.like,
                        "reply": subscription.reply,
                        "follow": subscription.follow,
                        "video_available": subscription.videoAvailable]

        return Request(method: .PATCH, path: Path, parameters: parameters)
    }
}

Add request extension for notification methods

//
//  Request+Notifications.swift
//  Pods
//
//  Created by Lim, Jennifer on 1/18/17.
//
//

public extension Request
{
    private static var Path: String { return "/me/notifications" }

    /// Create a request that updates the push notification subscriptions
    ///
    /// - Parameter subscription: The subscription object contains the boolean values for each of those: comment, credit, like, reply, follow, video_available that defines what the user is subscripted to.
    /// - Returns: The result of the .PATCH is a SubscriptionCollection
    public static func updateNotificationSubscriptions(subscription: Subscription) -> Request
    {
        let parameters = [
                        "comment": subscription.comment,
                        "credit": subscription.credit,
                        "like": subscription.like,
                        "reply": subscription.reply,
                        "follow": subscription.follow,
                        "video_available": subscription.videoAvailable]

        return Request(method: .PATCH, path: Path.stringByAppendingString("/subscriptions"), parameters: parameters)
    }

    public static func markLatestNotification(notification: VIMNotification) -> Request
    {
        var parameters:[String: AnyObject]? = nil
        if let uri = notification.uri
        {
            parameters = [
                "latest_notification_uri" : uri,
                "new" : true
            ]
        }

        return Request(method: .PATCH, path: Path, parameters: parameters)
    }

    public static func seenNotifications(notifications: [VIMNotification]) -> Request
    {
        var parameters: [[String: AnyObject]] = []
        notifications.map { (notification: VIMNotification) -> Void in
            if let uri = notification.uri
            {
                parameters.append([
                    "seen": true,
                    "uri": uri]
                )
            }
        }

        return Request(method: .PATCH, path: Path, parameters: parameters)
    }
}


//  Weather.swift
//  All-The-Weathers
//  Created by Peter Foti on 10/19/15.
//  Copyright © 2015 Peter Foti. All rights reserved.

import Foundation

final class Weather {
    var currentTemperature: Int!
    var dateOfRecord: NSDate!
    var temperatureString: String {
        get {
            return "\(self.currentTemperature)°"
        }
    }

    var dayOfWeek: String {
        get {
            return self.formatter.stringFromDate(self.dateOfRecord)
        }
    }

    private lazy var formatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE"

        return formatter
    }()
}

Add convenience init to weather model for use with json dict.

//  Weather.swift
//  All-The-Weathers
//  Created by Peter Foti on 10/19/15.
//  Copyright © 2015 Peter Foti. All rights reserved.

import Foundation

final class Weather {
    var currentTemperature: Int!
    var dateOfRecord: NSDate!
    var temperatureString: String {
        get {
            return "\(self.currentTemperature)°"
        }
    }

    var dayOfWeek: String {
        get {
            formatter.dateFormat = "EEEE"
            return formatter.stringFromDate(self.dateOfRecord)
        }
    }

    private lazy var formatter: NSDateFormatter = {
        let formatter = NSDateFormatter()

        return formatter
    }()

    convenience init(jsonDict: NSDictionary) {
        self.init()
        self.currentTemperature = (jsonDict["main"] as! NSDictionary)["temp"] as! Int
        self.formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        self.dateOfRecord = formatter.dateFromString(jsonDict["dt_txt"] as! String)
    }
}