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

import Foundation
import os
import OpenTelemetryApi
import OpenTelemetrySdk

/// A span processor that decorates spans with the origin attribute
@available(macOS 10.14, *)
public class SignPostIntegration: SpanProcessor {
    public let isStartRequired = true
    public let isEndRequired = true
    public let osLog = OSLog(subsystem: "OpenTelemetry", category: .pointsOfInterest)

    public init() {}

    public func onStart(parentContext: SpanContext?, span: ReadableSpan) {
        let signpostID = OSSignpostID(log: osLog, object: self)
        os_signpost(.begin, log: osLog, name: "Span", signpostID: signpostID, "%{public}@", span.name)
    }

    public func onEnd(span: ReadableSpan) {
        let signpostID = OSSignpostID(log: osLog, object: self)
        os_signpost(.end, log: osLog, name: "Span", signpostID: signpostID)
    }

    public func shutdown() {}
    public func forceFlush() {}
}

Replace Copyright header to a much more reduced model

/*
 * Copyright The OpenTelemetry Authors
 * SPDX-License-Identifier: Apache-2.0
 */

import Foundation
import os
import OpenTelemetryApi
import OpenTelemetrySdk

/// A span processor that decorates spans with the origin attribute
@available(macOS 10.14, *)
public class SignPostIntegration: SpanProcessor {
    public let isStartRequired = true
    public let isEndRequired = true
    public let osLog = OSLog(subsystem: "OpenTelemetry", category: .pointsOfInterest)

    public init() {}

    public func onStart(parentContext: SpanContext?, span: ReadableSpan) {
        let signpostID = OSSignpostID(log: osLog, object: self)
        os_signpost(.begin, log: osLog, name: "Span", signpostID: signpostID, "%{public}@", span.name)
    }

    public func onEnd(span: ReadableSpan) {
        let signpostID = OSSignpostID(log: osLog, object: self)
        os_signpost(.end, log: osLog, name: "Span", signpostID: signpostID)
    }

    public func shutdown() {}
    public func forceFlush() {}
}


//
//  AppDelegate.swift
//  Yomu
//
//  Created by Sendy Halim on 6/6/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var splitView: NSSplitView!

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

    let mangaViewController = MangaCollectionViewController(
      nibName: "MangaCollectionView",
      bundle: nil
    )!

    splitView.addSubview(mangaViewController.view)
  }

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

}

Add manga collection view to the left view

//
//  AppDelegate.swift
//  Yomu
//
//  Created by Sendy Halim on 6/6/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var splitView: NSSplitView!

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

    let mangaViewController = MangaCollectionViewController(
      nibName: "MangaCollectionView",
      bundle: nil
    )!

    splitView.subviews.first!.addSubview(mangaViewController.view)
  }

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

}


// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk -abi
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable-abi.json -input-paths %t.tmp/current-stdlib.json -abi -o %t.tmp/changes.txt
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-abi.swift.expected -o - | sed '/^\s*$/d' > %t.tmp/stability-stdlib-abi.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-abi.swift.expected %t.tmp/changes.txt.tmp

Change ABI checker expected file, allowing us to group entries by change, avoiding merge conflicts

// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk -abi
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable-abi.json -input-paths %t.tmp/current-stdlib.json -abi -o %t.tmp/changes.txt
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-abi.swift.expected -o - | sed '/^\s*$/d' | sort > %t.tmp/stability-stdlib-abi.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' | sort > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-abi.swift.expected %t.tmp/changes.txt.tmp


//
//  WelcomeViewController.swift
//  Darts301
//
//  Created by Greg Haines on 3/4/17.
//  Copyright © 2017 Aly & Friends. All rights reserved.
//

import UIKit

class WelcomeViewController : UIViewController {

    @IBOutlet weak var rulesButton: UIButton!
    @IBOutlet weak var startButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        startButton.layer.cornerRadius = 8.0
        rulesButton.layer.cornerRadius = 8.0
        rulesButton.layer.borderColor = UIColor.white.cgColor
        rulesButton.layer.borderWidth = 2.0
        Utils.addShadow(to: startButton)

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [
            Colors.player1Color.cgColor,
            UIColor(red:0.498, green:0.710, blue:0.702, alpha: 1).cgColor,
            Colors.player2Color.cgColor
        ]
        view.layer.insertSublayer(gradientLayer, at: 0)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

Update welcome gradient to better match mocks

//
//  WelcomeViewController.swift
//  Darts301
//
//  Created by Greg Haines on 3/4/17.
//  Copyright © 2017 Aly & Friends. All rights reserved.
//

import UIKit

class WelcomeViewController : UIViewController {

    @IBOutlet weak var rulesButton: UIButton!
    @IBOutlet weak var startButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        startButton.layer.cornerRadius = 8.0
        rulesButton.layer.cornerRadius = 8.0
        rulesButton.layer.borderColor = UIColor.white.cgColor
        rulesButton.layer.borderWidth = 2.0
        Utils.addShadow(to: startButton)

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [
            Colors.player1Color.cgColor,
            UIColor(red:0.451, green:0.686, blue:0.729, alpha: 1).cgColor,
            UIColor(red:0.659, green:0.784, blue:0.608, alpha: 1).cgColor,
            Colors.player2Color.cgColor
        ]
        view.layer.insertSublayer(gradientLayer, at: 0)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}


//
//  AboutViewController.swift
//  TrolleyTracker
//
//  Created by Austin Younts on 10/28/15.
//  Copyright © 2015 Code For Greenville. All rights reserved.
//

import UIKit

class AboutViewController: UIViewController {

    private let textView: UITextView = {
        let tv = UITextView().useAutolayout()
        tv.text = LS.openSourceTitle
        tv.font = .systemFont(ofSize: 17)
        tv.dataDetectorTypes = [.link]
        tv.tintColor = .ttAlternateTintColor()
        tv.backgroundColor = .clear
        return tv
    }()

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

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.navigationBar.barStyle = .blackTranslucent
        view.backgroundColor = .ttLightGray()

        view.addSubview(textView)
        textView.edgeAnchors == edgeAnchors + 20
    }

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

        navigationController?.setNavigationBarHidden(false, animated: true)
    }
}

Disable editing on About screen text view

//
//  AboutViewController.swift
//  TrolleyTracker
//
//  Created by Austin Younts on 10/28/15.
//  Copyright © 2015 Code For Greenville. All rights reserved.
//

import UIKit

class AboutViewController: UIViewController {

    private let textView: UITextView = {
        let tv = UITextView().useAutolayout()
        tv.font = .systemFont(ofSize: 17)
        tv.tintColor = .ttAlternateTintColor()
        tv.backgroundColor = .clear
        tv.isEditable = false
        tv.isSelectable = true
        tv.dataDetectorTypes = [.link]
        return tv
    }()

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

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.navigationBar.barStyle = .blackTranslucent
        view.backgroundColor = .ttLightGray()

        view.addSubview(textView)
        textView.edgeAnchors == edgeAnchors + 20

        textView.text = LS.openSourceTitle
    }

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

        navigationController?.setNavigationBarHidden(false, animated: true)
    }
}


//
//  SectionModelTestCase.swift
//  DTModelStorageTests
//
//  Created by Denys Telezhkin on 10.07.15.
//  Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//

import UIKit
import XCTest
import DTModelStorage

class SectionModelTestCase: XCTestCase {

    var section: SectionModel!

    override func setUp() {
        super.setUp()
        section = SectionModel()
    }

    func testItemsOfTypeWorks()
    {
        section.items = [1, 2, 3]

        XCTAssertEqual(section.items(ofType: Int.self), [1, 2, 3])
        XCTAssertEqual(section.item(at: 2) as? Int, 3)
        XCTAssertNil(section.item(at: 3))
    }
}

Add tests for creating SectionModel with items.

//
//  SectionModelTestCase.swift
//  DTModelStorageTests
//
//  Created by Denys Telezhkin on 10.07.15.
//  Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//

import UIKit
import XCTest
import DTModelStorage

class SectionModelTestCase: XCTestCase {

    var section: SectionModel!

    override func setUp() {
        super.setUp()
        section = SectionModel()
    }

    func testItemsOfTypeWorks()
    {
        section.items = [1, 2, 3]

        XCTAssertEqual(section.items(ofType: Int.self), [1, 2, 3])
        XCTAssertEqual(section.item(at: 2) as? Int, 3)
        XCTAssertNil(section.item(at: 3))
    }

    func testCreatingSectionWithItemsWorks() {
        let section = SectionModel(items: [1,2,3])
        XCTAssertEqual(section.numberOfItems, 3)
    }

    func testExplicitlySetSectionItemsCreateSectionModel() {
        let items: [Int] = [1,2,3]
        let section = SectionModel(items: items)

        XCTAssertEqual(section.numberOfItems, 3)
    }
}


//
//  ViewController.swift
//  SwiftChan
//
//  Created by Wilhelmina Drengwitz on 09/01/2015.
//  Copyright (c) 2015 Wilhelmina Drengwitz. All rights reserved.
//

import UIKit
import SwiftChan

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
		let app = <-applicationCh

		ASyncRecv { (name) in
			println(name)
		} <- applicationNameCh
    }

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

}

Change to print from println for swift 2

//
//  ViewController.swift
//  SwiftChan
//
//  Created by Wilhelmina Drengwitz on 09/01/2015.
//  Copyright (c) 2015 Wilhelmina Drengwitz. All rights reserved.
//

import UIKit
import SwiftChan

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
		let app = <-applicationCh

		ASyncRecv { (name) in
			print(name)
		} <- applicationNameCh
    }

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

}


//
//  SECUtilities.swift
//  SwiftyEcharts
//
//  Created by Pluto-Y on 10/01/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Foundation

// 自定义输出的方法，保证在打包Release版本的时候不会有输出信息
func printInfo(object: Any) {
    #if DEBUG
//        Swift.print(object)
    #endif
}

// 自定义错误输出的方法，保证不管是Debug还是Release版本都会输出信息
func printError(object: Any) {
    Swift.print(object)
}

Add log prefix and warning log method

//
//  SECUtilities.swift
//  SwiftyEcharts
//
//  Created by Pluto-Y on 10/01/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Foundation

// 自定义输出的方法，保证在打包Release版本的时候不会有输出信息
func printInfo(object: Any) {
    #if DEBUG
//        Swift.print(object)
    #endif
}

// 自定义错误输出的方法，保证不管是Debug还是Release版本都会输出信息
func printError(object: Any) {
    Swift.print("Error: \(object)")
}

// 自定义警告输出的方法，保证不管是Debug还是Release版本都会输出信息
func printWarning(object: Any) {
    Swift.print("Warning: \(object)")
}


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

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var image: UIImage
    public var highlightedImage: UIImage?

    public var backgroundColor = UIColor(red: 50.0 / 255.0, green: 49.0 / 255.0, blue: 73.0 / 255.0, alpha: 1.0)
    public var highlightedBackgroundColor = UIColor(red: 1.0, green: 61.0 / 255.0, blue: 130.0 / 255.0, alpha: 1.0)

    public var shadowColor = UIColor(white: 0.3, alpha: 0.3)

    // MARK: - Init
    public init(image: UIImage, highlightedImage: UIImage? = nil) {
        self.image = image
        self.highlightedImage = highlightedImage
    }
}

Update default shadow color for menu cells

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

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var image: UIImage
    public var highlightedImage: UIImage?

    public var backgroundColor = UIColor(red: 50.0 / 255.0, green: 49.0 / 255.0, blue: 73.0 / 255.0, alpha: 1.0)
    public var highlightedBackgroundColor = UIColor(red: 1.0, green: 61.0 / 255.0, blue: 130.0 / 255.0, alpha: 1.0)

    public var shadowColor = UIColor(white: 0.1, alpha: 0.3)

    // MARK: - Init
    public init(image: UIImage, highlightedImage: UIImage? = nil) {
        self.image = image
        self.highlightedImage = highlightedImage
    }
}


import Vapor

/// A value that can one of two types
public enum Either<L, R> {
    case left(L)
    case right(R)
}

extension Either: ResponseEncodable where L: ResponseEncodable, R: ResponseEncodable {
    /// See `ResponseEncodable.encode`
    public func encode(for req: Request) throws -> Future<Response> {
        switch self {
        case .left(let left): return try left.encode(for: req)
        case .right(let right): return try right.encode(for: req)
        }
    }
}

extension Future {
    /// Transforms a `Future` into one that can be either the value or an error of a given type.
    ///
    /// - Parameter type: The `Error` type to be promoted.
    /// - Returns: A `Future` that yields either a value or an error.
    public func promoteErrors<E: Error>(ofType type: E.Type = E.self) -> Future<Either<T, E>> {
        return map(Either.left)
            .catchMap {
                guard let error = $0 as? E else {
                    throw $0
                }
                return .right(error)
            }
    }
}

extension Either: Equatable where L: Equatable, R: Equatable {}

Add implementation for swift < 4.2

import Vapor

/// A value that can one of two types
public enum Either<L, R> {
    case left(L)
    case right(R)
}

extension Either: ResponseEncodable where L: ResponseEncodable, R: ResponseEncodable {
    /// See `ResponseEncodable.encode`
    public func encode(for req: Request) throws -> Future<Response> {
        switch self {
        case .left(let left): return try left.encode(for: req)
        case .right(let right): return try right.encode(for: req)
        }
    }
}

extension Future {
    /// Transforms a `Future` into one that can be either the value or an error of a given type.
    ///
    /// - Parameter type: The `Error` type to be promoted.
    /// - Returns: A `Future` that yields either a value or an error.
    public func promoteErrors<E: Error>(ofType type: E.Type = E.self) -> Future<Either<T, E>> {
        return map(Either.left)
            .catchMap {
                guard let error = $0 as? E else {
                    throw $0
                }
                return .right(error)
            }
    }
}

extension Either: Equatable where L: Equatable, R: Equatable {
    #if swift(>=4.2)
        // automatically synthesized in swift 4.2
    #else
    public static func == (lhs: Either<L, R>, rhs: Either<L, R>) -> Bool {
        switch (lhs, rhs) {
        case (.left(let lhs), .left(let rhs)) where lhs == rhs:
            return true
        case (.right(let lhs), .right(let rhs)) where lhs == rhs:
            return true
        default:
            return false
        }
    }
    #endif
}


// Regression test for optimizations that might incorrectly execute function
// on wrong process.
// This test updated for merged engine/server

// Check that worker task doesn't run twice in same context
@dispatch=WORKER
(int o) worker_task (int i) "turbine" "0.0.1" [
  "set <<o>> <<i>>; if { $turbine::mode != \"WORKER\" } { error $turbine::mode }; if [ info exists __ranhere ] { error \"Already ran here \" } ; set __ranhere 1"
];

@dispatch=CONTROL
(int o) control_task (int i) "turbine" "0.0.1" [
  "set <<o>> <<i>>; if { $turbine::mode != \"WORKER\" } { error $turbine::mode }"
];

import assert;

main {

  // Check that optimizer doesn't pull up worker task into control context
  int x = worker_task(1);

  // Check that optimizer doesn't pull up control task into worker context
  int y = control_task(x);

  assertEqual(y, 1, "y in main");

  // Check that same holds after inlining
  f(2);
}

f (int i) {
  int x = worker_task(i);
  int y = control_task(x);

  assertEqual(y, 2, "y in f");
}

Update test to use correct mode name

// Regression test for optimizations that might incorrectly execute function
// on wrong process.
// This test updated for merged engine/server

// Check that worker task doesn't run twice in same context
@dispatch=WORKER
(int o) worker_task (int i) "turbine" "0.0.1" [
  "set <<o>> <<i>>; if { $turbine::mode != \"WORK\" } { error $turbine::mode }; if [ info exists __ranhere ] { error \"Already ran here \" } ; set __ranhere 1"
];

@dispatch=CONTROL
(int o) control_task (int i) "turbine" "0.0.1" [
  "set <<o>> <<i>>; if { $turbine::mode != \"WORK\" } { error $turbine::mode }"
];

import assert;

main {

  // Check that optimizer doesn't pull up worker task into control context
  int x = worker_task(1);

  // Check that optimizer doesn't pull up control task into worker context
  int y = control_task(x);

  assertEqual(y, 1, "y in main");

  // Check that same holds after inlining
  f(2);
}

f (int i) {
  int x = worker_task(i);
  int y = control_task(x);

  assertEqual(y, 2, "y in f");
}


//___FILEHEADER___

struct ___VARIABLE_productName:identifier___Effect: ___VARIABLE_productName:identifier___Effectable {
    let model: ___VARIABLE_productName:identifier___Mutable
}

extension ___VARIABLE_productName:identifier___Effect {
    func fetch() async {
        let response = ___VARIABLE_productName:identifier___API.FetchResponse(message: "Hello, world!")
        await model.update(for: response)
    }
}

Fix model retain cycle in template

//___FILEHEADER___

struct ___VARIABLE_productName:identifier___Effect: ___VARIABLE_productName:identifier___Effectable {
    weak var model: ___VARIABLE_productName:identifier___Mutable?
}

extension ___VARIABLE_productName:identifier___Effect {
    func fetch() async {
        let response = ___VARIABLE_productName:identifier___API.FetchResponse(message: "Hello, world!")
        await model?.update(for: response)
    }
}


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

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var name: String?

    public var image: UIImage
    public var highlightedImage: UIImage?

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

Update default values for Menu Item

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

import Foundation
import UIKit.UIImage

public struct MenuItem {
    public var name: String?

    public var image: UIImage
    public var highlightedImage: UIImage?

    public var backgroundColor = UIColor(red: 50.0 / 255.0, green: 49.0 / 255.0, blue: 73.0 / 255.0, alpha: 1.0)
    public var highlightedBackgroundColor = UIColor(red: 1.0, green: 61.0 / 255.0, blue: 130.0 / 255.0, alpha: 1.0)

    public var shadowColor = UIColor(red: 41.0 / 255.0, green: 44.0 / 255.0, blue: 69.0 / 255.0, alpha: 1.0)
}


//
//  Response+ModelMapper.swift
//  Pods
//
//  Created by sunshinejr on 02.02.2016.
//  Copyright © 2016 sunshinejr. All rights reserved.
//

import Foundation
import Moya
import Mapper

public extension Response {

    /// Parse json (in ModelMapper it should be NSDictionary) to an object
    public func mapObject<T: Mappable>() throws -> T {
        guard let jsonDictionary = try mapJSON() as? NSDictionary, object = T.from(jsonDictionary) else {
            throw Error.JSONMapping(self)
        }
        return object
    }

    public func mapObject<T: Mappable>(withKeyPath keyPath: String) throws -> T {
        guard let jsonDictionary = try mapJSON() as? NSDictionary,
            let objectDictionary = jsonDictionary.valueForKeyPath(keyPath) as? NSDictionary,
            let object = T.from(objectDictionary) else {
                throw Error.JSONMapping(self)
        }

        return object
    }

    /// Since 1.0.3 version of ModelMapper is not out in cocoapods,
    /// we have to manually parse arrays
    public func mapArray<T: Mappable>() throws -> [T] {
        guard let jsonArray = try mapJSON() as? NSArray else {
            throw Error.JSONMapping(self)
        }

        var returnArray = [T]()
        for dict in jsonArray {
            if let dict = dict as? NSDictionary, object = T.from(dict) {
                returnArray.append(object)
            }
        }
        return returnArray
    }
}

Use Mappers native map function for array

//
//  Response+ModelMapper.swift
//  Pods
//
//  Created by sunshinejr on 02.02.2016.
//  Copyright © 2016 sunshinejr. All rights reserved.
//

import Foundation
import Moya
import Mapper

public extension Response {

    public func mapObject<T: Mappable>() throws -> T {
        guard let jsonDictionary = try mapJSON() as? NSDictionary, object = T.from(jsonDictionary) else {
            throw Error.JSONMapping(self)
        }
        return object
    }

    public func mapObject<T: Mappable>(withKeyPath keyPath: String) throws -> T {
        guard let jsonDictionary = try mapJSON() as? NSDictionary,
            let objectDictionary = jsonDictionary.valueForKeyPath(keyPath) as? NSDictionary,
            let object = T.from(objectDictionary) else {
                throw Error.JSONMapping(self)
        }

        return object
    }

    public func mapArray<T: Mappable>() throws -> [T] {
        guard let jsonArray = try mapJSON() as? NSArray, object = T.from(jsonArray) else {
            throw Error.JSONMapping(self)
        }
        return object
    }
}


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

import PackageDescription

let package = Package(
    name: "ViewInspector",
    platforms: [
        .macOS(.v10_15), .iOS(.v13), .tvOS(.v9), .watchOS(.v3)
    ],
    products: [
        .library(
            name: "ViewInspector", targets: ["ViewInspector"]),
    ],
    targets: [
        .target(
            name: "ViewInspector", dependencies: []),
        .testTarget(
            name: "ViewInspectorTests", dependencies: ["ViewInspector"]),
    ]
)

Fix min required os versions

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

import PackageDescription

let package = Package(
    name: "ViewInspector",
    platforms: [
        .macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)
    ],
    products: [
        .library(
            name: "ViewInspector", targets: ["ViewInspector"]),
    ],
    targets: [
        .target(
            name: "ViewInspector", dependencies: []),
        .testTarget(
            name: "ViewInspectorTests", dependencies: ["ViewInspector"]),
    ]
)


import PackageDescription

let package = Package(
    name: "RxTask",
    dependencies: [
        .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3)
    ]
)

Update SPM package for RxSwift version.

import PackageDescription

let package = Package(
    name: "RxTask",
    dependencies: [
        .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3, minorVersion: 2)
    ]
)


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

import PackageDescription

let package = Package(
    name: "OctoKit",

    products: [
        .library(
            name: "OctoKit",
            targets: ["OctoKit"]),
    ],
    dependencies: [
        .package(url: "https://github.com/nerdishbynature/RequestKit.git", .exact("2.3.0")),
    ],
    targets: [
        .target(
            name: "OctoKit",
            dependencies: ["RequestKit"],
            path: ".",
            sources: ["OctoKit"]),
        .testTarget(
            name: "OctoKitTests",
            dependencies: ["OctoKit"]),
    ]
)

Allow requestkit versions until next major

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

import PackageDescription

let package = Package(
    name: "OctoKit",

    products: [
        .library(
            name: "OctoKit",
            targets: ["OctoKit"]),
    ],
    dependencies: [
        .package(url: "https://github.com/nerdishbynature/RequestKit.git", from: "2.3.0"),
    ],
    targets: [
        .target(
            name: "OctoKit",
            dependencies: ["RequestKit"],
            path: ".",
            sources: ["OctoKit"]),
        .testTarget(
            name: "OctoKitTests",
            dependencies: ["OctoKit"]),
    ]
)


// swift-tools-version:5.0
//
// SwiftSpreadsheet
//

import PackageDescription

let package = Package(
    name: "SwiftSpreadsheet",
    products: [
        .library(
            name: "SwiftSpreadsheet",
            targets: ["SwiftSpreadsheet"]),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "SwiftSpreadsheet",
            dependencies: [],
            path: "SwiftSpreadsheet"
        ),
    ],
   swiftLanguageVersions:[.v5]
)

Refactor removal of comments and re-alignment of close bracket

// swift-tools-version:5.0
//
// SwiftSpreadsheet
//

import PackageDescription

let package = Package(
    name: "SwiftSpreadsheet",
    products: [
        .library(
            name: "SwiftSpreadsheet",
            targets: ["SwiftSpreadsheet"]),
    ],
    targets: [
        .target(
            name: "SwiftSpreadsheet",
            dependencies: [],
            path: "SwiftSpreadsheet"),
    ],
   swiftLanguageVersions:[.v5]
)


//
//  Container.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 7/23/15.
//  Copyright © 2015 DevSwinject. All rights reserved.
//

import Foundation

public final class Container {
    private var factories = [Any]()

    // The first argument is for a workaround to the problem that cannot explicitly specialize a generic function in Swift.
    // http://stackoverflow.com/questions/28726937/how-do-i-call-a-generic-swift-function-when-none-of-the-arguments-provides-the-g
    public func register<Service>(_: Service.Type, factory: Container -> Service) {
        factories += [factory as Any]
    }

    public func resolve<Service>(_: Service.Type) -> Service? {
        for factory in factories {
            if let factory = factory as? Container -> Service {
                return factory(self)
            }
        }
        return nil
    }
}

Use a dictionary to store the factories as Funq does.

//
//  Container.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 7/23/15.
//  Copyright © 2015 DevSwinject. All rights reserved.
//

import Foundation

public final class Container {
    private var factories = [String: Any]()

    public func register<Service>(serviceType: Service.Type, factory: Container -> Service) {
        factories[String(serviceType)] = factory as Any
    }

    public func resolve<Service>(serviceType: Service.Type) -> Service? {
        if let factory = factories[String(serviceType)] as? Container -> Service {
            return factory(self)
        }
        return nil
    }
}


// ------------------------------------------------------------------
// begin <%= @module %> module

// instantiate classes
var <%= @module.downcase %>Wireframe: <%= @prefixed_module %>Wireframe      = <%= @prefixed_module %>Wireframe()
var <%= @module.downcase %>Presenter: <%= @prefixed_module %>Presenter      = <%= @prefixed_module %>Presenter()
var <%= @module.downcase %>DataManager: <%= @prefixed_module %>DataManager  = <%= @prefixed_module %>DataManager()
var <%= @module.downcase %>Interactor: <%= @prefixed_module %>Interactor    = <%= @prefixed_module %>Interactor()

// presenter <-> wireframe
<%= @module.downcase %>Presenter.wireframe = <%= @module.downcase %>Wireframe
<%= @module.downcase %>Wireframe.presenter = <%= @module.downcase %>Presenter

// presenter <-> interactor
<%= @module.downcase %>Presenter.interactor = <%= @module.downcase %>Interactor
<%= @module.downcase %>Interactor.presenter = <%= @module.downcase %>Presenter

// interactor -> data_manager
<%= @module.downcase %>Interactor.dataManager = <%= @module.downcase %>DataManager

// data_manager -> data_store
// *** connect datastore

// connect wireframes
<%= @module.downcase %>Wireframe.rootWireframe = rootWireframe
// *** connect more wireframes

// configure delegate
// *** add delegate here if needed

// end <%= @module %> module
// ------------------------------------------------------------------

Fix warnings for unmutated variables in AppDependencies

// ------------------------------------------------------------------
// begin <%= @module %> module

// instantiate classes
let <%= @module.downcase %>Wireframe: <%= @prefixed_module %>Wireframe      = <%= @prefixed_module %>Wireframe()
let <%= @module.downcase %>Presenter: <%= @prefixed_module %>Presenter      = <%= @prefixed_module %>Presenter()
let <%= @module.downcase %>DataManager: <%= @prefixed_module %>DataManager  = <%= @prefixed_module %>DataManager()
let <%= @module.downcase %>Interactor: <%= @prefixed_module %>Interactor    = <%= @prefixed_module %>Interactor()

// presenter <-> wireframe
<%= @module.downcase %>Presenter.wireframe = <%= @module.downcase %>Wireframe
<%= @module.downcase %>Wireframe.presenter = <%= @module.downcase %>Presenter

// presenter <-> interactor
<%= @module.downcase %>Presenter.interactor = <%= @module.downcase %>Interactor
<%= @module.downcase %>Interactor.presenter = <%= @module.downcase %>Presenter

// interactor -> data_manager
<%= @module.downcase %>Interactor.dataManager = <%= @module.downcase %>DataManager

// data_manager -> data_store
// *** connect datastore

// connect wireframes
<%= @module.downcase %>Wireframe.rootWireframe = rootWireframe
// *** connect more wireframes

// configure delegate
// *** add delegate here if needed

// end <%= @module %> module
// ------------------------------------------------------------------


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

let package = Package(
    name: "Kanna",
    products: [
      .library(name: "Kanna", targets: ["Kanna"]),
    ],
    targets: [
        .systemLibrary(
            name: "libxml2",
            path: "Modules",
            pkgConfig: "libxml-2.0",
            providers: [
                .apt(["libxml2-dev"]),
                .brew(["libxml2"]),
            ]
        ),
        .target(
            name: "Kanna",
            dependencies: ["libxml2"],
            path: "Sources",
            exclude: [
                "Sources/Info.plist",
                "Sources/Kanna.h",
                "Tests/KannaTests/Data"
            ]
        ),
        .testTarget(
            name: "KannaTests",
            dependencies: ["Kanna"]
        )
    ],
    swiftLanguageVersions: [.v5]
)

Fix to make the package backward compatible

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

let package = Package(
    name: "Kanna",
    products: [
      .library(name: "Kanna", targets: ["Kanna"]),
    ],
    targets: [
        .systemLibrary(
            name: "libxml2",
            path: "Modules",
            pkgConfig: "libxml-2.0",
            providers: [
                .apt(["libxml2-dev"]),
                .brew(["libxml2"]),
            ]
        ),
        .target(
            name: "Kanna",
            dependencies: ["libxml2"],
            path: "Sources",
            exclude: [
                "Sources/Info.plist",
                "Sources/Kanna.h",
                "Tests/KannaTests/Data"
            ]
        ),
        .testTarget(
            name: "KannaTests",
            dependencies: ["Kanna"]
        )
    ],
    swiftLanguageVersions: [.v5]
)


import PackageDescription

let package = Package(
  name: "Commander",
  dependencies: [
    .Package(url: "https://github.com/kylef/Spectre", majorVersion: 0, minor: 7),
  ]
)

Use `.git` extension on dependencies URL

import PackageDescription

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


//
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//

import Foundation
import Dispatch

public extension RunLoop {
	public func waitForSemaphore(_ sem: DispatchSemaphore) {
        #if os(Linux)
		while true {
            // Bug workaround:
            // RunLoop.run() on Linux waits in a busy loop producing high CPU usage. Also, it freezes if
            // time interval is too small or negative. So, pick a minimal time interval when it still
            // doesn't freeze and add usleep(). This will minimize CPU usage when idling.
            let _ = run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.001))
		    if .success == sem.wait(timeout: DispatchTime.now()) {
                break
            }
            usleep(100000)
        }
        #else
		repeat {
            run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.01))
		} while .success != sem.wait(timeout: DispatchTime.now())
        #endif
	}
}

Raise RunLoop wait interval for Linux

//
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//

import Foundation
import Dispatch

public extension RunLoop {
	public func waitForSemaphore(_ sem: DispatchSemaphore) {
        #if os(Linux)
		while true {
            // Bug workaround:
            // RunLoop.run() on Linux waits in a busy loop producing high CPU usage. Also, it freezes if
            // time interval is too small or negative. So, pick a minimal time interval when it still
            // doesn't freeze and add usleep(). This will minimize CPU usage when idling.
            let _ = run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.002))
		    if .success == sem.wait(timeout: DispatchTime.now()) {
                break
            }
            usleep(100000)
        }
        #else
		repeat {
            run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.01))
		} while .success != sem.wait(timeout: DispatchTime.now())
        #endif
	}
}


//
//  ROCloudModelSettings.swift
//  ROCloudModel
//
//  Created by Robin Oster on 15/12/16.
//  Copyright © 2016 Prine Development. All rights reserved.
//

import Foundation
import CloudKit

public class ROCloudModelSettings {

    public var container = CKContainer.default()

    private init() {
        // Make constructor private
    }

    static let sharedInstance : ROCloudModelSettings = {
        let instance = ROCloudModelSettings()
        return instance
    }()
}

Make class and methods open

//
//  ROCloudModelSettings.swift
//  ROCloudModel
//
//  Created by Robin Oster on 15/12/16.
//  Copyright © 2016 Prine Development. All rights reserved.
//

import Foundation
import CloudKit

open class ROCloudModelSettings {

    open var container = CKContainer.default()

    private init() {
        // Make constructor private
    }

    static let sharedInstance : ROCloudModelSettings = {
        let instance = ROCloudModelSettings()
        return instance
    }()
}


import Charts
import SnapshotTesting
import UIKit

private enum Snapshot {
    static let tolerance: CGFloat = 0.001

    static func identifier(_ size: CGSize) -> String {
        #if os(tvOS)
            let identifier = "tvOS"
        #elseif os(iOS)
            let identifier = "iOS"
        #elseif os(OSX)
            let identifier = "macOS"
        #else
            let identifier = ""
        #endif

        return "\(identifier)_\(size.width)_\(size.height)"
    }
}

func assertChartSnapshot<Value: ChartViewBase>(
    matching value: @autoclosure () throws -> Value,
    record recording: Bool = false,
    timeout: TimeInterval = 5,
    file: StaticString = #file,
    testName: String = #function,
    line: UInt = #line
) {
    assertSnapshot(
        matching: try value(),
        as: .image,
        record: recording,
        timeout: timeout,
        file: file,
        testName: testName + Snapshot.identifier(UIScreen.main.bounds.size),
        line: line
    )
}

Include tolerance for snapshot testing

import Charts
import SnapshotTesting
import UIKit

private enum Snapshot {
    static let tolerance: Float = 0.001

    static func identifier(_ size: CGSize) -> String {
        #if os(tvOS)
            let identifier = "tvOS"
        #elseif os(iOS)
            let identifier = "iOS"
        #elseif os(OSX)
            let identifier = "macOS"
        #else
            let identifier = ""
        #endif

        return "\(identifier)_\(size.width)_\(size.height)"
    }
}

func assertChartSnapshot<Value: ChartViewBase>(
    matching value: @autoclosure () throws -> Value,
    record recording: Bool = false,
    timeout: TimeInterval = 5,
    file: StaticString = #file,
    testName: String = #function,
    line: UInt = #line
) {
    assertSnapshot(
        matching: try value(),
        as: .image(precision: Snapshot.tolerance),
        record: recording,
        timeout: timeout,
        file: file,
        testName: testName + Snapshot.identifier(UIScreen.main.bounds.size),
        line: line
    )
}


//
//  TooltipSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 26/08/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
import SwiftyEcharts

class TooltipSpec: QuickSpec {
    override func spec() {
        describe("For Tooltip.Trigger.TriggerOn") {
            let mousemoveString = "mousemove"
            let clickString = "click"
            let noneString = "none"

            let mousemoveTriggerOn = Tooltip.Trigger.TriggerOn.mousemove
            let clickTriggerOn = Tooltip.Trigger.TriggerOn.click
            let noneTriggerOn = Tooltip.Trigger.TriggerOn.none

            it("needs to check the enum case jsonString") {
                expect(mousemoveTriggerOn.jsonString).to(equal(mousemoveString.jsonString))
                expect(clickTriggerOn.jsonString).to(equal(clickString.jsonString))
                expect(noneTriggerOn.jsonString).to(equal(noneString.jsonString))
            }
        }
    }
}

Add test cases for `Tooltip.Trigger`

//
//  TooltipSpec.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 26/08/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

import Quick
import Nimble
import SwiftyEcharts

class TooltipSpec: QuickSpec {
    override func spec() {
        describe("For Tooltip.Trigger.TriggerOn") {
            let mousemoveString = "mousemove"
            let clickString = "click"
            let noneString = "none"

            let mousemoveTriggerOn = Tooltip.Trigger.TriggerOn.mousemove
            let clickTriggerOn = Tooltip.Trigger.TriggerOn.click
            let noneTriggerOn = Tooltip.Trigger.TriggerOn.none

            it("needs to check the enum case jsonString") {
                expect(mousemoveTriggerOn.jsonString).to(equal(mousemoveString.jsonString))
                expect(clickTriggerOn.jsonString).to(equal(clickString.jsonString))
                expect(noneTriggerOn.jsonString).to(equal(noneString.jsonString))
            }
        }

        describe("For Tooltip.Trigger") {
            let itemString = "item"
            let axisString = "axis"

            let itemTrigger = Tooltip.Trigger.item
            let axisTrigger = Tooltip.Trigger.axis

            it("needs to check the enum case jsonString") {
                expect(itemTrigger.jsonString).to(equal(itemString.jsonString))
                expect(axisTrigger.jsonString).to(equal(axisString.jsonString))
            }
        }
    }
}


public struct Route {

	public typealias Middleware = (request: MatchedRequest, next: (MatchedRequest) -> Response) -> Response

	public let method: Method
	public let path: WildcardPath
	public let middleware: [Middleware]

    let handler: RouteHandlingType

	init(method: Method, path: Path, pathTypes: [PathType.Type] = [], middleware: [Middleware] = [], handler: RouteHandlingType) {
		self.method = method
		self.path = WildcardPath(path: path, pathTypes: pathTypes)
		self.middleware = middleware
		self.handler = handler
	}

	public func matches(request: Request) -> Bool {
		return matches(request.method, path: request.path)
	}

	public func matches(method: Method, path: Path) -> Bool {
		guard self.method == method else { return false }
		guard self.path.matches(path) else { return false }
		return true
	}

	public func handle(request: Request) -> Response {
		let matchedRequest = MatchedRequest(request: request, route: self)
		return handle(matchedRequest, middlewareGenerator:  middleware.generate())
	}

	private func handle(request: MatchedRequest, middlewareGenerator: IndexingGenerator<[Middleware]>) -> Response {
		var mutableMiddlewareGenerator = middlewareGenerator
		if let middleware = mutableMiddlewareGenerator.next() {
			return middleware(request: request, next: { (aRequest) -> Response in
				return self.handle(aRequest, middlewareGenerator: mutableMiddlewareGenerator)
			})
		}

        return handler.perform(request)
	}

}

Rename to make variable more clear.

public struct Route {

	public typealias Middleware = (request: MatchedRequest, next: (MatchedRequest) -> Response) -> Response

	public let method: Method
	public let wildcardPath: WildcardPath
	public let middleware: [Middleware]

    let handler: RouteHandlingType

	init(method: Method, path: Path, pathTypes: [PathType.Type] = [], middleware: [Middleware] = [], handler: RouteHandlingType) {
		self.method = method
		self.wildcardPath = WildcardPath(path: path, pathTypes: pathTypes)
		self.middleware = middleware
		self.handler = handler
	}

	public func matches(request: Request) -> Bool {
		return matches(request.method, path: request.path)
	}

	public func matches(method: Method, path: Path) -> Bool {
		guard self.method == method else { return false }
		guard wildcardPath.matches(path) else { return false }
		return true
	}

	public func handle(request: Request) -> Response {
		let matchedRequest = MatchedRequest(request: request, route: self)
		return handle(matchedRequest, middlewareGenerator:  middleware.generate())
	}

	private func handle(request: MatchedRequest, middlewareGenerator: IndexingGenerator<[Middleware]>) -> Response {
		var mutableMiddlewareGenerator = middlewareGenerator
		if let middleware = mutableMiddlewareGenerator.next() {
			return middleware(request: request, next: { (aRequest) -> Response in
				return self.handle(aRequest, middlewareGenerator: mutableMiddlewareGenerator)
			})
		}

        return handler.perform(request)
	}

}


//
//  RequestBuilder.swift
//
//  Created by Alexandr Khmelevsky on 10/19/16.
//  Copyright © 2016 Alexandr Khmelevsky. All rights reserved.
//

import Foundation
import AFNetworking

@available(*, renamed:"Configurator", message: "Use Handlers.success(:)")
public typealias AFBuilder = RequestBuilder

open class RequestBuilder {

    // MARK: - Vars
    private(set) open var configurator: Configurator

    // MARK: - Init
    public init(manager:AFHTTPSessionManager, configurator: Configurator) {
        configurator.manager = manager
        self.configurator = configurator
    }

    // MARK: - Logic
    open func execute() {
        Request(builder: self).execute()
    }

}

// MARK: - Handlers control
extension RequestBuilder {

    open func addHandler(_ handler: HandlerProtocol) -> Self {
        configurator.handlers.append(handler)
        return self
    }

    open func removeHandler(_ handler: HandlerProtocol) -> Self {
        if let index = configurator.handlers.index(where: { $0 === handler }) {
            configurator.handlers.remove(at: index)
        }
        return self
    }

    open func removeAllHandlers() -> Self {
        configurator.handlers.removeAll()
        return self
    }
}

Add task like a weak property

//
//  RequestBuilder.swift
//
//  Created by Alexandr Khmelevsky on 10/19/16.
//  Copyright © 2016 Alexandr Khmelevsky. All rights reserved.
//

import Foundation
import AFNetworking

@available(*, renamed:"Configurator", message: "Use Handlers.success(:)")
public typealias AFBuilder = RequestBuilder

open class RequestBuilder {

    // MARK: - Vars
    private(set) open var configurator: Configurator
    open weak var task:URLSessionTask?

    // MARK: - Init
    public init(manager:AFHTTPSessionManager, configurator: Configurator) {
        configurator.manager = manager
        self.configurator = configurator
    }

    // MARK: - Logic
    open func execute() {
        Request(builder: self).execute()
    }

}

// MARK: - Handlers control
extension RequestBuilder {

    open func addHandler(_ handler: HandlerProtocol) -> Self {
        configurator.handlers.append(handler)
        return self
    }

    open func removeHandler(_ handler: HandlerProtocol) -> Self {
        if let index = configurator.handlers.index(where: { $0 === handler }) {
            configurator.handlers.remove(at: index)
        }
        return self
    }

    open func removeAllHandlers() -> Self {
        configurator.handlers.removeAll()
        return self
    }
}


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

extension Module {
	public static var finiteSet: Module {
		let Natural: Recur = "Natural"
		let FiniteSet: Recur = "FiniteSet"
		let finiteSet = Declaration("FiniteSet",
			type: Natural --> .Type,
			value: Natural => { n in n[.Type, .Type => { $0 --> $0 }, (Natural, .Type) => { (n: Recur, A) in (FiniteSet[n] --> A) --> A }] })

		let successor: Recur = "successor"
		let zeroth = Declaration("zeroth",
			type: Natural => { (n: Recur) in FiniteSet[successor[n]] },
			value: .Type => { A in A => id })

		let nextth = Declaration("nextth",
			type: Natural => { (n: Recur) in FiniteSet[n] --> FiniteSet[successor[n]] },
			value: Natural => { (n: Recur) in (FiniteSet[n], .Type) => { (prev: Recur, A) in (FiniteSet[n] --> A) => { $0[prev] } } })

		return Module("FiniteSet", [ natural ], [ finiteSet, zeroth, nextth ])
	}
}

import Prelude

Add a parameter to eliminate zeroth cases.

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

extension Module {
	public static var finiteSet: Module {
		let Natural: Recur = "Natural"
		let FiniteSet: Recur = "FiniteSet"
		let finiteSet = Declaration("FiniteSet",
			type: Natural --> .Type,
			value: Natural => { n in n[.Type, .Type => { $0 --> $0 }, (Natural, .Type) => { (n: Recur, A) in A --> (FiniteSet[n] --> A) --> A }] })

		let successor: Recur = "successor"
		let zeroth = Declaration("zeroth",
			type: Natural => { (n: Recur) in FiniteSet[successor[n]] },
			value: Natural => { (n: Recur) in .Type => { (A: Recur) in A => { (FiniteSet[n] --> A) --> $0 } } })

		let nextth = Declaration("nextth",
			type: Natural => { (n: Recur) in FiniteSet[n] --> FiniteSet[successor[n]] },
			value: Natural => { (n: Recur) in (FiniteSet[n], .Type) => { (prev: Recur, A) in A --> (FiniteSet[n] --> A) => { $0[prev] } } })

		return Module("FiniteSet", [ natural ], [ finiteSet, zeroth, nextth ])
	}
}

import Prelude


import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

      let viewController1 = UIViewController()
      viewController1.view.backgroundColor = UIColor.lightGrayColor()
      viewController1.title = "Controller A"

      let viewController2 = UIViewController()
      viewController2.view.backgroundColor = UIColor.whiteColor()
      viewController2.title = "Controller B"

      let pages = PagesController([viewController1, viewController2])
      pages.enableSwipe = false

      let navigationController = UINavigationController(rootViewController: pages)

      pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page", style: .Plain, target: pages, action: "previous")

      pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page", style: .Plain, target: pages, action: "next")

      self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
      self.window?.rootViewController = navigationController
      self.window?.makeKeyAndVisible()

      return true
    }
}

Add more controllers to demo

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

      let viewController1 = UIViewController()
      viewController1.view.backgroundColor = UIColor.redColor()
      viewController1.title = "Controller A"

      let viewController2 = UIViewController()
      viewController2.view.backgroundColor = UIColor.blueColor()
      viewController2.title = "Controller B"

      let viewController3 = UIViewController()
      viewController3.view.backgroundColor = UIColor.greenColor()
      viewController3.title = "Controller C"

      let viewController4 = UIViewController()
      viewController4.view.backgroundColor = UIColor.yellowColor()
      viewController4.title = "Controller D"

      let pages = PagesController([viewController1,
        viewController2,
        viewController3,
        viewController4
        ])

      pages.enableSwipe = false

      let navigationController = UINavigationController(rootViewController: pages)

      pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
        style: .Plain,
        target: pages,
        action: "previous")

      pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
        style: .Plain,
        target: pages,
        action: "next")

      self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
      self.window?.rootViewController = navigationController
      self.window?.makeKeyAndVisible()

      return true
    }
}


//
//  Account.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

struct AccountCommand: CommandType {
    typealias Options = NoOptions<MASError>
    let verb = "account"
    let function = "Prints the primary account Apple ID"

    func run(options: Options) -> Result<(), MASError> {
        if let account = ISStoreAccount.primaryAccount {
            print(account.identifier)
        }
        else {
            print("Not signed in")
            exit(MASErrorCode.NotSignedIn.exitCode)
        }
        return .Success(())
    }
}

Return an error instead of exiting

//
//  Account.swift
//  mas-cli
//
//  Created by Andrew Naylor on 21/08/2015.
//  Copyright (c) 2015 Andrew Naylor. All rights reserved.
//

struct AccountCommand: CommandType {
    typealias Options = NoOptions<MASError>
    let verb = "account"
    let function = "Prints the primary account Apple ID"

    func run(options: Options) -> Result<(), MASError> {
        if let account = ISStoreAccount.primaryAccount {
            print(account.identifier)
        }
        else {
            print("Not signed in")
            return .Failure(MASError(code: .NotSignedIn))
        }
        return .Success(())
    }
}


//
//  ConfirmEmailTableViewCell.swift
//  MercadoPagoSDK
//
//  Created by Eden Torres on 10/26/16.
//  Copyright © 2016 MercadoPago. All rights reserved.
//

import UIKit

class ConfirmEmailTableViewCell: UITableViewCell {

    @IBOutlet weak var label: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    func fillCell(payment: Payment, instruction: Instruction?) -> Void {
        label.font = Utils.getFont(size: label.font.pointSize)
        if let instruction = instruction?.secondaryInfo?[0] {
            label.text = instruction
        } else if payment.status == "approved"{
            label.text = ("Te enviaremos este comprobante a %0".localized as NSString).replacingOccurrences(of: "%0", with: "\(payment.payer.email!)")
        } else {
            label.text = "También enviamos el código a tu email".localized
        }
    }
}

Validate array properly in InstructionsVC

//
//  ConfirmEmailTableViewCell.swift
//  MercadoPagoSDK
//
//  Created by Eden Torres on 10/26/16.
//  Copyright © 2016 MercadoPago. All rights reserved.
//

import UIKit

class ConfirmEmailTableViewCell: UITableViewCell {

    @IBOutlet weak var label: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    func fillCell(payment: Payment, instruction: Instruction?) -> Void {
        label.font = Utils.getFont(size: label.font.pointSize)
        if !Array.isNullOrEmpty(instruction?.secondaryInfo) {
            if let instruction = instruction?.secondaryInfo?[0] {
                label.text = instruction
            } else if payment.status == "approved"{
                label.text = ("Te enviaremos este comprobante a %0".localized as NSString).replacingOccurrences(of: "%0", with: "\(payment.payer.email!)")
            } else {
                label.text = "También enviamos el código a tu email".localized
            }
        }
    }
}


import XCTest
import class Foundation.Bundle

final class swiftsearchTests: XCTestCase {
    func testExample() throws {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct
        // results.

        // Some of the APIs that we use below are available in macOS 10.13 and above.
        guard #available(macOS 10.13, *) else {
            return
        }

        let fooBinary = productsDirectory.appendingPathComponent("swiftsearch")

        let process = Process()
        process.executableURL = fooBinary

        let pipe = Pipe()
        process.standardOutput = pipe

        try process.run()
        process.waitUntilExit()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)

        XCTAssertEqual(output, "Hello, world!\n")
    }

    /// Returns path to the built products directory.
    var productsDirectory: URL {
      #if os(macOS)
        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
            return bundle.bundleURL.deletingLastPathComponent()
        }
        fatalError("couldn't find the products directory")
      #else
        return Bundle.main.bundleURL
      #endif
    }

    static var allTests = [
        ("testExample", testExample),
    ]
}

Fix included sample test in swift version

import XCTest
import class Foundation.Bundle

final class swiftsearchTests: XCTestCase {
    func testExample() throws {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct
        // results.

        // Some of the APIs that we use below are available in macOS 10.13 and above.
        guard #available(macOS 10.13, *) else {
            return
        }

        let fooBinary = productsDirectory.appendingPathComponent("swiftsearchApp")

        let process = Process()
        process.executableURL = fooBinary

        let pipe = Pipe()
        process.standardOutput = pipe

        try process.run()
        process.waitUntilExit()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)

        XCTAssert(output!.hasPrefix("\nERROR: Startpath not defined"))
    }

    /// Returns path to the built products directory.
    var productsDirectory: URL {
      #if os(macOS)
        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
            return bundle.bundleURL.deletingLastPathComponent()
        }
        fatalError("couldn't find the products directory")
      #else
        return Bundle.main.bundleURL
      #endif
    }

    static var allTests = [
        ("testExample", testExample),
    ]
}


// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test

// CHECK-NOT: Reallocations exceeded 30
func testReallocation() {
  var x = "The quick brown fox jumped over the lazy dog\n"._split(separator: " ")

  var story = "Let me tell you a story:"
  var laps = 1000

  var reallocations = 0
  for i in 0..<laps {
    for s in x {
      var lastBase = story._core._baseAddress
      story += " "
      story += s
      if lastBase != story._core._baseAddress {
        reallocations += 1

        // To avoid dumping a vast string here, just write the first
        // part of the story out each time there's a reallocation.
        var intro = story._split(":")[0]
        print("reallocation \(reallocations), with intro \(intro)")

        if reallocations >= 30 {
          print("Reallocations exceeded 30")
          return
        }
      }
    }
    story += "."
  }
  print("total reallocations = \(reallocations)")
}

testReallocation()
print("done!")

Add missing separator label that escaped previous audit.

// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test

// CHECK-NOT: Reallocations exceeded 30
func testReallocation() {
  var x = "The quick brown fox jumped over the lazy dog\n"._split(separator: " ")

  var story = "Let me tell you a story:"
  var laps = 1000

  var reallocations = 0
  for i in 0..<laps {
    for s in x {
      var lastBase = story._core._baseAddress
      story += " "
      story += s
      if lastBase != story._core._baseAddress {
        reallocations += 1

        // To avoid dumping a vast string here, just write the first
        // part of the story out each time there's a reallocation.
        var intro = story._split(separator: ":")[0]
        print("reallocation \(reallocations), with intro \(intro)")

        if reallocations >= 30 {
          print("Reallocations exceeded 30")
          return
        }
      }
    }
    story += "."
  }
  print("total reallocations = \(reallocations)")
}

testReallocation()
print("done!")


//
//  ViewController.swift
//  FireRecord
//
//  Created by victoralissont5@gmail.com on 08/09/2017.
//  Copyright (c) 2017 victoralissont5@gmail.com. All rights reserved.
//

import UIKit
import FireRecord

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let user = User()
        user.name = "Sanford"

        user.save { error in print(error ?? "=)")}
        user.destroy { error in print(error ?? "=)")}

        User.findFirst { user in
            print(user.name ?? "Does not contain name")
            user.update(completion: { error in
                print(error ?? "=)")
            })
        }
        User.findLast { user in
            print(user.name ?? "Does not contain name")
        }

        User.all { users in
            let names = users.flatMap({$0.name})
            names.forEach({print($0)})
        }
    }
}
class User: FireRecord {
    public var name: String?
    init(name: String) { self.name = name }
    required public init() {}
}

Add examples with all protocol methods

//
//  ViewController.swift
//  FireRecord
//
//  Created by victoralissont5@gmail.com on 08/09/2017.
//  Copyright (c) 2017 victoralissont5@gmail.com. All rights reserved.
//

import UIKit
import FireRecord

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let user = User()
        user.name = "Victor"

        user.save { error in print(error ?? "=)")}
        user.destroy { error in print(error ?? "=)")}

        User.findFirst { user in
            user.name = "Alisson"
            user.update(completion: { error in
                print(error ?? "=)")
            })
        }
        User.findFirst(3) { users in
            users.forEach({print($0.name ?? "Does not contain name")})
        }
//
        User.findLast(3) { users in
            users.forEach({print($0.name ?? "Does not contain name")})
        }
        User.findLast { user in
            print(user.name ?? "Does not contain name")
        }
        User.all { users in
            let names = users.flatMap({$0.name})
            names.forEach({print($0)})
        }
    }
}
class User: FireRecord {
    public var name: String?
    init(name: String) { self.name = name }
    required public init() {}
}


//
//  StoryboardType.swift
//  FuntastyKit
//
//  Created by Aleš Kocur on 21.05.16.
//  Copyright © 2016 The Funtasty. All rights reserved.
//

import Foundation
import UIKit

public protocol StoryboardType {
    static var name: String { get }
}

public struct StoryboardReference<S: StoryboardType, T> {

    public let id: String

    public init(id: String) {
        self.id = id
    }

    public func instantiate() -> T {
        if let controller = UIStoryboard(name: S.name, bundle: nil).instantiateViewController(withIdentifier: id) as? T {
            return controller
        } else {
            fatalError("Instantiated controller with \(id) has different type than expected!")
        }
    }

}

Add custom bundle identifier specification

//
//  StoryboardType.swift
//  FuntastyKit
//
//  Created by Aleš Kocur on 21.05.16.
//  Copyright © 2016 The Funtasty. All rights reserved.
//

import Foundation
import UIKit

public protocol StoryboardType {
    static var name: String { get }
}

public struct StoryboardReference<S: StoryboardType, T> {

    public let id: String
    public let bundle: Bundle?

    public init(id: String, bundle: Bundle? = nil) {
        self.bundle = bundle
        self.id = id
    }

    public func instantiate() -> T {
        if let controller = UIStoryboard(name: S.name, bundle: bundle).instantiateViewController(withIdentifier: id) as? T {
            return controller
        } else {
            fatalError("Instantiated controller with \(id) has different type than expected!")
        }
    }
}


//
//  SettingsAboutView.swift
//  NetNewsWire-iOS
//
//  Created by Maurice Parker on 9/16/19.
//  Copyright © 2019 Ranchero Software. All rights reserved.
//

import SwiftUI
import Combine

struct SettingsAboutView: View {

	@StateObject var viewModel = SettingsAboutModel()

    var body: some View {
		GeometryReader { geometry in
			List {
				Text("NetNewsWire").font(.largeTitle)
				AttributedStringView(string: self.viewModel.about, preferredMaxLayoutWidth: geometry.size.width - 20)
				Section(header: Text("CREDITS")) {
					AttributedStringView(string: self.viewModel.credits, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
				Section(header: Text("THANKS")) {
					AttributedStringView(string: self.viewModel.thanks, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
				Section(header: Text("DEDICATION"), footer: Text("Copyright © 2002-2020 BrentSimmons").font(.footnote)) {
					AttributedStringView(string: self.viewModel.dedication, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
			}.listStyle(InsetGroupedListStyle())
		}
    }

}

struct SettingsAboutView_Previews: PreviewProvider {
    static var previews: some View {
		SettingsAboutView()
    }
}

Add title for About view

//
//  SettingsAboutView.swift
//  NetNewsWire-iOS
//
//  Created by Maurice Parker on 9/16/19.
//  Copyright © 2019 Ranchero Software. All rights reserved.
//

import SwiftUI
import Combine

struct SettingsAboutView: View {

	@StateObject var viewModel = SettingsAboutModel()

    var body: some View {
		GeometryReader { geometry in
			List {
				Text("NetNewsWire").font(.largeTitle)
					AttributedStringView(string: self.viewModel.about, preferredMaxLayoutWidth: geometry.size.width - 20)
				Section(header: Text("CREDITS")) {
					AttributedStringView(string: self.viewModel.credits, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
				Section(header: Text("THANKS")) {
					AttributedStringView(string: self.viewModel.thanks, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
				Section(header: Text("DEDICATION"), footer: Text("Copyright © 2002-2020 BrentSimmons").font(.footnote)) {
					AttributedStringView(string: self.viewModel.dedication, preferredMaxLayoutWidth: geometry.size.width - 20)
				}
			}.listStyle(InsetGroupedListStyle())
		}
		.navigationTitle(Text("About"))
    }

}

struct SettingsAboutView_Previews: PreviewProvider {
    static var previews: some View {
		SettingsAboutView()
    }
}


//
//  PromiseZipTests.swift
//  Promise
//
//  Created by Soroush Khanlou on 8/19/16.
//
//

import XCTest
import Foundation

import Promise

class PromiseZipTests: XCTestCase {
    func testZipping2() {
        weak var expectation = self.expectation(description: "`Promises.zip` should be type safe.")

        let promise = Promise(value: 2)
        let promise2 = Promise(value: "some string")
        let zipped = Promises.zip(promise, promise2)
        zipped.always({
            expectation?.fulfill()
        })

        waitForExpectations(timeout: 1, handler: nil)
        guard let tuple = zipped.value else { XCTFail(); return }
        XCTAssertEqual(tuple.0, 2)
        XCTAssertEqual(tuple.1, "some string")
    }
}

Add a test for multiple parameter zip

//
//  PromiseZipTests.swift
//  Promise
//
//  Created by Soroush Khanlou on 8/19/16.
//
//

import XCTest
import Foundation

import Promise

class PromiseZipTests: XCTestCase {
    func testZipping2() {
        weak var expectation = self.expectation(description: "`Promises.zip` should be type safe.")

        let promise = Promise(value: 2)
        let promise2 = Promise(value: "some string")
        let zipped = Promises.zip(promise, promise2)
        zipped.always({
            expectation?.fulfill()
        })

        waitForExpectations(timeout: 1, handler: nil)
        guard let tuple = zipped.value else { XCTFail(); return }
        XCTAssertEqual(tuple.0, 2)
        XCTAssertEqual(tuple.1, "some string")
    }

    func testMultipleParameters() {
        // The >2 parameter variants of zip are all generated, so testing one
        // *should* mean all others work too.

        weak var expectation = self.expectation(description: "`Promises.zip` should be type safe.")

        let promise = Promise(value: 2)
        let promise2 = Promise(value: "some string")
        let promise3 = Promise(value: [1, 1, 2, 3, 5])
        let promise4 = Promise(value: ["two", "strings"])
        let zipped = Promises.zip(promise, promise2, promise3, promise4)
        zipped.always({
            expectation?.fulfill()
        })

        waitForExpectations(timeout: 1, handler: nil)
        guard let tuple = zipped.value else { XCTFail(); return }
        XCTAssertEqual(tuple.0, 2)
        XCTAssertEqual(tuple.1, "some string")
        XCTAssertEqual(tuple.2, [1, 1, 2, 3, 5])
        XCTAssertEqual(tuple.3, ["two", "strings"])
    }
}


//
//  JSONExtension.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 17/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public extension JSON {
    public func boolValue() throws -> Bool {
        guard let boolValue = bool else { throw JSONModelError.invalidElement }
        return boolValue
    }

    public func intValue() throws -> Int {
        guard let intValue = int else { throw JSONModelError.invalidElement }
        return intValue
    }

    public func doubleValue() throws -> Double {
        guard let doubleValue = double else { throw JSONModelError.invalidElement }
        return doubleValue
    }

    public func stringValue() throws -> String {
        guard let stringValue = string else { throw JSONModelError.invalidElement }
        return stringValue
    }

    public func arrayValue() throws -> [JSON] {
        guard let arrayValue = array else { throw JSONModelError.invalidElement }
        return arrayValue
    }

    public func dictionaryValue() throws -> [String: JSON] {
        guard let dictValue = dictionary else { throw JSONModelError.invalidElement }
        return dictValue
    }

    public func uuidStringValue() throws -> String {
        guard let stringValue = string else { throw JSONModelError.invalidElement }
        guard let uuidStrigValue = NSUUID(uuidString: stringValue) else {
            throw JSONModelError.invalidUUIDString
        }

        return uuidStrigValue.uuidString
    }
}

public extension Dictionary {
    public func value(for key: Key) throws -> Value {
        guard let value = self[key] else { throw JSONModelError.elementAbsent }
        return value
    }
}

Remove Dictionary's throwable value for key method


//
//  AppDelegate.swift
//  Habits
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let navigationController = UINavigationController(rootViewController: HabitsController())

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }
}

Initialize `HabitsController` with view model

//
//  AppDelegate.swift
//  Habits
//
//  Created by Julian Grosshauser on 26/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let navigationController = UINavigationController(rootViewController: HabitsController(viewModel: HabitsViewModel()))

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }
}


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

final class TelescopeTests: XCTestCase {
	// MARK: Types

	func testEmptyDataConstructorHasUnitType() {
		assert(Telescope.End.type("A"), ==, .UnitType)
	}

	func testRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.End).type("A"), ==, .lambda("A", const(.UnitType)))
	}

	func testMultiplyRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.Recursive(.End)).type("A"), ==, .lambda("A", const(.lambda("A", const(.UnitType)))))
	}

	func testArgumentDataConstructorHasFunctionType() {
		assert(Telescope.Argument("B", const(.Recursive(.End))).type("A"), ==, .lambda("B", const(.lambda("A", const(.UnitType)))))
	}

	// MARK: Values

	func testEmptyDataConstructorHasUnitValue() {
		assert(Telescope.End.value("A"), ==, .Unit)
	}

	func testRecursiveDataConstructorHasLambdaValueReturningProductValue() {
		assert(Telescope.Recursive(.End).value("A"), ==, .lambda("A", { .Product($0, .Unit) }))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest

Test with multiple recursive parameters.

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

final class TelescopeTests: XCTestCase {
	// MARK: Types

	func testEmptyDataConstructorHasUnitType() {
		assert(Telescope.End.type("A"), ==, .UnitType)
	}

	func testRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.End).type("A"), ==, .lambda("A", const(.UnitType)))
	}

	func testMultiplyRecursiveDataConstructorHasFunctionType() {
		assert(Telescope.Recursive(.Recursive(.End)).type("A"), ==, .lambda("A", const(.lambda("A", const(.UnitType)))))
	}

	func testArgumentDataConstructorHasFunctionType() {
		assert(Telescope.Argument("B", const(.Recursive(.End))).type("A"), ==, .lambda("B", const(.lambda("A", const(.UnitType)))))
	}

	// MARK: Values

	func testEmptyDataConstructorHasUnitValue() {
		assert(Telescope.End.value("A"), ==, .Unit)
	}

	func testRecursiveDataConstructorHasLambdaValueReturningProductValue() {
		assert(Telescope.Recursive(.End).value("A"), ==, .lambda("A", { .Product($0, .Unit) }))
	}

	func testMultiplyRecursiveDataConstructorHasLambdaValueReturningProductValue() {
		assert(Telescope.Recursive(.Recursive(.End)).value("A"), ==, .lambda("A", "A", { .Product($0, .Product($1, .Unit)) }))
	}
}

import Assertions
@testable import Manifold
import Prelude
import XCTest


//
//  FileResource.swift
//  Pods
//
//  Created by Mathijs Kadijk on 06-01-16.
//
//

import Foundation

public protocol FileResourceType {

  /// Bundle this file is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the file file on disk
  var name: String { get }

  /// Extension of the file on disk
  var pathExtension: String { get }
}

public extension FileResourceType {
  /**
   Returns the full pathname for this resource.

   - returns: The full pathname for this resource or nil if the file could not be located.
   */
  func path() -> String? {
    return bundle?.pathForResource(self)
  }

  /**
   Returns the file URL for this resource.

   - returns: The file URL for this resource or nil if the file could not be located.
   */
  func url() -> NSURL? {
    return bundle?.urlForResource(self)
  }
}

public struct FileResource: FileResourceType {
  /// Bundle this file is in or nil for main bundle
  public let bundle: NSBundle?

  /// Name of the file file on disk
  public let name: String

  /// Extension of the file on disk
  public let pathExtension: String

  public init(bundle: NSBundle?, name: String, pathExtension: String) {
    self.bundle = bundle
    self.name = name
    self.pathExtension = pathExtension
  }
}

Fix compile error by fixing capitalization

//
//  FileResource.swift
//  Pods
//
//  Created by Mathijs Kadijk on 06-01-16.
//
//

import Foundation

public protocol FileResourceType {

  /// Bundle this file is in or nil for main bundle
  var bundle: NSBundle? { get }

  /// Name of the file file on disk
  var name: String { get }

  /// Extension of the file on disk
  var pathExtension: String { get }
}

public extension FileResourceType {
  /**
   Returns the full pathname for this resource.

   - returns: The full pathname for this resource or nil if the file could not be located.
   */
  func path() -> String? {
    return bundle?.pathForResource(self)
  }

  /**
   Returns the file URL for this resource.

   - returns: The file URL for this resource or nil if the file could not be located.
   */
  func url() -> NSURL? {
    return bundle?.URLForResource(self)
  }
}

public struct FileResource: FileResourceType {
  /// Bundle this file is in or nil for main bundle
  public let bundle: NSBundle?

  /// Name of the file file on disk
  public let name: String

  /// Extension of the file on disk
  public let pathExtension: String

  public init(bundle: NSBundle?, name: String, pathExtension: String) {
    self.bundle = bundle
    self.name = name
    self.pathExtension = pathExtension
  }
}


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

import Foundation

final class ResetPasswordRequest: BackendAPIRequest {

    private let email: String

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

    var endpoint: String {
        return "/users/emails"
    }

    var method: NetworkService.Method {
        return .POST
    }

    var parameters: [String: Any]? {
        return [
            "email": email
        ]
    }

    var headers: [String: String]? {
        return defaultJSONHeaders()
    }

}

Add a comment to change endpoint when BE will release function for resseting password.

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

import Foundation

final class ResetPasswordRequest: BackendAPIRequest {

    private let email: String

    init(email: String) {
        self.email = email
    }
//Will be changed when possible
    var endpoint: String {
        return "/users/emails"
    }

    var method: NetworkService.Method {
        return .POST
    }

    var parameters: [String: Any]? {
        return [
            "email": email
        ]
    }

    var headers: [String: String]? {
        return defaultJSONHeaders()
    }

}


//
//  ReloadImageViewerController.swift
//  RDImageViewerController_Example
//
//  Created by Akira Matsuda on 2019/04/12.
//  Copyright © 2019 CocoaPods. All rights reserved.
//

import UIKit
import RDImageViewerController

class ReloadImageViewerController: RDImageViewerController {
    override init(contents: [RDPageContentData], direction: RDPagingView.ForwardDirection) {
        super.init(contents: contents, direction: direction)
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reload))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func reload() {
        currentPageIndex = 0
        let contents = ContentsFactory.randomContents()
        print(contents)
        update(contents: contents)
    }
}

Add button to push an another viewer.

//
//  ReloadImageViewerController.swift
//  RDImageViewerController_Example
//
//  Created by Akira Matsuda on 2019/04/12.
//  Copyright © 2019 CocoaPods. All rights reserved.
//

import UIKit
import RDImageViewerController

class ReloadImageViewerController: RDImageViewerController {
    override init(contents: [RDPageContentData], direction: RDPagingView.ForwardDirection) {
        super.init(contents: contents, direction: direction)
        let items = [UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reload)), UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(push))]
        navigationItem.setRightBarButtonItems(items, animated: true)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func reload() {
        currentPageIndex = 0
        let contents = ContentsFactory.randomContents()
        print(contents)
        update(contents: contents)
    }

    @objc func push() {
        let viewController = ReloadImageViewerController(contents: ContentsFactory.scrollContents(), direction: pagingView.direction)
        viewController.showSlider = showSlider
        viewController.showPageNumberHud = showPageNumberHud
        viewController.title = "View and Image"
        navigationController?.pushViewController(viewController, animated: true)
    }
}


import Foundation

struct Generator {
  static func timeStrings24H() -> [String] {
    var numbers = [String]()
    numbers.append("00:00")

    for i in 1...24 {
      let i = i % 24
      var string = i < 10 ? "0" + String(i) : String(i)
      string.append(":00")
      numbers.append(string)
    }

    return numbers
  }

  static func timeStrings12H() -> [String] {
    var numbers = [String]()
    numbers.append("12")

    for i in 1...11 {
      let string = String(i)
      numbers.append(string)
    }

    var am = numbers.map { $0 + " AM" }
    var pm = numbers.map { $0 + " PM" }
    am.append("Noon")
    pm.removeFirst()
    pm.append(am.first!)
    return am + pm
  }
}

Make generator enum instead of struct

import Foundation

enum Generator {
  static func timeStrings24H() -> [String] {
    var numbers = [String]()
    numbers.append("00:00")

    for i in 1...24 {
      let i = i % 24
      var string = i < 10 ? "0" + String(i) : String(i)
      string.append(":00")
      numbers.append(string)
    }

    return numbers
  }

  static func timeStrings12H() -> [String] {
    var numbers = [String]()
    numbers.append("12")

    for i in 1...11 {
      let string = String(i)
      numbers.append(string)
    }

    var am = numbers.map { $0 + " AM" }
    var pm = numbers.map { $0 + " PM" }
    am.append("Noon")
    pm.removeFirst()
    pm.append(am.first!)
    return am + pm
  }
}


enum WrapperModifier {
    case optional
    case list
    case reference
}

protocol Wrapper {
    static var wrappedType: Any.Type { get }
    static var modifier: WrapperModifier { get }
}

extension Optional : Wrapper {
    static var wrappedType: Any.Type {
        return Wrapped.self
    }

    static var modifier: WrapperModifier {
        return .optional
    }
}

extension Array : Wrapper {
    static var wrappedType: Any.Type {
        return Element.self
    }

    static var modifier: WrapperModifier {
        return .list
    }
}

Make Set a wrapper type.

enum WrapperModifier {
    case optional
    case list
    case reference
}

protocol Wrapper {
    static var wrappedType: Any.Type { get }
    static var modifier: WrapperModifier { get }
}

extension Optional : Wrapper {
    static var wrappedType: Any.Type {
        return Wrapped.self
    }

    static var modifier: WrapperModifier {
        return .optional
    }
}

extension Array : Wrapper {
    static var wrappedType: Any.Type {
        return Element.self
    }

    static var modifier: WrapperModifier {
        return .list
    }
}

extension Set : Wrapper {
    static var wrappedType: Any.Type {
        return Element.self
    }

    static var modifier: WrapperModifier {
        return .list
    }
}


import SwiftUI
import PhotosUI

struct PhotoPicker: UIViewControllerRepresentable {
    @Binding var isPresented: Bool
    @Binding var isLoadingPhoto: Bool

    func makeUIViewController(context: Context) -> PHPickerViewController {
        let configuration = PHPickerConfiguration(photoLibrary: .shared())
        let controller = PHPickerViewController(configuration: configuration)
        controller.delegate = context.coordinator
        return controller
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
        // nothing to update
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(view: self)
    }

    class Coordinator: PHPickerViewControllerDelegate {
        private let view: PhotoPicker

        init(view: PhotoPicker) {
            self.view = view
        }

        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            guard let provider = results.first?.itemProvider, provider.canLoadObject(ofClass: UIImage.self) else { return }
            view.isLoadingPhoto = true

            provider.loadObject(ofClass: UIImage.self) { image, error in
                if let image = image as? UIImage {
                    DispatchQueue.main.async {
                        Appearance.shared.backgroundImage = image
                    }
                }
                self.view.isLoadingPhoto = false
                self.view.isPresented = false
            }
        }
    }
}

Add an image filter to the photo picker.

import SwiftUI
import PhotosUI

struct PhotoPicker: UIViewControllerRepresentable {
    @Binding var isPresented: Bool
    @Binding var isLoadingPhoto: Bool

    func makeUIViewController(context: Context) -> PHPickerViewController {
        var configuration = PHPickerConfiguration(photoLibrary: .shared())
        configuration.filter = .images

        let controller = PHPickerViewController(configuration: configuration)
        controller.delegate = context.coordinator

        return controller
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
        // nothing to update
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(view: self)
    }

    class Coordinator: PHPickerViewControllerDelegate {
        private let view: PhotoPicker

        init(view: PhotoPicker) {
            self.view = view
        }

        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            guard let provider = results.first?.itemProvider, provider.canLoadObject(ofClass: UIImage.self) else { return }
            view.isLoadingPhoto = true

            provider.loadObject(ofClass: UIImage.self) { image, error in
                if let image = image as? UIImage {
                    DispatchQueue.main.async {
                        Appearance.shared.backgroundImage = image
                    }
                }
                self.view.isLoadingPhoto = false
                self.view.isPresented = false
            }
        }
    }
}


import Foundation
import Plot
import Publish

struct PersonalWebsite: Website {
    enum SectionID: String, WebsiteSectionID {
        case articles
        case about
    }

    struct ItemMetadata: WebsiteItemMetadata {
    }

    var url = URL(string: "http://www.ryanjdavies.com")!
    var name = "Ryan's Website"
    var description = "A website by Ryan."
    var language: Language { .english }
    var imagePath: Path? { "images/logo.png" }
}

try! PersonalWebsite().publish(withTheme: .foundation)

Add deployment to GitHub from Publish

import Foundation
import Plot
import Publish

struct PersonalWebsite: Website {
    enum SectionID: String, WebsiteSectionID {
        case articles
        case about
    }

    struct ItemMetadata: WebsiteItemMetadata {
    }

    var url = URL(string: "http://www.ryanjdavies.com")!
    var name = "Ryan's Website"
    var description = "A website by Ryan."
    var language: Language { .english }
    var imagePath: Path? { "images/logo.png" }
}

try! PersonalWebsite().publish(
  withTheme: .foundation,
  deployedUsing: .gitHub("iotize/iotize.github.com")
)


import UIKit
import Wall
import Campaign

class ViewController: CampaignController {

  let generator = ContentGenerator()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = "Campaign Ready"

    config.wall.thumbnailForAttachment = {
      (attachment: Attachment, size: CGSize) -> URLStringConvertible in
      return String(format: attachment.thumbnail.string, Int(size.width), Int(size.height))
    }
    config.wall.post.title.textAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(18)

    campaign = generator.campaign()
    reloadPosts()
  }
}

Update demo with rounded status icon

import UIKit
import Wall
import Campaign

class ViewController: CampaignController {

  let generator = ContentGenerator()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = "Campaign Ready"

    config.wall.thumbnailForAttachment = {
      (attachment: Attachment, size: CGSize) -> URLStringConvertible in
      return String(format: attachment.thumbnail.string, Int(size.width), Int(size.height))
    }
    config.wall.post.title.textAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(18)
    campaignConfig.campaign.content.statusIcon.rounded = true

    campaign = generator.campaign()
    reloadPosts()
  }
}


//
//  26_RemoveDuplicatesFromSortedArray.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-11-05.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:26 Remove Duplicates from sorted array
	URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
	Space: O(N)
	Time: O(N)
 */

class RemoveDuplicatesFromSortedArray_Solution {
  func removeDuplicates(_ nums: inout [Int]) -> Int {
    guard nums.count > 1 else {
      return nums.count
    }

    var lastFoundUnrepeatedIndex = 0
    for num in nums {
      if num != nums[lastFoundUnrepeatedIndex] {
        lastFoundUnrepeatedIndex += 1
        nums[lastFoundUnrepeatedIndex] = num
      }
    }
    return lastFoundUnrepeatedIndex + 1
  }
}

Add in improvement for problem 26.

//
//  26_RemoveDuplicatesFromSortedArray.swift
//  LeetcodeSwift
//
//  Created by yansong li on 2016-11-05.
//  Copyright © 2016 YANSONG LI. All rights reserved.
//

import Foundation

/**
	Title:26 Remove Duplicates from sorted array
	URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
	Space: O(N)
	Time: O(N)
 */

class RemoveDuplicatesFromSortedArray_Solution {
  func removeDuplicates(_ nums: inout [Int]) -> Int {
    guard nums.count > 1 else {
      return nums.count
    }

    var lastFoundUnrepeatedIndex = 0
    // Add in a local tmp to reduce array index query and improve performance.
    var currentComparisonElement = nums[lastFoundUnrepeatedIndex]
    for num in nums {
      if num != currentComparisonElement {
        lastFoundUnrepeatedIndex += 1
        nums[lastFoundUnrepeatedIndex] = num
        currentComparisonElement = num
      }
    }
    return lastFoundUnrepeatedIndex + 1
  }
}


// Shirley
// Written in 2015 by Nate Stedman <nate@natestedman.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

import ReactiveCocoa
import Shirley

struct SquareSession: SessionType
{
    typealias Request = Int
    typealias Value = Int
    typealias Error = NoError

    func producerForRequest(request: Int) -> SignalProducer<Int, NoError>
    {
        return SignalProducer(value: request * request)
    }
}

struct ErrorSession: SessionType
{
    typealias Request = Int
    typealias Value = Int
    typealias Error = TestError

    func producerForRequest(request: Int) -> SignalProducer<Int, TestError>
    {
        return SignalProducer(error: TestError(value: request))
    }
}

struct TestError: ErrorType
{
    let value: Int
}

Remove extra whitespace at end of file.


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

import Foundation

final class NewsResponseMapper: ArrayResponseMapper<NewsItem>, ResponseMapperProtocol {

    static func process(_ obj: AnyObject?) throws -> [NewsItem] {
        return try process(obj, mapper: { jsonNode in
            guard let publishDate = jsonNode["published"] as? Int? else { return nil }
            guard let title = jsonNode["title"] as? String else { return nil }
            guard let contents = jsonNode["contents"] as? String else { return nil }
            guard let photoUrl = jsonNode["imageUrl"] as? String? else { return nil }
            var published: Date? = nil
            if let publishDate = publishDate {
                published = Date(timeIntervalSince1970: TimeInterval(publishDate/1000))
            }
            var photoURL: URL? = nil
            if let photoUrl = photoUrl {
                photoURL = BackendConfiguration.shared.photosURL.appendingPathComponent(photoUrl)
            }
            return NewsItem(title: title, contents: contents, photoUrl: photoURL, published: published)
        })
    }
}

Revert "Rename news jsonNode photoUrl to imageUrl"

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

import Foundation

final class NewsResponseMapper: ArrayResponseMapper<NewsItem>, ResponseMapperProtocol {

    static func process(_ obj: AnyObject?) throws -> [NewsItem] {
        return try process(obj, mapper: { jsonNode in
            guard let publishDate = jsonNode["published"] as? Int? else { return nil }
            guard let title = jsonNode["title"] as? String else { return nil }
            guard let contents = jsonNode["contents"] as? String else { return nil }
            guard let photoUrl = jsonNode["photoUrl"] as? String? else { return nil }
            var published: Date? = nil
            if let publishDate = publishDate {
                published = Date(timeIntervalSince1970: TimeInterval(publishDate/1000))
            }
            var photoURL: URL? = nil
            if let photoUrl = photoUrl {
                photoURL = BackendConfiguration.shared.photosURL.appendingPathComponent(photoUrl)
            }
            return NewsItem(title: title, contents: contents, photoUrl: photoURL, published: published)
        })
    }
}


import UIKit

class ViewController: UIViewController {

  @IBAction func print(sender: AnyObject) {
    let urlPath = "https://cdn2.raywenderlich.com/wp-content/uploads/2014/06/RW-Swift-Cheatsheet-0_3.pdf"
    let _ = NSURL(string: urlPath).flatMap{ printUrl($0) }
  }

  func printUrl(url: NSURL) {
    if (UIPrintInteractionController.canPrintURL(url)) {
      showPrintInteraction(url)
    } else {
      Swift.print("Unable to print: \(url)")
    }
  }

  func showPrintInteraction(url: NSURL) {
    let controller = UIPrintInteractionController.sharedPrintController()
    controller.printingItem = url
    controller.printInfo = printerInfo(url.lastPathComponent!)
    controller.showsPageRange = true
    controller.presentAnimated(true, completionHandler: nil)
  }

  func printerInfo(jobName: String) -> UIPrintInfo {
    let printInfo = UIPrintInfo.printInfo()
    printInfo.outputType = .General
    printInfo.jobName = jobName
    Swift.print("Printing: \(jobName)")
    return printInfo
  }
}

Use guard to see if we can print the url.

import UIKit

class ViewController: UIViewController {

  @IBAction func print(sender: AnyObject) {
    let urlPath = "https://cdn2.raywenderlich.com/wp-content/uploads/2014/06/RW-Swift-Cheatsheet-0_3.pdf"
    let _ = NSURL(string: urlPath).flatMap{ printUrl($0) }
  }

  func printUrl(url: NSURL) {
    guard (UIPrintInteractionController.canPrintURL(url)) else {
      Swift.print("Unable to print: \(url)")
      return
    }

    showPrintInteraction(url)
  }

  func showPrintInteraction(url: NSURL) {
    let controller = UIPrintInteractionController.sharedPrintController()
    controller.printingItem = url
    controller.printInfo = printerInfo(url.lastPathComponent!)
    controller.showsPageRange = true
    controller.presentAnimated(true, completionHandler: nil)
  }

  func printerInfo(jobName: String) -> UIPrintInfo {
    let printInfo = UIPrintInfo.printInfo()
    printInfo.outputType = .General
    printInfo.jobName = jobName
    Swift.print("Printing: \(jobName)")
    return printInfo
  }
}