//
//  HelpCommand.swift
//  Flock
//
//  Created by Jake Heiser on 10/28/16.
//
//

import SwiftCLI

class HelpCommand: SwiftCLI.HelpCommand {

    let name = "--help"
    let signature = "[<opt>] ..."
    let shortDescription = "Prints help information"

    let failOnUnrecognizedOptions = false
    let unrecognizedOptionsPrintingBehavior = UnrecognizedOptionsPrintingBehavior.printNone
    let helpOnHFlag = false

    var allCommands: [Command] = []
    var printCLIDescription = true

    func setupOptions(options: OptionRegistry) {}

    func execute(arguments: CommandArguments) throws {
        print("Available tasks:")
        for task in Flock.tasks {
            print("flock \(task.fullName)")
        }
    }

}

// This will never actually be invoked
class VersionCommand: Command {

    let name = "--version"
    let signature = ""
    let shortDescription = ""

    func execute(arguments: CommandArguments) throws {}

}

Print how to get flock help

//
//  HelpCommand.swift
//  Flock
//
//  Created by Jake Heiser on 10/28/16.
//
//

import SwiftCLI

class HelpCommand: SwiftCLI.HelpCommand {

    let name = "--help"
    let signature = "[<opt>] ..."
    let shortDescription = "Prints help information"

    let failOnUnrecognizedOptions = false
    let unrecognizedOptionsPrintingBehavior = UnrecognizedOptionsPrintingBehavior.printNone
    let helpOnHFlag = false

    var allCommands: [Command] = []
    var printCLIDescription = true

    func setupOptions(options: OptionRegistry) {}

    func execute(arguments: CommandArguments) throws {
        print("Available tasks:")
        for task in Flock.tasks {
            print("flock \(task.fullName)")
        }
        print()
        print("flock --help")
    }

}

// This will never actually be invoked
class VersionCommand: Command {

    let name = "--version"
    let signature = ""
    let shortDescription = ""

    func execute(arguments: CommandArguments) throws {}

}


/// Represents a HTTP Header, Key and Value
public typealias Header = (String, String)

/// Represents a HTTP request or response body
public protocol PayloadType {
  /// Returns the next byte in the payload
  mutating func next() -> UInt8?
}

/// Represents a HTTP Request
public protocol RequestType {
  var method:String { get }
  var path:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

/// Represents a HTTP Response
public protocol ResponseType {
  var statusLine:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

public typealias Application = RequestType -> ResponseType

Make the payload return an array of int's

/// Represents a HTTP Header, Key and Value
public typealias Header = (String, String)

/// Represents a HTTP request or response body
public protocol PayloadType {
  /// Returns the next byte in the payload
  mutating func next() -> [UInt8]?
}

/// Represents a HTTP Request
public protocol RequestType {
  var method:String { get }
  var path:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

/// Represents a HTTP Response
public protocol ResponseType {
  var statusLine:String { get }
  var headers:[Header] { get }
  var body: PayloadType? { get set }
}

public typealias Application = RequestType -> ResponseType


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

import Foundation

#if !os(Linux)
	typealias NCRegularExpression = NSRegularExpression
	typealias NCTextCheckingResult = NSTextCheckingResult
#else
	typealias NCRegularExpression = NSRegularExpression
	typealias NCTextCheckingResult = TextCheckingResult
#endif

Fix platform types for Linux

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

import Foundation

#if !os(Linux)
	typealias NCRegularExpression = NSRegularExpression
	typealias NCTextCheckingResult = NSTextCheckingResult
#else
	typealias NCRegularExpression = NSRegularExpression
	typealias NCTextCheckingResult = NSTextCheckingResult
#endif


//
//  MarkdownNotesViewController.swift
//  Notes
//
//  Created by Yohannes Wijaya on 9/23/16.
//  Copyright © 2016 Yohannes Wijaya. All rights reserved.
//

import UIKit

class MarkdownNotesViewController: UIViewController {

  // MARK: - Stored Properties

  var note: Notes?

  // MARK: - IBOutlet Properties

  @IBOutlet weak var markdownNotesTextView: UITextView! {
    didSet {
      guard let validNote = self.note else { return }
      let markdownNote = SwiftyMarkdown(string: validNote.entry)
      markdownNote.body.fontName = "AvenirNext-Regular"
      markdownNote.h1.color = UIColor.red
      markdownNote.h1.fontName = "AvenirNext-Bold"
      self.markdownNotesTextView.attributedText = markdownNote.attributedString()
    }
  }
}

Integrate Safari View Controller to intercept clicked url

//
//  MarkdownNotesViewController.swift
//  Notes
//
//  Created by Yohannes Wijaya on 9/23/16.
//  Copyright © 2016 Yohannes Wijaya. All rights reserved.
//

import UIKit
import SafariServices

class MarkdownNotesViewController: UIViewController, UITextViewDelegate {

  // MARK: - Stored Properties

  var note: Notes?

  // MARK: - IBOutlet Properties

  @IBOutlet weak var markdownNotesTextView: UITextView! {
    didSet {
      guard let validNote = self.note else { return }
      let markdownNote = SwiftyMarkdown(string: validNote.entry)
      markdownNote.body.fontName = "AvenirNext-Regular"
      markdownNote.h1.color = UIColor.red
      markdownNote.h1.fontName = "AvenirNext-Bold"
      self.markdownNotesTextView.attributedText = markdownNote.attributedString()
    }
  }

  // MARK: - UIViewController Methods

  override func viewDidLoad() {
    super.viewDidLoad()

    self.markdownNotesTextView.delegate = self
  }

  // MARK: - UITextFieldDelegate Methods

  func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    let safariViewController = SFSafariViewController(url: URL)
    self.present(safariViewController, animated: true, completion: nil)
    return false
  }
}


//
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//

import Foundation
@_exported import AnyCodable

// MARK: - Bundle

extension Bundle {
    private class XcoreMarker {}
    public static var xcore: Bundle {
        #if SWIFT_PACKAGE
        return .module
        #else
        return .init(for: XcoreMarker.self)
        #endif
    }
}

extension AnyCodable {
    public static func from(_ value: Any) -> Self {
        self.init(value)
    }
}

Fix for package depending on other packages fix

//
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//

import Foundation
@_exported import AnyCodable

// MARK: - Bundle

extension Bundle {
    private class XcoreMarker {}
    public static var xcore: Bundle {
        #if SWIFT_PACKAGE
        return .myModule
        #else
        return .init(for: XcoreMarker.self)
        #endif
    }
}

extension AnyCodable {
    public static func from(_ value: Any) -> Self {
        self.init(value)
    }
}

// Fix for package depending on other packages fix
// =============================================================================
// TODO: Check previews under Xcode 14 to see if this is fixed?
private let name = "Xcore"

private class CurrentBundleFinder {}

// Unable to find Bundle in package target tests or SwiftUI Previews when
// package depends on another package containing resources accessed via
// Bundle.module.
//
// - SeeAlso: https://forums.swift.org/t/unable-to-find-bundle-in-package-target-tests-when-package-depends-on-another-package-containing-resources-accessed-via-bundle-module/43974/2
extension Foundation.Bundle {
    /// Returns the resource bundle associated with the current Swift module.
    static var myModule: Bundle = {
        let bundleName = "Xcore_\(name)"
        let localBundleName = "LocalPackages_\(name)"

        let candidates = [
            // Bundle should be present here when the package is linked into an App.
            Bundle.main.resourceURL,

            // Bundle should be present here when the package is linked into a framework.
            Bundle(for: CurrentBundleFinder.self).resourceURL,

            // For command-line tools.
            Bundle.main.bundleURL,

            // Bundle should be present here when running previews from a different package (this is the path to "…/Debug-iphonesimulator/").
            Bundle(for: CurrentBundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent(),
            Bundle(for: CurrentBundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent()
        ]

        for candidate in candidates {
            let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
            if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
                return bundle
            }

            let localBundlePath = candidate?.appendingPathComponent(localBundleName + ".bundle")
            if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
                return bundle
            }
        }

        fatalError("Unable to find bundle named \(name).")
    }()
}
// =============================================================================


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

import PackageDescription

let pkgName = "gir2swift"

let package = Package(
    name: pkgName,
    dependencies: [ .package(url: "https://github.com/rhx/SwiftLibXML.git", from: "2.0.0"), ],
    targets: [
        .target(name: pkgName, dependencies: ["SwiftLibXML"]),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.byNameItem(name: pkgName)]),
    ]
)

Use SwiftLibXML from master branch

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

import PackageDescription

let pkgName = "gir2swift"

let package = Package(
    name: pkgName,
    dependencies: [ .package(url: "https://github.com/rhx/SwiftLibXML.git", .branch("master")) ],
    targets: [
        .target(name: pkgName, dependencies: ["SwiftLibXML"]),
        .testTarget(name: "\(pkgName)Tests", dependencies: [.byNameItem(name: pkgName)]),
    ]
)


// swift-tools-version:5.3

import PackageDescription

struct ProjectSettings {
    static let marketingVersion: String = "3.0.1"
}

let package = Package(
    name: "SRGLogger",
    platforms: [
        .iOS(.v9),
        .tvOS(.v12),
        .watchOS(.v5)
    ],
    products: [
        .library(
            name: "SRGLogger",
            targets: ["SRGLogger"]
        ),
        .library(
            name: "SRGLoggerSwift",
            targets: ["SRGLoggerSwift"]
        )
    ],
    targets: [
        .target(
            name: "SRGLogger",
            cSettings: [
                .define("MARKETING_VERSION", to: "\"\(ProjectSettings.marketingVersion)\"")
            ]
        ),
        .target(
            name: "SRGLoggerSwift",
            dependencies: ["SRGLogger"]
        ),
        .testTarget(
            name: "SRGLoggerTests",
            dependencies: ["SRGLogger"]
        ),
        .testTarget(
            name: "SRGLoggerSwiftTests",
            dependencies: ["SRGLoggerSwift"]
        )
    ]
)

Remove assertions in release builds

// swift-tools-version:5.3

import PackageDescription

struct ProjectSettings {
    static let marketingVersion: String = "3.0.1"
}

let package = Package(
    name: "SRGLogger",
    platforms: [
        .iOS(.v9),
        .tvOS(.v12),
        .watchOS(.v5)
    ],
    products: [
        .library(
            name: "SRGLogger",
            targets: ["SRGLogger"]
        ),
        .library(
            name: "SRGLoggerSwift",
            targets: ["SRGLoggerSwift"]
        )
    ],
    targets: [
        .target(
            name: "SRGLogger",
            cSettings: [
                .define("MARKETING_VERSION", to: "\"\(ProjectSettings.marketingVersion)\""),
                .define("NS_BLOCK_ASSERTIONS", to: "1", .when(configuration: .release))
            ]
        ),
        .target(
            name: "SRGLoggerSwift",
            dependencies: ["SRGLogger"],
            cSettings: [
                .define("NS_BLOCK_ASSERTIONS", to: "1", .when(configuration: .release))
            ]
        ),
        .testTarget(
            name: "SRGLoggerTests",
            dependencies: ["SRGLogger"]
        ),
        .testTarget(
            name: "SRGLoggerSwiftTests",
            dependencies: ["SRGLoggerSwift"]
        )
    ]
)


//
//  CardSet.swift
//  HSTracker
//
//  Created by Benjamin Michotte on 8/06/16.
//  Copyright © 2016 Benjamin Michotte. All rights reserved.
//

import Foundation

// swiftlint:disable type_name
enum CardSet: String {
    case all // fake one
    case core, expert1, naxx, gvg, brm,
    tgt, loe, promo, reward, hero_skins,
    og, kara, gangs, ungoro, hof, fp1, pe1

    static func allValues() -> [CardSet] {
        return [.core, .expert1, .naxx, .gvg, .brm,
                .tgt, .loe, .promo, .reward, .hero_skins,
                .og, .kara, .gangs, .ungoro]
    }

    static func deckManagerValidCardSets() -> [CardSet] {
        return [.all, .expert1, .naxx, .gvg, .brm, .tgt, .loe, .og, .kara, .gangs, .ungoro]
    }

    static func wildSets() -> [CardSet] {
        return [.naxx, .gvg, .brm, .tgt, .loe, .hof, .fp1, .pe1, .promo]
    }
}

Add Hall Of Fame cards

//
//  CardSet.swift
//  HSTracker
//
//  Created by Benjamin Michotte on 8/06/16.
//  Copyright © 2016 Benjamin Michotte. All rights reserved.
//

import Foundation

// swiftlint:disable type_name
enum CardSet: String {
    case all // fake one
    case core, expert1, naxx, gvg, brm,
    tgt, loe, promo, reward, hero_skins,
    og, kara, gangs, ungoro, hof

    static func allValues() -> [CardSet] {
        return [.core, .expert1, .naxx, .gvg, .brm,
                .tgt, .loe, .promo, .reward, .hero_skins,
                .og, .kara, .gangs, .ungoro, .hof]
    }

    static func deckManagerValidCardSets() -> [CardSet] {
        return [.all, .expert1, .naxx, .gvg, .brm, .tgt, .loe, .og, .kara, .gangs, .ungoro]
    }

    static func wildSets() -> [CardSet] {
        return [.naxx, .gvg, .brm, .tgt, .loe, .hof, .promo]
    }
}


// swift-tools-version:5.2

import PackageDescription

let package = Package(
    name: "Gtk",
    products: [ .library(name: "Gtk", targets: ["Gtk"]) ],
    dependencies: [
        .package(name: "Atk", url: "https://github.com/rhx/SwiftAtk.git", .branch("master")),
        .package(name: "Gdk", url: "https://github.com/rhx/SwiftGdk.git", .branch("master")),
    ],
    targets: [
	.systemLibrary(name: "CGtk", pkgConfig: "gtk-3.0 gdk-3.0 pangocairo pangoft2 pango gio-unix-2.0 glib-2.0",
	    providers: [
		.brew(["gtk+3", "glib", "glib-networking", "gobject-introspection"]),
		.apt(["libgtk-3-dev", "libglib2.0-dev", "glib-networking", "gobject-introspection", "libgirepository1.0-dev"])
	    ]),
        .target(name: "Gtk", dependencies: ["GtkCHelpers", "Gdk", "Atk"]),
        .target(name: "GtkCHelpers", dependencies: ["CGtk"]),
        .testTarget(name: "GtkTests", dependencies: ["Gtk"]),
    ]
)

Remove the need to use build sh

// swift-tools-version:5.2

import PackageDescription

let package = Package(
    name: "Gtk",
    products: [ .library(name: "Gtk", targets: ["Gtk"]) ],
    dependencies: [
        .package(name: "Atk", url: "https://github.com/mikolasstuchlik/SwiftAtk.git", .branch("master")),
        .package(name: "Gdk", url: "https://github.com/mikolasstuchlik/SwiftGdk.git", .branch("master")),
    ],
    targets: [
	.systemLibrary(name: "CGtk", pkgConfig: "gtk+-3.0",
	    providers: [
		.brew(["gtk+3", "glib", "glib-networking", "gobject-introspection"]),
		.apt(["libgtk-3-dev", "libglib2.0-dev", "glib-networking", "gobject-introspection", "libgirepository1.0-dev"])
	    ]),
        .target(name: "Gtk", dependencies: ["GtkCHelpers", "Gdk", "Atk"]),
        .target(name: "GtkCHelpers", dependencies: ["CGtk"]),
        .testTarget(name: "GtkTests", dependencies: ["Gtk"]),
    ]
)


// swift-tools-version:5.0
import PackageDescription

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

Put a minimum iOS deployment level in

// swift-tools-version:5.0
import PackageDescription

let package = Package(
  name: "DynamicColor",
  platforms: [
	.iOS("11.0")
	],
  products: [
    .library(name: "DynamicColor", targets: ["DynamicColor"]),
  ],
  targets: [
    .target(
      name: "DynamicColor",
      dependencies: [],
      path: "Sources"),
    .testTarget(
      name: "DynamicColorTests",
      dependencies: ["DynamicColor"],
      path: "Tests"),
  ]
)


import XCTest
@testable import HaCWebsiteLib

class DateUtilsTests: HaCWebsiteLibTestCase {
  func testDate() {
    let readableDate = Date.from(year: 2017, month: 10, day: 25, hour: 19, minute: 00)
    let timestampDate = Date(timeIntervalSince1970: 1508954400)

    XCTAssertEqual(readableDate, timestampDate)
  }

  func testTwiceOccurringDate() {
    // This time occurs twice because the clocks go back
    // We should take the time that this represents in the original time zone
    let twiceOccuringDate = Date.from(year: 2017, month: 10, day: 29, hour: 01, minute: 30)
    let timestampDate = Date(timeIntervalSince1970: 1509240600)

    XCTAssertEqual(twiceOccuringDate, timestampDate)
  }

  static var allTests : [(String, (DateUtilsTests) -> () -> Void)] {
    return [
      ("testDate", testDate),
      ("testTwiceOccuringDate", testTwiceOccurringDate)
    ]
  }
}

Add test for date with single digit month

import XCTest
@testable import HaCWebsiteLib

class DateUtilsTests: HaCWebsiteLibTestCase {
  func testSingleDigitDate() {
    let readableDate = Date.from(year: 2017, month: 3, day: 2, hour: 9, minute: 0)
    let timestampDate = Date(timeIntervalSince1970: 1488445200)

    XCTAssertEqual(readableDate, timestampDate)
  }

  func testDoubleDigitDate() {
    let readableDate = Date.from(year: 2017, month: 10, day: 25, hour: 19, minute: 00)
    let timestampDate = Date(timeIntervalSince1970: 1508954400)

    XCTAssertEqual(readableDate, timestampDate)
  }

  func testTwiceOccurringDate() {
    // This time occurs twice because the clocks go back
    // We should take the time that this represents in the original time zone
    let twiceOccuringDate = Date.from(year: 2017, month: 10, day: 29, hour: 01, minute: 30)
    let timestampDate = Date(timeIntervalSince1970: 1509240600)

    XCTAssertEqual(twiceOccuringDate, timestampDate)
  }

  static var allTests : [(String, (DateUtilsTests) -> () -> Void)] {
    return [
      ("testSingleDigitDate", testSingleDigitDate),
      ("testDoubleDigitDate", testDoubleDigitDate),
      ("testTwiceOccuringDate", testTwiceOccurringDate)
    ]
  }
}


import UIKit

class PagingScrollView: UIScrollView {

  var reusableViews = [UIView]()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

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

  func configure() {
    pagingEnabled = true
    directionalLockEnabled = true
  }

  override func layoutSubviews() {
    super.layoutSubviews()
    recenterIfNecessary()
  }

  func recenterIfNecessary() {
    if reusableViews.isEmpty { return }
    let contentWidth = contentSize.width
    let centerOffsetX = (contentWidth - bounds.size.width) / 2

    let distanceFromCenter = contentOffset.x - centerOffsetX

    if fabs(distanceFromCenter) > (contentWidth / 3) {
      contentOffset = CGPoint(x: centerOffsetX, y: contentOffset.y)

      if distanceFromCenter > 0 {
        reusableViews.shiftRight()
      } else {
        reusableViews.shiftLeft()
      }
      for (index, subview) in reusableViews.enumerate() {
        subview.frame.origin.x = bounds.width * CGFloat(index)
        subview.frame.size = bounds.size
      }
    }
  }
}

extension Array {
  mutating func shiftLeft() {
    insert(removeFirst(), atIndex: 0)
  }

  mutating func shiftRight() {
    append(removeFirst())
  }
}

Add Reusable protocol declaration to scrollview

import UIKit

protocol Reusable: class {
  func prepareForReuse()
}

class PagingScrollView: UIScrollView {

  var reusableViews = [UIView]()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

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

  func configure() {
    pagingEnabled = true
    directionalLockEnabled = true
  }

  override func layoutSubviews() {
    super.layoutSubviews()
    recenterIfNecessary()
  }

  func recenterIfNecessary() {
    if reusableViews.isEmpty { return }
    let contentWidth = contentSize.width
    let centerOffsetX = (contentWidth - bounds.size.width) / 2

    let distanceFromCenter = contentOffset.x - centerOffsetX

    if fabs(distanceFromCenter) > (contentWidth / 3) {
      contentOffset = CGPoint(x: centerOffsetX, y: contentOffset.y)

      if distanceFromCenter > 0 {
        reusableViews.shiftRight()
      } else {
        reusableViews.shiftLeft()
      }
      for (index, subview) in reusableViews.enumerate() {
        subview.frame.origin.x = bounds.width * CGFloat(index)
        subview.frame.size = bounds.size
      }
    }
  }
}

extension Array {
  mutating func shiftLeft() {
    insert(removeFirst(), atIndex: 0)
  }

  mutating func shiftRight() {
    append(removeFirst())
  }
}


// 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: "Conductor",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .executable(
            name: "Conductor",
            targets: ["Conductor"]
        ),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(url: "https://github.com/danger/swift.git", from: "3.0.0"),
        .package(url: "https://github.com/kylef/Commander.git", from: "0.9.1"),
        .package(url: "https://github.com/davecom/SwiftGraph.git", .branch("master")),
    ],
    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: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph"]
        ),
        .testTarget(
            name: "ConductorTests",
            dependencies: ["Conductor"]
        ),
    ]
)

Update dependency danger/swift to from: "3.10.1"

// 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: "Conductor",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .executable(
            name: "Conductor",
            targets: ["Conductor"]
        ),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(url: "https://github.com/danger/swift.git", from: "3.10.1"),
        .package(url: "https://github.com/kylef/Commander.git", from: "0.9.1"),
        .package(url: "https://github.com/davecom/SwiftGraph.git", .branch("master")),
    ],
    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: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph"]
        ),
        .testTarget(
            name: "ConductorTests",
            dependencies: ["Conductor"]
        ),
    ]
)


import PackageDescription

let package = Package(
    name: "zosconnectforswift",
    targets: [],
    dependencies: [
      .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0)..<Version(3, .max, .max)),
      .Package(url: "https://github.com/IBM-Swift/Kitura-net",
          majorVersion: 1, minor: 3),
    ]
)

Revert to IBM-Swift/SwiftyJSON for Linux support

import PackageDescription

let package = Package(
    name: "zosconnectforswift",
    targets: [],
    dependencies: [
      .Package(url: "https://github.com/IBM-Swift/SwiftyJSON", versions: Version(1,0,0)..<Version(15, .max, .max)),
      .Package(url: "https://github.com/IBM-Swift/Kitura-net",
          majorVersion: 1, minor: 3),
    ]
)


//
//  DateUtil.swift
//  eSportsKitProject
//
//  Created by Taylor Caldwell on 7/10/15.
//  Copyright (c) 2015 Rithms. All rights reserved.
//

import Foundation

extension String {

    func toNSDate() -> NSDate? {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mmZ"
        return formatter.dateFromString(self)
    }
}

Add optional date format parameter to toNSDate method

//
//  DateUtil.swift
//  eSportsKitProject
//
//  Created by Taylor Caldwell on 7/10/15.
//  Copyright (c) 2015 Rithms. All rights reserved.
//

import Foundation

extension String {

    func toNSDate(format: String = "yyyy-MM-dd'T'HH:mmZ") -> NSDate? {
        let formatter = NSDateFormatter()
        formatter.dateFormat = format
        return formatter.dateFromString(self)
    }
}


//
//  UIView+PAYJP.swift
//  PAYJP
//
//  Created by Li-Hsuan Chen on 2019/08/09.
//  Copyright © 2019 PAY, Inc. All rights reserved.
//

import Foundation

Add UIView's extension to fetch its view controller.

//
//  UIView+PAYJP.swift
//  PAYJP
//
//  Created by Li-Hsuan Chen on 2019/08/09.
//  Copyright © 2019 PAY, Inc. All rights reserved.
//

import Foundation

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}


//
//  MediaViewerController.swift
//  AtMe
//
//  Created by Joel Rorseth on 2018-04-28.
//  Copyright © 2018 Joel Rorseth. All rights reserved.
//

import UIKit

class MediaViewerController: UIViewController {

    var contentImageView: UIImageView!
    var image: UIImage?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.black

        contentImageView = UIImageView(frame: self.view.frame)
        contentImageView.contentMode = UIViewContentMode.scaleAspectFit
        view.addSubview(contentImageView)

//        contentImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
//        contentImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
//        contentImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
//        contentImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

        if let image = image {
            contentImageView.image = image
        } else { print("Error: No image provided to MediaViewerController") }

        let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MediaViewerController.viewTapped))
        view.addGestureRecognizer(tapRecognizer)
    }

    @objc func viewTapped() {
        dismiss(animated: true, completion: nil)
    }
}

Implement pinch to zoom in media viewer

//
//  MediaViewerController.swift
//  AtMe
//
//  Created by Joel Rorseth on 2018-04-28.
//  Copyright © 2018 Joel Rorseth. All rights reserved.
//

import UIKit

class MediaViewerController: UIViewController {

  var scrollView: UIScrollView!
  var contentImageView: UIImageView!
  var image: UIImage?

  override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.black

    scrollView = UIScrollView(frame: view.frame)
    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 5.0
    scrollView.delegate = self

    contentImageView = UIImageView(frame: self.view.frame)
    contentImageView.contentMode = UIViewContentMode.scaleAspectFit

    // Form view hierarchy -- UIView -> UIScrollView -> UIImageView
    view.addSubview(scrollView)
    scrollView.addSubview(contentImageView)

    // Provide the UIImage to the UIImageView
    if let image = image {
      contentImageView.image = image
    } else { print("Error: No image provided to MediaViewerController") }

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MediaViewerController.viewTapped))
    view.addGestureRecognizer(tapRecognizer)
  }

  // Handler for tap gesture on the view
  @objc func viewTapped() {
    dismiss(animated: true, completion: nil)
  }
}

// MARK: UIScrollViewDelegate
extension MediaViewerController: UIScrollViewDelegate {

  // Provide the view to be scaled when zooming in the UIScrollView
  func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return contentImageView
  }
}


import Foundation

struct Vector: CustomStringConvertible {

    var x: Double
    var y: Double

    init(x: Double, y: Double){
        self.x = x;
        self.y = y;
    }

    func magnititude() -> Double {
        return pow(x * x + y * y, 1/2)
    }

    var description: String {
        return "<\(x),\(y)>"
    }
}

func + (left: Vector, right: Vector) -> Vector {
    return Vector(x: left.x + right.x, y: left.y + right.y)
}

func * (left: Vector, right: Vector) -> Double {
    return left.x * right.x + left.y * right.y
}

let u = Vector(x: 3, y: 4)
let v = Vector(x: -5, y: 10)

assert(u.x == 3)
assert(u.y == 4)
assert(u.magnititude() == 5)
print(String(u + v))
assert(String(u + v) == "<-2.0,14.0>")
assert(u * v == 25)

Use sqrt, since 1/2 is actually 0 in isolation

import Foundation

struct Vector: CustomStringConvertible {

    var x: Double
    var y: Double

    init(x: Double, y: Double){
        self.x = x;
        self.y = y;
    }

    func magnititude() -> Double {
        return sqrt(x * x + y * y)
    }

    var description: String {
        return "<\(x),\(y)>"
    }
}

func + (left: Vector, right: Vector) -> Vector {
    return Vector(x: left.x + right.x, y: left.y + right.y)
}

func * (left: Vector, right: Vector) -> Double {
    return left.x * right.x + left.y * right.y
}

let u = Vector(x: 3, y: 4)
let v = Vector(x: -5, y: 10)

assert(u.x == 3)
assert(u.y == 4)
assert(u.magnititude() == 5)
assert(String(u + v) == "<-2.0,14.0>")
assert(u * v == 25)


extension Properties {
  public struct Color: Property, SimpleProperty, StyleComponent {
    public let label = "color"
    public let value: String

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

  public struct Opacity: Property, SimpleProperty, StyleComponent {
    public let label = "opacity"
    public let value: String

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

Make opacity property use a double

extension Properties {
  public struct Color: Property, SimpleProperty, StyleComponent {
    public let label = "color"
    public let value: String

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

  public struct Opacity: Property, SimpleProperty, StyleComponent {
    public let label = "opacity"
    public let value: String

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

    public init(_ value: PropertyValues.Reset) {
      self.value = value.stringValue
    }
  }
}


type messagefile {}

(messagefile t) greeting(string m) {
    app {
        echo m stdout=@filename(t);
    }
}

messagefile outfile <"091-case.out">;

int selector = 8;

print(selector);

string message;

switch(selector) {
  case 3:
    message="first message";
  case 8:
    message="eighth message";
  case 57:
    message="last message";
  default:
    message="no message at all...";
}

outfile = greeting(message);

Remove uses of print in language-behaviour test, as this was removed in r2921

type messagefile {}

(messagefile t) greeting(string m) {
    app {
        echo m stdout=@filename(t);
    }
}

messagefile outfile <"091-case.out">;

int selector = 8;

trace(selector);

string message;

switch(selector) {
  case 3:
    message="first message";
  case 8:
    message="eighth message";
  case 57:
    message="last message";
  default:
    message="no message at all...";
}

outfile = greeting(message);


import Foundation

/// This class has the only responsibility of creating visual-only elements.
///
class VisualOnlyElementFactory {

    /// Creates a visual-only newline, inheriting the specified string attributes.
    ///
    /// - Parameters:
    ///     - inheritedAttributes: the string attributes that the element must inherit.
    ///             Defaults to `nil`.
    ///
    /// - Returns: the requested visual-only element.
    ///
    func newline(inheritingAttributes inheritedAttributes: [String:Any]? = nil) -> NSAttributedString {
        var attributes = inheritedAttributes ?? [String:Any]()

        attributes[VisualOnlyAttributeName] = VisualOnlyElement.newline

        return NSAttributedString(.newline, attributes: attributes)
    }

    /// Creates a visual-only zero width space, inheriting the specified string attributes.
    ///
    /// - Parameters:
    ///     - inheritedAttributes: the string attributes that the element must inherit.
    ///             Defaults to `nil`.
    ///
    /// - Returns: the requested visual-only element.
    ///
    func zeroWidthSpace(inheritingAttributes inheritedAttributes: [String:Any]? = nil) -> NSAttributedString {
        var attributes = inheritedAttributes ?? [String:Any]()

        attributes[VisualOnlyAttributeName] = VisualOnlyElement.zeroWidthSpace

        return NSAttributedString(.zeroWidthSpace, attributes: attributes)
    }
}

Make the Visual attributes being saved to be string in order to copy/paste to work.

import Foundation

/// This class has the only responsibility of creating visual-only elements.
///
class VisualOnlyElementFactory {

    /// Creates a visual-only newline, inheriting the specified string attributes.
    ///
    /// - Parameters:
    ///     - inheritedAttributes: the string attributes that the element must inherit.
    ///             Defaults to `nil`.
    ///
    /// - Returns: the requested visual-only element.
    ///
    func newline(inheritingAttributes inheritedAttributes: [String:Any]? = nil) -> NSAttributedString {
        var attributes = inheritedAttributes ?? [String:Any]()

        attributes[VisualOnlyAttributeName] = VisualOnlyElement.newline.rawValue

        return NSAttributedString(.newline, attributes: attributes)
    }

    /// Creates a visual-only zero width space, inheriting the specified string attributes.
    ///
    /// - Parameters:
    ///     - inheritedAttributes: the string attributes that the element must inherit.
    ///             Defaults to `nil`.
    ///
    /// - Returns: the requested visual-only element.
    ///
    func zeroWidthSpace(inheritingAttributes inheritedAttributes: [String:Any]? = nil) -> NSAttributedString {
        var attributes = inheritedAttributes ?? [String:Any]()

        attributes[VisualOnlyAttributeName] = VisualOnlyElement.zeroWidthSpace.rawValue

        return NSAttributedString(.zeroWidthSpace, attributes: attributes)
    }
}


//
//  EmailTextValidator.swift
//  ReusableBehaviors
//
//  Created by Scott Williams on 8/5/15.
//  Copyright (c) 2015 Tallwave. All rights reserved.
//

import UIKit

public class EmailTextValidator: RegularExpressionValidator {
    private let _pattern = "^\\S+@\\S+\\.\\S+$"
    @IBInspectable override var pattern: String {
        get { return _pattern }
        set {}
    }
}

Remove IBInspectable since it can't be set anyway

//
//  EmailTextValidator.swift
//  ReusableBehaviors
//
//  Created by Scott Williams on 8/5/15.
//  Copyright (c) 2015 Tallwave. All rights reserved.
//

import UIKit

public class EmailTextValidator: RegularExpressionValidator {
    private let _pattern = "^\\S+@\\S+\\.\\S+$"
    override var pattern: String {
        get { return _pattern }
        set {}
    }
}


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

import Foundation

/// The domain for all errors originating within Carthage.
public let CarthageErrorDomain: NSString = "org.carthage.Carthage"

/// Possible error codes within `CarthageErrorDomain`.
public enum CarthageError {
	/// In a user info dictionary, associated with the exit code from a child
	/// process.
	static let exitCodeKey = "CarthageErrorExitCode"

	/// A launched task failed with an erroneous exit code.
	case ShellTaskFailed(exitCode: Int)

	/// An `NSError` object corresponding to this error code.
	public var error: NSError {
		switch (self) {
		case let .ShellTaskFailed(code):
			return NSError(domain: CarthageErrorDomain, code: 1, userInfo: [ CarthageError.exitCodeKey: code  ])
		}
	}
}

Add description to ShellTaskFailed errors

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

import Foundation

/// The domain for all errors originating within Carthage.
public let CarthageErrorDomain: NSString = "org.carthage.Carthage"

/// Possible error codes within `CarthageErrorDomain`.
public enum CarthageError {
	/// In a user info dictionary, associated with the exit code from a child
	/// process.
	static let exitCodeKey = "CarthageErrorExitCode"

	/// A launched task failed with an erroneous exit code.
	case ShellTaskFailed(exitCode: Int)

	/// An `NSError` object corresponding to this error code.
	public var error: NSError {
		switch (self) {
		case let .ShellTaskFailed(code):
			return NSError(domain: CarthageErrorDomain, code: 1, userInfo: [
				NSLocalizedDescriptionKey: "A shell task failed with exit code \(code)",
				CarthageError.exitCodeKey: code
			])
		}
	}
}


//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        if let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "") {
            return "<\(file):\(line)>"
        }
        return ""
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}

Remove conditional unwrapping for expression which can no longer potentially return nil

//
//  Loggable.swift
//  Loggable
//
//  Created by Michael Fourre on 2/4/17.
//

public protocol Loggable {

}

public extension Loggable {
    fileprivate static func position(file: String, function: String, line: Int) -> String {
        let path = file.components(separatedBy: "/")
        let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "")
        return "<\(file):\(line)>"
    }

    fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
        print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
    }

    fileprivate static func logRemaining(_ strArr: [String]?) {
        guard let count = strArr?.count , count > 1 else { return }
        for newLine in 1..<count {
            if let line = strArr?[newLine] {
                print(line)
            }
        }
    }

    public static func log(type: String, string: String?, file: String, function: String, line: Int) {
        let strArr = string?.components(separatedBy: "\n")
        self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
        self.logRemaining(strArr)
    }
}


/*
 This source file is part of the Swift.org open source project

 Copyright 2016 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
 */

import XCTest
import Basic
import libc
import Utility
import TestSupport

class InterruptHandlerTests: XCTestCase {
    func testBasics() throws {
        mktmpdir { path in
            let exec = SwiftPMProduct.TestSupportExecutable.path.asString
            let waitFile = path.appending(component: "waitFile")
            let process = Process(args: exec, "interruptHandlerTest", waitFile.asString)
            try process.launch()
            guard waitForFile(waitFile) else {
                return XCTFail("Couldn't launch the process")
            }
            process.signal(SIGINT)
            let result = try process.waitUntilExit()
            XCTAssertEqual(try result.utf8Output(), "Hello from handler!\n")
        }
    }

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

Disable interrupt Handler test due to SR-5042

/*
 This source file is part of the Swift.org open source project

 Copyright 2016 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
 */

import XCTest
import Basic
import libc
import Utility
import TestSupport

class InterruptHandlerTests: XCTestCase {
    func testBasics() throws {
        // Disabled because it sometimes hangs the CI, possibly due to https://bugs.swift.org/browse/SR-5042
      #if false
        mktmpdir { path in
            let exec = SwiftPMProduct.TestSupportExecutable.path.asString
            let waitFile = path.appending(component: "waitFile")
            let process = Process(args: exec, "interruptHandlerTest", waitFile.asString)
            try process.launch()
            guard waitForFile(waitFile) else {
                return XCTFail("Couldn't launch the process")
            }
            process.signal(SIGINT)
            let result = try process.waitUntilExit()
            XCTAssertEqual(try result.utf8Output(), "Hello from handler!\n")
        }
      #endif
    }

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


// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "Bond",
    products: [
        .library(name: "Bond", targets: ["Bond"])
    ],
    dependencies: [
        .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.10.0")),
        .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.1"))
    ],
    targets: [
        .target(name: "BNDProtocolProxyBase"),
        .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
        .testTarget(name: "BondTests", dependencies: ["Bond"])
    ]
)

Add ReactiveKit as test dependency

// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "Bond",
    products: [
        .library(name: "Bond", targets: ["Bond"])
    ],
    dependencies: [
        .package(url: "https://github.com/DeclarativeHub/ReactiveKit.git", .upToNextMajor(from: "3.10.0")),
        .package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.4.1"))
    ],
    targets: [
        .target(name: "BNDProtocolProxyBase"),
        .target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
        .testTarget(name: "BondTests", dependencies: ["Bond", "ReactiveKit"])
    ]
)


//
// Created by Alexander Maslennikov on 27.01.16.
// Copyright (c) 2016 Heads and Hands. All rights reserved.
//

import UIKit
import ChameleonFramework

extension UIColor {

    static func hhkl_mainColor() -> UIColor {
        return UIColor.flatBlackColorDark()
    }

    static func hhkl_secondaryColor() -> UIColor {
        return UIColor.flatWhiteColor()
    }

    static func hhkl_tertiaryColor() -> UIColor {
        return UIColor.flatWhiteColorDark()
    }

    static func hhkl_yellowFlatColor() -> UIColor {
        return UIColor.flatYellowColor()
    }

    static func hhkl_redFlatColor() -> UIColor {
        return UIColor.flatRedColor()
    }

    static func hhkl_textColor() -> UIColor {
        return UIColor(contrastingBlackOrWhiteColorOn:UIColor.hhkl_mainColor(), isFlat: true)
    }
}

Add new yellow and red colors

//
// Created by Alexander Maslennikov on 27.01.16.
// Copyright (c) 2016 Heads and Hands. All rights reserved.
//

import UIKit
import ChameleonFramework

extension UIColor {

    static func hhkl_mainColor() -> UIColor {
        return UIColor.flatBlackColorDark()
    }

    static func hhkl_secondaryColor() -> UIColor {
        return UIColor.flatWhiteColor()
    }

    static func hhkl_tertiaryColor() -> UIColor {
        return UIColor.flatWhiteColorDark()
    }

    static func hhkl_yellowFlatColor() -> UIColor {
        return UIColor(red: 252/255, green: 186/255, blue: 4/255, alpha: 1.0)
    }

    static func hhkl_redFlatColor() -> UIColor {
        return UIColor(red: 186/255, green: 45/255, blue: 11/255, alpha: 1.0)
    }

    static func hhkl_textColor() -> UIColor {
        return UIColor(contrastingBlackOrWhiteColorOn:UIColor.hhkl_mainColor(), isFlat: true)
    }
}


import PackageDescription

let package = Package(
    name: "Swinject",
    dependencies: [
        .Package(url: "https://github.com/Quick/Quick", majorVersion: 1),
        .Package(url: "https://github.com/Quick/Nimble", majorVersion: 7, minor: 1),
    ]
)

Fix for swiftlint (hound ci).

import PackageDescription

let package = Package(
    name: "Swinject",
    dependencies: [
        .Package(url: "https://github.com/Quick/Quick", majorVersion: 1),
        .Package(url: "https://github.com/Quick/Nimble", majorVersion: 7, minor: 1)
    ]
)


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

import UIKit
import Foundation
import CoreText

class FontLoader: NSObject {
    class func loadFont(_ fontName: String) {

        let bundle = Bundle(for: FontLoader.self)
        var fontURL = URL(string: "")
        for filePath : String in bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) {
            let filename = NSURL(fileURLWithPath: filePath).lastPathComponent!
            if filename.lowercased().range(of: fontName.lowercased()) != nil {
                fontURL = NSURL(fileURLWithPath: filePath) as URL
            }
        }

        do
        {
            let data = try Data(contentsOf: fontURL!)

            let provider = CGDataProvider(data: data as CFData)
            let font = CGFont.init(provider!)

            var error: Unmanaged<CFError>?
            if !CTFontManagerRegisterGraphicsFont(font, &error) {
                let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue())
                let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
                NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
            }

        } catch {

        }

    }
}

Fix build error on XCode 9. Minor refactoring to improve type safety

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

import UIKit
import Foundation
import CoreText

class FontLoader: NSObject {

    class func loadFont(_ fontName: String) {

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

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

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

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

                return
        }

        guard CTFontManagerRegisterGraphicsFont(font, &error) else {

            return
        }

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


import RxSwift

extension StoreProtocol where Self: ObservableType, Self.State == Self.E {
    func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
        let unsubscribe = subscribe { state in
            observer.onNext(state)
        }

        return Disposables.create {
            unsubscribe()
        }
    }
}

Enable stores to behave like Observers

import RxSwift

extension StoreProtocol where Self: ObservableType, Self.State == Self.E {
    func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
        let unsubscribe = subscribe { state in
            observer.onNext(state)
        }

        return Disposables.create {
            unsubscribe()
        }
    }
}

extension StoreProtocol {
    func asObserver() -> AnyObserver<State> {
        return AnyObserver { event in
            if case .next(let action) = event {
                self.dispatch(action)
            }
        }
    }
}


import UIKit

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
    view.tintColor = UIColor.redColor()
  }

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

Create mock events for datasource request

import UIKit
import DateTools

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
    view.tintColor = UIColor.redColor()

    dayView.dataSource = self
  }

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

extension DayViewController: DayViewDataSource {
  func eventViewsForDate(date: NSDate) -> [EventView] {

    let datePeriod = DTTimePeriod(size: .Hour, startingAt: date)
    let eventView = EventView()
    eventView.datePeriod = datePeriod

    return [eventView]
  }
}


//
//  ContentViewController.swift
//  AppearanceNavigationController
//
//  Created by zen on 28/10/15.
//  Copyright © 2015 Zen. All rights reserved.
//

import Foundation
import UIKit

class ContentViewController: UIViewController, AppearanceNavigationControllerContext {

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

        navigationItem.rightBarButtonItem = editButtonItem()
    }

    var appearance: Appearance? {
        didSet {
            setNeedsUpdateNavigationControllerAppearance()
        }
    }

    // mark: - Actions

    override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        setNeedsUpdateNavigationControllerAppearance()
    }

    // mark: - AppearanceNavigationControllerContent

    func prefersNavigationControllerToolbarHidden(navigationController: AppearanceNavigationController) -> Bool {
        return editing
    }

    func preferredNavigationControllerAppearance(navigationController: AppearanceNavigationController) -> Appearance? {
        return editing ? appearance?.inversedAppearance : appearance
    }
}

Add comments for content view controller

//
//  ContentViewController.swift
//  AppearanceNavigationController
//
//  Created by zen on 28/10/15.
//  Copyright © 2015 Zen. All rights reserved.
//

import Foundation
import UIKit

class ContentViewController: UIViewController, AppearanceNavigationControllerContext {

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

        navigationItem.rightBarButtonItem = editButtonItem()
    }

    var appearance: Appearance? {
        didSet {
            setNeedsUpdateNavigationControllerAppearance()
        }
    }

    // mark: - Actions

    override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        setNeedsUpdateNavigationControllerAppearance()
    }

    // mark: - AppearanceNavigationControllerContent

    func prefersNavigationControllerToolbarHidden(navigationController: AppearanceNavigationController) -> Bool {
        // hide toolbar during editing
        return editing
    }

    func preferredNavigationControllerAppearance(navigationController: AppearanceNavigationController) -> Appearance? {
        // inverse navigation bar color and status bar during editing
        return editing ? appearance?.inversedAppearance : appearance
    }
}


//
//  Copyright © 2016 Cleverlance. All rights reserved.
//

public protocol AbstractClass {}

extension AbstractClass {
    var virtualMethod: Never { fatalError() }
}

Make virtual method marker public

//
//  Copyright © 2016 Cleverlance. All rights reserved.
//

public protocol AbstractClass {}

extension AbstractClass {
    public var virtualMethod: Never { fatalError() }
}


//
//  CarouselView.swift
//  CHCarouselView
//
//  Created by Calvin on 8/5/16.
//  Copyright © 2016 CapsLock. All rights reserved.
//

import UIKit

public class CarouselView: UIScrollView {
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet public var views: [UIView] = []

    public var currentPage: Int = 0
    public var selectedCallback: ((currentPage: Int) -> ())?

    override public init(frame: CGRect) {
        super.init(frame: frame)

        self.configure()
    }

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

        self.configure()
    }

    override public func drawRect(rect: CGRect) {
    }

    // MARK: - Private Methods
    private func configure() {
        self.delegate = self
        self.pagingEnabled = true
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
        self.scrollsToTop = false
    }
}

extension CarouselView: UIScrollViewDelegate {
    public func scrollViewDidScroll(scrollView: UIScrollView) {

    }
}

Arrange views to carousel's content and set content size.

//
//  CarouselView.swift
//  CHCarouselView
//
//  Created by Calvin on 8/5/16.
//  Copyright © 2016 CapsLock. All rights reserved.
//

import UIKit

public class CarouselView: UIScrollView {
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet public var views: [UIView] = []

    public var currentPage: Int = 0
    public var selectedCallback: ((currentPage: Int) -> ())?

    override public init(frame: CGRect) {
        super.init(frame: frame)

        self.configure()
    }

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

        self.configure()
    }

    override public func drawRect(rect: CGRect) {
        views.enumerate().forEach { (index: Int, view: UIView) in
            let viewOffset = CGPoint(x: CGFloat(index) * self.bounds.width, y: 0)
            view.frame = CGRect(origin: viewOffset, size: self.bounds.size)

            self.addSubview(view)
        }

        self.contentSize = CGSize(width: CGFloat(views.count) * self.bounds.width, height: self.bounds.height)
    }

    // MARK: - Private Methods
    private func configure() {
        self.delegate = self
        self.pagingEnabled = true
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
        self.scrollsToTop = false
    }
}

extension CarouselView: UIScrollViewDelegate {
    public func scrollViewDidScroll(scrollView: UIScrollView) {

    }
}


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

final class EitherTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}

	func testAutomaticallyEncodedDefinitionsAreEquivalentToHandEncodedDefinitions() {
		let churchModule = Module<Term>.churchEither
		module.definitions.forEach { symbol, type, value in
			assert(churchModule.context[symbol], ==, type)
			assert(churchModule.environment[symbol], ==, value)
		}
	}
}

private let module = Module<Term>.either

import Assertions
@testable import Manifold
import XCTest

Print the symbol when comparing hand-encoded definitions.

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

final class EitherTests: XCTestCase {
	func testModuleTypechecks() {
		module.typecheck().forEach { XCTFail($0.description) }
	}

	func testAutomaticallyEncodedDefinitionsAreEquivalentToHandEncodedDefinitions() {
		let churchModule = Module<Term>.churchEither
		module.definitions.forEach { symbol, type, value in
			assert(churchModule.context[symbol], ==, type, message: "\(symbol)")
			assert(churchModule.environment[symbol], ==, value, message: "\(symbol)")
		}
	}
}

private let module = Module<Term>.either

import Assertions
@testable import Manifold
import XCTest


//
//  MASErrorTestCase.swift
//  mas-tests
//
//  Created by Ben Chatelain on 2/11/18.
//  Copyright © 2018 Andrew Naylor. All rights reserved.
//

//@testable import mas
import XCTest
import Foundation

class MASErrorTestCase: XCTestCase {
    var error: MASError!

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

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

    func testNotSignedIn() {
        error = .notSignedIn
        XCTAssertEqual(error.description, "Not signed in")
    }
}

Add sign in failed tests

//
//  MASErrorTestCase.swift
//  mas-tests
//
//  Created by Ben Chatelain on 2/11/18.
//  Copyright © 2018 Andrew Naylor. All rights reserved.
//

//@testable import mas
import XCTest
import Foundation

class MASErrorTestCase: XCTestCase {
    private let errorDomain = "MAS"
    var error: MASError!
    var nserror: NSError!

    /// Convenience property for setting the value which will be use for the localized description
    /// value of the next NSError created. Only used when the NSError does not have a user info
    /// entry for localized description.
    var localizedDescription: String {
        get { return "dummy value" }
        set {
            NSError.setUserInfoValueProvider(forDomain: errorDomain) { (error: Error, userInfoKey: String) -> Any? in
                return newValue
            }
        }
    }

    override func setUp() {
        super.setUp()
        nserror = NSError(domain: errorDomain, code: 999) //, userInfo: ["NSLocalizedDescriptionKey": "foo"])
    }

    override func tearDown() {
        nserror = nil
        error = nil
        super.tearDown()
    }

    func testNotSignedIn() {
        error = .notSignedIn
        XCTAssertEqual(error.description, "Not signed in")
    }

    func testSignInFailed() {
        error = .signInFailed(error: nil)
        XCTAssertEqual(error.description, "Sign in failed")
    }

    func testSignInFailedError() {
        localizedDescription = "foo"
        error = .signInFailed(error: nserror)
        XCTAssertEqual("Sign in failed: foo", error.description)
    }
}


import Vapor

@available(*, deprecated, renamed: "ModelAuthenticatable")
public typealias ModelUser = ModelAuthenticatable

@available(*, deprecated, renamed: "ModelAuthenticatable")
public typealias ModelUserToken = ModelTokenAuthenticatable

extension Application.Fluent.Sessions {
    @available(*, deprecated, renamed: "Model.sessionAuthenticator()")
    public func middleware<User>(
        for user: User.Type,
        databaseID: DatabaseID? = nil
    ) -> Middleware
        where User: SessionAuthenticatable, User: Model, User.SessionID == User.IDValue
    {
        User.sessionAuthenticator(databaseID)
    }
}

Fix deprecated renamed fix for ModelTokenAuthenticatable

import Vapor

@available(*, deprecated, renamed: "ModelAuthenticatable")
public typealias ModelUser = ModelAuthenticatable

@available(*, deprecated, renamed: "ModelTokenAuthenticatable")
public typealias ModelUserToken = ModelTokenAuthenticatable

extension Application.Fluent.Sessions {
    @available(*, deprecated, renamed: "Model.sessionAuthenticator()")
    public func middleware<User>(
        for user: User.Type,
        databaseID: DatabaseID? = nil
    ) -> Middleware
        where User: SessionAuthenticatable, User: Model, User.SessionID == User.IDValue
    {
        User.sessionAuthenticator(databaseID)
    }
}


//
//  ReactorComponents.swift
//  Reactor
//
//  Created by Suyeol Jeon on 13/04/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

public protocol ReactorComponents {
  associatedtype Action
  associatedtype Mutation
  associatedtype State
}

public struct NoAction {}
public struct NoMutation {}

Add default action and mutation types

//
//  ReactorComponents.swift
//  Reactor
//
//  Created by Suyeol Jeon on 13/04/2017.
//  Copyright © 2017 Suyeol Jeon. All rights reserved.
//

public protocol ReactorComponents {
  associatedtype Action = NoAction
  associatedtype Mutation = Action
  associatedtype State
}

public struct NoAction {}
public struct NoMutation {}


precedencegroup MonadicPrecedenceRight {
    associativity: right
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup MonadicPrecedenceLeft {
    associativity: left
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup ApplicativePrecedence {
    associativity: left
    higherThan: LogicalConjunctionPrecedence
    lowerThan: NilCoalescingPrecedence
}

infix operator >>- : MonadicPrecedenceLeft
infix operator -<< : MonadicPrecedenceRight

infix operator <^> : ApplicativePrecedence
infix operator <*> : ApplicativePrecedence

Add `ResultK` prefix to `precedencegroup`s

precedencegroup ResultKMonadicPrecedenceRight {
    associativity: right
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup ResultKMonadicPrecedenceLeft {
    associativity: left
    lowerThan: LogicalDisjunctionPrecedence
    higherThan: AssignmentPrecedence
}

precedencegroup ResultKApplicativePrecedence {
    associativity: left
    higherThan: LogicalConjunctionPrecedence
    lowerThan: NilCoalescingPrecedence
}

infix operator >>- : ResultKMonadicPrecedenceLeft
infix operator -<< : ResultKMonadicPrecedenceRight

infix operator <^> : ResultKApplicativePrecedence
infix operator <*> : ResultKApplicativePrecedence


//
//  Container.Logging.swift
//  Swinject
//
//  Created by Jakub Vaňo on 30/09/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

public typealias LoggingFunctionType = (String) -> Void

public extension Container {
    /// Function to be used for logging debugging data.
    /// Default implementation writes to standard output.
    public static var logingFunction: LoggingFunctionType? {
        get { return _logingFunction }
        set { _logingFunction = newValue }
    }

    internal static func log(_ message: String) {
        _logingFunction?(message)
    }
}

private var _logingFunction: LoggingFunctionType? = { print($0) }

Fix typo in API from `logingFunction` to `loggingFunction`.

//
//  Container.Logging.swift
//  Swinject
//
//  Created by Jakub Vaňo on 30/09/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

public typealias LoggingFunctionType = (String) -> Void

public extension Container {
    /// Function to be used for logging debugging data.
    /// Default implementation writes to standard output.
    public static var loggingFunction: LoggingFunctionType? {
        get { return _loggingFunction }
        set { _loggingFunction = newValue }
    }

    internal static func log(_ message: String) {
        _loggingFunction?(message)
    }
}

private var _loggingFunction: LoggingFunctionType? = { print($0) }


import UIKit

extension UIViewController {

  // MARK: - Method Swizzling

  public override class func initialize() {
    struct Static {
      static var token: dispatch_once_t = 0
    }

    if self !== UIViewController.self { return }

    dispatch_once(&Static.token) {
      MethodSwizzler.swizzleMethod("viewWillAppear:", cls: self)
      MethodSwizzler.swizzleMethod("viewWillDisappear:", cls: self)
    }
  }

  func jukebox_viewWillAppear(animated: Bool) {
    jukebox_viewWillAppear(animated)

    guard animated else { return }

    var sound: Sound?

    if isMovingToParentViewController() {
      sound = .Push
    } else if isBeingPresented() {
      sound = .Present
    }

    guard let autoSound = sound else { return }

    Jukebox.autoPlay(autoSound)
  }

  func jukebox_viewWillDisappear(animated: Bool) {
    jukebox_viewWillDisappear(animated)

    guard animated && Jukebox.autoPlay else { return }

    var sound: Sound?

    if isMovingFromParentViewController() {
      sound = .Pop
    } else if isBeingDismissed() {
      sound = .Dismiss
    }

    guard let autoSound = sound else { return }

    Jukebox.autoPlay(autoSound)
  }
}

Remove check for auto play

import UIKit

extension UIViewController {

  // MARK: - Method Swizzling

  public override class func initialize() {
    struct Static {
      static var token: dispatch_once_t = 0
    }

    if self !== UIViewController.self { return }

    dispatch_once(&Static.token) {
      MethodSwizzler.swizzleMethod("viewWillAppear:", cls: self)
      MethodSwizzler.swizzleMethod("viewWillDisappear:", cls: self)
    }
  }

  func jukebox_viewWillAppear(animated: Bool) {
    jukebox_viewWillAppear(animated)

    guard animated else { return }

    var sound: Sound?

    if isMovingToParentViewController() {
      sound = .Push
    } else if isBeingPresented() {
      sound = .Present
    }

    guard let autoSound = sound else { return }

    Jukebox.autoPlay(autoSound)
  }

  func jukebox_viewWillDisappear(animated: Bool) {
    jukebox_viewWillDisappear(animated)

    guard animated else { return }

    var sound: Sound?

    if isMovingFromParentViewController() {
      sound = .Pop
    } else if isBeingDismissed() {
      sound = .Dismiss
    }

    guard let autoSound = sound else { return }

    Jukebox.autoPlay(autoSound)
  }
}


import Quick
import Nimble
import Engine

class InPortSpec: QuickSpec {
    override func spec() {

        describe("InPort") {
            var process: BareComponent!

            beforeEach {
                let network = Network()
                process = BareComponent(network)
            }

            it("should belong to a process") {
                let inPort = InPort<Int>(process) { packet in }
                let processId = ObjectIdentifier(process).hashValue
                let inPortProcessId = ObjectIdentifier(inPort.process).hashValue
                expect(inPortProcessId).to(equal(processId))
            }

            it("should have a unique ID") {
                let firstInPort = InPort<Int>(process) { packet in }
                let secondInPort = InPort<Int>(process) { packet in }
                expect(firstInPort.id).toNot(equal(secondInPort.id))
            }

            it("should receive packets") {
                waitUntil { done in
                    let intPacket = 1

                    let inPort = InPort<Int>(process) { packet in
                        expect(packet).to(equal(intPacket))
                        done()
                    }

                    inPort.receive(intPacket)
                }
            }
        }
    }
}

Use an underscore for unused parameters.

import Quick
import Nimble
import Engine

class InPortSpec: QuickSpec {
    override func spec() {

        describe("InPort") {
            var process: BareComponent!

            beforeEach {
                let network = Network()
                process = BareComponent(network)
            }

            it("should belong to a process") {
                let inPort = InPort<Int>(process) { _ in }
                let processId = ObjectIdentifier(process).hashValue
                let inPortProcessId = ObjectIdentifier(inPort.process).hashValue
                expect(inPortProcessId).to(equal(processId))
            }

            it("should have a unique ID") {
                let firstInPort = InPort<Int>(process) { _ in }
                let secondInPort = InPort<Int>(process) { _ in }
                expect(firstInPort.id).toNot(equal(secondInPort.id))
            }

            it("should receive packets") {
                waitUntil { done in
                    let intPacket = 1

                    let inPort = InPort<Int>(process) { packet in
                        expect(packet).to(equal(intPacket))
                        done()
                    }

                    inPort.receive(intPacket)
                }
            }
        }
    }
}


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

import UIKit

public extension String {

    func height(with width: CGFloat, font: UIFont = UIFont.preferredFont(forTextStyle: .body)) -> CGFloat {
        let nsString = self as NSString
        let rect = nsString.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
    }

}

Add string helper for nil or empty

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

import UIKit

public extension String {

    func height(with width: CGFloat, font: UIFont = UIFont.preferredFont(forTextStyle: .body)) -> CGFloat {
        let nsString = self as NSString
        let rect = nsString.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
    }

}

public extension Optional where Wrapped == String {

    var isBlank: Bool {
        return (self ?? "").isEmpty
    }

}


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

extension String.UTF16View.Index {
  /// Construct from an integer offset.
  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public init(_ offset: Int) {
    _precondition(offset >= 0, "Negative UTF16 index offset not allowed")
    self.init(_offset: offset)
  }

  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public func distance(to other: String.UTF16View.Index?) -> Int {
    return _offset.distance(to: other!._offset)
  }

  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public func advanced(by n: Int) -> String.UTF16View.Index {
    return String.UTF16View.Index(_offset.advanced(by: n))
  }
}

Simplify and prepare for more resilience.

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

extension String.UTF16View.Index {
  /// Construct from an integer offset.
  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public init(_ offset: Int) {
    _precondition(offset >= 0, "Negative UTF16 index offset not allowed")
    self.init(encodedOffset: offset)
  }

  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public func distance(to other: String.UTF16View.Index?) -> Int {
    return _offset.distance(to: other!._offset)
  }

  @available(swift, deprecated: 3.2)
  @available(swift, obsoleted: 4.0)
  public func advanced(by n: Int) -> String.UTF16View.Index {
    return String.UTF16View.Index(_offset.advanced(by: n))
  }
}


//
//  LayoutViewPosition.swift
//  NotAutoLayout
//
//  Created by 史翔新 on 2017/02/09.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

extension LayoutView {

	public enum Position {
		case absolute(CGRect)
		case relative(CGRect)
	}

}

extension LayoutView.Position {

	func absoluteRect(in size: CGSize) -> CGRect {

		switch self {
		case .absolute(let rect):
			return rect

		case .relative(let rect):
			return rect.absoluteRectApplied(to: size)
		}

	}

}

Add a custom position case which user can define each property absolute or relative in a rect

//
//  LayoutViewPosition.swift
//  NotAutoLayout
//
//  Created by 史翔新 on 2017/02/09.
//  Copyright © 2017年 史翔新. All rights reserved.
//

import Foundation

extension LayoutView {

	public enum Position {

		public enum CustomValue {
			case absolute(CGFloat)
			case relative(CGFloat)
		}

		case absolute(CGRect)
		case relative(CGRect)
		case custom(x: CustomValue, y: CustomValue, width: CustomValue, height: CustomValue)

	}

}

extension LayoutView.Position.CustomValue {

	func absoluteValue(in length: CGFloat) -> CGFloat {

		switch self {
		case .absolute(let value):
			return value

		case .relative(let value):
			return value * length
		}

	}

}

extension LayoutView.Position {

	func absoluteRect(in size: CGSize) -> CGRect {

		switch self {
		case .absolute(let rect):
			return rect

		case .relative(let rect):
			return rect.absoluteRectApplied(to: size)

		case .custom(x: let x, y: let y, width: let width, height: let height):
			let x = x.absoluteValue(in: size.width)
			let y = y.absoluteValue(in: size.height)
			let width = width.absoluteValue(in: size.width)
			let height = height.absoluteValue(in: size.height)
			return CGRect(x: x, y: y, width: width, height: height)
		}

	}

}


import Cocoa
import WebKit

class FreedrawView: WebView {
    weak var document: Document?
}

// MARK: - Event Handling

extension FreedrawView {

    override func magnifyWithEvent(event: NSEvent) {
        let position = self.convertPoint(event.locationInWindow, fromView: nil)
        document?.callHook("dispatchMagnify", withArguments: [position.x, position.y, event.magnification], error: nil)
    }
}

Fix magnify hook mouse Y position

import Cocoa
import WebKit

class FreedrawView: WebView {
    weak var document: Document?
}

// MARK: - Event Handling

extension FreedrawView {

    override func magnifyWithEvent(event: NSEvent) {
        let position = self.convertPoint(event.locationInWindow, fromView: nil)
        document?.callHook("dispatchMagnify", withArguments: [position.x, frame.height - position.y, event.magnification], error: nil)
    }
}


//
//  UIApplication+SafeShared.swift
//  Tabman
//
//  Created by Merrick Sapsford on 05/01/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

internal extension UIApplication {

    static var safeShared: UIApplication? {
        guard #available(iOSApplicationExtension 8, *) else {
            return nil
        }

        guard UIApplication.responds(to: NSSelectorFromString("sharedApplication")),
            let unmanagedSharedApplication = UIApplication.perform(NSSelectorFromString("sharedApplication")) else {
                return nil
        }

        return unmanagedSharedApplication.takeRetainedValue() as? UIApplication
    }
}

Fix issue with UIApplication extension

//
//  UIApplication+SafeShared.swift
//  Tabman
//
//  Created by Merrick Sapsford on 05/01/2018.
//  Copyright © 2018 UI At Six. All rights reserved.
//

import UIKit

internal extension UIApplication {

    static var safeShared: UIApplication? {
        guard #available(iOSApplicationExtension 8, *) else {
            return nil
        }

        guard UIApplication.responds(to: NSSelectorFromString("sharedApplication")),
            let unmanagedSharedApplication = UIApplication.perform(NSSelectorFromString("sharedApplication")) else {
                return nil
        }

        return unmanagedSharedApplication.takeUnretainedValue() as? UIApplication
    }
}


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Bluetooth",
    products: [
        .library(
            name: "Bluetooth",
            type: .dynamic,
            targets: ["Bluetooth"]
        )
    ],
    targets: [
        .target(name: "Bluetooth", path: "./Sources"),
        .testTarget(name: "BluetoothTests", dependencies: ["Bluetooth"])
    ],
    swiftLanguageVersions: [.v5]
)

Build dynamic framework on Linux

// swift-tools-version:5.0
import PackageDescription

#if os(Linux)
let libraryType: PackageDescription.Product.Library.LibraryType = .dynamic
#else
let libraryType: PackageDescription.Product.Library.LibraryType = .static
#endif

let package = Package(
    name: "Bluetooth",
    products: [
        .library(
            name: "Bluetooth",
            type: libraryType,
            targets: ["Bluetooth"]
        )
    ],
    targets: [
        .target(name: "Bluetooth", path: "./Sources"),
        .testTarget(name: "BluetoothTests", dependencies: ["Bluetooth"])
    ],
    swiftLanguageVersions: [.v5]
)


//
//  PoseGalleryUITests.swift
//  PoseGalleryUITests
//
//  Copyright © 2016 Trollwerks Inc. All rights reserved.
//

import XCTest

final class PoseGalleryUITests: XCTestCase {

    override func setUp() {
        super.setUp()

        continueAfterFailure = false

        let app = XCUIApplication()
        app.launchArguments = ["UI_TESTING_MODE"]
        app.launch()
    }

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

    func testTabNavigation() {
        let app = XCUIApplication()
        let tabBarsQuery = app.tabBars
        let first = tabBarsQuery.buttons["First"]
        let second = tabBarsQuery.buttons["Second"]

        XCTAssert(first.selected == true)

        second.tap()

        let selectedPredicate = NSPredicate(format: "selected == true")
        expectationForPredicate(selectedPredicate, evaluatedWithObject: second, handler: nil)
        waitForExpectationsWithTimeout(5, handler: nil)

        first.tap()

        expectationForPredicate(selectedPredicate, evaluatedWithObject: first, handler: nil)
        waitForExpectationsWithTimeout(5, handler: nil)
    }
}

Improve UITest tab bar reliability, add OpenRadar note

//
//  PoseGalleryUITests.swift
//  PoseGalleryUITests
//
//  Copyright © 2016 Trollwerks Inc. All rights reserved.
//

import XCTest

final class PoseGalleryUITests: XCTestCase {

    override func setUp() {
        super.setUp()

        continueAfterFailure = false

        let app = XCUIApplication()
        app.launchArguments = ["UI_TESTING_MODE"]
        app.launch()
    }

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

    func testTabNavigation() {
        let app = XCUIApplication()
        let tabBar = app.tabBars.elementBoundByIndex(0)
        let first = tabBar.buttons.elementBoundByIndex(0)
        let second = tabBar.buttons.elementBoundByIndex(1)

        XCTAssert(first.selected == true, "first tab not selected at startup")

        // note foreseeable failure here:
        // https://openradar.appspot.com/26493495
        second.tap()

        let selectedPredicate = NSPredicate(format: "selected == true")
        expectationForPredicate(selectedPredicate, evaluatedWithObject: second, handler: nil)
        waitForExpectationsWithTimeout(5, handler: nil)

        first.tap()

        expectationForPredicate(selectedPredicate, evaluatedWithObject: first, handler: nil)
        waitForExpectationsWithTimeout(5, handler: nil)
    }
}


//
//  Game.swift
//  eSportsKitProject
//
//  Created by Taylor Caldwell on 7/10/15.
//  Copyright (c) 2015 Rithms. All rights reserved.
//

import Foundation

struct Game {

    var id: String? // Unique numeric identifier for this game
    var winnerId: String? // Team ID of this game's winner
    var noVods: Bool? // This game will never contain any vods
    var hasVods: Bool? // Streams are available for this game

    init(data: AnyObject) {

        id = data[LolEsportsClient.JSONKeys.Id] as? String
        winnerId = data[LolEsportsClient.JSONKeys.WinnerId] as? String
        let noVodsInt = data[LolEsportsClient.JSONKeys.NoVods] as? Int
        noVods = noVodsInt?.toBool()
        let hasVodsInt = data[LolEsportsClient.JSONKeys.HasVods] as? Int
        hasVods = hasVodsInt?.toBool()
    }

    static func gamesFromResults(results: [String : AnyObject]) -> [Game] {

        var games = [Game]()

        for (key, value) in results {
            games.append(Game(data: value))
        }

        return games
    }
}

Change variable name to better reflect data


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

import XCTest

class RequestBuilderTests: XCTestCase {

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

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

}

Add test for RequestBuilder init

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

import XCTest
@testable import BreweryDB

class RequestBuilderTests: XCTestCase {

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

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

    func testRequestBuilderInitsWithRequestEndPoint() {
        let requestBuilder = RequestBuilder(endPoint: .Beer)
        XCTAssertNotNil(requestBuilder)
    }

}


//
//  Copyright © 2015 Tomas Linhart. All rights reserved.
//

import SwiftGtk

let app = Application(applicationId: "com.tomaslinhart.swiftgtk.example")
app.run { window in
    window.title = "Hello World"
    window.defaultSize = Size(width: 400, height: 400)
    window.resizable = true

    let buttonBox = ButtonBox(orientation: .Vertical)

    let label = Label()
    label.selectable = true
    buttonBox.add(label)

    let button = Button(label: "Press")
    button.label = "Press Me"
    button.clicked = { [unowned label] _ in
        label.text = "Oh, you pressed the button."

        let newWindow = Window(windowType: .TopLevel)
        newWindow.title = "Just a window"
        newWindow.defaultSize = Size(width: 200, height: 200)
        let labelPressed = Label(text: "Oh, you pressed the button.")
        newWindow.add(labelPressed)

        newWindow.showAll()
    }

    buttonBox.add(button)
    window.add(buttonBox)
}

Remove whitespace from end of line


//
//  basename.swift
//  posix
//
//  Created by Rene Hexel on 3/08/2014.
//  Copyright (c) 2014, 2016 Rene Hexel. All rights reserved.
//
#if os(Linux)
    import Glibc

    /// just a slash
    private let slash = "/".utf16.first!

    /// return the base name of a string
    extension String {
        var baseName: String {
            let u = utf16
            let s = u.startIndex
            let e = u.endIndex
            var i = e
            while i != s {
                let j = u.index(before: i)
                if u[j] == slash { return String(u[i..<e]) }
                i = j
            }
            return self
        }
    }
#else
    import Darwin

    /// return the base name of a string
    extension String {
        var baseName: String {
            return String(cString: basename(cstring(self)))
        }
    }
#endif

Make this compile on Linux

//
//  basename.swift
//  posix
//
//  Created by Rene Hexel on 3/08/2014.
//  Copyright (c) 2014, 2016 Rene Hexel. All rights reserved.
//
#if os(Linux)
    import Glibc

    /// just a slash
    private let slash = "/".utf16.first!

    /// return the base name of a string
    extension String {
        var baseName: String {
            let u = utf16
            let s = u.startIndex
            let e = u.endIndex
            var i = e
            while i != s {
                let j = u.index(before: i)
                if u[j] == slash { return String(describing: u[i..<e]) }
                i = j
            }
            return self
        }
    }
#else
    import Darwin

    /// return the base name of a string
    extension String {
        var baseName: String {
            return String(cString: basename(cstring(self)))
        }
    }
#endif


import SwiftUI

@main
struct CountoutApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            TabView {
                MainView()
                    .tabItem { Label("Countdown", systemImage: "stopwatch") }
                    .onAppear { CountdownTimer.shared.isScheduled = false }
                DateView()
                    .tabItem { Label("Schedule", systemImage: "calendar") }
                    .onAppear { CountdownTimer.shared.isScheduled = true }
            }
        }
    }
}

Update isScheduled on tab selection as .onAppear seems to get called on init.

import SwiftUI

@main
struct CountoutApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    @State private var tabSelection = 0

    var body: some Scene {
        WindowGroup {
            TabView(selection: $tabSelection) {
                MainView()
                    .tabItem { Label("Countdown", systemImage: "stopwatch") }.tag(0)
                DateView()
                    .tabItem { Label("Schedule", systemImage: "calendar") }.tag(1)
            }
            .onChange(of: tabSelection) { tabIndex in
                CountdownTimer.shared.isScheduled = tabIndex == 1
            }
        }
    }
}


// RUN: %target-swift-frontend -emit-sil %s -Onone -Xllvm \
// RUN:   -sil-print-after=mandatory-inlining \
// RUN:   -enable-ownership-stripping-after-serialization \
// RUN:   -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s

// CHECK: begin_borrow {{.*}} : $OSLog, loc {{.*}}, scope 3
// CHECK: tuple (), loc {{.*}}, scope 3
// CHECK: end_borrow %3 : $OSLog, loc {{.*}}, scope 3

import os

func bar() {
  foo(OSLog.default)
}

@_transparent
func foo(_ logObject: OSLog) { }

Add a missing REQUIRES and availability macro.

// REQUIRES: objc_interop

// RUN: %target-swift-frontend -emit-sil %s -Onone -Xllvm \
// RUN:   -sil-print-after=mandatory-inlining \
// RUN:   -enable-ownership-stripping-after-serialization \
// RUN:   -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s

// CHECK: begin_borrow {{.*}} : $OSLog, loc {{.*}}, scope 5
// CHECK: tuple (), loc {{.*}}, scope 5
// CHECK: end_borrow %9 : $OSLog, loc {{.*}}, scope 5

import os

func bar() {
  if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) {
    foo(OSLog.default)
  }
}

@_transparent
func foo(_ logObject: OSLog) { }


//
//  FuelGaugeTabTests.swift
//  GaugesDemo
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class FuelGaugeTabTests: XCTestCase {

    var vc: FirstViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
        vc = storyboard.instantiateViewControllerWithIdentifier("FuelVC") as! FirstViewController

        let dummy = vc.view // force loading subviews and setting outlets

        vc.viewDidLoad()
    }

    func testFirstViewControllerLoaded() {
        XCTAssertNotNil(vc, "FirstViewController not found")
    }

    func testSliderCreated() {
        let slider = vc.slider
        XCTAssertNotNil(slider, "Slider not created or connected")
    }

    func testEmptyButtonCreated() {
        let emptyButton = vc.emptyButton
        XCTAssertNotNil(emptyButton, "Empty button not created or connected")
    }

    func testFullButtonCreated() {
        let fullButton = vc.fullButton
        XCTAssertNotNil(fullButton, "Full button not created or connected")
    }

}

Add failing test that pressing empty sets slider to zero. Test fails to compile because empty action not created yet.

//
//  FuelGaugeTabTests.swift
//  GaugesDemo
//
//  Created by Ron Lisle on 4/5/15.
//  Copyright (c) 2015 Ron Lisle. All rights reserved.
//

import UIKit
import XCTest

class FuelGaugeTabTests: XCTestCase {

    var vc: FirstViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
        vc = storyboard.instantiateViewControllerWithIdentifier("FuelVC") as! FirstViewController

        let dummy = vc.view // force loading subviews and setting outlets

        vc.viewDidLoad()
    }

    func testFirstViewControllerLoaded() {
        XCTAssertNotNil(vc, "FirstViewController not found")
    }

    func testSliderCreated() {
        let slider = vc.slider
        XCTAssertNotNil(slider, "Slider not created or connected")
    }

    func testEmptyButtonCreated() {
        let emptyButton = vc.emptyButton
        XCTAssertNotNil(emptyButton, "Empty button not created or connected")
    }

    func testFullButtonCreated() {
        let fullButton = vc.fullButton
        XCTAssertNotNil(fullButton, "Full button not created or connected")
    }

    func testEmptyButtonSetsSliderToZero() {
        vc.emptyPressed(vc.emptyButton)
        let level = vc.slider.value
        XCTAssertNotEqualWithAccuracy(level, 0.0, 0.0001, "Slider s/b zero but is \(level)")
    }

}


import Foundation
import AVFoundation

class HuntForKey : Mode {

    let synthesizer = AVSpeechSynthesizer()

    let letters = Array("abcdefghijklmnopqrstuvwxyz")
    var targetKey = ""

    func start()  {
        randomizeKey()
    }

    func respondTo(key: String)  {
        if(key == targetKey)
        {
            immediatelySay("Great job! You pressed the letter \(targetKey)")

            randomizeKey()
        }
        else
        {
            immediatelySay("No.  Try again.  Press the \(targetKey) key")
        }
    }

    func randomizeKey () {
        let randomLetterIndex = Int.random(in: 0 ... letters.count-1)
        targetKey = String(letters[randomLetterIndex])

        say("Press the \(targetKey) key")
    }

    func say(_ word: String) {
        let utterance = AVSpeechUtterance(string: word.lowercased())
        synthesizer.speak(utterance)
    }

    func immediatelySay(_ word: String) {
        let utterance = AVSpeechUtterance(string: word.lowercased())
        synthesizer.stopSpeaking(at: .immediate)
        synthesizer.speak(utterance)
    }

}

Switch from len/index conversion to using a half open range

import Foundation
import AVFoundation

class HuntForKey : Mode {

    let synthesizer = AVSpeechSynthesizer()

    let letters = Array("abcdefghijklmnopqrstuvwxyz")
    var targetKey = ""

    func start()  {
        randomizeKey()
    }

    func respondTo(key: String)  {
        if(key == targetKey)
        {
            immediatelySay("Great job! You pressed the letter \(targetKey)")

            randomizeKey()
        }
        else
        {
            immediatelySay("No.  Try again.  Press the \(targetKey) key")
        }
    }

    func randomizeKey () {
        let randomLetterIndex = Int.random(in: 0 ..< letters.count)
        targetKey = String(letters[randomLetterIndex])

        say("Press the \(targetKey) key")
    }

    func say(_ word: String) {
        let utterance = AVSpeechUtterance(string: word.lowercased())
        synthesizer.speak(utterance)
    }

    func immediatelySay(_ word: String) {
        let utterance = AVSpeechUtterance(string: word.lowercased())
        synthesizer.stopSpeaking(at: .immediate)
        synthesizer.speak(utterance)
    }

}


//
//  BeerRequest.swift
//  BreweryDB
//
//  Created by Jake on 08/01/2016.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

enum BeerRequestParam {
    case Identifier
    case Name
    case Abv
    case Ibu
    case GlasswareId
    case SrmId
    case AvaliableId
    case StyleId
    case IsOrganic
    case HasLabels
    case Year
    case Since
    case Status
    case RandomCount
}

class BeerRequest {

}

Add optional init which takes request params

//
//  BeerRequest.swift
//  BreweryDB
//
//  Created by Jake on 08/01/2016.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

enum BeerRequestParam {
    case Identifier
    case Name
    case Abv
    case Ibu
    case GlasswareId
    case SrmId
    case AvaliableId
    case StyleId
    case IsOrganic
    case HasLabels
    case Year
    case Since
    case Status
    case RandomCount
}

class BeerRequest {
    let requestParams: [BeerRequestParam: String]

    init?(requestParams params: [BeerRequestParam: String]) {
        if params.count == 0 {
            requestParams = [:]
            return nil
        }

        requestParams = params
    }
}


import Foundation

extension MHomeStrategy
{
    //MARK: private

    private class func strategyMap() -> [MSession.Status:MHomeStrategy.Type]
    {
        let map:[MSession.Status:MHomeStrategy.Type] = [
            MSession.Status.new:MHomeStrategyNew.self,
            MSession.Status.loading:MHomeStrategyLoading.self,
            MSession.Status.sync:MHomeStrategySync.self,
            MSession.Status.authLocation:MHomeStrategyAuthLocation.self,
            MSession.Status.loaded:MHomeStrategyLoaded.self]

        return map
    }

    //MARK: internal

    class func factoryStrategy(controller:CHome) -> MHomeStrategy?
    {
         let map:[MSession.Status:MHomeStrategy.Type] = strategyMap()
         let currentStatus:MSession.Status = controller.model.session.status

         guard

             let strategyType:MHomeStrategy.Type = map[currentStatus]

         else
         {
             return nil
         }

         let strategy:MHomeStrategy = strategyType.init(
            controller:controller)

         return strategy
    }
}

Add waiting location to factory

import Foundation

extension MHomeStrategy
{
    //MARK: private

    private class func strategyMap() -> [MSession.Status:MHomeStrategy.Type]
    {
        let map:[MSession.Status:MHomeStrategy.Type] = [
            MSession.Status.new:MHomeStrategyNew.self,
            MSession.Status.loading:MHomeStrategyLoading.self,
            MSession.Status.sync:MHomeStrategySync.self,
            MSession.Status.authLocation:MHomeStrategyAuthLocation.self,
            MSession.Status.waitingLocation:MHomeStrategyWaitingLocation.self,
            MSession.Status.loaded:MHomeStrategyLoaded.self]

        return map
    }

    //MARK: internal

    class func factoryStrategy(controller:CHome) -> MHomeStrategy?
    {
         let map:[MSession.Status:MHomeStrategy.Type] = strategyMap()
         let currentStatus:MSession.Status = controller.model.session.status

         guard

             let strategyType:MHomeStrategy.Type = map[currentStatus]

         else
         {
             return nil
         }

         let strategy:MHomeStrategy = strategyType.init(
            controller:controller)

         return strategy
    }
}