//
//  Transformer.swift
//  DribbbleKit
//
//  Created by 林達也 on 2017/04/15.
//  Copyright © 2017年 jp.sora0077. All rights reserved.
//

import Foundation
import Alter

struct Transformer {
    static let date: (String) throws -> Date = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        return {
            guard let date = formatter.date(from: $0) else {
                throw typeMismatch(expected: Date.self, actual: $0)
            }
            return date
        }
    }()
    static let url: (String) throws -> URL = {
        guard let url = URL(string: $0) else {
            throw typeMismatch(expected: URL.self, actual: $0)
        }
        return url
    }

    private static func typeMismatch(expected: Any.Type, actual: Any) -> Error {
        return DecodeError.typeMismatch(expected: expected, actual: actual, keyPath: [])
    }

    private init() {}
}

struct ParameterTransformer {
    static let date: (Date) -> String = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string
    }()

    private init() {}
}

Fix URL transfomer when contains white space

//
//  Transformer.swift
//  DribbbleKit
//
//  Created by 林達也 on 2017/04/15.
//  Copyright © 2017年 jp.sora0077. All rights reserved.
//

import Foundation
import Alter

struct Transformer {
    static let date: (String) throws -> Date = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        return {
            guard let date = formatter.date(from: $0) else {
                throw typeMismatch(expected: Date.self, actual: $0)
            }
            return date
        }
    }()
    static let url: (String) throws -> URL = {
        guard let url = URL(string: $0.trimmingCharacters(in: .whitespacesAndNewlines)) else {
            throw typeMismatch(expected: URL.self, actual: $0)
        }
        return url
    }

    private static func typeMismatch(expected: Any.Type, actual: Any) -> Error {
        return DecodeError.typeMismatch(expected: expected, actual: actual, keyPath: .empty)
    }

    private init() {}
}

struct ParameterTransformer {
    static let date: (Date) -> String = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string
    }()

    private init() {}
}


//
//  FontLoader.swift
//  SwiftIconFont
//
//  Created by Sedat Ciftci on 18/03/16.
//  Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved.
//

import UIKit
import Foundation
import CoreText

class FontLoader: NSObject {

    class func loadFont(_ fontName: String) {

        let bundle = Bundle(for: FontLoader.self)
        let paths = bundle.paths(forResourcesOfType: "ttf", inDirectory: nil)
        var fontURL = URL(string: "")
        var error: Unmanaged<CFError>?

        paths.forEach() {
            guard let filename = NSURL(fileURLWithPath: $0).lastPathComponent,
                let _ = filename.lowercased().range(of: fontName.lowercased()) else {
                    return
            }

            fontURL = NSURL(fileURLWithPath: $0) as URL
        }

        guard let unwrappedFontURL = fontURL,
            let data = try? Data(contentsOf: unwrappedFontURL),
            let provider = CGDataProvider(data: data as CFData),
            let font = CGFont.init(provider) else {

                return
        }

        guard CTFontManagerRegisterGraphicsFont(font, &error) else {

            return
        }

        let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue())
        let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
        NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
    }
}

Fix failure in logic. Addressing linter's comments

//
//  FontLoader.swift
//  SwiftIconFont
//
//  Created by Sedat Ciftci on 18/03/16.
//  Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved.
//

import UIKit
import Foundation
import CoreText

class FontLoader: NSObject {

    class func loadFont(_ fontName: String) {

        let bundle = Bundle(for: FontLoader.self)
        let paths = bundle.paths(forResourcesOfType: "ttf", inDirectory: nil)
        var fontURL = URL(string: "")
        var error: Unmanaged<CFError>?

        paths.forEach {
            guard let filename = NSURL(fileURLWithPath: $0).lastPathComponent,
                filename.lowercased().range(of: fontName.lowercased()) != nil else {
                    return
            }

            fontURL = NSURL(fileURLWithPath: $0) as URL
        }

        guard let unwrappedFontURL = fontURL,
            let data = try? Data(contentsOf: unwrappedFontURL),
            let provider = CGDataProvider(data: data as CFData),
            let font = CGFont.init(provider) else {

                return
        }

        guard !CTFontManagerRegisterGraphicsFont(font, &error),
            let unwrappedError = error else {

            return
        }

        let errorDescription: CFString = CFErrorCopyDescription(unwrappedError.takeUnretainedValue())
        let nsError = error!.takeUnretainedValue() as AnyObject as! NSError

        NSException(name: NSExceptionName.internalInconsistencyException,
                    reason: errorDescription as String,
                    userInfo: [NSUnderlyingErrorKey: nsError]).raise()
    }
}


//
//  NuimoController.swift
//  Nuimo
//
//  Created by Lars Blumberg on 10/9/15.
//  Copyright © 2015 Senic. All rights reserved.
//
//  This software may be modified and distributed under the terms
//  of the MIT license.  See the LICENSE file for details.

@objc public protocol NuimoController {
    var uuid: String {get}
    var delegate: NuimoControllerDelegate? {get set}

    var state: NuimoConnectionState {get}
    var batteryLevel: Int {get set}

    func connect()

    func disconnect()

    func writeMatrix(name: String)

    func writeBarMatrix(percent: Int)
}

@objc public enum NuimoConnectionState: Int {
    case
    Connecting,
    Connected,
    Disconnecting,
    Disconnected
}

@objc public protocol NuimoControllerDelegate {
    optional func nuimoControllerDidStartConnecting(controller: NuimoController)
    optional func nuimoControllerDidConnect(controller: NuimoController)
    optional func nuimoControllerDidFailToConnect(controller: NuimoController)
    optional func nuimoControllerDidDisconnect(controller: NuimoController)
    optional func nuimoControllerDidInvalidate(controller: NuimoController)
    optional func nuimoControllerDidDiscoverMatrixService(controller: NuimoController)
    optional func nuimoController(controller: NuimoController, didUpdateBatteryLevel bateryLevel: Int)
    optional func nuimoController(controller: NuimoController, didReceiveGestureEvent gestureEvent: NuimoGestureEvent)
}

Rename delegate argument gestureEvent to event

//
//  NuimoController.swift
//  Nuimo
//
//  Created by Lars Blumberg on 10/9/15.
//  Copyright © 2015 Senic. All rights reserved.
//
//  This software may be modified and distributed under the terms
//  of the MIT license.  See the LICENSE file for details.

@objc public protocol NuimoController {
    var uuid: String {get}
    var delegate: NuimoControllerDelegate? {get set}

    var state: NuimoConnectionState {get}
    var batteryLevel: Int {get set}

    func connect()

    func disconnect()

    func writeMatrix(name: String)

    func writeBarMatrix(percent: Int)
}

@objc public enum NuimoConnectionState: Int {
    case
    Connecting,
    Connected,
    Disconnecting,
    Disconnected
}

@objc public protocol NuimoControllerDelegate {
    optional func nuimoControllerDidStartConnecting(controller: NuimoController)
    optional func nuimoControllerDidConnect(controller: NuimoController)
    optional func nuimoControllerDidFailToConnect(controller: NuimoController)
    optional func nuimoControllerDidDisconnect(controller: NuimoController)
    optional func nuimoControllerDidInvalidate(controller: NuimoController)
    optional func nuimoControllerDidDiscoverMatrixService(controller: NuimoController)
    optional func nuimoController(controller: NuimoController, didUpdateBatteryLevel bateryLevel: Int)
    optional func nuimoController(controller: NuimoController, didReceiveGestureEvent event: NuimoGestureEvent)
}


import Darwin.POSIX
import Dispatch
import struct Foundation.TimeInterval

func sleep(for timeInterval: TimeInterval) {
	let microSeconds: useconds_t = .init(timeInterval * 1_000_000)
	usleep(microSeconds)
}

extension DispatchGroup {
	func wait(for timeInterval: TimeInterval) -> DispatchTimeoutResult {
		let dispatchTime = DispatchTime.now() + (timeInterval * 1_000_000_000)
		return wait(timeout: dispatchTime)
	}
}

Use constants for time conversions

import Darwin.POSIX
import Dispatch
import struct Foundation.TimeInterval

func sleep(for timeInterval: TimeInterval) {
	let microSeconds: useconds_t = .init(timeInterval * Double(USEC_PER_SEC))
	usleep(microSeconds)
}

extension DispatchGroup {
	func wait(for timeInterval: TimeInterval) -> DispatchTimeoutResult {
		let dispatchTime = DispatchTime.now() + (timeInterval * Double(NSEC_PER_SEC))
		return wait(timeout: dispatchTime)
	}
}


// RUN: %swift -target x86_64-apple-darwin10 -emit-ir %s | FileCheck %s

// Make sure we use an intrinsic for functions such as sqrt
// CHECK: tail call float @llvm.sqrt.f32
func(f : Float) -> Float {
  return sqrt(f)
}

// CHECK: tail call float @llvm.sqrt.f64
func(f : Double) -> Double {
  return sqrt(f)
}

Fix test to import Darwin and use correct check lines

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

import Darwin

// Make sure we use an intrinsic for functions such as sqrt
// CHECK: call float @llvm.sqrt.f32
func test1(f : Float) -> Float {
  return sqrt(f)
}

// CHECK: call double @llvm.sqrt.f64
func test2(f : Double) -> Double {
  return _sqrt(f)
}


// RUN: %target-parse-verify-swift

// Warn when the indentation is the same.
func f_returns_void() {}
func unreachable_returns_void() {
  return
  f_returns_void() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
}

func f_returns_Int() {}
func unreachable_returns_Int() {
  return
  f_returns_Int() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
}

func f_closure_returns_void() {
  _ = {
    return
    f_closure_returns_void() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
  }
}

// Do not warn when the indentation is differnt.
func reachable_returns_void() {
  return
    f_returns_void() // no-warning
}

func reachable_returns_Int() {
  return
f_returns_Int() // no-warning
}

Fix typo: differnt → different

// RUN: %target-parse-verify-swift

// Warn when the indentation is the same.
func f_returns_void() {}
func unreachable_returns_void() {
  return
  f_returns_void() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
}

func f_returns_Int() {}
func unreachable_returns_Int() {
  return
  f_returns_Int() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
}

func f_closure_returns_void() {
  _ = {
    return
    f_closure_returns_void() // expected-warning {{expression following 'return' is treated as an argument of the 'return'}} // expected-note{{indent the expression to silence this warning}}
  }
}

// Do not warn when the indentation is different.
func reachable_returns_void() {
  return
    f_returns_void() // no-warning
}

func reachable_returns_Int() {
  return
f_returns_Int() // no-warning
}


import Foundation
import ProjectSpec
import SwiftCLI

public class XcodeGenCLI {
    private class Manipulator: ArgumentListManipulator {
        let commandName: String

        init(commandName: String) {
            self.commandName = commandName
        }

        func manipulate(arguments: ArgumentList) {
            if !arguments.hasNext() || arguments.nextIsOption() {
                arguments.manipulate { existing in
                    return [commandName] + existing
                }
            }
        }
    }

    let cli: CLI

    public init(version: Version) {
        let generateCommand = GenerateCommand(version: version)

        cli = CLI(
            name: "xcodegen",
            version: version.string,
            description: "Generates Xcode projects",
            commands: [generateCommand]
        )
        let manipulator = Manipulator(commandName: generateCommand.name)
        cli.argumentListManipulators.insert(manipulator, at: 0)
        cli.parser.routeBehavior = .searchWithFallback(generateCommand)
    }

    public func execute(arguments: [String]? = nil) {
        let status: Int32
        if let arguments = arguments {
            status = cli.go(with: arguments)
        } else {
            status = cli.go()
        }
        exit(status)
    }
}

Use struct instead of class

import Foundation
import ProjectSpec
import SwiftCLI

public class XcodeGenCLI {
    private struct Manipulator: ArgumentListManipulator {
        let commandName: String

        func manipulate(arguments: ArgumentList) {
            if !arguments.hasNext() || arguments.nextIsOption() {
                arguments.manipulate { existing in
                    return [commandName] + existing
                }
            }
        }
    }

    let cli: CLI

    public init(version: Version) {
        let generateCommand = GenerateCommand(version: version)

        cli = CLI(
            name: "xcodegen",
            version: version.string,
            description: "Generates Xcode projects",
            commands: [generateCommand]
        )
        let manipulator = Manipulator(commandName: generateCommand.name)
        cli.argumentListManipulators.insert(manipulator, at: 0)
        cli.parser.routeBehavior = .searchWithFallback(generateCommand)
    }

    public func execute(arguments: [String]? = nil) {
        let status: Int32
        if let arguments = arguments {
            status = cli.go(with: arguments)
        } else {
            status = cli.go()
        }
        exit(status)
    }
}


//
//  JUWConstants.swift
//  Ajuda
//
//  Created by Juwe Takeheshi on 9/21/17.
//  Copyright © 2017 Juwe Takeheshi. All rights reserved.
//

import Foundation

//let kCollectionCentersUrl = "http://acopio-api.skycatch.net/v1/acopios"
let kCollectionCentersUrl = "https://hapi.balterbyte.com/api/acopios"
let kCollectionCenterNeedsUrl = "https://hapi.balterbyte.com/api/acopios/%@/productos"
let kCollectionCenterContactInfoUrl = "https://hapi.balterbyte.com/api/acopios/%@/contactos"

Add New constant for the search product URL

//
//  JUWConstants.swift
//  Ajuda
//
//  Created by Juwe Takeheshi on 9/21/17.
//  Copyright © 2017 Juwe Takeheshi. All rights reserved.
//

import Foundation

//let kCollectionCentersUrl = "http://acopio-api.skycatch.net/v1/acopios"
let kCollectionCentersUrl = "https://hapi.balterbyte.com/api/acopios"
let kCollectionCenterNeedsUrl = "https://hapi.balterbyte.com/api/acopios/%@/productos"
let kCollectionCenterContactInfoUrl = "https://hapi.balterbyte.com/api/acopios/%@/contactos"
let kCollectionCenterSearchProductUrl = "https://hapi.balterbyte.com/api/productos?filter={\"where\":{\"nombre\":{\"like\":\"%@\"}}}"


//
//  NotificationService.swift
//  WonderPushNotificationServiceExtension
//
//  Created by Stéphane JAIS on 09/03/2021.
//  Copyright © 2021 WonderPush. All rights reserved.
//

import WonderPushExtension

class NotificationService: WPNotificationServiceExtension {
    override class func clientId() -> String {
        return "YOUR_CLIENT_ID"
    }
    override class func clientSecret() -> String {

        return "YOUR_CLIENT_SECRET"

    }

}

Change placeholder to match the one in AppDelegate.m

//
//  NotificationService.swift
//  WonderPushNotificationServiceExtension
//
//  Created by Stéphane JAIS on 09/03/2021.
//  Copyright © 2021 WonderPush. All rights reserved.
//

import WonderPushExtension

class NotificationService: WPNotificationServiceExtension {
    override class func clientId() -> String {
        return "ENTER_CLIENT_ID"
    }
    override class func clientSecret() -> String {

        return "ENTER_CLIENT_SECRET"

    }

}


//
//  Ashton.swift
//  Ashton
//
//  Created by Michael Schwarz on 16.09.17.
//  Copyright © 2017 Michael Schwarz. All rights reserved.
//

import Foundation
import Ashton.AshtonObjc

/// Transforms AttributedString into HTML in both directions
public final class Ashton {

	public typealias HTML = String

	public static func encode(_ attributedString: NSAttributedString) -> HTML {
		return AshtonHTMLWriter().encode(attributedString)
	}

	public static func decode(_ html: HTML) -> NSAttributedString {
        //return AshtonObjcHTMLReader().decodeAttributedString(fromHTML: html)
		return AshtonHTMLReader().decode(html) // swift implementation
	}
}

Use objc implementation for decoding

//
//  Ashton.swift
//  Ashton
//
//  Created by Michael Schwarz on 16.09.17.
//  Copyright © 2017 Michael Schwarz. All rights reserved.
//

import Foundation
import Ashton.AshtonObjc

/// Transforms AttributedString into HTML in both directions
public final class Ashton {

	public typealias HTML = String

	public static func encode(_ attributedString: NSAttributedString) -> HTML {
		return AshtonHTMLWriter().encode(attributedString)
	}

	public static func decode(_ html: HTML) -> NSAttributedString {
        return AshtonObjcHTMLReader().decodeAttributedString(fromHTML: html)

		// swift implementation is substantially slower (using swift4 to compile)
        // return AshtonHTMLReader().decode(html) // swift implementation
	}
}


/**
 * Question Link: https://leetcode.com/problems/add-two-numbers/
 * Primary idea: use carry and iterate through both linked lists
 * Time Complexity: O(n), Space Complexity: O(1)
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class AddTwoNumbers {
    func addTwoNumbers(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var carry = 0
        var sum = 0
        let dummy = ListNode(0)
        var node = dummy
        var l1 = l1
        var l2 = l2

        while l1 != nil || l2 != nil || carry != 0 {
            sum = carry

            if l1 != nil {
                sum += l1!.val
                l1 = l1!.next
            }
            if l2 != nil {
                sum += l2!.val
                l2 = l2!.next
            }

            carry = sum / 10
            sum = sum % 10

            node.next = ListNode(sum)
            node = node.next!
        }

        return dummy.next

    }
}

Optimize solution to Add Two Numbers

/**
 * Question Link: https://leetcode.com/problems/add-two-numbers/
 * Primary idea: use carry and iterate through both linked lists
 * Time Complexity: O(n), Space Complexity: O(1)
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class AddTwoNumbers {
    func addTwoNumbers(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var carry = 0, sum = 0, l1 = l1, l2 = l2
        let dummy = ListNode(0)
        var node = dummy

        while l1 != nil || l2 != nil || carry != 0 {
            sum = carry

            if l1 != nil {
                sum += l1!.val
                l1 = l1!.next
            }
            if l2 != nil {
                sum += l2!.val
                l2 = l2!.next
            }

            carry = sum / 10

            node.next = ListNode(sum % 10)
            node = node.next!
        }

        return dummy.next

    }
}


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

import UIKit

public extension UIButton {

    func setTitleWithoutFlashing(to title: String?, for state: UIControlState = .normal) {
        UIView.performWithoutAnimation {
            setTitle(title, for: state)
            layoutIfNeeded()
        }
    }

}

Add helper for setting button images

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

import UIKit

public extension UIButton {

    func setTitleWithoutFlashing(to title: String?, for state: UIControlState = []) {
        UIView.performWithoutAnimation {
            setTitle(title, for: state)
            layoutIfNeeded()
        }
    }

    func setImageWithoutFlashing(to image: UIImage?, for state: UIControlState = []) {
        UIView.performWithoutAnimation {
            setImage(image, for: state)
            layoutIfNeeded()
        }
    }

}


//
//  SWXMLSelectMapping.swift
//  SWXMLMapping
//
//  Created by Samuel Williams on 12/02/16.
//
//

import Foundation

@objc(SWXMLSelection)
public protocol SWXMLSelection {
	init(attributes: [String : String]!)

	func mapObject(object: AnyObject!, withKeyPath keyPath: String!) -> AnyObject!
}

/*
	This mapping allows you to make a selection by instantiating a class which manages the query against a object/keyPath relationship. The result is essentially a collection of items.

	<select keyPath="property">
*/
@objc(SWXMLSelectMapping)
public class SWXMLSelectMapping: SWXMLMemberMapping {
	let mappingClass: SWXMLSelection.Type

	override init!(tag: String!, keyPath: String!, attributes: [String : String]!) {
		mappingClass = NSClassFromString(attributes["class"]!) as! SWXMLSelection.Type

		super.init(tag: tag, keyPath: keyPath, attributes: attributes)
	}

	override public func serializedObjectMember(object: AnyObject!, withMapping mapping: SWXMLMapping!) -> String! {
		let mappingObject = mappingClass.init(attributes: self.attributes)

		let mappedObject = mappingObject.mapObject(object, withKeyPath: self.keyPath)

		return SWXMLTags.tagNamed(self.tag, forValue: mapping.serializeObject(mappedObject))
	}
}

Allow mapping to be passed in, for access to e.g. metadata

//
//  SWXMLSelectMapping.swift
//  SWXMLMapping
//
//  Created by Samuel Williams on 12/02/16.
//
//

import Foundation

@objc(SWXMLSelection)
public protocol SWXMLSelection {
	init(attributes: [String : String]!, mapping: SWXMLMapping)

	func mapObject(object: AnyObject!, withKeyPath keyPath: String!) -> AnyObject!
}

/*
	This mapping allows you to make a selection by instantiating a class which manages the query against a object/keyPath relationship. The result is essentially a collection of items.

	<select keyPath="property">
*/
@objc(SWXMLSelectMapping)
public class SWXMLSelectMapping: SWXMLMemberMapping {
	let mappingClass: SWXMLSelection.Type

	override init!(tag: String!, keyPath: String!, attributes: [String : String]!) {
		mappingClass = NSClassFromString(attributes["class"]!) as! SWXMLSelection.Type

		super.init(tag: tag, keyPath: keyPath, attributes: attributes)
	}

	override public func serializedObjectMember(object: AnyObject!, withMapping mapping: SWXMLMapping!) -> String! {
		let mappingObject = mappingClass.init(attributes: self.attributes, mapping: mapping)

		let mappedObject = mappingObject.mapObject(object, withKeyPath: self.keyPath)

		return SWXMLTags.tagNamed(self.tag, forValue: mapping.serializeObject(mappedObject))
	}
}


//
//  main.swift
//  Carthage
//
//  Created by Justin Spahr-Summers on 2014-10-10.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import Foundation
import LlamaKit

// Hopefully this will be built into the standard library someday.
func combineDictionaries<K, V>(lhs: [K: V], rhs: [K: V]) -> [K: V] {
    var result = Dictionary<K, V>()
    for (key, value) in lhs {
        result.updateValue(value, forKey: key)
    }
    for (key, value) in rhs {
        result.updateValue(value, forKey: key)
    }
    return result
}

let commandTypes = [
	HelpCommand.self
]

let commands = commandTypes.map { [$0.verb: $0] }.reduce([:], combine: combineDictionaries)
var arguments = Process.arguments

assert(arguments.count >= 1)
arguments.removeAtIndex(0)

let verb = arguments.first ?? HelpCommand.verb
let args = arguments.count > 0 ? dropFirst(arguments) : []

let result = commands[verb]?(args).run()

switch result {
case .Some(.Success):
	exit(EXIT_SUCCESS)

case let .Some(.Failure(error)):
	fputs("Error executing command \(verb): \(error)", stderr)
	exit(EXIT_FAILURE)

case .None:
	fputs("Unrecognized command: '\(verb)'. See `carthage help`.", stderr)
	exit(EXIT_FAILURE)
}

Copy the left-hand side to start

//
//  main.swift
//  Carthage
//
//  Created by Justin Spahr-Summers on 2014-10-10.
//  Copyright (c) 2014 Carthage. All rights reserved.
//

import Foundation
import LlamaKit

// Hopefully this will be built into the standard library someday.
func combineDictionaries<K, V>(lhs: [K: V], rhs: [K: V]) -> [K: V] {
	var result = lhs
    for (key, value) in rhs {
        result.updateValue(value, forKey: key)
    }
    return result
}

let commandTypes = [
	HelpCommand.self
]

let commands = commandTypes.map { [$0.verb: $0] }.reduce([:], combine: combineDictionaries)
var arguments = Process.arguments

assert(arguments.count >= 1)
arguments.removeAtIndex(0)

let verb = arguments.first ?? HelpCommand.verb
let args = arguments.count > 0 ? dropFirst(arguments) : []

let result = commands[verb]?(args).run()

switch result {
case .Some(.Success):
	exit(EXIT_SUCCESS)

case let .Some(.Failure(error)):
	fputs("Error executing command \(verb): \(error)", stderr)
	exit(EXIT_FAILURE)

case .None:
	fputs("Unrecognized command: '\(verb)'. See `carthage help`.", stderr)
	exit(EXIT_FAILURE)
}


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

public struct Term: FixpointType {
	public init(_ out: Constructor<Term>) {
		self.out = out
	}

	public static func out(term: Term) -> Constructor<Term> {
		return term.out
	}

	public let out: Constructor<Term>
}

public protocol FixpointType {
	typealias F
	init(F)
	static func out(Self) -> F
}

public func cata<T, Fix: FixpointType where Fix.F == Constructor<Fix>>(f: Constructor<T> -> T)(_ term: Fix) -> T {
	return term |> (Fix.out >>> (flip(uncurry(Constructor.map)) <| cata(f)) >>> f)
}

// MARK: - Imports

import Prelude

Rename the fixpoint typealias to Recur.

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

public struct Term: FixpointType {
	public init(_ out: Constructor<Term>) {
		self.out = out
	}

	public static func out(term: Term) -> Constructor<Term> {
		return term.out
	}

	public let out: Constructor<Term>
}

public protocol FixpointType {
	typealias Recur
	init(Recur)
	static func out(Self) -> Recur
}

public func cata<T, Fix: FixpointType where Fix.Recur == Constructor<Fix>>(f: Constructor<T> -> T)(_ term: Fix) -> T {
	return term |> (Fix.out >>> (flip(uncurry(Constructor.map)) <| cata(f)) >>> f)
}

// MARK: - Imports

import Prelude


//
//  EmojiSearcher.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 1/9/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

typealias EmojiSearchResult = (emoji: Emoji, suggestion: String)

class EmojiSearcher {
    let emojis: [Emoji]

    init(emojis: [Emoji]) {
        self.emojis = emojis
    }

    func search(shortname: String, custom: [Emoji]) -> [EmojiSearchResult] {
        return (emojis + custom).flatMap { emoji -> EmojiSearchResult? in
            if let suggestion = emoji.shortname.contains(shortname) ? emoji.shortname : nil {
                return (emoji: emoji, suggestion: suggestion)
            } else if let suggestion = emoji.alternates.filter({ $0.contains(shortname) }).first {
                return (emoji: emoji, suggestion: suggestion)
            }

            return nil
        }.sorted {
            ($0.suggestion.count - shortname.count) < ($1.suggestion.count - shortname.count)
        }
    }
}

extension EmojiSearcher {
    static let standard = EmojiSearcher(emojis:
            Emojione.people +
            Emojione.nature +
            Emojione.food +
            Emojione.activity +
            Emojione.travel +
            Emojione.objects +
            Emojione.symbols +
            Emojione.flags
    )
}

Append colons to custom emojis in autocomplete

//
//  EmojiSearcher.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 1/9/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

typealias EmojiSearchResult = (emoji: Emoji, suggestion: String)

class EmojiSearcher {
    let emojis: [Emoji]

    init(emojis: [Emoji]) {
        self.emojis = emojis
    }

    func search(shortname: String, custom: [Emoji]) -> [EmojiSearchResult] {
        return (emojis + custom).flatMap { emoji -> EmojiSearchResult? in
            if let suggestion = emoji.shortname.contains(shortname) ? emoji.shortname : emoji.alternates.filter({ $0.contains(shortname) }).first {
                return (emoji: emoji, suggestion: suggestion.contains(":") ? suggestion : ":\(suggestion):")
            }

            return nil
        }.sorted {
            ($0.suggestion.count - shortname.count) < ($1.suggestion.count - shortname.count)
        }
    }
}

extension EmojiSearcher {
    static let standard = EmojiSearcher(emojis:
            Emojione.people +
            Emojione.nature +
            Emojione.food +
            Emojione.activity +
            Emojione.travel +
            Emojione.objects +
            Emojione.symbols +
            Emojione.flags
    )
}


// RUN: %empty-directory(%t)
// RUN: split-file %s %t

// RUN: touch %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod.h -I %t -enable-experimental-cxx-interop

// RUN: %FileCheck %s < %t/swiftMod.h

// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod2.h -I %t -enable-experimental-cxx-interop

// RUN: %check-interop-cxx-header-in-clang(%t/swiftMod2.h -Wno-error)

//--- header.h
#include "swiftMod.h"

//--- module.modulemap
module SwiftToCxxTest {
    header "header.h"
    requires cplusplus
}

//--- swiftMod.swift
import SwiftToCxxTest

@_expose(Cxx)
public func testFunction() -> String {
    let arr = Swift.Array<Int>()
    let rng = Swift.SystemRandomNumberGenerator()
    return ""
}

// CHECK: namespace Swift __attribute__((swift_private)) {
// CHECK: namespace SwiftMod __attribute__((swift_private)) {
// CHECK-NOT: namespace Swift {

Disable new SwiftToCxxToSwift Interop test

// RUN: %empty-directory(%t)
// RUN: split-file %s %t

// RUN: touch %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod.h -I %t -enable-experimental-cxx-interop

// RUN: %FileCheck %s < %t/swiftMod.h

// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod2.h -I %t -enable-experimental-cxx-interop

// RUN: %check-interop-cxx-header-in-clang(%t/swiftMod2.h -Wno-error)

// XFAIL: OS=linux-android, OS=linux-androideabi

//--- header.h
#include "swiftMod.h"

//--- module.modulemap
module SwiftToCxxTest {
    header "header.h"
    requires cplusplus
}

//--- swiftMod.swift
import SwiftToCxxTest

@_expose(Cxx)
public func testFunction() -> String {
    let arr = Swift.Array<Int>()
    let rng = Swift.SystemRandomNumberGenerator()
    return ""
}

// CHECK: namespace Swift __attribute__((swift_private)) {
// CHECK: namespace SwiftMod __attribute__((swift_private)) {
// CHECK-NOT: namespace Swift {


////
///  UserAvatarsCellPresenter.swift
//

public struct UserAvatarsCellPresenter {

    public static func configure(
        cell: UICollectionViewCell,
        streamCellItem: StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath,
        currentUser: User?)
    {
        guard let cell = cell as? UserAvatarsCell,
            model = streamCellItem.jsonable as? UserAvatarCellModel else {
                return
        }
        cell.imageView.image = model.icon.normalImage
        cell.userAvatarCellModel = model
        cell.loadingLabel.hidden = model.hasUsers
    }
}

Tidy things up a bit


//
//  FirebaseStorable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation
import FirebaseCommunity

public protocol FirebaseStorable: Storable {

}

public extension FirebaseStorable where Reference == StorageReference {

    public static var reference: StorageReference {
        return Storage.storage().reference()
    }
}

public extension FirebaseStorable {
    public func upload(with name: String) {
        guard let data = data else {
            return
        }

        let uploadTask = Self.reference.child("images/decentPath").putData(data, metadata: StorageMetadata()) { (metadata, error) in

            if let error = error{
                print(error.localizedDescription as Any)
            }
            else {
                guard let urlStorage = metadata?.downloadURL()!.absoluteString else {
                    fatalError("couldn't generate the storage url")
                }
                let result = (name: name, path: urlStorage)
                //TODO: return the result
            }
            if let error = error {
                //TODO: Return an error
            }
        }
        uploadTask.resume()
    }
}

Fix associated type where in extension

//
//  FirebaseStorable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation
import FirebaseCommunity

public protocol FirebaseStorable: Storable where Reference == StorageReference  {

}

public extension FirebaseStorable {

    public static var reference: StorageReference {
        return Storage.storage().reference()
    }
}

public extension FirebaseStorable {
    public func upload(with name: String) {
        guard let data = data else {
            return
        }

        let uploadTask = Self.reference.child("images/decentPath").putData(data, metadata: StorageMetadata()) { (metadata, error) in

            if let error = error{
                print(error.localizedDescription as Any)
            }
            else {
                guard let urlStorage = metadata?.downloadURL()!.absoluteString else {
                    fatalError("couldn't generate the storage url")
                }
                let result = (name: name, path: urlStorage)
                //TODO: return the result
            }
            if let error = error {
                //TODO: Return an error
            }
        }
        uploadTask.resume()
    }
}


//
//  Types.swift
//  CUDA
//
//  Created by Richard Wei on 11/5/16.
//
//

import CCuBLAS

public extension BLAS {
    public enum DataType : UInt32 {
        case float = 0
        case double = 1
        case half = 2
        case int8 = 3
        case uint8 = 8
        case int32 = 10
        case uint32 = 12

        public init?(_ dataType: cublasDataType_t) {
            /// Complex data types are not yet supported
            self.init(rawValue: dataType.rawValue)
        }
    }
}

public protocol BLASDataProtocol {
    static var blasDataType: BLAS.DataType { get }
}

extension BLASDataProtocol {
    static var cType: cublasDataType_t {
        return cublasDataType_t(blasDataType.rawValue)
    }
}

extension Float : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .float
    }
}

extension Double : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .double
    }
}

extension Int8 : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .int8
    }
}

Add support for UInt8 type

//
//  Types.swift
//  CUDA
//
//  Created by Richard Wei on 11/5/16.
//
//

import CCuBLAS

public extension BLAS {
    public enum DataType : UInt32 {
        case float = 0
        case double = 1
        case half = 2
        case int8 = 3
        case uint8 = 8
        case int32 = 10
        case uint32 = 12

        public init?(_ dataType: cublasDataType_t) {
            /// Complex data types are not yet supported
            self.init(rawValue: dataType.rawValue)
        }
    }
}

public protocol BLASDataProtocol {
    static var blasDataType: BLAS.DataType { get }
}

extension BLASDataProtocol {
    static var cType: cublasDataType_t {
        return cublasDataType_t(blasDataType.rawValue)
    }
}

extension Float : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .float
    }
}

extension Double : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .double
    }
}

extension Int8 : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .int8
    }
}

extension UInt8 : BLASDataProtocol {
    public static var blasDataType: BLAS.DataType {
        return .uint8
    }
}


import Darwin

extension Tensor {
    public var softmax: Tensor {
        let exps = exp
        let sum = exps.elements.reduce(0.0, combine: +)
        return exps / sum
    }

    public var relu: Tensor {
        return Tensor(shape: shape, elements: elements.map { fmax($0, 0.0) })
    }
}

Add `maxPool` and `conv2d` without implementations

import Darwin

extension Tensor {
    public var softmax: Tensor {
        let exps = exp
        let sum = exps.elements.reduce(0.0, combine: +)
        return exps / sum
    }

    public var relu: Tensor {
        return Tensor(shape: shape, elements: elements.map { fmax($0, 0.0) })
    }
}

extension Tensor {
    public func maxPool(ksize ksize: [Int], strides: [Int]) -> Tensor { // padding = Same
        assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
        assert(ksize.count >= 4, "`ksize.count` must be greater than or equal to 4: \(ksize.count)")
        assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")

        fatalError("Unimplemented yet.")
    }

    public func conv2d(filter filter: Tensor, strides: [Int]) -> Tensor { // padding = Same
        assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
        assert(filter.shape.dimensions.count == 4, "`filter.shape.dimensions.count` must be 4: \(filter.shape.dimensions.count)")
        assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")

        fatalError("Unimplemented yet.")
    }
}


//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc func setRootViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void = {}) {
        if animated {

            UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
                let oldState = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)

                self.rootViewController = viewController

                UIView.setAnimationsEnabled(oldState)
            }, completion: { (finished) -> Void in
                completion()
            })
        } else {
            self.rootViewController = viewController
        }
    }
}

Fix completion block to match the one in UIView.transition

//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> ())? = nil) {
        if animated {
            UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
                let oldState = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)

                self.rootViewController = viewController

                UIView.setAnimationsEnabled(oldState)
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}


//
//  FriendUserCell.swift
//  RoadTripPlanner
//
//  Created by Diana Fisher on 10/23/17.
//  Copyright © 2017 RoadTripPlanner. All rights reserved.
//

import UIKit
import Parse

class FriendUserCell: UITableViewCell {

    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var addRemoveButton: UIButton!

    var avatarFile: PFFile?

    var user: PFUser! {
        didSet {
            usernameLabel.text = user.username
            avatarFile = user.avatarFile
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        guard let avatarFile = self.avatarFile else { return }
        Utils.fileToImage(file: avatarFile) { (image) in
            self.avatarImageView.image = image
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func addRemoveButtonPressed(_ sender: Any) {

    }
}

Load user avatar file and display it as a circle.

//
//  FriendUserCell.swift
//  RoadTripPlanner
//
//  Created by Diana Fisher on 10/23/17.
//  Copyright © 2017 RoadTripPlanner. All rights reserved.
//

import UIKit
import Parse

class FriendUserCell: UITableViewCell {

    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var addRemoveButton: UIButton!

    var user: PFUser! {
        didSet {
            usernameLabel.text = user.username
            guard let avatarFile = user.avatarFile else { return }

            Utils.fileToImage(file: avatarFile) { (image) in
                self.avatarImageView.image = image
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        avatarImageView.layer.cornerRadius = avatarImageView.frame.size.height / 2
        avatarImageView.clipsToBounds = true
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func addRemoveButtonPressed(_ sender: Any) {

    }
}


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

public let naturalEnvironment: Environment = Environment([], [
	"Natural": Value.forall(const(Value.function(Value.function(.Type, .Type), Value.forall(const(.Type))))),
	"Zero": Value.forall { X in .pi(.function(X, X), const(.pi(X, id))) }, // ∀ X : Type . λ f : X → X . λ x : X . x
	"One": Value.forall { X in Value.pi(.function(X, X)) { f in Value.pi(X) { x in Value.application(f.neutral!, x) } } }, // ∀ F : Type . ∀ X : Type . λ f : F . λ x : X . f(x)
	"Successor": Value.forall { N in Value.forall { X in Value.pi(N) { n in Value.pi(.function(X, X)) { f in Value.pi(X) { x in .application(f.neutral!, .application(.application(n.neutral!, f), x)) } } } } }, // ∀ N . ∀ F . ∀ X . λ n : N . λ f : F . λ x : X . f ((n f) x)
])

import Prelude

Use value application to define Successor.

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

public let naturalEnvironment: Environment = Environment([], [
	"Natural": Value.forall(const(Value.function(Value.function(.Type, .Type), Value.forall(const(.Type))))),
	"Zero": Value.forall { X in .pi(.function(X, X), const(.pi(X, id))) }, // ∀ X : Type . λ f : X → X . λ x : X . x
	"One": Value.forall { X in Value.pi(.function(X, X)) { f in Value.pi(X) { x in Value.application(f.neutral!, x) } } }, // ∀ F : Type . ∀ X : Type . λ f : F . λ x : X . f(x)
	"Successor": Value.forall { N in Value.forall { X in Value.pi(N) { n in Value.pi(.function(X, X)) { f in Value.pi(X) { x in f.apply(n.apply(f).apply(x)) } } } } }, // ∀ N . ∀ F . ∀ X . λ n : N . λ f : F . λ x : X . f ((n f) x)
])

import Prelude


infix operator <^> { associativity left }
infix operator <*> { associativity left }
infix operator >>- { associativity left precedence 150 }
infix operator -<< { associativity right precedence 150 }

Set precedence of `<^>` and `<*>` to be higher than `>>-`

infix operator <^> { associativity left precedence 155 }
infix operator <*> { associativity left precedence 155 }
infix operator >>- { associativity left precedence 150 }
infix operator -<< { associativity right precedence 150 }


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

import UIKit
import WebKit

class CollectThemAllViewController: UIViewController, CollectThemAllScene {

    // MARK: Properties

    private var webView: WKWebView?

    // MARK: Actions

    @IBAction func refreshButtonTapped(_ sender: Any) {
        webView?.reload()
    }

    // MARK: Overrides

    override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.preferences.javaScriptEnabled = true
        webConfiguration.websiteDataStore = .nonPersistent()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView?.allowsLinkPreview = false
        view = webView
        delegate?.collectThemAllSceneDidLoad()
    }

    // MARK: CollectThemAllScene

    private var delegate: CollectThemAllSceneDelegate?
    func setDelegate(_ delegate: CollectThemAllSceneDelegate) {
        self.delegate = delegate
    }

    func setShortCollectThemAllTitle(_ shortTitle: String) {
        tabBarItem.title = shortTitle
    }

    func setCollectThemAllTitle(_ title: String) {
        navigationItem.title = title
    }

    func loadGame(at urlRequest: URLRequest) {
        webView?.load(urlRequest)
    }

}

Add missing back/forward gesture in collect ‘em all

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

import UIKit
import WebKit

class CollectThemAllViewController: UIViewController, CollectThemAllScene {

    // MARK: Properties

    private var webView: WKWebView?

    // MARK: Actions

    @IBAction func refreshButtonTapped(_ sender: Any) {
        webView?.reload()
    }

    // MARK: Overrides

    override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.preferences.javaScriptEnabled = true
        webConfiguration.websiteDataStore = .nonPersistent()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView?.allowsLinkPreview = false
        webView?.allowsBackForwardNavigationGestures = true
        view = webView
        delegate?.collectThemAllSceneDidLoad()
    }

    // MARK: CollectThemAllScene

    private var delegate: CollectThemAllSceneDelegate?
    func setDelegate(_ delegate: CollectThemAllSceneDelegate) {
        self.delegate = delegate
    }

    func setShortCollectThemAllTitle(_ shortTitle: String) {
        tabBarItem.title = shortTitle
    }

    func setCollectThemAllTitle(_ title: String) {
        navigationItem.title = title
    }

    func loadGame(at urlRequest: URLRequest) {
        webView?.load(urlRequest)
    }

}


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

extension Expression where Recur: FixpointType {
	public static var Natural: Definition {
		return (
			symbol: "Natural",
			value: lambda(.BooleanType) { .If($0, .Variable("Natural"), .UnitType) },
			type: lambda(.BooleanType, const(.Type(0))))
	}

	public static var zero: Definition {
		return (
			symbol: "zero",
			value: .Annotation(.Product(.Boolean(false), .Unit), .Variable("Natural")),
			type: .Variable("Natural"))
	}

	public static var successor: Definition {
		return (
			symbol: "successor",
			value: lambda(.Variable("Natural")) { predecessor in .Annotation(.lambda(.Boolean(true), const(predecessor)), .Variable("Natural")) },
			type: lambda(.Variable("Natural"), const(.Variable("Natural"))))
	}

	public static var natural: Space {
		return defineSpace([
			Natural,
			zero,
			successor
		])
	}
}

import Prelude

Correct the definition of successor to construct a product.

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

extension Expression where Recur: FixpointType {
	public static var Natural: Definition {
		return (
			symbol: "Natural",
			value: lambda(.BooleanType) { .If($0, .Variable("Natural"), .UnitType) },
			type: lambda(.BooleanType, const(.Type(0))))
	}

	public static var zero: Definition {
		return (
			symbol: "zero",
			value: .Annotation(.Product(.Boolean(false), .Unit), .Variable("Natural")),
			type: .Variable("Natural"))
	}

	public static var successor: Definition {
		return (
			symbol: "successor",
			value: lambda(.Variable("Natural")) { predecessor in .Annotation(.Product(.Boolean(true), predecessor), .Variable("Natural")) },
			type: lambda(.Variable("Natural"), const(.Variable("Natural"))))
	}

	public static var natural: Space {
		return defineSpace([
			Natural,
			zero,
			successor
		])
	}
}

import Prelude


import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

        // Add the button to the screen
        self.addChild(self.playButton)

        // Set the background color
        self.backgroundColor = UIColor(hex: 0x809DFF)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch:AnyObject in touches{
            // Grab the touch location
            let location = touch.locationInNode(self)
            // Retrieve the sprite in that location
            // If the sprite at that location is matching play button, the do something!
            if( self.nodeAtPoint(location) == self.playButton){
                // Create a new PlayScene with the same size
                let playScene = PlayScene(size:self.size)
                let view = self.view as SKView
                // Ignore sibling order
                view.ignoresSiblingOrder = true

                // Scale mode for the new PlayScene
                scene.scaleMode = .ResizeFill

            }
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Set the size for the new scene

import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

        // Add the button to the screen
        self.addChild(self.playButton)

        // Set the background color
        self.backgroundColor = UIColor(hex: 0x809DFF)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch:AnyObject in touches{
            // Grab the touch location
            let location = touch.locationInNode(self)
            // Retrieve the sprite in that location
            // If the sprite at that location is matching play button, the do something!
            if( self.nodeAtPoint(location) == self.playButton){
                // Create a new PlayScene with the same size
                let playScene = PlayScene(size:self.size)
                let view = self.view as SKView
                // Ignore sibling order
                view.ignoresSiblingOrder = true

                // Scale mode for the new PlayScene
                scene.scaleMode = .ResizeFill
                // Set the scene size
                scene.size = self.view.bounds.size
            }
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}


extension String: Error {
  public func print(terminator: String = "") {
    Swift.print(self, terminator: terminator)
  }
}

extension Array {
  public mutating func transform(by transforming: (Element) throws -> Element) rethrows {
    for index in 0..<count {
      self[index] = try transforming(self[index])
    }
  }

  public mutating func transform<S: Sequence>(at indices: S, by transforming: (Element) throws -> Element) rethrows
  where Index == S.Iterator.Element {
    for index in indices {
      self[index] = try transforming(self[index])
    }
  }
}

Add extension for removing multiple indices

extension String: Error {
  public func print(terminator: String = "") {
    Swift.print(self, terminator: terminator)
  }
}

extension Array {
  public mutating func transform(by transforming: (Element) throws -> Element) rethrows {
    for index in 0..<count {
      self[index] = try transforming(self[index])
    }
  }

  public mutating func transform<S: Sequence>(at indices: S, by transforming: (Element) throws -> Element) rethrows
  where Index == S.Iterator.Element {
    for index in indices {
      self[index] = try transforming(self[index])
    }
  }

  public mutating func remove(at indices: [Index]) -> [Element] {
    var removed: [Element] = []
    for index in indices {
      removed.append(remove(at: index))
    }
    return removed
  }
}


//
//  Copyright (c) 2015 Itty Bitty Apps. All rights reserved.
//

import UIKit

final class HomeCell: BasicCell {
  @IBOutlet private(set) weak var iconImageView: UIImageView!

  override func awakeFromNib() {
    super.awakeFromNib()

    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
      self.backgroundView = UIView()
      self.selectedBackgroundView = UIView()
      self.selectedBackgroundView?.backgroundColor = UIColor.revertTintColor()
    }
  }
}

class BasicCell: UITableViewCell {
  @IBOutlet private(set) weak var titleLabel: UILabel!
  @IBOutlet private(set) weak var subtitleLabel: UILabel!

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

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applyDynamicType:", name:
      UIContentSizeCategoryDidChangeNotification, object: nil)
  }

  deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
  }

  func applyDynamicType(notification: NSNotification? = nil) {
    self.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
    self.subtitleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
  }
}

Make sure to initially apply the font-category after the IBOutlet have been connected

//
//  Copyright (c) 2015 Itty Bitty Apps. All rights reserved.
//

import UIKit

final class HomeCell: BasicCell {
  @IBOutlet private(set) weak var iconImageView: UIImageView!

  override func awakeFromNib() {
    super.awakeFromNib()

    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
      self.backgroundView = UIView()
      self.selectedBackgroundView = UIView()
      self.selectedBackgroundView?.backgroundColor = UIColor.revertTintColor()
    }
  }
}

class BasicCell: UITableViewCell {
  @IBOutlet private(set) weak var titleLabel: UILabel!
  @IBOutlet private(set) weak var subtitleLabel: UILabel!

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

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applyDynamicType:", name:
      UIContentSizeCategoryDidChangeNotification, object: nil)
  }

  deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
  }

  override func awakeFromNib() {
    super.awakeFromNib()

    self.applyDynamicType()
  }

  func applyDynamicType(notification: NSNotification? = nil) {
    self.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
    self.subtitleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
  }
}


import Foundation
import Firebase

final class Analytics
{
    //MARK: internal

    class func start()
    {
        FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.min)
        FirebaseApp.configure()
    }
}

Add manual screen tracking for analytics

import Foundation
import Firebase

final class Analytics
{
    //MARK: internal

    class func start()
    {
        FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.max)
        FirebaseApp.configure()
    }

    class func setScreenView(controller:UIViewController)
    {
        let controllerType:UIViewController.Type = type(of:controller)
        let controllerName:String = String(describing:controllerType)
        Firebase.Analytics.setScreenName(controllerName, screenClass:controllerName)
    }
}


import UIKit

class VSpinner:UIImageView
{
    private let kAnimationDuration:TimeInterval = 1

    init()
    {
        super.init(frame:CGRect.zero)

        let images:[UIImage] = [
            #imageLiteral(resourceName: "assetSpinner0"),
            #imageLiteral(resourceName: "assetSpinner1"),
            #imageLiteral(resourceName: "assetSpinner2"),
            #imageLiteral(resourceName: "assetSpinner3"),
            #imageLiteral(resourceName: "assetSpinner4"),
            #imageLiteral(resourceName: "assetSpinner5"),
            #imageLiteral(resourceName: "assetSpinner6"),
            #imageLiteral(resourceName: "assetSpinner7"),
            #imageLiteral(resourceName: "assetSpinner8")]

        isUserInteractionEnabled = false
        translatesAutoresizingMaskIntoConstraints = false
        clipsToBounds = true
        animationDuration = kAnimationDuration
        animationImages = images
        contentMode = UIViewContentMode.center
        startAnimating()
    }

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

Update view spinner with assets

import UIKit

class VSpinner:UIImageView
{
    private let kAnimationDuration:TimeInterval = 1.5

    init()
    {
        super.init(frame:CGRect.zero)

        let images:[UIImage] = [
            #imageLiteral(resourceName: "assetSpinner0"),
            #imageLiteral(resourceName: "assetSpinner1"),
            #imageLiteral(resourceName: "assetSpinner2"),
            #imageLiteral(resourceName: "assetSpinner3"),
            #imageLiteral(resourceName: "assetSpinner4"),
            #imageLiteral(resourceName: "assetSpinner5"),
            #imageLiteral(resourceName: "assetSpinner6"),
            #imageLiteral(resourceName: "assetSpinner7"),
            #imageLiteral(resourceName: "assetSpinner8"),
            #imageLiteral(resourceName: "assetSpinner9"),
            #imageLiteral(resourceName: "assetSpinner10"),
            #imageLiteral(resourceName: "assetSpinner11"),
            #imageLiteral(resourceName: "assetSpinner12"),
            #imageLiteral(resourceName: "assetSpinner13"),
            #imageLiteral(resourceName: "assetSpinner14"),
            #imageLiteral(resourceName: "assetSpinner15"),
            #imageLiteral(resourceName: "assetSpinner16"),
            #imageLiteral(resourceName: "assetSpinner17"),
            #imageLiteral(resourceName: "assetSpinner18")]

        isUserInteractionEnabled = false
        translatesAutoresizingMaskIntoConstraints = false
        clipsToBounds = true
        animationDuration = kAnimationDuration
        animationImages = images
        contentMode = UIViewContentMode.center
        startAnimating()
    }

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


//
//  ViewController.swift
//  Animations
//
//  Created by Alisa Mylnikova on 07/08/2018.
//  Copyright © 2018 Exyte. All rights reserved.
//

import UIKit

//func classFromString(_ className: String) -> AnyClass! {
//    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
//    return NSClassFromString("\(namespace).\(className)")!
//}

class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    fileprivate var viewControllers = [
        MaterialViewController(),
        TrajectoryViewController(),
        TimingViewController(),
        FocusViewController(),
        SecondaryViewController(),
        AnticipationViewController(),
        RhythmViewController(),
        OverlappingViewController()
    ]

    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewControllers.count
    }

    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "menu_cell")!
        cell.textLabel?.text = String(describing: type(of: viewControllers[indexPath.row]))
        return cell
    }

    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.navigationController?.pushViewController(viewControllers[indexPath.row], animated: true)
    }

}

Rename menu options for animations example

//
//  ViewController.swift
//  Animations
//
//  Created by Alisa Mylnikova on 07/08/2018.
//  Copyright © 2018 Exyte. All rights reserved.
//

import UIKit

class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    fileprivate var viewControllers = [
        MaterialViewController(),
        TrajectoryViewController(),
        TimingViewController(),
        FocusViewController(),
        SecondaryViewController(),
        AnticipationViewController(),
        RhythmViewController(),
        OverlappingViewController()
    ]

    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewControllers.count
    }

    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "menu_cell")!
        cell.textLabel?.text = String(describing: type(of: viewControllers[indexPath.row])).replacingOccurrences(of: "ViewController", with: "")
        return cell
    }

    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.navigationController?.pushViewController(viewControllers[indexPath.row], animated: true)
    }

}


import UIKit
import Foundation

public extension UIViewController {
    public static var topVisibleViewController: UIViewController? {
        if var tc = UIApplication.shared.keyWindow?.rootViewController {
            while let vc = tc.presentedViewController {
                tc = vc
            }
            return tc
        }
        return nil
    }

    public var topVisibleViewController: UIViewController {
        if let tc = UIViewController.topVisibleViewController {
            return tc
        }
        return self
    }
}

Add VC Extension for init from storyboard

import UIKit
import Foundation

public extension UIViewController {
    public static var topVisibleViewController: UIViewController? {
        if var tc = UIApplication.shared.keyWindow?.rootViewController {
            while let vc = tc.presentedViewController {
                tc = vc
            }
            return tc
        }
        return nil
    }

    public var topVisibleViewController: UIViewController {
        if let tc = UIViewController.topVisibleViewController {
            return tc
        }
        return self
    }

    public static func initFromStoryboard<T>(name: String, identifier: String) -> T {
        guard let vc = UIStoryboard(name: name, bundle: nil)
            .instantiateViewController(withIdentifier: identifier) as? T else {
                fatalError("\(identifier) could not be loaded from \(name) as \(T.self)")
        }

        return vc
    }
}


import UIKit
import Observable

class ViewController: UIViewController {

    private lazy var collectionView = CollectionView()
    private lazy var slider = Slider(frame: .zero)

    private var disposal = Disposal()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        view.addSubview(collectionView)
        view.addSubview(slider)

        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
            collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10),

            slider.topAnchor.constraint(equalTo: collectionView.bottomAnchor),
            slider.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            slider.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            slider.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            slider.heightAnchor.constraint(equalToConstant: 100)
            ])

        collectionView.scrollPercentage.observe { [weak self] percentage in
            guard let slider = self?.slider else { return }
            slider.value = percentage * slider.maximumValue
        }.add(to: &disposal)

        slider.position.observe { [weak self] position in
            guard let collectionView = self?.collectionView else { return }
            collectionView.contentOffset.x = position * collectionView.contentSize.width - (collectionView.frame.width * position)
        }.add(to: &disposal)
    }
}

Update examples with old value.

import UIKit
import Observable

class ViewController: UIViewController {

    private lazy var collectionView = CollectionView()
    private lazy var slider = Slider(frame: .zero)

    private var disposal = Disposal()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        view.addSubview(collectionView)
        view.addSubview(slider)

        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
            collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10),

            slider.topAnchor.constraint(equalTo: collectionView.bottomAnchor),
            slider.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            slider.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            slider.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            slider.heightAnchor.constraint(equalToConstant: 100)
            ])

        collectionView.scrollPercentage.observe { [weak self] percentage, oldValue in
            guard let slider = self?.slider else { return }
            slider.value = percentage * slider.maximumValue
        }.add(to: &disposal)

        slider.position.observe { [weak self] position, oldValue in
            guard let collectionView = self?.collectionView else { return }
            collectionView.contentOffset.x = position * collectionView.contentSize.width - (collectionView.frame.width * position)
        }.add(to: &disposal)
    }
}


//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}
  /*
internal extension Collection {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript (safe index: Index) -> Generator.Element? {
    let val = self[index];
    return self.indices ~= index ? self[index] : nil;

    return indices.contains(index) ? self[index] : nil
  }
}
*/

Add Enum (with RawValue) and string extension.

//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

internal extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable where RawValue == String {
  init?(raw: String?) {
    guard let string = raw else {
      return nil
    }
    self.init(rawValue:string)
  }
}
internal extension RawRepresentable {
  init(raw: RawValue?,  defaultValue:Self) {
    if let value = raw  {
      self = Self.init(rawValue:value) ?? defaultValue
    }
    self = defaultValue
  }
}


import Quick
import Nimble

import Dobby

class MockSpec: QuickSpec {
    override func spec() {
        var mock: Mock<Int>!

        beforeEach {
            mock = Mock<Int>()
            record(mock, 1)
            record(mock, 2)
            record(mock, 3)
        }

        describe("Recording an interaction") {
            it("should append to the mock's interactions") {
                expect(mock.interactions).to(equal([ 1, 2, 3 ]))
            }
        }

        describe("Verifying interactions") {
            it("should check in-order") {
                expect(verify(mock, [ 1, 3 ])).to(beTrue())
                expect(verify(mock, [ 3, 1 ])).to(beFalse())
            }
        }
    }
}

Test verification with no expected interaction

import Quick
import Nimble

import Dobby

class MockSpec: QuickSpec {
    override func spec() {
        var mock: Mock<Int>!

        beforeEach {
            mock = Mock<Int>()
            record(mock, 1)
            record(mock, 2)
            record(mock, 3)
        }

        describe("Recording an interaction") {
            it("should append to the mock's interactions") {
                expect(mock.interactions).to(equal([ 1, 2, 3 ]))
            }
        }

        describe("Verifying interactions") {
            it("should check in-order") {
                expect(verify(mock, [])).to(beTrue())
                expect(verify(mock, [ 1, 3 ])).to(beTrue())
                expect(verify(mock, [ 3, 1 ])).to(beFalse())
            }
        }
    }
}


////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

import XCTest
import RealmSwift
import Foundation

class ObjectSchemaInitializationTests: TestCase {
    func testAllValidTypes() {
    }

    func testInvalidObjects() {
    }

    func testPrimaryKey() {
    }

    func testIgnoredProperties() {
    }

    func testIndexedProperties() {
    }
}

Add tests for ignored properties

////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

import XCTest
import RealmSwift
import Foundation

class ObjectSchemaInitializationTests: TestCase {
    func testAllValidTypes() {
    }

    func testInvalidObjects() {
    }

    func testPrimaryKey() {
    }

    func testIgnoredProperties() {
        let schema = SwiftIgnoredPropertiesObject().objectSchema
        XCTAssertNil(schema["runtimeProperty"], "The object schema shouldn't contain ignored properties")
        XCTAssertNil(schema["runtimeDefaultProperty"], "The object schema shouldn't contain ignored properties")
        XCTAssertNil(schema["readOnlyProperty"], "The object schema shouldn't contain read-only properties")
    }

    func testIndexedProperties() {
    }
}


import SpeltKit
import Commandant
import Result

struct NewCommand: CommandProtocol {
    struct Options: OptionsProtocol {
        let path: String
        let force: Bool

        static func create(_ path: String) -> (Bool) -> Options {
            return { force in
                return Options(path: path.absoluteStandardizedPath, force: force);
            }
        }

        static func evaluate(_ m: CommandMode) -> Result<Options, CommandantError<SpeltError>> {
            return create
                <*> m <| Argument(defaultValue: nil, usage: "PATH (where project should be created)")
                <*> m <| Option(key: "force", defaultValue: false, usage: "Force creation even if PATH already exists")
        }
    }

    let verb = "new"
    let function = "Create scaffolding for a new site"

    func run(_ options: Options) -> Result<(), SpeltError> {
        guard let templatePath = Bundle(for: SiteServer.self).resourcePath?.stringByAppendingPathComponent("default-template") else {
            fatalError("Unable to locate template files")
        }

        do {
            print("Create project at path: \(options.path)")
            try SiteScaffolding(destinationPath: options.path, templatePath: templatePath).create(options.force)
        }
        catch {
            return Result.failure(SpeltError(underlyingError: error))
        }

        return Result.success()
    }
}

Use SpeltKit bundle ID in new command

import SpeltKit
import Commandant
import Result

struct NewCommand: CommandProtocol {
    struct Options: OptionsProtocol {
        let path: String
        let force: Bool

        static func create(_ path: String) -> (Bool) -> Options {
            return { force in
                return Options(path: path.absoluteStandardizedPath, force: force);
            }
        }

        static func evaluate(_ m: CommandMode) -> Result<Options, CommandantError<SpeltError>> {
            return create
                <*> m <| Argument(defaultValue: nil, usage: "PATH (where project should be created)")
                <*> m <| Option(key: "force", defaultValue: false, usage: "Force creation even if PATH already exists")
        }
    }

    let verb = "new"
    let function = "Create scaffolding for a new site"

    func run(_ options: Options) -> Result<(), SpeltError> {
        guard let templatePath = Bundle(identifier: SpeltKitBundleIdentifier)?.resourcePath?.stringByAppendingPathComponent("default-template") else {
            fatalError("Unable to locate template files")
        }

        do {
            print("Create project at path: \(options.path)")
            try SiteScaffolding(destinationPath: options.path, templatePath: templatePath).create(options.force)
        }
        catch {
            return Result.failure(SpeltError(underlyingError: error))
        }

        return Result.success()
    }
}


import Foundation

public class Promise<T> {
    fileprivate let lock = NSRecursiveLock()

    fileprivate var value: T?
    fileprivate var handlers: [(T) -> ()] = []

    public init(_ value: T) {
        self.value = value
    }

    public init(_ executor: (_ resolve: @escaping (Promise<T>) -> ()) -> ()) {
        executor(resolve)
    }

    fileprivate func resolve(_ promise: Promise<T>) {
        promise.reserve {
            self.lock.lock()
            if self.value == nil {
                self.value = $0

                for handler in self.handlers {
                    handler($0)
                }
                self.handlers.removeAll(keepingCapacity: false)
            }
            self.lock.unlock()
        }
    }

    fileprivate func reserve(_ handler: @escaping (T) -> ()) {
        lock.lock()
        if let value = self.value {
            handler(value)
        } else {
            handlers.append(handler)
        }
        lock.unlock()
    }

    public func map<U>(_ f: @escaping (T) -> U) -> Promise<U> {
        return flatMap { Promise<U>(f($0)) }
    }

    public func flatMap<U>(_ f: @escaping (T) -> Promise<U>) -> Promise<U> {
        return Promise<U> { resolve in self.reserve { resolve(f($0)) } }
    }
}

extension Promise : CustomStringConvertible {
    public var description: String {
        if let value = self.value {
            return "Promise(\(value))"
        } else {
            return "Promise"
        }
    }
}

Change unnecessary `fileprivate` to `private`

import Foundation

public class Promise<T> {
    private let lock = NSRecursiveLock()

    fileprivate var value: T?
    private var handlers: [(T) -> ()] = []

    public init(_ value: T) {
        self.value = value
    }

    public init(_ executor: (_ resolve: @escaping (Promise<T>) -> ()) -> ()) {
        executor(resolve)
    }

    private func resolve(_ promise: Promise<T>) {
        promise.reserve {
            self.lock.lock()
            if self.value == nil {
                self.value = $0

                for handler in self.handlers {
                    handler($0)
                }
                self.handlers.removeAll(keepingCapacity: false)
            }
            self.lock.unlock()
        }
    }

    private func reserve(_ handler: @escaping (T) -> ()) {
        lock.lock()
        if let value = self.value {
            handler(value)
        } else {
            handlers.append(handler)
        }
        lock.unlock()
    }

    public func map<U>(_ f: @escaping (T) -> U) -> Promise<U> {
        return flatMap { Promise<U>(f($0)) }
    }

    public func flatMap<U>(_ f: @escaping (T) -> Promise<U>) -> Promise<U> {
        return Promise<U> { resolve in self.reserve { resolve(f($0)) } }
    }
}

extension Promise : CustomStringConvertible {
    public var description: String {
        if let value = self.value {
            return "Promise(\(value))"
        } else {
            return "Promise"
        }
    }
}


public final class Faker {
  public var locale: String {
    didSet {
      if locale != oldValue {
        parser.locale = locale
      }
    }
  }

  public let address: Address
  public let app: App
  public let business: Business
  public let company: Company
  public let commerce: Commerce
  public let internet: Internet
  public let lorem: Lorem
  public let name: Name
  public let phoneNumber: PhoneNumber
  public let team: Team
  public let number: Number
  public let bank: Bank
  public let date: Date

  let parser: Parser

  // MARK: - Initialization

  public init(locale: String = Config.defaultLocale) {
    self.locale = locale
    parser = Parser(locale: self.locale)
    address = Address(parser: parser)
    app = App(parser: parser)
    business = Business(parser: parser)
    company = Company(parser: parser)
    commerce = Commerce(parser: parser)
    internet = Internet(parser: parser)
    lorem = Lorem(parser: parser)
    name = Name(parser: parser)
    phoneNumber = PhoneNumber(parser: parser)
    team = Team(parser: parser)
    number = Number()
    bank = Bank(parser: parser)
    date = Date()
  }
}

Add vehicle to generator to make is accessible

public final class Faker {
  public var locale: String {
    didSet {
      if locale != oldValue {
        parser.locale = locale
      }
    }
  }

  public let address: Address
  public let app: App
  public let business: Business
  public let company: Company
  public let commerce: Commerce
  public let internet: Internet
  public let lorem: Lorem
  public let name: Name
  public let phoneNumber: PhoneNumber
  public let team: Team
  public let number: Number
  public let bank: Bank
  public let date: Date
  public let vehicle: Vehicle

  let parser: Parser

  // MARK: - Initialization

  public init(locale: String = Config.defaultLocale) {
    self.locale = locale
    parser = Parser(locale: self.locale)
    address = Address(parser: parser)
    app = App(parser: parser)
    business = Business(parser: parser)
    company = Company(parser: parser)
    commerce = Commerce(parser: parser)
    internet = Internet(parser: parser)
    lorem = Lorem(parser: parser)
    name = Name(parser: parser)
    phoneNumber = PhoneNumber(parser: parser)
    team = Team(parser: parser)
    number = Number()
    bank = Bank(parser: parser)
    date = Date()
    vehicle = Vehicle(parser: parser)
  }
}


//
//  Stevia+Center.swift
//  Stevia
//
//  Created by Sacha Durand Saint Omer on 10/02/16.
//  Copyright © 2016 Sacha Durand Saint Omer. All rights reserved.
//

import UIKit

public extension UIView {

    public func centerInContainer() {
        if let spv = superview {
            alignCenter(self, with: spv)
        }
    }

    public func centerHorizontallyInContainer() {
        if let spv = superview {
            alignVertically([self,spv])
        }
    }

    public func centerVerticallyInContainer() {
        if let spv = superview {
            alignHorizontally([self,spv])
        }
    }
}

Make center methods return the view

//
//  Stevia+Center.swift
//  Stevia
//
//  Created by Sacha Durand Saint Omer on 10/02/16.
//  Copyright © 2016 Sacha Durand Saint Omer. All rights reserved.
//

import UIKit

public extension UIView {

    public func centerInContainer() -> UIView  {
        if let spv = superview {
            alignCenter(self, with: spv)
        }
        return self
    }

    public func centerHorizontally() -> UIView {
        if let spv = superview {
            alignVertically([self,spv])
        }
        return self
    }

    public func centerVertically() -> UIView {
        if let spv = superview {
            alignHorizontally([self,spv])
        }
        return self
    }
}


import UIKit

final class VCreateTravelListCell:UICollectionViewCell
{
    override init(frame:CGRect)
    {
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear
    }

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

    //MARK: internal

    func config(model:MCreateTravelProtocol)
    {

    }
}

Add hover to create-travel list

import UIKit

final class VCreateTravelListCell:UICollectionViewCell
{
    private weak var imageView:UIImageView!

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

        let imageView:UIImageView = UIImageView()
        imageView.isUserInteractionEnabled = false
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = UIViewContentMode.center
        imageView.clipsToBounds = true
        self.imageView = imageView

        addSubview(imageView)

        NSLayoutConstraint.equals(
            view:imageView,
            toView:self)
    }

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

    override var isSelected:Bool
    {
        didSet
        {
            hover()
        }
    }

    override var isHighlighted:Bool
    {
        didSet
        {
            hover()
        }
    }

    //MARK: private

    private func hover()
    {
        if isSelected || isHighlighted
        {
            imageView.tintColor = UIColor.white
        }
        else
        {
            imageView.tintColor = UIColor.colourBackgroundDark
        }
    }

    //MARK: internal

    func config(model:MCreateTravelProtocol)
    {
        imageView.image = model.icon.withRenderingMode(
            UIImageRenderingMode.alwaysTemplate)
        hover()
    }
}


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SteamPress",
    products: [
        .library(name: "SteamPress", targets: ["SteamPress"]),
    ],
    dependencies: [
    	.package(url: "https://github.com/vapor/vapor.git", from: "2.2.0"),
        .package(url: "https://github.com/scinfu/SwiftSoup.git", from: "1.4.0"),
        .package(url: "https://github.com/vapor-community/markdown-provider.git", from: "1.0.0"),
        .package(url: "https://github.com/vapor/leaf-provider.git", from: "1.1.0"),
        .package(url: "https://github.com/vapor/fluent-provider.git", from: "1.1.0"),
        .package(url: "https://github.com/vapor/auth-provider.git", from: "1.2.0"),
        .package(url: "https://github.com/vapor/validation.git", from: "1.0.1"),
    ],
    targets: [
        .target(name: "SteamPress", dependencies: ["Vapor", "SwiftSoup", "MarkdownProvider", "LeafProvider",
                                                   "FluentProvider", "AuthProvider", "Validation"]),
        .testTarget(name: "SteamPressTests", dependencies: ["SteamPress"]),
    ]
)

Bring in SwiftSoup with version that works with Swift 4

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SteamPress",
    products: [
        .library(name: "SteamPress", targets: ["SteamPress"]),
    ],
    dependencies: [
    	.package(url: "https://github.com/vapor/vapor.git", from: "2.2.0"),
        .package(url: "https://github.com/scinfu/SwiftSoup.git", from: "1.5.1"),
        .package(url: "https://github.com/vapor-community/markdown-provider.git", from: "1.0.0"),
        .package(url: "https://github.com/vapor/leaf-provider.git", from: "1.1.0"),
        .package(url: "https://github.com/vapor/fluent-provider.git", from: "1.1.0"),
        .package(url: "https://github.com/vapor/auth-provider.git", from: "1.2.0"),
        .package(url: "https://github.com/vapor/validation.git", from: "1.0.1"),
    ],
    targets: [
        .target(name: "SteamPress", dependencies: ["Vapor", "SwiftSoup", "MarkdownProvider", "LeafProvider",
                                                   "FluentProvider", "AuthProvider", "Validation"]),
        .testTarget(name: "SteamPressTests", dependencies: ["SteamPress"]),
    ]
)


//
//  DiskCache.swift
//  ImageCache
//
//  Created by Julian Grosshauser on 27/06/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

/**
Caches data on disk asynchronously
*/
public class DiskCache {

    //MARK: Properties

    /**
    Data will be cached at this path, e.g. `Library/Caches/com.domain.App.DiskCache`
    */
    public let path: String

    //MARK: Initialization

    public init(identifier: String) {
        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let cachePath = paths.first!

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

    public convenience init() {
        self.init(identifier: "DiskCache")
    }
}

Use nil coalescing operator instead of `if let ..`

//
//  DiskCache.swift
//  ImageCache
//
//  Created by Julian Grosshauser on 27/06/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

/**
Caches data on disk asynchronously
*/
public class DiskCache {

    //MARK: Properties

    /**
    Data will be cached at this path, e.g. `Library/Caches/com.domain.App.DiskCache`
    */
    public let path: String

    //MARK: Initialization

    public init(identifier: String) {
        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let cachePath = paths.first!

        // use "DiskCache" as `bundleIdentifier` iff `mainBundle()`s `bundleIdentifier` is `nil`
        let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier ?? "DiskCache"

        path = cachePath.stringByAppendingPathComponent("\(bundleIdentifier).\(identifier)")
    }

    public convenience init() {
        self.init(identifier: "DiskCache")
    }
}


import Foundation

let RequiredXcodeVersion = "Xcode 6.3"

func isRequiredXcodeIsInstalled() -> Bool {
    return currentXcodeVersion() == RequiredXcodeVersion
}

func currentXcodeVersion() -> String? {
    return run("xcodebuild -version").first
}

Fix Xcode version check to detect versions higher than 6.3

import Foundation

let RequiredXcodeVersion = "Xcode 6.3"

func isRequiredXcodeIsInstalled() -> Bool {

    if let comparationResult = currentXcodeVersion()?.localizedCaseInsensitiveCompare(RequiredXcodeVersion) {
        switch comparationResult {
        case .OrderedDescending, .OrderedSame: return true
        default: ()
        }
    }
    return false
}

func currentXcodeVersion() -> String? {
    return run("xcodebuild -version").first
}


//  Copyright © 2016 Compass. All rights reserved.

#if os(iOS) || os(tvOS)
import UIKit
#else
import Foundation
#endif

extension UIViewController {
    public var disposer: Disposer {
        return view.disposer
    }
}

Revert "Using VC main view disposer as VC Disposer"

//  Copyright © 2016 Compass. All rights reserved.

#if os(iOS) || os(tvOS)
import UIKit
#else
import Foundation
#endif

extension UIViewController {
    private static var disposerKey = "com.compass.Snail.UIViewController.disposer"

    public var disposer: Disposer {
        if let disposer = objc_getAssociatedObject(self, &UIViewController.disposerKey) as? Disposer {
            return disposer
        }
        let disposer = Disposer()
        objc_setAssociatedObject(self, &UIViewController.disposerKey, disposer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        return disposer
    }
}


//: Playground - noun: a place where people can play

import DBNetworkStack
import PlaygroundSupport

//Setup Playground environment
PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

//Prepare NetworkAccess & NetworkService
let networkAccess = URLSession(configuration: .default)
let networkService = NetworkService(networkAccess: networkAccess)

struct IPOrigin {
    let ipAdress: String
}

extension IPOrigin: JSONMappable {
    init(object: Dictionary<String, Any>) throws {
        guard let ipAdress = object["origin"] as? String else {
            throw DBNetworkStackError.serializationError(description: "", data: nil)
        }
        self.ipAdress = ipAdress
    }
}

let url: URL! = URL(string: "https://www.httpbin.org")
let request = URLRequest(path: "ip", baseURL: url)
let resource = JSONResource<IPOrigin>(request: request)

networkService.request(resource, onCompletion: { origin in
    print(origin)
    }, onError: { error in
        print(error)
})

Use Codeable Ressource instead of JSONRessource

//: Playground - noun: a place where people can play

import DBNetworkStack
import PlaygroundSupport

//Setup Playground environment
PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

//Prepare NetworkAccess & NetworkService
let networkAccess = URLSession(configuration: .default)
let networkService = NetworkService(networkAccess: networkAccess)

struct IPOrigin: Codable {
    let origin: String
}

let url: URL! = URL(string: "https://www.httpbin.org")
let request = URLRequest(path: "ip", baseURL: url)

let resource = Resource<IPOrigin>(request: request, decoder: JSONDecoder())

networkService.request(resource, onCompletion: { origin in
    print(origin)
    }, onError: { error in
        print(error)
})


//
//  ViewController.swift
//  Landscape2dgen
//
//  Created by Toni Jovanoski on 2/28/17.
//  Copyright © 2017 Antonie Jovanoski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Add mid point displacement function

//
//  ViewController.swift
//  Landscape2dgen
//
//  Created by Toni Jovanoski on 2/28/17.
//  Copyright © 2017 Antonie Jovanoski. All rights reserved.
//

import UIKit

struct Point {
    let x: Float
    let y: Float
}

extension Array {
    func sample() -> Element {
        let index = Int(arc4random_uniform(UInt32(self.count)))

        return self[index]
    }
}

func midPointDisplacement(start: Point, end: Point, roughtness: Float, verticalDisplacement: Float = 0.0, numOfIterations: Int = 16) -> [Point] {
    var vd = verticalDisplacement

    if verticalDisplacement == 0.0 {
        vd = (start.y + end.y) / 2.0
    }

    var points = [start, end]

    var iteration = 1

    while iteration <= numOfIterations {
        let p = points

        for i in 0..<p.count - 1 {
            let midpoint = Point(x: (p[i].x + p[i+1].x) / 2.0,
                                 y: (p[i].y + p[i+1].y) / 2.0)

            let dispMidpoint = Point(x: midpoint.x,
                                     y: midpoint.y + [-vd, vd].sample())

            points.insert(dispMidpoint, at: 2 * i + 1)

        }

        vd *= pow(2, -roughtness)

        iteration += 1
    }
    return points
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


//
//  SideBarTableViewCell.swift
//  Tempo
//
//  Created by Annie Cheng on 4/22/15.
//  Copyright (c) 2015 Lucas Derraugh. All rights reserved.
//

import UIKit

class SideBarTableViewCell: UITableViewCell {

    @IBOutlet weak var categorySymbol: UIImageView!
    @IBOutlet weak var categoryLabel: UILabel!
    @IBOutlet weak var selectedCellView: UIView!
    @IBOutlet weak var customSeparator: UIView!

    override func didMoveToSuperview() {
        selectionStyle = .none
        backgroundColor = .tempoDarkGray
        customSeparator.backgroundColor = .separatorGray
        selectedCellView.frame = CGRect(x: 0, y: 0, width: 8, height: frame.height + 10)
        selectedCellView.backgroundColor = .tempoRed
    }

    // Custom selected cell view
    override func setSelected(_ selected: Bool, animated: Bool) {
		contentView.backgroundColor = selected ? .tempoLightGray : .clear
		selectedCellView.isHidden = !selected
    }

}

Change colors in Side Bar Cells

//
//  SideBarTableViewCell.swift
//  Tempo
//
//  Created by Annie Cheng on 4/22/15.
//  Copyright (c) 2015 Lucas Derraugh. All rights reserved.
//

import UIKit

class SideBarTableViewCell: UITableViewCell {

    @IBOutlet weak var categorySymbol: UIImageView!
    @IBOutlet weak var categoryLabel: UILabel!
    @IBOutlet weak var selectedCellView: UIView!
    @IBOutlet weak var customSeparator: UIView!

    override func didMoveToSuperview() {
        selectionStyle = .none
        backgroundColor = .readCellColor
        customSeparator.backgroundColor = .unreadCellColor
        selectedCellView.frame = CGRect(x: 0, y: 0, width: 8, height: frame.height + 10)
        selectedCellView.backgroundColor = .tempoRed
    }

    // Custom selected cell view
    override func setSelected(_ selected: Bool, animated: Bool) {
		contentView.backgroundColor = selected ? .unreadCellColor : .clear
		selectedCellView.isHidden = !selected
    }

}