//
//  DoubleLayout.swift
//  PhotoCollectionView
//
//  Created by luan on 9/2/17.
//
//

import UIKit

class DoubleLayout: PhotoLayoutProtocol {
    var contentSize: CGSize = CGSize.zero

    var maxPhoto: Int {
        return 2
    }

    func frame(at index: Int, in photoCollectionView: PhotoCollectionView) -> CGRect {
        guard index >= 0 && index < maxPhoto else {
            return CGRect.zero
        }

        contentSize = photoCollectionView.bounds.size
        guard let image = photoCollectionView.image(at: index) else {
            return CGRect(origin: .zero, size: contentSize)
        }
        let width = (photoCollectionView.bounds.width - spacing * CGFloat(maxPhoto + 1)) / CGFloat(maxPhoto)
        var height = width * image.size.height / image.size.width
        height = min(height, width * 1.25)
        contentSize = CGSize(width: width, height: height)
        return CGRect(origin: .zero, size: contentSize)
    }

    func contentSize(of photoCollectionView: PhotoCollectionView) -> CGSize {
        return contentSize
    }

}

Add item size and fix content size for double layout

//
//  DoubleLayout.swift
//  PhotoCollectionView
//
//  Created by luan on 9/2/17.
//
//

import UIKit

class DoubleLayout: PhotoLayoutProtocol {
    var contentSize: CGSize = CGSize.zero
    var itemSize: CGSize = CGSize.zero

    var maxPhoto: Int {
        return 2
    }

    func frame(at index: Int, in photoCollectionView: PhotoCollectionView) -> CGRect {
        guard index >= 0 && index < maxPhoto else {
            return CGRect.zero
        }

        contentSize = photoCollectionView.bounds.size
        guard let image = photoCollectionView.image(at: index) else {
            return CGRect(origin: .zero, size: contentSize)
        }
        let width = (photoCollectionView.bounds.width - spacing * CGFloat(maxPhoto + 1)) / CGFloat(maxPhoto)
        var height = width * image.size.height / image.size.width
        height = min(height, width * 1.25)
        itemSize = CGSize(width: width, height: height)
        contentSize = CGSize(width: photoCollectionView.bounds.width, height: height)
        return CGRect(origin: .zero, size: contentSize)
    }

    func contentSize(of photoCollectionView: PhotoCollectionView) -> CGSize {
        return contentSize
    }

}


//
//  IValueFormatter.swift
//  Charts
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/Charts
//

import Foundation

/// Interface that allows custom formatting of all values inside the chart before they are being drawn to the screen.
///
/// Simply create your own formatting class and let it implement ValueFormatter.
///

@objc(IChartValueFormatter)
public protocol IValueFormatter: class
{

    /// Called when a value (from labels inside the chart) is formatted before being drawn.
    ///
    /// For performance reasons, avoid excessive calculations and memory allocations inside this method.
    ///
    /// - returns: The formatted label ready for being drawn
    ///
    /// - parameter value:           The value to be formatted
    ///
    /// - parameter axis:            The entry the value belongs to - in e.g. BarChart, this is of class BarEntry
    ///
    /// - parameter dataSetIndex:    The index of the DataSet the entry in focus belongs to
    ///
    /// - parameter viewPortHandler: provides information about the current chart state (scale, translation, ...)
    ///
    func stringForValue(_ value: Double,
                        entry: ChartDataEntry,
                        dataSetIndex: Int,
                        viewPortHandler: ViewPortHandler?) -> String
}

Update code comment to reference stringForValue()

//
//  IValueFormatter.swift
//  Charts
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/Charts
//

import Foundation

/// Interface that allows custom formatting of all values inside the chart before they are drawn to the screen.
///
/// Simply create your own formatting class and let it implement ValueFormatter. Then override the stringForValue()
/// method and return whatever you want.

@objc(IChartValueFormatter)
public protocol IValueFormatter: class
{

    /// Called when a value (from labels inside the chart) is formatted before being drawn.
    ///
    /// For performance reasons, avoid excessive calculations and memory allocations inside this method.
    ///
    /// - returns:                   The formatted label ready to be drawn
    ///
    /// - parameter value:           The value to be formatted
    ///
    /// - parameter dataSetIndex:    The index of the DataSet the entry in focus belongs to
    ///
    /// - parameter viewPortHandler: provides information about the current chart state (scale, translation, ...)
    ///
    func stringForValue(_ value: Double,
                        entry: ChartDataEntry,
                        dataSetIndex: Int,
                        viewPortHandler: ViewPortHandler?) -> String
}


public protocol ContextType {
  func context(name:String, closure:ContextType -> ())
  func describe(name:String, closure:ContextType -> ())
  func before(closure:() throws -> ())
  func after(closure:() throws -> ())
  func it(name:String, closure:() throws -> ())
}

class Context : ContextType, CaseType {
  let name:String
  var cases = [CaseType]()

  //var befores
  //var afters

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

  func context(name:String, closure:ContextType -> ()) {
    let context = Context(name: name)
    closure(context)
    cases.append(context)
  }

  func describe(name:String, closure:ContextType -> ()) {
    let context = Context(name: name)
    closure(context)
    cases.append(context)
  }

  func before(closure:() throws -> ()) {

  }

  func after(closure:() throws -> ()) {

  }

  func it(name:String, closure:() throws -> ()) {
    cases.append(Case(name: name, closure: closure))
  }

  func run(reporter:ContextReporter) {
    reporter.report(name) { reporter in
      cases.forEach { $0.run(reporter) }
    }
  }
}

Add support for befores and afters

public protocol ContextType {
  func context(name:String, closure:ContextType -> ())
  func describe(name:String, closure:ContextType -> ())
  func before(closure:() -> ())
  func after(closure:() -> ())
  func it(name:String, closure:() throws -> ())
}

class Context : ContextType, CaseType {
  let name:String
  var cases = [CaseType]()

  typealias Before = (() -> ())
  typealias After = (() -> ())

  var befores = [Before]()
  var afters = [After]()

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

  func context(name:String, closure:ContextType -> ()) {
    let context = Context(name: name)
    closure(context)
    cases.append(context)
  }

  func describe(name:String, closure:ContextType -> ()) {
    let context = Context(name: name)
    closure(context)
    cases.append(context)
  }

  func before(closure:() -> ()) {
    befores.append(closure)
  }

  func after(closure:() -> ()) {
    afters.append(closure)
  }

  func it(name:String, closure:() throws -> ()) {
    cases.append(Case(name: name, closure: closure))
  }

  func run(reporter:ContextReporter) {
    reporter.report(name) { reporter in
      cases.forEach {
        befores.forEach { $0() }
        $0.run(reporter)
        afters.forEach { $0() }
      }
    }
  }
}


for c in 1...50 {
    for b in 1..<c {
        for a in 1..<b {
            if a * a + b * b == c * c {
                println("\(a), \(b), \(c)")
            }
        }
    }
}

Upgrade example to Swift 2.1


//
//  HotKeyManagerTests.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 4/18/17.
//  Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//

@testable import Amethyst
import Nimble
import Quick
import Silica

final class HotKeyManagerTests: QuickSpec {
    override func spec() {
        describe("hotKeyNameToDefaultsKey") {
            it("has the right number of screens") {
                let keyMapping = HotKeyManager<SIApplication>.hotKeyNameToDefaultsKey()
                let screenCommands = keyMapping.filter { $0[1].hasPrefix(CommandKey.focusScreenPrefix.rawValue) }
                expect(screenCommands.count).to(equal(4))
            }
        }
    }
}

Update test to account for more screen focus commands

//
//  HotKeyManagerTests.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 4/18/17.
//  Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//

@testable import Amethyst
import Nimble
import Quick
import Silica

final class HotKeyManagerTests: QuickSpec {
    override func spec() {
        describe("hotKeyNameToDefaultsKey") {
            it("has the right number of screens") {
                let keyMapping = HotKeyManager<SIApplication>.hotKeyNameToDefaultsKey()
                let screenCommands = keyMapping.filter { $0[1].hasPrefix(CommandKey.focusScreenPrefix.rawValue) }
                expect(screenCommands.count).to(equal(6))
            }
        }
    }
}


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

import XCTest
import SwiftyJSON
@testable import SwiftyJSONModel

struct FullName {
    let firstName: String
    let lastName: String
}

extension FullName: JSONModelType {
    enum PropertyKey: String {
        case firstName, lastName
    }

    init(properties: [PropertyKey : JSON]) throws {
        firstName = try properties.value(for: .firstName).stringValue()
        lastName = try properties.value(for: .lastName).stringValue()
    }

    var dictValue: [PropertyKey : JSON] {
        return [.firstName: JSON(firstName), .lastName: JSON(lastName)]
    }
}

extension FullName: Equatable {}
func == (left: FullName, right: FullName) -> Bool {
    return left.firstName == right.firstName && left.lastName == right.lastName
}

class SwiftyJSONModelTests: XCTestCase {

    func testJSONModelProtocols() {
        let name = FullName(firstName: "John", lastName: "Doe")
        XCTAssertEqual(try? FullName(json: name.jsonValue), name)
    }

}

Update test model with more properties

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

import XCTest
import SwiftyJSON
@testable import SwiftyJSONModel

struct Person {
    let firstName: String
    let lastName: String
    let age: Int
    let isMarried: Bool
    let height: Double
}

extension Person: JSONModelType {
    enum PropertyKey: String {
        case firstName, lastName, age, isMarried, height
    }

    init(properties: [PropertyKey : JSON]) throws {
        firstName = try properties.value(for: .firstName).stringValue()
        lastName = try properties.value(for: .lastName).stringValue()
        age = try properties.value(for: .age).intValue()
        isMarried = try properties.value(for: .isMarried).boolValue()
        height = try properties.value(for: .height).doubleValue()
    }

    var dictValue: [PropertyKey : JSONRepresentable] {
        return [.firstName: firstName, .lastName: lastName, .age: age, .isMarried: isMarried, .height: height]
    }
}

extension Person: Equatable {}
func == (left: Person, right: Person) -> Bool {
    return left.firstName == right.firstName && left.lastName == right.lastName &&
           left.age == right.age && left.isMarried == right.isMarried && left.height == right.height
}

class SwiftyJSONModelTests: XCTestCase {

    func testJSONModelProtocols() {
        let person = Person(firstName: "John", lastName: "Doe", age: 21, isMarried: false, height: 180)
        XCTAssertEqual(try? Person(json: person.jsonValue), person)
    }

}


//
// Parser.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//

import Result
import Runes

// TODO: Implement ParserError
public typealias ParserError = String

public struct Parser <Token, Output> {
	public let parse: ParserInput<Token> -> Result<(output: Output, nextinput: ParserInput<Token>), ParserError>
}

/** Match a single token. */
public func token <T: Equatable> (token: T) -> Parser<T, T> {
	return Parser { input in
		return input.read(expect: toString(token)) >>- { next in
			if next.head == token {
				return .success(output:token, nextinput:next.tail)
			} else {
				return .failure("expected '\(token)', got '\(next.head)'.")
			}
		}
	}
}

/** Return whatever the next token is. */
public func any <T> () -> Parser<T, T> {
	return Parser { input in
		return input.read(expect: "anything") >>- { .success(output:$0.head, nextinput:$0.tail) }
	}
}

Make 'satisfy' parser, have 'any' and 'token' use it.

//
// Parser.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//

import Result
import Runes

// TODO: Implement ParserError
public typealias ParserError = String

public struct Parser <Token, Output> {
	public let parse: ParserInput<Token> -> Result<(output: Output, nextinput: ParserInput<Token>), ParserError>
}

/** Succeeds iff 'condition' is true. Returns the token it read. */
public func satisfy <T> (# expect: String, condition: T -> Bool) -> Parser<T, T> {
	return Parser { input in
		return input.read(expect: expect) >>- { next in
			if condition(next.head) {
				return .success(output:next.head, nextinput:next.tail)
			} else {
				return .failure("expected '\(expect)', got '\(next.head)'.")
			}
		}
	}
}

/** Match a single token. */
public func token <T: Equatable> (token: T) -> Parser<T, T> {
	return satisfy(expect: toString(token)) { $0 == token }
}

/** Return whatever the next token is. */
public func any <T> () -> Parser<T, T> {
	return satisfy(expect: "anything") { T in true }
}


// RUN: %target-swift-frontend -enable-sil-ownership -O -emit-silgen -primary-file %s | %FileCheck %s

// CHECK-LABEL: sil private [transparent] @$S18subscript_accessor1XVxSgycimytfU_
// CHECK: [[SETTER:%.*]] = function_ref @$S18subscript_accessor1XVxSgycis
// CHECK-NEXT: apply [[SETTER]]<T>
struct X<T> {
  subscript () -> T? {
    get {
      return nil
    }
    set { }
  }
}

  // CHECK: sil{{.*}}S18subscript_accessor9testXRead1xxAA1XVyxG_tlF
@_specialize(where T == (Int, Int))
func testXRead<T>(x: X<T>) -> T {
  return x[]!
}

Improve newly-added test that involves @_specialize

// RUN: %target-swift-frontend -enable-sil-ownership -O -emit-sil -primary-file %s | %FileCheck %s

// CHECK-LABEL: sil private [transparent] @$S18subscript_accessor1XVxSgycimytfU_
// CHECK: [[SETTER:%.*]] = function_ref @$S18subscript_accessor1XVxSgycis
// CHECK-NEXT: apply [[SETTER]]<T>
struct X<T> {
  subscript () -> T? {
    get {
      return nil
    }
    set { }
  }
}

  // CHECK: sil{{.*}}S18subscript_accessor9testXRead1xxAA1XVyxG_tlF
@_specialize(where T == (Int, Int))
func testXRead<T>(x: X<T>) -> T {
  return x[]!
}
// CHECK: $S18subscript_accessor1XVxSgycisTf4dn_n


//
//  FetchIssuesOperation.swift
//  FiveCalls
//
//  Created by Ben Scheirman on 1/31/17.
//  Copyright © 2017 5calls. All rights reserved.
//

import Foundation

class FetchIssuesOperation : BaseOperation {
    let zipCode: String?

    var httpResponse: HTTPURLResponse?

    var error: Error?

    var issuesList: IssuesList?

    init(zipCode: String?) {
        self.zipCode = zipCode
    }

    lazy var sessionConfiguration = URLSessionConfiguration.default
    lazy var session: URLSession = { return URLSession(configuration: self.sessionConfiguration) }()

    override func execute() {
        let url = URL(string: "https://5calls.org/issues/")!
        let task = session.dataTask(with: url) { (data, response, error) in
            if let e = error {
                print("Error fetching issues: \(e.localizedDescription)")
            } else {
                let http = response as! HTTPURLResponse
                self.httpResponse = http
                if http.statusCode == 200 {
                    do {
                        try self.parseIssues(data: data!)
                    } catch let e {
                        print("Error parsing issues: \(e.localizedDescription)")
                    }
                } else {
                    print("Received HTTP \(http.statusCode)")
                }
            }

            self.finish()
        }
        task.resume()
    }

    private func parseIssues(data: Data) throws {
        let json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
        issuesList = IssuesList(dictionary: json)
    }
}

Add some logging so we can see when requests are made

//
//  FetchIssuesOperation.swift
//  FiveCalls
//
//  Created by Ben Scheirman on 1/31/17.
//  Copyright © 2017 5calls. All rights reserved.
//

import Foundation

class FetchIssuesOperation : BaseOperation {
    let zipCode: String?

    var httpResponse: HTTPURLResponse?

    var error: Error?

    var issuesList: IssuesList?

    init(zipCode: String?) {
        self.zipCode = zipCode
    }

    lazy var sessionConfiguration = URLSessionConfiguration.default
    lazy var session: URLSession = { return URLSession(configuration: self.sessionConfiguration) }()

    override func execute() {
        let url = URL(string: "https://5calls.org/issues/")!
        let task = session.dataTask(with: url) { (data, response, error) in
            if let e = error {
                print("Error fetching issues: \(e.localizedDescription)")
            } else {
                let http = response as! HTTPURLResponse
                print("HTTP \(http.statusCode)")
                self.httpResponse = http
                if http.statusCode == 200 {
                    do {
                        try self.parseIssues(data: data!)
                    } catch let e {
                        print("Error parsing issues: \(e.localizedDescription)")
                    }
                } else {
                    print("Received HTTP \(http.statusCode)")
                }
            }

            self.finish()
        }

        print("Fetching issues (zip: \(zipCode ?? ""))...")
        task.resume()
    }

    private func parseIssues(data: Data) throws {
        let json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
        issuesList = IssuesList(dictionary: json)
    }
}


import SwiftParser
import SwiftSyntax

import CASTBridging

extension ASTGenVisitor {
  public func visit(_ node: StringLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    var segment = node.segments.first!.as(StringSegmentSyntax.self)!.content.text
    return segment.withUTF8 { buf in
      let id = SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count)
      return SwiftStringLiteralExpr_create(ctx, id, buf.count, loc)
    }
  }

  public func visit(_ node: IntegerLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    var segment = node.digits.text
    return segment.withUTF8 { buf in
      let id = SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count)
      return SwiftIntegerLiteralExpr_create(ctx, id, buf.count, loc)
    }
  }

  public func visit(_ node: BooleanLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    let value = node.booleanLiteral == .trueKeyword()
    return SwiftBooleanLiteralExpr_create(ctx, value, loc)
  }
}

Fix integer and string literal mapping

import SwiftParser
import SwiftSyntax

import CASTBridging

extension ASTGenVisitor {
  public func visit(_ node: StringLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    var segment = node.segments.first!.as(StringSegmentSyntax.self)!.content.text
    return segment.withUTF8 { buf in
      return SwiftStringLiteralExpr_create(ctx, buf.baseAddress, buf.count, loc)
    }
  }

  public func visit(_ node: IntegerLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    var segment = node.digits.text
    return segment.withUTF8 { buf in
      return SwiftIntegerLiteralExpr_create(ctx, buf.baseAddress, buf.count, loc)
    }
  }

  public func visit(_ node: BooleanLiteralExprSyntax) -> UnsafeMutableRawPointer {
    let loc = self.base.advanced(by: node.position.utf8Offset).raw
    let value = node.booleanLiteral == .trueKeyword()
    return SwiftBooleanLiteralExpr_create(ctx, value, loc)
  }
}


class SCConstants {
    static let appID = 1141711201
    static let bundleID = "com.davidzhang.Spycodes"
    static let versionURL = "https://itunes.apple.com/lookup?bundleId=\(bundleID)"
    static let supportURL = "https://www.spycodes.net/support/"
    static let appStoreURL = "itms-apps://itunes.apple.com/app/id\(appID)"
    static let appStoreWebURL = "https://itunes.apple.com/ca/app/spycodes/id1141711201?mt=8"
    static let githubURL = "https://github.com/davidozhang/spycodes"
    static let icons8URL = "https://icons8.com"
    static let websiteURL = "https://www.spycodes.net/"

    static let cardCount = 22
    static let accessCodeLength = 4
    static let regularGameMaxSize = 8
    static let minigameMaxSize = 4  // Account for additional CPU player
}

Use US App Store web URL

class SCConstants {
    static let appID = 1141711201
    static let bundleID = "com.davidzhang.Spycodes"
    static let versionURL = "https://itunes.apple.com/lookup?bundleId=\(bundleID)"
    static let supportURL = "https://www.spycodes.net/support/"
    static let appStoreURL = "itms-apps://itunes.apple.com/app/id\(appID)"
    static let appStoreWebURL = "https://itunes.apple.com/app/spycodes/id1141711201?mt=8"
    static let githubURL = "https://github.com/davidozhang/spycodes"
    static let icons8URL = "https://icons8.com"
    static let websiteURL = "https://www.spycodes.net/"

    static let cardCount = 22
    static let accessCodeLength = 4
    static let regularGameMaxSize = 8
    static let minigameMaxSize = 4  // Account for additional CPU player
}


//
//  PostControllable.swift
//  SwiftyPress
//
//  Created by Basem Emara on 5/6/16.
//
//

import Foundation

protocol PostControllable: RealmControllable {
    associatedtype DataType: Post

    var categoryID: Int { get set }
    func didCategorySelect() -> Void
}

extension PostControllable where Self: UIViewController {

    func prepareForSegue(_ segue: UIStoryboardSegue) {
        guard let segueIdentifier = segue.identifier else { return }

        switch (segueIdentifier, segue.destination) {
            case (PostDetailViewController.segueIdentifier, let controller as PostDetailViewController):
                // Set post detail
                guard let row = indexPathForSelectedItem?.row,
                    let model = models?[row] else { break }
                controller.model = model
            case (CategoriesViewController.segueIdentifier, let navController as UINavigationController):
                guard let controller = navController.topViewController as? CategoriesViewController else { break }

                // Set category and prepare to retrieve category
                controller.selectedID = categoryID
                controller.prepareForUnwind = { id in
                    self.categoryID = id
                }
            default: break
        }
    }
}

Fix protocol generic for Realm extension.

//
//  PostControllable.swift
//  SwiftyPress
//
//  Created by Basem Emara on 5/6/16.
//
//

import Foundation

protocol PostControllable: RealmControllable {
    var categoryID: Int { get set }
    func didCategorySelect() -> Void
}

extension PostControllable where Self: UIViewController {

    func prepareForSegue(_ segue: UIStoryboardSegue) {
        guard let segueIdentifier = segue.identifier else { return }

        switch (segueIdentifier, segue.destination) {
            case (PostDetailViewController.segueIdentifier, let controller as PostDetailViewController):
                // Set post detail
                guard let row = indexPathForSelectedItem?.row,
                    let model = models?[row] else { break }
                controller.model = model as? Post
            case (CategoriesViewController.segueIdentifier, let navController as UINavigationController):
                guard let controller = navController.topViewController as? CategoriesViewController else { break }

                // Set category and prepare to retrieve category
                controller.selectedID = categoryID
                controller.prepareForUnwind = { id in
                    self.categoryID = id
                }
            default: break
        }
    }
}


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

public struct Module<Recur> {
	public typealias Environment = Expression<Recur>.Environment
	public typealias Context = Expression<Recur>.Context

	public init<D: SequenceType, S: SequenceType where D.Generator.Element == Module, S.Generator.Element == Binding<Recur>>(_ dependencies: D, _ definitions: S) {
		self.dependencies = Array(dependencies)
		self.definitions = Array(definitions)
	}

	public let dependencies: [Module]
	public let definitions: [Binding<Recur>]

	public var environment: Environment {
		let dependencies = lazy(self.dependencies).map { $0.environment }
		let definitions = lazy(self.definitions).map { [$0.symbol: $0.value] }
		return dependencies
			.concat(definitions)
			.reduce(Environment(), combine: +)
	}

	public var context: Context {
		let dependencies = lazy(self.dependencies).map { $0.context }
		let definitions = lazy(self.definitions).map { [$0.symbol: $0.type] }
		return dependencies
			.concat(definitions)
			.reduce(Context(), combine: +)
	}
}

Add a definitions-only module constructor.

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

public struct Module<Recur> {
	public typealias Environment = Expression<Recur>.Environment
	public typealias Context = Expression<Recur>.Context

	public init<D: SequenceType, S: SequenceType where D.Generator.Element == Module, S.Generator.Element == Binding<Recur>>(_ dependencies: D, _ definitions: S) {
		self.dependencies = Array(dependencies)
		self.definitions = Array(definitions)
	}

	public init<S: SequenceType where S.Generator.Element == Binding<Recur>>(_ definitions: S) {
		self.init([], definitions)
	}

	public let dependencies: [Module]
	public let definitions: [Binding<Recur>]

	public var environment: Environment {
		let dependencies = lazy(self.dependencies).map { $0.environment }
		let definitions = lazy(self.definitions).map { [$0.symbol: $0.value] }
		return dependencies
			.concat(definitions)
			.reduce(Environment(), combine: +)
	}

	public var context: Context {
		let dependencies = lazy(self.dependencies).map { $0.context }
		let definitions = lazy(self.definitions).map { [$0.symbol: $0.type] }
		return dependencies
			.concat(definitions)
			.reduce(Context(), combine: +)
	}
}


// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -o %t_asan-binary
// RUN: %target-codesign %t_asan-binary
// RUN: env ASAN_OPTIONS=detect_leaks=0 %target-run %t_asan-binary
// REQUIRES: executable_test
// REQUIRES: asan_runtime

// Make sure that we do not use-after-free here.

class Box<T> {
  var value: T
  init(_ inputValue: T) { value = inputValue }
}

enum Value<U> {
  case inline(U)
  indirect case box(Box<U>)
}

func evaluate<U>(_ v: Value<U>) {
  switch v {
  case .inline:
    return print("foo")
  case .box(let box):
    return print("bar \(box)")
  }
}

func main() {
  let v = Value.box(Box<[Int]>([1, 2, 3]))
  evaluate(v)
  print(v)
}

main()

Disable test that uses asan with remote_run like the rest of the asan tests.

// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -o %t_asan-binary
// RUN: %target-codesign %t_asan-binary
// RUN: env ASAN_OPTIONS=detect_leaks=0 %target-run %t_asan-binary

// REQUIRES: executable_test
// REQUIRES: asan_runtime

// rdar://problem/47367694 tracks re-enabling this test for backward deployment.
// UNSUPPORTED: remote_run

// Make sure that we do not use-after-free here.

class Box<T> {
  var value: T
  init(_ inputValue: T) { value = inputValue }
}

enum Value<U> {
  case inline(U)
  indirect case box(Box<U>)
}

func evaluate<U>(_ v: Value<U>) {
  switch v {
  case .inline:
    return print("foo")
  case .box(let box):
    return print("bar \(box)")
  }
}

func main() {
  let v = Value.box(Box<[Int]>([1, 2, 3]))
  evaluate(v)
  print(v)
}

main()


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

public enum Elaborated<Term: TermType>: TermContainerType {
	indirect case Unroll(Term, Expression<Elaborated>)

	/// Construct an elaborated term by coiteration.
	public static func coiterate(elaborate: Term throws -> Expression<Term>)(_ seed: Term) rethrows -> Elaborated {
		return try .Unroll(seed, elaborate(seed).map { try coiterate(elaborate)($0) })
	}

	public var type: Term {
		return destructure.0
	}

	public var term: Term {
		return Term(term: self)
	}

	public var destructure: (Term, Expression<Elaborated>) {
		switch self {
		case let .Unroll(all):
			return all
		}
	}

	// MARK: TermContainerType

	public var out: Expression<Elaborated> {
		switch self {
		case let .Unroll(_, term):
			return term
		}
	}
}

Implement `out` in terms of `destructure`.

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

public enum Elaborated<Term: TermType>: TermContainerType {
	indirect case Unroll(Term, Expression<Elaborated>)

	/// Construct an elaborated term by coiteration.
	public static func coiterate(elaborate: Term throws -> Expression<Term>)(_ seed: Term) rethrows -> Elaborated {
		return try .Unroll(seed, elaborate(seed).map { try coiterate(elaborate)($0) })
	}

	public var type: Term {
		return destructure.0
	}

	public var term: Term {
		return Term(term: self)
	}

	public var destructure: (Term, Expression<Elaborated>) {
		switch self {
		case let .Unroll(all):
			return all
		}
	}

	// MARK: TermContainerType

	public var out: Expression<Elaborated> {
		return destructure.1
	}
}


//
//  Error.swift
//  SwiftCLIPackageDescription
//
//  Created by Jake Heiser on 8/30/17.
//

public protocol ProcessError: Swift.Error {
    var message: String? { get }
    var exitStatus: Int32 { get }
    init(message: String?, exitStatus: Int32)
}

extension ProcessError {
    public init() {
        self.init(exitStatus: 1)
    }

    public init<T: SignedInteger>(exitStatus: T) {
        self.init(message: nil, exitStatus: Int32(exitStatus))
    }

    public init(message: String) {
        self.init(message: message, exitStatus: 1)
    }
}

extension CLI {

    public struct Error: ProcessError {
        public let message: String?
        public let exitStatus: Int32
        public init(message: String?, exitStatus: Int32) {
            self.message = message
            self.exitStatus = exitStatus
        }

    }

}

// MARK: -

@available(*, deprecated, message: "use CLI.Error instead")
public enum CLIError: Error {
    case error(String)
    case emptyError
}

Fix error init for swift 3

//
//  Error.swift
//  SwiftCLIPackageDescription
//
//  Created by Jake Heiser on 8/30/17.
//

public protocol ProcessError: Swift.Error {
    var message: String? { get }
    var exitStatus: Int32 { get }
    init(message: String?, exitStatus: Int32)
}

extension ProcessError {
    public init() {
        self.init(exitStatus: 1)
    }

    #if swift(>=4.0)
    public init<T: SignedInteger>(exitStatus: T) {
        self.init(message: nil, exitStatus: Int32(exitStatus))
    }
    #else
    public init(exitStatus: Int) {
        self.init(message: nil, exitStatus: Int32(exitStatus))
    }
    public init(exitStatus: Int32) {
        self.init(message: nil, exitStatus: exitStatus)
    }
    #endif

    public init(message: String) {
        self.init(message: message, exitStatus: 1)
    }
}

extension CLI {

    public struct Error: ProcessError {
        public let message: String?
        public let exitStatus: Int32
        public init(message: String?, exitStatus: Int32) {
            self.message = message
            self.exitStatus = exitStatus
        }

    }

}

// MARK: -

@available(*, deprecated, message: "use CLI.Error instead")
public enum CLIError: Error {
    case error(String)
    case emptyError
}


import Foundation

final class MCreateSaveBuilder
{
    weak var model:MCreateSave?
    var renders:[MCreateSaveRender]
    var urls:[URL]
    let directory:URL
    private(set) weak var timer:Timer?
    private let kTimeout:TimeInterval = 9

    init(renders:[MCreateSaveRender], directory:URL)
    {
        self.renders = renders
        self.directory = directory
        urls = []
    }

    deinit
    {
        timer?.invalidate()
    }

    //MARK: selectors

    @objc
    private func selectorTimeout(sender timer:Timer)
    {
        timer.invalidate()
        model?.buildingError()
    }

    //MARK: private

    private func asyncStartTimer()
    {
        let timer:Timer = Timer.scheduledTimer(
            timeInterval:kTimeout,
            target:self,
            selector:#selector(selectorTimeout(sender:)),
            userInfo:nil,
            repeats:false)

        self.timer = timer
    }

    //MARK: internal

    func startTimer()
    {
        timer?.invalidate()

        DispatchQueue.main.async
        { [weak self] in

            self?.asyncStartTimer()
        }
    }
}

Add total renders to builder

import Foundation

final class MCreateSaveBuilder
{
    weak var model:MCreateSave?
    var renders:[MCreateSaveRender]
    var urls:[URL]
    let directory:URL
    let totalRenders:Int
    private(set) weak var timer:Timer?
    private let kTimeout:TimeInterval = 9

    init(renders:[MCreateSaveRender], directory:URL)
    {
        self.renders = renders
        self.directory = directory
        totalRenders = renders.count
        urls = []
    }

    deinit
    {
        timer?.invalidate()
    }

    //MARK: selectors

    @objc
    private func selectorTimeout(sender timer:Timer)
    {
        timer.invalidate()
        model?.buildingError()
    }

    //MARK: private

    private func asyncStartTimer()
    {
        let timer:Timer = Timer.scheduledTimer(
            timeInterval:kTimeout,
            target:self,
            selector:#selector(selectorTimeout(sender:)),
            userInfo:nil,
            repeats:false)

        self.timer = timer
    }

    //MARK: internal

    func startTimer()
    {
        timer?.invalidate()

        DispatchQueue.main.async
        { [weak self] in

            self?.asyncStartTimer()
        }
    }
}


//
//  DezignableHiddenNavigationBar.swift
//  Pods
//
//  Created by Daniel van Hoesel on 02-03-16.
//
//

import UIKit

public protocol DezignableHiddenNavigationBar {
  var navigationBarHidden: Bool { get set }
}

public extension DezignableHiddenNavigationBar where Self: UIViewController {
  public func setupHiddenNavigationBar() {
    self.navigationController?.navigationBarHidden = self.navigationBarHidden
    self.automaticallyAdjustsScrollViewInsets = false
  }

  public func resetHiddenNavigationBar() {
    self.navigationController?.navigationBarHidden = false
    self.automaticallyAdjustsScrollViewInsets = true
  }
}

Fix issue with scroll inset for hidden nav bar

//
//  DezignableHiddenNavigationBar.swift
//  Pods
//
//  Created by Daniel van Hoesel on 02-03-16.
//
//

import UIKit

public protocol DezignableHiddenNavigationBar {
  var navigationBarHidden: Bool { get set }
}

public extension DezignableHiddenNavigationBar where Self: UIViewController {
  public func setupHiddenNavigationBar() {
    self.navigationController?.navigationBarHidden = self.navigationBarHidden
    self.automaticallyAdjustsScrollViewInsets = !self.navigationBarHidden
  }

  public func resetHiddenNavigationBar() {
    self.navigationController?.navigationBarHidden = false
    self.automaticallyAdjustsScrollViewInsets = true
  }
}


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

final class SubstitutionTests: XCTestCase {
	let (a, b) = (Variable(), Variable())
	let (c, d) = (Variable(), Variable())
	var t1: Type { return Type(c) }
	var t2: Type { return Type(d) }

	func testCompositionIsIdempotentIfOperandsAreIdempotent() {
		let s1 = Substitution(elements: [ a: t1 ])
		let s2 = Substitution(elements: [ b: t2 ])
		assertEqual(s1.compose(s2).occurringVariables, Set())
		assertEqual(s2.compose(s1).occurringVariables, Set())
	}

	func testCompositionIsNotIdempotentIfLeftOperandIsNotIdempotent() {
		let s1 = Substitution(elements: [ a: Type(a) ])
		let s2 = Substitution(elements: [ b: t2 ])
		assertEqual(s1.compose(s2).occurringVariables, Set(a))
	}

	func testCompositionIsNotIdempotentIfRightOperandIsNotIdempotent() {
		let s1 = Substitution(elements: [ a: t1 ])
		let s2 = Substitution(elements: [ b: Type(b) ])
		assertEqual(s1.compose(s2).occurringVariables, Set(b))
	}
}

// MARK: - Imports

import Manifold
import Set
import XCTest

Use a function for one of the fixtures.

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

final class SubstitutionTests: XCTestCase {
	let (a, b) = (Variable(), Variable())
	let (c, d) = (Variable(), Variable())
	var t1: Type { return Type(c) }
	var t2: Type { return Type(function: Type(d), Type(d)) }

	func testCompositionIsIdempotentIfOperandsAreIdempotent() {
		let s1 = Substitution(elements: [ a: t1 ])
		let s2 = Substitution(elements: [ b: t2 ])
		assertEqual(s1.compose(s2).occurringVariables, Set())
		assertEqual(s2.compose(s1).occurringVariables, Set())
	}

	func testCompositionIsNotIdempotentIfLeftOperandIsNotIdempotent() {
		let s1 = Substitution(elements: [ a: Type(a) ])
		let s2 = Substitution(elements: [ b: t2 ])
		assertEqual(s1.compose(s2).occurringVariables, Set(a))
	}

	func testCompositionIsNotIdempotentIfRightOperandIsNotIdempotent() {
		let s1 = Substitution(elements: [ a: t1 ])
		let s2 = Substitution(elements: [ b: Type(b) ])
		assertEqual(s1.compose(s2).occurringVariables, Set(b))
	}
}

// MARK: - Imports

import Manifold
import Set
import XCTest


//
//  AppDelegate.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 06/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window?.rootViewController = UINavigationController(rootViewController: SetupController())
        window?.makeKeyAndVisible()
        return true
    }
}

Set theme when app did finish launching

//
//  AppDelegate.swift
//  HomeControl
//
//  Created by Julian Grosshauser on 06/11/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = .whiteColor()
        return window
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ThemeManager.currentTheme = Theme(variant: .Light, primaryColorName: .Red)
        window?.rootViewController = UINavigationController(rootViewController: SetupController())
        window?.makeKeyAndVisible()
        return true
    }
}


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

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

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

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

        pinpointKit.show(from: self)

        let screenshotType = Feedback.ScreenshotType.original(image: #imageLiteral(resourceName: "liberatore"))
        let preferredImage = screenshotType.preferredImage
        let applicationInformation: Feedback.ApplicationInformation = Feedback.ApplicationInformation(version: nil, build: nil, name: nil, bundleIdentifier: nil, operatingSystemVersion: nil)

        let feedbackConfiguration = FeedbackConfiguration(recipients: ["feedback@example.com"])

        let feedback = Feedback(screenshot: screenshotType, applicationInformation: applicationInformation, configuration: feedbackConfiguration)

        let mimeType = MIMEType.PlainText
        print(mimeType.fileExtension)

        // Just to silence warnings of unused variables.
        print(preferredImage)
        print(feedback)
    }
}

Revert "Adds test code to show full access to exposed Feedback and MIMEType"

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

import UIKit
import PinpointKit

final class ViewController: UITableViewController {

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

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

        pinpointKit.show(from: self)
    }
}


extension Tester {
    public func testInsertAndFind() throws {
        Atom.database = database
        try Atom.prepare(database)
        defer {
            try! Atom.revert(database)
        }

        let hydrogen = Atom(id: "asdf", name: "Hydrogen", protons: 1, weight: 1.007)

        guard hydrogen.exists == false else {
            throw Error.failed("Exists should be false since not yet saved.")
        }
        try hydrogen.save()

        guard hydrogen.id?.string == "asdf" else {
            throw Error.failed("Saved ID not equal to set id.")
        }

        guard hydrogen.exists == true else {
            throw Error.failed("Exists should be true since just saved.")
        }

        guard let id = hydrogen.id else {
            throw Error.failed("ID not set on Atom after save.")
        }

        guard let found = try Atom.find(id) else {
            throw Error.failed("Could not find Atom by id.")
        }

        guard hydrogen.id == found.id else {
            throw Error.failed("ID retrieved different than what was saved.")
        }

        guard hydrogen.name == found.name else {
            throw Error.failed("Name retrieved different than what was saved.")
        }

        guard hydrogen.protons == found.protons else {
            throw Error.failed("Protons retrieved different than what was saved.")
        }

        guard hydrogen.weight == found.weight else {
            throw Error.failed("Weight retrieved different than what was saved.")
        }

    }
}

Use valid UUID for insert-and-fix

extension Tester {
    public func testInsertAndFind() throws {
        Atom.database = database
        try Atom.prepare(database)
        defer {
            try! Atom.revert(database)
        }

        let uuid = UUID()
        let hydrogen = Atom(id: Identifier(uuid.uuidString), name: "Hydrogen", protons: 1, weight: 1.007)

        guard hydrogen.exists == false else {
            throw Error.failed("Exists should be false since not yet saved.")
        }
        try hydrogen.save()

        guard hydrogen.id?.string?.lowercased() == uuid.uuidString.lowercased() else {
            throw Error.failed("Saved ID not equal to set id.")
        }

        guard hydrogen.exists == true else {
            throw Error.failed("Exists should be true since just saved.")
        }

        guard let id = hydrogen.id else {
            throw Error.failed("ID not set on Atom after save.")
        }

        guard let found = try Atom.find(id) else {
            throw Error.failed("Could not find Atom by id.")
        }

        guard hydrogen.id == found.id else {
            throw Error.failed("ID retrieved different than what was saved.")
        }

        guard hydrogen.name == found.name else {
            throw Error.failed("Name retrieved different than what was saved.")
        }

        guard hydrogen.protons == found.protons else {
            throw Error.failed("Protons retrieved different than what was saved.")
        }

        guard hydrogen.weight == found.weight else {
            throw Error.failed("Weight retrieved different than what was saved.")
        }
    }
}


//
//  Forecast+JSON.swift
//  Jetstream
//
//  Created by Andrew Shepard on 11/20/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import CoreData

extension Forecast {
    class func forecasts(with json: JSON, in context: NSManagedObjectContext) -> [Forecast] {
        guard let daily = json["daily"] as? JSON else { return [] }
        guard let data = daily["data"] as? [JSON] else { return [] }

        let forecasts = data.flatMap { (obj) -> Forecast? in
            return forecast(with: obj, in: context)
        }

        return forecasts
    }

    class func forecast(with json: JSON, in context: NSManagedObjectContext) -> Forecast? {
        guard
            let timestamp = json["time"] as? TimeInterval,
            let summary = json["summary"] as? String,
            let icon = json["icon"] as? String,
            let highTemp = json["temperatureMin"] as? Double,
            let lowTemp = json["temperatureMax"] as? Double
        else {
            return nil
        }

        guard let forecast = NSEntityDescription.insertNewObject(forEntityName: "Forecast", into: context) as? Forecast else {
            return nil
        }

        forecast.summary = summary
        forecast.icon = icon

        forecast.highTemp = highTemp
        forecast.lowTemp = lowTemp

        forecast.timestamp = NSDate(timeIntervalSince1970: timestamp)

        return forecast
    }
}

Fix min and max parsing error

//
//  Forecast+JSON.swift
//  Jetstream
//
//  Created by Andrew Shepard on 11/20/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import CoreData

extension Forecast {
    class func forecasts(with json: JSON, in context: NSManagedObjectContext) -> [Forecast] {
        guard let daily = json["daily"] as? JSON else { return [] }
        guard let data = daily["data"] as? [JSON] else { return [] }

        let forecasts = data.flatMap { (obj) -> Forecast? in
            return forecast(with: obj, in: context)
        }

        return forecasts
    }

    class func forecast(with json: JSON, in context: NSManagedObjectContext) -> Forecast? {
        guard
            let timestamp = json["time"] as? TimeInterval,
            let summary = json["summary"] as? String,
            let icon = json["icon"] as? String,
            let highTemp = json["temperatureMax"] as? Double,
            let lowTemp = json["temperatureMin"] as? Double
        else {
            return nil
        }

        guard let forecast = NSEntityDescription.insertNewObject(forEntityName: "Forecast", into: context) as? Forecast else {
            return nil
        }

        forecast.summary = summary
        forecast.icon = icon

        forecast.highTemp = highTemp
        forecast.lowTemp = lowTemp

        forecast.timestamp = NSDate(timeIntervalSince1970: timestamp)

        return forecast
    }
}


// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t -enable-library-evolution %S/Inputs/OpaqueTypeStructured.swift
// RUN: %target-swift-frontend -emit-sil -I %t %s | %FileCheck -check-prefix=SIL %s
// RUN: %target-swift-ide-test -print-module -source-filename %s -module-to-print OpaqueTypeStructured -I %t | %FileCheck -check-prefix=AST %s
import OpaqueTypeStructured

func acceptR<T: R>(_: T) { }

// AST: func f() -> (some P, [some Q])

func passAnX(x: X) {
  // SIL: $@convention(method) (@in_guaranteed X) -> (@out @_opaqueReturnTypeOf("$s20OpaqueTypeStructured1XV1fQr_SayQrGtyF", 0) __, @owned Array<@_opaqueReturnTypeOf("$s20OpaqueTypeStructured1XV1fQr_SayQrGtyF", 1) __>)
  acceptR(x)
  let _: X.A = x.f()
}

Disable availability checking in opaque result types test

// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -disable-availability-checking -o %t -enable-library-evolution %S/Inputs/OpaqueTypeStructured.swift
// RUN: %target-swift-frontend -emit-sil -disable-availability-checking -I %t %s | %FileCheck -check-prefix=SIL %s
// RUN: %target-swift-ide-test -print-module -source-filename %s -module-to-print OpaqueTypeStructured -I %t | %FileCheck -check-prefix=AST %s
import OpaqueTypeStructured

func acceptR<T: R>(_: T) { }

// AST: func f() -> (some P, [some Q])

func passAnX(x: X) {
  // SIL: $@convention(method) (@in_guaranteed X) -> (@out @_opaqueReturnTypeOf("$s20OpaqueTypeStructured1XV1fQr_SayQrGtyF", 0) __, @owned Array<@_opaqueReturnTypeOf("$s20OpaqueTypeStructured1XV1fQr_SayQrGtyF", 1) __>)
  acceptR(x)
  let _: X.A = x.f()
}


//
//  PXOneTapApplication.swift
//  MercadoPagoSDKV4
//
//  Created by Jonathan Scaramal on 16/03/2021.
//
public struct PXApplicationPaymentMethod: Codable {
    var id: String?
    var type: String?
}

public struct PXApplicationValidationProgram: Codable {
    var id: String
    var mandatory: Bool
}

public struct PXOneTapApplication: Codable {
    var paymentMethod: PXApplicationPaymentMethod
    var validationPrograms: [PXApplicationValidationProgram]
    var status: PXStatus

    public enum CodingKeys: String, CodingKey {
        case paymentMethod = "payment_method"
        case validationPrograms = "validation_programs"
        case status = "status"
    }
}

Add new propertie on PXOneTapDto

//
//  PXOneTapApplication.swift
//  MercadoPagoSDKV4
//
//  Created by Jonathan Scaramal on 16/03/2021.
//
public struct PXApplicationPaymentMethod: Codable {
    var id: String?
    var type: String?
}

public struct PXApplicationValidationProgram: Codable {
    var id: String
    var mandatory: Bool
}

public struct PXApplicationStatus: Codable {
    var enabled: Bool
    var mainMessage: PXText?
    var secondaryMessage: PXText?
    var detail: String

    public enum CodingKeys: String, CodingKey {
        case enabled = "enabled"
        case mainMessage = "main_message"
        case secondaryMessage = "secondary_message"
        case detail = "detail"
    }
}

public struct PXOneTapApplication: Codable {
    var paymentMethod: PXApplicationPaymentMethod
    var validationPrograms: [PXApplicationValidationProgram]
    var status: PXApplicationStatus

    public enum CodingKeys: String, CodingKey {
        case paymentMethod = "payment_method"
        case validationPrograms = "validation_programs"
        case status = "status"
    }
}


import PackageDescription

let package = Package(
  name: "SourceKittenDaemon",

  targets: [
    Target(name: "SourceKittenDaemon"),
    Target(name: "sourcekittend", dependencies: [.Target(name: "SourceKittenDaemon")])
  ],

  dependencies: [
    .Package(url: "https://github.com/Carthage/Commandant.git", Version(0, 11, 2)),
    .Package(url: "https://github.com/jpsim/SourceKitten.git", Version(0, 15, 0)),
    .Package(url: "https://github.com/vapor/vapor.git", Version(1, 1, 12)),
    .Package(url: "https://github.com/nanzhong/Xcode.swift.git", Version(0, 4, 1))
  ],

  exclude: [
    "Tests/SourceKittenDaemonTests/Fixtures/Sources"
  ]
)

Upgrade sourcekitten, resolve build error in newer version of Xcode

import PackageDescription

let package = Package(
  name: "SourceKittenDaemon",

  targets: [
    Target(name: "SourceKittenDaemon"),
    Target(name: "sourcekittend", dependencies: [.Target(name: "SourceKittenDaemon")])
  ],

  dependencies: [
    .Package(url: "https://github.com/Carthage/Commandant.git", versions: Version(0, 12, 0)..<Version(0, 12, .max)),
    .Package(url: "https://github.com/jpsim/SourceKitten.git", Version(0, 17, 2)),
    .Package(url: "https://github.com/vapor/vapor.git", Version(1, 1, 12)),
    .Package(url: "https://github.com/nanzhong/Xcode.swift.git", Version(0, 4, 1))
  ],

  exclude: [
    "Tests/SourceKittenDaemonTests/Fixtures/Sources"
  ]
)


//
//  SIApplication+Amethyst.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 5/8/16.
//  Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//

import Foundation
import Silica

public extension SIApplication {
    public func floating() -> Bool {
        let runningApplication = NSRunningApplication(processIdentifier: self.processIdentifier())
        return UserConfiguration.shared.runningApplicationShouldFloat(runningApplication!)
    }
}

Allow for optional applications from process identifiers

//
//  SIApplication+Amethyst.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 5/8/16.
//  Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//

import Foundation
import Silica

public extension SIApplication {
    public func floating() -> Bool {
        guard let runningApplication = NSRunningApplication(processIdentifier: processIdentifier()) else {
            return true
        }

        return UserConfiguration.shared.runningApplicationShouldFloat(runningApplication)
    }
}


//
//  AKBluetoothMIDIButton.swift
//  AudioKit For iOS
//
//  Created by Aurelius Prochazka on 1/21/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import CoreAudioKit

public class AKBluetoothMIDIButton: UIButton {

    override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        let viewController = CABTMIDICentralViewController()
        let navController = UINavigationController(rootViewController: viewController)
        viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: nil)
        navController.modalPresentationStyle = .popover
        let popC = navController.popoverPresentationController
        popC?.permittedArrowDirections = .any
        popC?.sourceRect = self.frame
        popC?.sourceView = self.superview
        let controller = self.superview?.next as? UIViewController
        controller?.present(navController, animated: true, completion: nil)
    }
}

Fix for the AKBluetoothMIDIBUtton on iPhone - added Done button

//
//  AKBluetoothMIDIButton.swift
//  AudioKit For iOS
//
//  Created by Aurelius Prochazka on 1/21/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import CoreAudioKit

class AKBTMIDICentralViewController: CABTMIDICentralViewController {
    var uiViewController: UIViewController?

    override public func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAction))
    }

    public func doneAction() {
        uiViewController?.dismiss(animated: true, completion: nil)
    }
}

public class AKBluetoothMIDIButton: UIButton {

    override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        let bluetoothMIDIViewController = AKBTMIDICentralViewController()
        let navController = UINavigationController(rootViewController: bluetoothMIDIViewController)
        navController.modalPresentationStyle = .popover
        let popC = navController.popoverPresentationController
        popC?.permittedArrowDirections = .any
        popC?.sourceRect = self.frame
        popC?.sourceView = self.superview
        let controller = self.superview?.next as? UIViewController
        controller?.present(navController, animated: true, completion: nil)
        bluetoothMIDIViewController.uiViewController = controller

    }

}


//
//  UITableViewExtensions.swift
//  KTSwiftExtensions
//
//  Created by Kyle Thomas on 6/27/16.
//  Copyright © 2016 Kyle Thomas. All rights reserved.
//

import UIKit

public extension UITableView {

    subscript(reuseIdentifier: String) -> UITableViewCell {
        return dequeueReusableCell(withIdentifier: reuseIdentifier)!
    }

    subscript(reuseIdentifier: String, indexPath: IndexPath) -> UITableViewCell {
        return dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
    }

    subscript(row: Int) -> UITableViewCell {
        return cellForRow(at: IndexPath(row: row, section: 0))!
    }

    subscript(row: Int, section: Int) -> UITableViewCell {
        return cellForRow(at: IndexPath(row: row, section: section))!
    }
}

Add a convenience extension on UITableView and UICollectionView that can be used to dequeue the cell when the identifier matches the class name

//
//  UITableViewExtensions.swift
//  KTSwiftExtensions
//
//  Created by Kyle Thomas on 6/27/16.
//  Copyright © 2016 Kyle Thomas. All rights reserved.
//

import UIKit

public extension UITableView {

    subscript(reuseIdentifier: String) -> UITableViewCell {
        return dequeueReusableCell(withIdentifier: reuseIdentifier)!
    }

    subscript(reuseIdentifier: String, indexPath: IndexPath) -> UITableViewCell {
        return dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
    }

    subscript(row: Int) -> UITableViewCell {
        return cellForRow(at: IndexPath(row: row, section: 0))!
    }

    subscript(row: Int, section: Int) -> UITableViewCell {
        return cellForRow(at: IndexPath(row: row, section: section))!
    }
}

public extension UITableView {

    // This method can be used when the reuseIdentifier matches the name of the class
    func dequeue<CellClass>(_ cellClass: CellClass.Type, for indexPath: IndexPath) -> CellClass {
        let reuseIdentifier = "\(cellClass)"
        guard let cell = dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? CellClass else {
            fatalError("Could not find a cell with reuseIdentifier: \(reuseIdentifier). Please ensure that the reuseidentifier for \(cellClass) is set to \(reuseIdentifier)")
        }
        return cell
    }
}

public extension UICollectionView {

    // This method can be used when the reuseIdentifier matches the name of the class
    func dequeue<CellClass>(_ cellClass: CellClass.Type, for indexPath: IndexPath) -> CellClass {
        let reuseIdentifier = "\(cellClass)"
        guard let cell = dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? CellClass else {
            fatalError("Could not find a cell with reuseIdentifier: \(reuseIdentifier). Please ensuer that the reuseidentifier for \(cellClass) is set to \(reuseIdentifier)")
        }
        return cell
    }
}


//
//  UICollectionView+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 6/2/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import UIKit

extension UICollectionView {
    public func registerCell<T: UICollectionViewCell>(_ cellClass: T.Type) {
        register(UINib(nibName: "\(T.self)", bundle: nil), forCellWithReuseIdentifier: "\(T.self)")
    }

    public func dequeueCell<T: UICollectionViewCell>(forItemAt indexPath: IndexPath) -> T {
        return dequeueReusableCell(withReuseIdentifier: "\(T.self)", for: indexPath) as! T
    }
}

Add new collection view helper methods

//
//  UICollectionView+Extensions.swift
//  Utilities
//
//  Created by Caio Mello on 6/2/19.
//  Copyright © 2019 Caio Mello. All rights reserved.
//

import UIKit

extension UICollectionView {
    public func registerCell<T: UICollectionViewCell>(_ type: T.Type) {
        register(UINib(nibName: "\(T.self)", bundle: nil), forCellWithReuseIdentifier: "\(T.self)")
    }

    public func registerSupplementaryView<T: UICollectionReusableView>(ofKind kind: String, _ type: T.Type) {
        register(UINib(nibName: "\(T.self)", bundle: nil), forSupplementaryViewOfKind: kind, withReuseIdentifier: "\(T.self)")
    }

    public func dequeueCell<T: UICollectionViewCell>(forItemAt indexPath: IndexPath) -> T {
        return dequeueReusableCell(withReuseIdentifier: "\(T.self)", for: indexPath) as! T
    }

    public func dequeueSupplementaryView<T: UICollectionReusableView>(ofKind kind: String, at indexPath: IndexPath) -> T {
        return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "\(T.self)", for: indexPath) as! T
    }
}


// RUN: %empty-directory(%t)
// RUN: %target-build-swift -target x86_64-apple-macosx12 %s -o %t/linking_direct
// RUN: %target-build-swift -target x86_64-apple-macosx11 %s -o %t/linking_rpath
// RUN: %target-build-swift -target x86_64-apple-macosx10.10 %s -o %t/linking_rpath_old

// RUN: otool -L %t/linking_direct | %FileCheck -check-prefix CHECK-DIRECT %s
// RUN: otool -L %t/linking_rpath | %FileCheck -check-prefix CHECK-RPATH %s
// RUN: otool -L %t/linking_rpath_old | %FileCheck -check-prefix CHECK-RPATH %s

// REQUIRES: OS=macosx

// CHECK-DIRECT: /usr/lib/swift/libswift_Concurrency.dylib
// CHECK-RPATH: @rpath/libswift_Concurrency.dylib

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct X {
  public func f() async -> Int { return 0 }
  public func g() async -> Int {
    await f()
  }
}

Add REQUIRES: CPU=x86_64 to test that is failing in CI

// RUN: %empty-directory(%t)
// RUN: %target-build-swift -target x86_64-apple-macosx12 %s -o %t/linking_direct
// RUN: %target-build-swift -target x86_64-apple-macosx11 %s -o %t/linking_rpath
// RUN: %target-build-swift -target x86_64-apple-macosx10.10 %s -o %t/linking_rpath_old

// RUN: otool -L %t/linking_direct | %FileCheck -check-prefix CHECK-DIRECT %s
// RUN: otool -L %t/linking_rpath | %FileCheck -check-prefix CHECK-RPATH %s
// RUN: otool -L %t/linking_rpath_old | %FileCheck -check-prefix CHECK-RPATH %s

// REQUIRES: OS=macosx
// REQUIRES: CPU=x86_64

// CHECK-DIRECT: /usr/lib/swift/libswift_Concurrency.dylib
// CHECK-RPATH: @rpath/libswift_Concurrency.dylib

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct X {
  public func f() async -> Int { return 0 }
  public func g() async -> Int {
    await f()
  }
}


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

extension Module {
	public static var string: Module {
		let List: Term = "List"
		let cons: Term = "cons"
		let `nil`: Term = "nil"

		let String = Declaration("String",
			type: .Type,
			value: .Embedded(Swift.String.self))

		let Character = Declaration("Character",
			type: .Type,
			value: .Embedded(Swift.Character.self))

		return Module("String", [ String, Character ])
	}
}

Write a function to construct a List Character from a String.

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

extension Module {
	public static var string: Module {
		let List: Term = "List"
		let cons: Term = "cons"
		let `nil`: Term = "nil"

		let String = Declaration("String",
			type: .Type,
			value: .Embedded(Swift.String.self))

		let Character = Declaration("Character",
			type: .Type,
			value: .Embedded(Swift.Character.self))

		return Module("String", [ String, Character ])
		func toTerm(characters: Swift.String.CharacterView) -> Term {
			switch characters.first {
			case let .Some(c):
				return cons[Character.ref, .Embedded(c), toTerm(characters.dropFirst())]
			default:
				return `nil`[Character.ref]
			}
		}
	}
}


import UIKit
import WMF

final class TalkPageCellCommentSeparator: SetupView {

    // MARK: - UI Elements

    lazy var stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()

    lazy var horizontalLine: VerticalSpacerView = {
        let view = VerticalSpacerView.spacerWith(space: 1)
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    // MARK: - Lifecycle

    override func setup() {
        addSubview(stackView)
        stackView.addArrangedSubview(horizontalLine)

        NSLayoutConstraint.activate([
            stackView.topAnchor.constraint(equalTo: topAnchor, constant: 20),
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
            stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20)
        ])
    }

}

extension TalkPageCellCommentSeparator: Themeable {

    func apply(theme: Theme) {
        horizontalLine.backgroundColor = theme.colors.tertiaryText
    }

}

Use expanded size for comment separator's intrinsic content size.

import UIKit
import WMF

final class TalkPageCellCommentSeparator: SetupView {

    // MARK: - UI Elements

    lazy var stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()

    lazy var horizontalLine: VerticalSpacerView = {
        let view = VerticalSpacerView.spacerWith(space: 1)
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    override var intrinsicContentSize: CGSize {
        return UIView.layoutFittingExpandedSize
    }

    // MARK: - Lifecycle

    override func setup() {
        addSubview(stackView)
        stackView.addArrangedSubview(horizontalLine)

        NSLayoutConstraint.activate([
            stackView.topAnchor.constraint(equalTo: topAnchor, constant: 20),
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
            stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20)
        ])
    }

}

extension TalkPageCellCommentSeparator: Themeable {

    func apply(theme: Theme) {
        horizontalLine.backgroundColor = theme.colors.tertiaryText
    }

}


//
//  DCPodTests.swift
//  DCPodTests
//
//  Created by Daniel Contreras on 7/5/17.
//  Copyright © 2017 DC. All rights reserved.
//

import XCTest
@testable import DCPod

class DCPodTests: 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 testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

Add unit test for sum method.

//
//  DCPodTests.swift
//  DCPodTests
//
//  Created by Daniel Contreras on 7/5/17.
//  Copyright © 2017 DC. All rights reserved.
//

import XCTest
@testable import DCPod

class DCPodTests: 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 testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

    func testSumIntegers() {
        XCTAssertEqual(sum(a: 1, b: 2), 3)
    }

}


import CoreGraphics

public class GraphicsCanvas: Canvas {

    private var tortoiseCharmer = TortoiseCharmer(tortoiseCount: 0)
    private let graphicsContext: GraphicsContext

    public init(size: CGSize, context: CGContext) {
        #if os(iOS)
            let isUIViewContext = true
        #else
            let isUIViewContext = false
        #endif
        self.graphicsContext = GraphicsContext(size: size,
                                               cgContext: context,
                                               backgroundColor: color?.cgColor,
                                               isUIViewContext: isUIViewContext)
    }

    // MARK: - Canvas Protocol

    public func drawing(drawingBlock: @escaping (Tortoise) -> Void) {
        tortoiseCharmer.initialize(tortoiseCount: 1)
        drawingBlock(tortoiseCharmer.tortoises[0])
        tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
    }

    public func drawingWithTortoises(count: Int, drawingBlock: @escaping ([Tortoise]) -> Void) {
        tortoiseCharmer.initialize(tortoiseCount: count)
        drawingBlock(tortoiseCharmer.tortoises)
        tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
    }

    public var color: Color?

}

Allow TortoiseCharmer to use default value on initialization to prevent run-time crash

import CoreGraphics

public class GraphicsCanvas: Canvas {

    private var tortoiseCharmer = TortoiseCharmer()
    private let graphicsContext: GraphicsContext

    public init(size: CGSize, context: CGContext) {
        #if os(iOS)
            let isUIViewContext = true
        #else
            let isUIViewContext = false
        #endif
        self.graphicsContext = GraphicsContext(size: size,
                                               cgContext: context,
                                               backgroundColor: color?.cgColor,
                                               isUIViewContext: isUIViewContext)
    }

    // MARK: - Canvas Protocol

    public func drawing(drawingBlock: @escaping (Tortoise) -> Void) {
        tortoiseCharmer.initialize(tortoiseCount: 1)
        drawingBlock(tortoiseCharmer.tortoises[0])
        tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
    }

    public func drawingWithTortoises(count: Int, drawingBlock: @escaping ([Tortoise]) -> Void) {
        tortoiseCharmer.initialize(tortoiseCount: count)
        drawingBlock(tortoiseCharmer.tortoises)
        tortoiseCharmer.charm(with: graphicsContext, toFrame: nil)
    }

    public var color: Color?

}


import ArgumentParser
import Foundation
import Plot
import Publish
import SplashPublishPlugin

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

    struct ItemMetadata: WebsiteItemMetadata {
      var title: String
      var date: String?
    }

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

struct Publisher: ParsableCommand {
    func run() throws {
        try! PersonalWebsite().publish(
            withTheme: .custom,
            plugins: [.splash(withClassPrefix: "classPrefix")]
        )
    }
}

Publisher.main()

Remove class prefix from formatted Swift snippets

import ArgumentParser
import Foundation
import Plot
import Publish
import SplashPublishPlugin

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

    struct ItemMetadata: WebsiteItemMetadata {
      var title: String
      var date: String?
    }

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

struct Publisher: ParsableCommand {
    func run() throws {
        try! PersonalWebsite().publish(
            withTheme: .custom,
            plugins: [.splash(withClassPrefix: "")]
        )
    }
}

Publisher.main()


//
//  FluxStandardActionSpec.swift
//  ReduxKit
//
//  Created by Aleksander Herforth Rendtslev on 06/11/15.
//  Copyright © 2015 Kare Media. All rights reserved.
//

import Quick
import Nimble
@testable import ReduxKit

class FluxStandardActionSpec: QuickSpec {

    override func spec() {

        describe("FluxStandardActionSpec") {

            // swiftlint:disable line_length
            it("should succesfully retrieve payload from FluxStandardAction types") {

                // Arrange
                let incrementAction = IncrementAction() as FluxStandardAction
                let pushAction = PushAction(payload: nil) as FluxStandardAction
                let updateTextFieldAction = UpdateTextFieldAction(payload: nil) as FluxStandardAction

                // Act
                let incrementPayload = incrementAction.payload
                let pushPayload = pushAction.payload
                let updateTextFieldPayload = updateTextFieldAction.payload

                // Assert
                expect(incrementPayload is Int).to(beTruthy())
                expect(pushPayload is PushAction.Payload).to(beTruthy())
                expect(updateTextFieldPayload is UpdateTextFieldAction.Payload).to(beTruthy())
            }
        }
    }
}

Fix naming of FSA spec

//
//  FluxStandardActionSpec.swift
//  ReduxKit
//
//  Created by Aleksander Herforth Rendtslev on 06/11/15.
//  Copyright © 2015 Kare Media. All rights reserved.
//

import Quick
import Nimble
@testable import ReduxKit

class FluxStandardActionSpec: QuickSpec {

    override func spec() {

        describe("FluxStandardAction") {

            // swiftlint:disable line_length
            it("should succesfully retrieve payload from FluxStandardAction types") {

                // Arrange
                let incrementAction = IncrementAction() as FluxStandardAction
                let pushAction = PushAction(payload: nil) as FluxStandardAction
                let updateTextFieldAction = UpdateTextFieldAction(payload: nil) as FluxStandardAction

                // Act
                let incrementPayload = incrementAction.payload
                let pushPayload = pushAction.payload
                let updateTextFieldPayload = updateTextFieldAction.payload

                // Assert
                expect(incrementPayload is Int).to(beTruthy())
                expect(pushPayload is PushAction.Payload).to(beTruthy())
                expect(updateTextFieldPayload is UpdateTextFieldAction.Payload).to(beTruthy())
            }
        }
    }
}


//
//  ModelHandler.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 13/01/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import Foundation
import SwiftyJSON
import RealmSwift

protocol ModelHandler {
    func add(_ values: JSON, realm: Realm)
    func update(_ values: JSON, realm: Realm)
    func remove(_ values: JSON, realm: Realm)
}

extension ModelHandler where Self: BaseModel {
    static func handle(msg: ResponseMessage, primaryKey: String, values: JSON) {
        Realm.execute({ (realm) in
            var object: Self!

            if let existentObject = realm.object(ofType: Self.self, forPrimaryKey: primaryKey as AnyObject) {
                object = existentObject
            }

            if object == nil {
                object = Self()
                object.setValue(primaryKey, forKey: Self.primaryKey() ?? "")
            }

            switch msg {
            case .added:
                object.add(values, realm: realm)
            case .changed:
                object.update(values, realm: realm)
            case .removed:
                object.remove(values, realm: realm)
            default:
                object.update(values, realm: realm)
            }
        })
    }
}

Handle "inserted" message from WebSocket

//
//  ModelHandler.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 13/01/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import Foundation
import SwiftyJSON
import RealmSwift

protocol ModelHandler {
    func add(_ values: JSON, realm: Realm)
    func update(_ values: JSON, realm: Realm)
    func remove(_ values: JSON, realm: Realm)
}

extension ModelHandler where Self: BaseModel {
    static func handle(msg: ResponseMessage, primaryKey: String, values: JSON) {
        Realm.execute({ (realm) in
            var object: Self!

            if let existentObject = realm.object(ofType: Self.self, forPrimaryKey: primaryKey as AnyObject) {
                object = existentObject
            }

            if object == nil {
                object = Self()
                object.setValue(primaryKey, forKey: Self.primaryKey() ?? "")
            }

            switch msg {
            case .added, .inserted:
                object.add(values, realm: realm)
            case .changed:
                object.update(values, realm: realm)
            case .removed:
                object.remove(values, realm: realm)
            default:
                object.update(values, realm: realm)
            }
        })
    }
}


import Nimble
import Moya

public func beOfSameErrorType(_ expectedValue: MoyaError) -> Predicate<MoyaError> {
    return Predicate { expression -> PredicateResult in
        let test: Bool
        if let value = try expression.evaluate() {
            switch value {
            case .imageMapping:
                switch expectedValue {
                case .imageMapping:
                    test = true
                default:
                    test = false
                }
            case .jsonMapping:
                switch expectedValue {
                case .jsonMapping:
                    test = true
                default:
                    test = false
                }
            case .stringMapping:
                switch expectedValue {
                case .stringMapping:
                    test = true
                default:
                    test = false
                }
            case .objectMapping:
                switch expectedValue {
                case .objectMapping:
                    test = true
                default:
                    test = false
                }
            case .encodableMapping:
                switch expectedValue {
                case .objectMapping:
                    test = true
                default:
                    test = false
                }
            case .statusCode:
                switch expectedValue {
                case .statusCode:
                    test = true
                default:
                    test = false
                }
            case .underlying:
                switch expectedValue {
                case .underlying:
                    test = true
                default:
                    test = false
                }
            case .requestMapping:
                switch expectedValue {
                case .requestMapping:
                    test = true
                default:
                    test = false
                }
            case .parameterEncoding:
                switch expectedValue {
                case .parameterEncoding:
                    test = true
                default:
                    test = false
                }
            }
        } else {
            test = false
        }

        return PredicateResult(bool: test, message: .expectedActualValueTo("<\(expectedValue)>"))
    }
}

Fix copy-paste error in switch

import Nimble
import Moya

public func beOfSameErrorType(_ expectedValue: MoyaError) -> Predicate<MoyaError> {
    return Predicate { expression -> PredicateResult in
        let test: Bool
        if let value = try expression.evaluate() {
            switch value {
            case .imageMapping:
                switch expectedValue {
                case .imageMapping:
                    test = true
                default:
                    test = false
                }
            case .jsonMapping:
                switch expectedValue {
                case .jsonMapping:
                    test = true
                default:
                    test = false
                }
            case .stringMapping:
                switch expectedValue {
                case .stringMapping:
                    test = true
                default:
                    test = false
                }
            case .objectMapping:
                switch expectedValue {
                case .objectMapping:
                    test = true
                default:
                    test = false
                }
            case .encodableMapping:
                switch expectedValue {
                case .encodableMapping:
                    test = true
                default:
                    test = false
                }
            case .statusCode:
                switch expectedValue {
                case .statusCode:
                    test = true
                default:
                    test = false
                }
            case .underlying:
                switch expectedValue {
                case .underlying:
                    test = true
                default:
                    test = false
                }
            case .requestMapping:
                switch expectedValue {
                case .requestMapping:
                    test = true
                default:
                    test = false
                }
            case .parameterEncoding:
                switch expectedValue {
                case .parameterEncoding:
                    test = true
                default:
                    test = false
                }
            }
        } else {
            test = false
        }

        return PredicateResult(bool: test, message: .expectedActualValueTo("<\(expectedValue)>"))
    }
}


//
//  Copyright © 2017 Carousell. All rights reserved.
//

import UIKit

internal final class SlideUpPresentationController: UIPresentationController {

    override func presentationTransitionWillBegin() {
        // Calculate the presented frame that doesn't cover the navigation bar.
        let targetFrame: CGRect

        if let navigationBar = presentingViewController.view.subviews.filter({ $0 is UINavigationBar }).first {
            targetFrame = presentingViewController.view.frame.divided(atDistance: navigationBar.frame.maxY, from: .minYEdge).remainder
        } else {
            targetFrame = presentingViewController.view.frame
        }

        containerView?.frame = targetFrame
    }

}

Update the container frame for photo albums after device rotation

//
//  Copyright © 2017 Carousell. All rights reserved.
//

import UIKit

internal final class SlideUpPresentationController: UIPresentationController {

    override func presentationTransitionWillBegin() {
        adjustContainerFrame()
    }

    // MARK: - UITraitEnvironment

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        if previousTraitCollection != nil {
            // Update the frame for the container view after device rotation.
            adjustContainerFrame()
        }
    }

    // MARK: - Private

    private func adjustContainerFrame() {
        // Calculate the presented frame that doesn't cover the navigation bar.
        let targetFrame: CGRect

        if let navigationBar = presentingViewController.view.subviews.filter({ $0 is UINavigationBar }).first {
            targetFrame = presentingViewController.view.frame.divided(atDistance: navigationBar.frame.maxY, from: .minYEdge).remainder
        } else {
            targetFrame = presentingViewController.view.frame
        }

        containerView?.frame = targetFrame
    }

}


import Foundation
import LoggerAPI
@testable import LicensePlistCore

class TestUtil {
    static func setGitHubToken() {
        // Specify your `github_token.txt` location
        let url = URL(fileURLWithPath: "/Users/mono/Git/Lib/LicensePlist/Tests/LicensePlistTests/Resources/github_token.txt")
        do {
            GitHubAuthorizatoin.shared.token = try String(contentsOf: url,
                                                           encoding: String.Encoding.utf8)
        } catch {
            Log.warning("\(url) not found. You can execute without github_token, but API limit will exceed sometimes.")
        }
    }
}

Change default github_token path for test

import Foundation
import LoggerAPI
@testable import LicensePlistCore

class TestUtil {
    static func setGitHubToken() {
        // Specify your `github_token.txt` location
        let url = URL(fileURLWithPath: "/Users/mono/Git/Private/LicensePlist/Tests/LicensePlistTests/Resources/github_token.txt")
        do {
            GitHubAuthorizatoin.shared.token = try String(contentsOf: url,
                                                           encoding: String.Encoding.utf8)
        } catch {
            Log.warning("\(url) not found. You can execute without github_token, but API limit will exceed sometimes.")
        }
    }
}


//
//  AppDelegate.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2015-09-13.
//  Copyright © 2015 Sandcastle Application Development. All rights reserved.
//

import UIKit
import AWSCore
import AWSS3

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

	var window: UIWindow?

	struct AwsConstants
	{
		static let RegionType = AWSRegionType.USEast1
		static let IdentityPool = "***REMOVED***"
		static let BackgroundSession = "com.sandcastleapps.partyup.session"
	}

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

		let credentialProvider = AWSCognitoCredentialsProvider(
			regionType: AwsConstants.RegionType,
			identityPoolId: AwsConstants.IdentityPool)
		let configuration = AWSServiceConfiguration(
			region: AwsConstants.RegionType,
			credentialsProvider: credentialProvider)

		AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

		return true
	}

	func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {

		AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: AwsConstants.BackgroundSession, completionHandler: completionHandler)
	}

}

Set up the PartyUpConstants and made the AWSConstants private since no other objects need to see them.

//
//  AppDelegate.swift
//  PartyUP
//
//  Created by Fritz Vander Heide on 2015-09-13.
//  Copyright © 2015 Sandcastle Application Development. All rights reserved.
//

import UIKit
import AWSCore
import AWSS3

struct PartyUpConstants
{
	static let StorageBucket = "com.sandcastleapps.partyup"
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

	var window: UIWindow?

	private struct AwsConstants
	{
		static let RegionType = AWSRegionType.USEast1
		static let IdentityPool = "***REMOVED***"
		static let BackgroundSession = "com.sandcastleapps.partyup.session"
	}

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

		let credentialProvider = AWSCognitoCredentialsProvider(
			regionType: AwsConstants.RegionType,
			identityPoolId: AwsConstants.IdentityPool)
		let configuration = AWSServiceConfiguration(
			region: AwsConstants.RegionType,
			credentialsProvider: credentialProvider)

		AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

		return true
	}

	func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {

		AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: AwsConstants.BackgroundSession, completionHandler: completionHandler)
	}

}


import Foundation

extension Bundle {
    @objc public class var aztecBundle: Bundle {
        let defaultBundle = Bundle(for: EditorView.self)
        // If installed with CocoaPods, resources will be in WordPress-Aztec-iOS.bundle
        if let bundleURL = defaultBundle.resourceURL,
            let resourceBundle = Bundle(url: bundleURL.appendingPathComponent("WordPress-Aztec-iOS")) {
            return resourceBundle
        }
        // Otherwise, the default bundle is used for resources
        return defaultBundle
    }
}

Fix typo in NSBundle path

import Foundation

extension Bundle {
    @objc public class var aztecBundle: Bundle {
        let defaultBundle = Bundle(for: EditorView.self)
        // If installed with CocoaPods, resources will be in WordPress-Aztec-iOS.bundle
        if let bundleURL = defaultBundle.resourceURL,
            let resourceBundle = Bundle(url: bundleURL.appendingPathComponent("WordPress-Aztec-iOS.bundle")) {
            return resourceBundle
        }
        // Otherwise, the default bundle is used for resources
        return defaultBundle
    }
}


//
//  Realm+Extra.swift
//  Pods
//
//  Created by Jean-Charles SORIN on 09/11/2016.
//
//

import Foundation
import RealmSwift

public extension Results {

  /// Convert your Results<T> to a sequence
  ///
  /// - returns: Sequence [T]
  public func toArray() -> [T] {
    return self.map { $0 }
  }

  /// Safety getter object on your results
  ///
  /// - parameter index: The desired index
  ///
  /// - returns: Your Realm result object at the correct index, nil if out of bound
  public subscript (safe index: Int) -> T? {
    return index < count && index >= 0 ? self[index] : nil
  }
}

public extension RealmSwift.List {

  /// Convert your List<T> to a sequence
  ///
  /// - returns: Sequence [T]
  public func toArray() -> [T] {
    return self.map { $0 }
  }
}

Remove toArray on Realm Results

//
//  Realm+Extra.swift
//  Pods
//
//  Created by Jean-Charles SORIN on 09/11/2016.
//
//

import Foundation
import RealmSwift

public extension Results {

  /// Safety getter object on your results
  ///
  /// - parameter index: The desired index
  ///
  /// - returns: Your Realm result object at the correct index, nil if out of bound
  public subscript (safe index: Int) -> T? {
    return index < count && index >= 0 ? self[index] : nil
  }
}


//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Medium)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 24, left: 16, bottom: 8, right: 16)

        textLabel.numberOfLines = 0
        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.edges == superview.edgesWithinMargins
        }
    }
}

Increase font size for contest list header

//
//  ContentListHeaderView.swift
//  JumuNordost
//
//  Created by Martin Richter on 02/03/16.
//  Copyright © 2016 Martin Richter. All rights reserved.
//

import Cartography

class ContestListHeaderView: UIView {

    private let textLabel = Label(fontWeight: .Regular, fontStyle: .Italic, fontSize: .Large)

    // MARK: - Lifecycle

    convenience init(text: String) {
        self.init()

        self.layoutMargins = UIEdgeInsets(top: 24, left: 16, bottom: 8, right: 16)

        textLabel.numberOfLines = 0
        textLabel.textAlignment = .Center
        textLabel.textColor = Color.secondaryTextColor
        textLabel.text = text

        addSubview(textLabel)
        makeConstraints()
    }

    // MARK: - Layout

    private func makeConstraints() {
        constrain(textLabel, self) { textLabel, superview in
            textLabel.edges == superview.edgesWithinMargins
        }
    }
}


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

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

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionType() {
		let generated = constraints(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: []))
		assert(simplify(generated.0), == ,.function(0, .Unit))
	}
}

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

import Assertions
import Manifold
import TesseractCore
import XCTest

Sort the type variables for predictability of results.

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

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

	func testGraphsWithOneParameterAndNoReturnsHaveFunctionType() {
		let generated = constraints(Graph(nodes: [Identifier(): .Parameter((0, .Unit))], edges: []))
		assert(simplify(generated.0), == ,.function(0, .Unit))
	}
}

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

import Assertions
import Manifold
import Prelude
import TesseractCore
import XCTest


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

import Foundation

 /// Base URL for the Vimeo API
let VimeoBaseURL = URL(string: "https://api.vimeo.com")!

 /// Default API version to use for requests
let VimeoDefaultAPIVersionString = "3.2"

Change VimeoBaseURL constant access to public

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

import Foundation

 /// Base URL for the Vimeo API
public let VimeoBaseURL = URL(string: "https://api.vimeo.com")!

 /// Default API version to use for requests
let VimeoDefaultAPIVersionString = "3.2"