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

import Foundation

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

class BeerRequest {
    let requestParams: [BeerRequestParam: String]

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

        requestParams = params
    }
}

Add function for loading beers

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

import Foundation

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

class BeerRequest {
    let requestParams: [BeerRequestParam: String]

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

        requestParams = params
    }

    func loadBeersWithCompletionHandler(completionHandler: ((beers: [Beer])->Void)) {
        BreweryDBApiKey
    }
}


import Cocoa
import WebKit

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

// MARK: - Event Handling

extension FreedrawView {

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

Use shorter callHook in magnify event handler

import Cocoa
import WebKit

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

// MARK: - Event Handling

extension FreedrawView {

    override func magnifyWithEvent(event: NSEvent) {
        document?.callHook("dispatchMagnify", forEvent: event, withArguments: [event.magnification])
    }
}


//
//  GiftCell.swift
//  Babies
//
//  Created by phi161 on 27/05/16.
//  Copyright © 2016 Stanhope Road. All rights reserved.
//

import UIKit

class GiftCell: UITableViewCell {

    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var dateLabel: UILabel!
    @IBOutlet var currencyLabel: UILabel!

    func updateInterface(gift: Gift) {
        let textPrompt = NSLocalizedString("TAP_TO_EDIT_GIFT", comment: "Prompt text when the gift details is nil or empty")
        titleLabel.text = (gift.details ?? "").isEmpty ? textPrompt : gift.details!
        if let date = gift.date {
            dateLabel.text = NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)
        } else {
            dateLabel.text = "n/a"
        }
        currencyLabel.text = gift.price?.stringValue
    }
}

Use a currency formatter to display the gift's price

//
//  GiftCell.swift
//  Babies
//
//  Created by phi161 on 27/05/16.
//  Copyright © 2016 Stanhope Road. All rights reserved.
//

import UIKit

class GiftCell: UITableViewCell {

    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var dateLabel: UILabel!
    @IBOutlet var currencyLabel: UILabel!

    func updateInterface(gift: Gift) {

        // Details
        let textPrompt = NSLocalizedString("TAP_TO_EDIT_GIFT", comment: "Prompt text when the gift details is nil or empty")
        titleLabel.text = (gift.details ?? "").isEmpty ? textPrompt : gift.details!

        // Date
        if let date = gift.date {
            dateLabel.text = NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)
        } else {
            dateLabel.text = "n/a"
        }

        // Price
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .CurrencyStyle
        formatter.locale = NSLocale.currentLocale()

        currencyLabel.text = formatter.stringFromNumber(gift.price!)
    }
}


//
//  SKMesurement.swift
//  SKPhotoBrowser
//
//  Created by 鈴木 啓司 on 2016/08/09.
//  Copyright © 2016年 suzuki_keishi. All rights reserved.
//

import Foundation
import UIKit

struct SKMesurement {
    static let isPhone: Bool = UIDevice.current.userInterfaceIdiom == .phone
    static let isPad: Bool = UIDevice.current.userInterfaceIdiom == .pad
    static var statusBarH: CGFloat {
        return UIApplication.shared.statusBarFrame.height
    }
    static var screenHeight: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.height ?? UIScreen.main.bounds.height
    }
    static var screenWidth: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.width ?? UIScreen.main.bounds.width
    }
    static var screenScale: CGFloat {
        return UIScreen.main.scale
    }
    static var screenRatio: CGFloat {
        return screenWidth / screenHeight
    }
    static var isPhoneX: Bool {
        if isPhone && UIScreen.main.nativeBounds.height == 2436 {
           return true
        }
        return false
    }
}

Support for iPhoneXs, XsMax and Xr

//
//  SKMesurement.swift
//  SKPhotoBrowser
//
//  Created by 鈴木 啓司 on 2016/08/09.
//  Copyright © 2016年 suzuki_keishi. All rights reserved.
//

import Foundation
import UIKit

struct SKMesurement {
    static let isPhone: Bool = UIDevice.current.userInterfaceIdiom == .phone
    static let isPad: Bool = UIDevice.current.userInterfaceIdiom == .pad
    static var statusBarH: CGFloat {
        return UIApplication.shared.statusBarFrame.height
    }
    static var screenHeight: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.height ?? UIScreen.main.bounds.height
    }
    static var screenWidth: CGFloat {
        return UIApplication.shared.preferredApplicationWindow?.bounds.width ?? UIScreen.main.bounds.width
    }
    static var screenScale: CGFloat {
        return UIScreen.main.scale
    }
    static var screenRatio: CGFloat {
        return screenWidth / screenHeight
    }
    static var isPhoneX: Bool {
        let iPhoneXHeights: [CGFloat] = [2436, 2688, 1792]
        if isPhone, iPhoneXHeights.contains(UIScreen.main.nativeBounds.height) {
           return true
        }
        return false
    }
}


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

import Argo

struct Performance {
    let id: String
    let stageTime: NSDate
    let categoryName: String
    let ageGroup: String
    let predecessorHostName: String?
    let predecessorHostCountry: String?
    let appearances: [Appearance]
    let pieces: [Piece]
}

// MARK: - Equatable

extension Performance: Equatable {}

func ==(lhs: Performance, rhs: Performance) -> Bool {
    return lhs.id == rhs.id
}

// MARK: - Decodable

extension Performance: Decodable {
    private static func create(id: String)(stageTime: NSDate)(categoryName: String)(ageGroup: String)(predecessorHostName: String?)(predecessorHostCountry: String?)(appearances: [Appearance])(pieces: [Piece]) -> Performance {
        return Performance(
            id: id,
            stageTime: stageTime,
            categoryName: categoryName,
            ageGroup: ageGroup,
            predecessorHostName: predecessorHostName,
            predecessorHostCountry: predecessorHostCountry,
            appearances: appearances,
            pieces: pieces
        )
    }

    static func decode(json: JSON) -> Decoded<Performance> {
        return create // curry(self.init) is currently too complex to compile
            <^> json <| "id"
            <*> json <| "stage_time"
            <*> json <| "category_name"
            <*> json <| "age_group"
            <*> json <|? "predecessor_host_name"
            <*> json <|? "predecessor_host_country"
            <*> json <|| "appearances"
            <*> json <|| "pieces"
    }
}

Use Curry for decoding performances, now that the compiler can handle the complexity

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

import Argo
import Curry

struct Performance {
    let id: String
    let stageTime: NSDate
    let categoryName: String
    let ageGroup: String
    let predecessorHostName: String?
    let predecessorHostCountry: String?
    let appearances: [Appearance]
    let pieces: [Piece]
}

// MARK: - Equatable

extension Performance: Equatable {}

func ==(lhs: Performance, rhs: Performance) -> Bool {
    return lhs.id == rhs.id
}

// MARK: - Decodable

extension Performance: Decodable {
    static func decode(json: JSON) -> Decoded<Performance> {
        return curry(self.init)
            <^> json <| "id"
            <*> json <| "stage_time"
            <*> json <| "category_name"
            <*> json <| "age_group"
            <*> json <|? "predecessor_host_name"
            <*> json <|? "predecessor_host_country"
            <*> json <|| "appearances"
            <*> json <|| "pieces"
    }
}


@testable import Brick
import Quick
import Nimble
import Fakery

class ExtensionsSpec: QuickSpec {

  override func spec() {
    describe("Array+Brick") {
      var items =  [ViewModel]()

      beforeEach {
        for index in 0..<10 {
          var item = ViewModel(title: "Test")
          item.index = 9 - index

          items.append(item)
        }
      }

      describe("#refreshIndexes") {
        it("sets proper indexes") {
          for index in 0..<10 {
            expect(items[index].index).to(equal(9 - index))
          }

          items.refreshIndexes()

          for index in 0..<10 {
            expect(items[index].index).to(equal(index))
          }
        }
      }
    }
  }
}

Add tests for dictionary extension

@testable import Brick
import Quick
import Nimble
import Fakery

class ExtensionsSpec: QuickSpec {

  override func spec() {
    describe("Array+Brick") {
      var items = [ViewModel]()

      beforeEach {
        for index in 0..<10 {
          var item = ViewModel(title: "Test")
          item.index = 9 - index

          items.append(item)
        }
      }

      describe("#refreshIndexes") {
        it("sets proper indexes") {
          for index in 0..<10 {
            expect(items[index].index).to(equal(9 - index))
          }

          items.refreshIndexes()

          for index in 0..<10 {
            expect(items[index].index).to(equal(index))
          }
        }
      }
    }

    describe("Dictionary+Brick") {
      var items = [String: String]()

      beforeEach {
        items = ["title": "test"]
      }

      describe("#subscript") {
        it("sets a proper value based on a string representation of a view model Key") {
          items[.Subtitle] = "subtitle"
          expect(items["subtitle"]).to(equal("subtitle"))
        }

        it("returns a proper value based on a string representation of a view model Key") {
          expect(items[.Title]).to(equal("test"))
        }
      }
    }
  }
}


//
//  StatusBar.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015-2017 noraesae and project contributors.
//  Licensed under the MIT License.
//

import AppKit
import Cocoa

class StatusBar: NSObject {
    static var preferenceWindowController: PreferenceWindowController?
    static let statusBar = NSStatusBar.system()
    static var item: NSStatusItem? = nil

    static func initWithPreferenceWindowController(_ preferenceWindowController: PreferenceWindowController) {
        self.preferenceWindowController = preferenceWindowController

        if Settings.get(.showMenubarIcon, withDefaultValue: true) {
            createStatusBarItem()
        }
    }

    static func createStatusBarItem() {
        if item == nil {
            item = statusBar.statusItem(withLength: -1)

            let button = item!.button!
            button.target = self
            button.action = #selector(StatusBar.action(_:))
            button.image = NSImage(named: "StatusItemIcon")
            button.appearsDisabled = false;
            button.toolTip = "Click to open preferences"
        }
    }

    static func action(_ sender: AnyObject) {
        preferenceWindowController!.showAndActivate(sender)
    }

    static func removeStatusBarItem() {
        if item != nil {
            statusBar.removeStatusItem(item!)
            item = nil
        }
    }
}

Make statusbar icon visible in dark UI

//
//  StatusBar.swift
//  kawa
//
//  Created by noraesae on 27/07/2015.
//  Copyright (c) 2015-2017 noraesae and project contributors.
//  Licensed under the MIT License.
//

import AppKit
import Cocoa

class StatusBar: NSObject {
    static var preferenceWindowController: PreferenceWindowController?
    static let statusBar = NSStatusBar.system()
    static var item: NSStatusItem? = nil

    static func initWithPreferenceWindowController(_ preferenceWindowController: PreferenceWindowController) {
        self.preferenceWindowController = preferenceWindowController

        if Settings.get(.showMenubarIcon, withDefaultValue: true) {
            createStatusBarItem()
        }
    }

    static func createStatusBarItem() {
        if item == nil {
            item = statusBar.statusItem(withLength: -1)

            let buttonImage = NSImage(named: "StatusItemIcon")
            buttonImage?.isTemplate = true

            let button = item!.button!
            button.target = self
            button.action = #selector(StatusBar.action(_:))
            button.image = buttonImage
            button.appearsDisabled = false;
            button.toolTip = "Click to open preferences"
        }
    }

    static func action(_ sender: AnyObject) {
        preferenceWindowController!.showAndActivate(sender)
    }

    static func removeStatusBarItem() {
        if item != nil {
            statusBar.removeStatusItem(item!)
            item = nil
        }
    }
}


// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SRP",
    products: [
        .library(name: "SRP", targets: ["SRP"]),
    ],
    dependencies: [
        .package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "0.8.16"),
        .package(url: "https://github.com/attaswift/BigInt.git", from: "3.0.0"),
    ],
    targets: [
        .target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
        .testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
    ],
    swiftLanguageVersions: [4]
)

Increase minimum versions of dependencies

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SRP",
    products: [
        .library(name: "SRP", targets: ["SRP"]),
    ],
    dependencies: [
        .package(url: "https://github.com/IBM-Swift/BlueCryptor.git", from: "0.8.27"),
        .package(url: "https://github.com/attaswift/BigInt.git", from: "3.0.2"),
    ],
    targets: [
        .target(name: "SRP", dependencies: ["Cryptor", "BigInt"], path: "Sources"),
        .testTarget(name: "SRPTests", dependencies: ["Cryptor", "SRP"]),
    ],
    swiftLanguageVersions: [4]
)


import PackageDescription

let package = Package(
    name: "GIO",
    dependencies: [
        .Package(url: "https://github.com/rhx/SwiftGObject.git", majorVersion: 2, minor: 46)
    ]
)

Remove minor version from generic branch

import PackageDescription

let package = Package(
    name: "GIO",
    dependencies: [
        .Package(url: "https://github.com/rhx/SwiftGObject.git", majorVersion: 2)
    ]
)


import Crypto
import Foundation

public struct Client {
    let server: String
    let key: String
    let secret: String

    public init(server: String, key: String, secret: String) {
        self.server = server
        self.key = key
        self.secret = secret
    }

    public func getURL(graph: Graph, _ URLString: String, _ format: String? = nil) -> NSURL? {
        if let components = NSURLComponents(string: server) {

            let input = NSURLQueryItem(name: "input", value: URLString)
            components.queryItems = [ input ] + graph.queryItems

            if let query = components.percentEncodedQuery {
                let derivedFormat: String?

                if let providedFormat = format {
                    derivedFormat = providedFormat
                } else if let pathExtension = NSURL(string: URLString)?.pathExtension where !pathExtension.isEmpty {
                    derivedFormat = pathExtension.lowercaseString == "jpg:large" ? "jpg" : pathExtension
                } else {
                    derivedFormat = nil
                }

                let graphNameWithFormat: String

                if let format = derivedFormat {
                    graphNameWithFormat = graph.rawValue + "." + format.lowercaseString
                } else {
                    graphNameWithFormat = graph.rawValue
                }

                let token = "\(graphNameWithFormat)?\(query)\(secret)".MD5 as String
                components.path = "/" + ([ "graph", key, token, graphNameWithFormat ]).joinWithSeparator("/")
            } else {
                return .None
            }

            return components.URL
        } else {
            return .None
        }
    }
}

Add changes to support updates to Crypto.

import Crypto
import Foundation

public struct Client {
    let server: String
    let key: String
    let secret: String

    public init(server: String, key: String, secret: String) {
        self.server = server
        self.key = key
        self.secret = secret
    }

    public func getURL(graph: Graph, _ URLString: String, _ format: String? = nil) -> NSURL? {
        if let components = NSURLComponents(string: server) {

            let input = NSURLQueryItem(name: "input", value: URLString)
            components.queryItems = [ input ] + graph.queryItems

            if let query = components.percentEncodedQuery {
                let derivedFormat: String?

                if let providedFormat = format {
                    derivedFormat = providedFormat
                } else if let pathExtension = NSURL(string: URLString)?.pathExtension where !pathExtension.isEmpty {
                    derivedFormat = pathExtension.lowercaseString == "jpg:large" ? "jpg" : pathExtension
                } else {
                    derivedFormat = nil
                }

                let graphNameWithFormat: String

                if let format = derivedFormat {
                    graphNameWithFormat = graph.rawValue + "." + format.lowercaseString
                } else {
                    graphNameWithFormat = graph.rawValue
                }

                if let token = "\(graphNameWithFormat)?\(query)\(secret)".MD5 {
                    components.path = "/" + ([ "graph", key, token, graphNameWithFormat ]).joinWithSeparator("/")
                } else {
                    return .None
                }
            } else {
                return .None
            }

            return components.URL
        } else {
            return .None
        }
    }
}


import Foundation
import PathKit

/// Protocol that defines how an entity can be writed into disk
public protocol Writable {

    /// Writes the object that conforms the protocol.
    ///
    /// - Parameter path: The path to write to
    /// - Parameter override: True if the content should be overriden if it already exists.
    /// - Throws: writing error if something goes wrong.
    func write(path: Path, override: Bool) throws

}

Add method for writing with path string

import Foundation
import PathKit

/// Protocol that defines how an entity can be writed into disk
public protocol Writable {

    /// Writes the object that conforms the protocol.
    ///
    /// - Parameter path: The path to write to
    /// - Parameter override: True if the content should be overriden if it already exists.
    /// - Throws: writing error if something goes wrong.
    func write(path: Path, override: Bool) throws

    /// Writes the object that conforms the protocol.
    ///
    /// - Parameter pathString: The path string to write to
    /// - Parameter override: True if the content should be overriden if it already exists.
    /// - Throws: writing error if something goes wrong.
    func write(pathString: String, override: Bool) throws
}

extension Writable {

    public func write(pathString: String, override: Bool) throws {
        let path = Path(pathString)
        try write(path: path, override: override)
    }
}


// The MIT License (MIT)
//
// Copyright (c) 2015 Rudolf Adamkovič
//
// 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 CoreGraphics

extension CGRect {

    var diagonal: CGFloat {
        return sqrt(pow(width, 2) + pow(height, 2))
    }

}

Add link to Wikipedia's Pythagorean theorem page

// The MIT License (MIT)
//
// Copyright (c) 2015 Rudolf Adamkovič
//
// 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 CoreGraphics

extension CGRect {

    var diagonal: CGFloat {
        // NOTE: Pythagorean theorem
        // https://en.wikipedia.org/wiki/Pythagorean_theorem
        return sqrt(pow(width, 2) + pow(height, 2))
    }

}


import Foundation

struct MVitaPtpLocalStatus
{
    static let connection:UInt32 = 0
    static let unknown:UInt32 = 1
    static let deactive:UInt32 = 2
    static let connectionEnd:UInt32 = 3
    static let connectionStart:UInt32 = 4
    static let unknownOther:UInt32 = 5
}

Use local status as enum

import Foundation

enum MVitaPtpLocalStatus:UInt32
{
    case connection = 0
    case unknown = 1
    case deactive = 2
    case connectionEnd = 3
    case connectionStart = 4
    case unknownOther = 5
}


import XCTest
import SwiftUI
@testable import ViewInspector

final class AnyViewTests: XCTestCase {

    func testEnclosedView() throws {
        let sampleView = Text("Test")
        let view = AnyView(sampleView)
        let sut = try view.inspect().text().view as? Text
        XCTAssertEqual(sut, sampleView)
    }

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

Add more tests for any view

import XCTest
import SwiftUI
@testable import ViewInspector

final class AnyViewTests: XCTestCase {

    func testEnclosedView() throws {
        let sampleView = Text("Test")
        let view = AnyView(sampleView)
        let sut = try view.inspect().text().view as? Text
        XCTAssertEqual(sut, sampleView)
    }

    func testExtractionFromSingleViewContainer() throws {
        let view = Button(action: { }, label: { AnyView(Text("")) })
        XCTAssertNoThrow(try view.inspect().anyView())
    }

    func testExtractionFromMultipleViewContainer() throws {
        let view = HStack {
            AnyView(Text(""))
            AnyView(Text(""))
        }
        XCTAssertNoThrow(try view.inspect().anyView(0))
        XCTAssertNoThrow(try view.inspect().anyView(1))
    }

    static var allTests = [
        ("testEnclosedView", testEnclosedView),
        ("testExtractionFromSingleViewContainer", testExtractionFromSingleViewContainer),
        ("testExtractionFromMultipleViewContainer", testExtractionFromMultipleViewContainer),
    ]
}


/*
 - XCConfigurationList has existing configurations
 - XCConfigurationList defaultConfigurationName exists

*/

Update validators swift file adding the validations that must be implemented.

/*
 - XCConfigurationList has existing configurations
 - XCConfigurationList defaultConfigurationName exists
 - PBXTargetDependency is proxying to a target that exists
 - PBXTargetDependency is proxying to a PBXContainerItemProxy that exists.
 - PBXContainerItemProxy is pointing to a containerPortal that exists.
 - PBXContainerItemProxy is pointing to a remoteGlobalIDString that exists.
 - PBXSourcesBuildPhase files is pointing to a file that doesn't exist.
 - PBXShellScriptBuildPhase files is pointing to a file that doesn't exist.
 - PBXGroup files pointing to files that don't exist.
 - PBXNativeTarget is referencing to an existing configuration list.
 - PBXNativeTarget is refering to existing build phases.
 - PBXNativeTarget is refering to existing dependencies
 - PBXNativeTarget is refering to a valid product reference.
 - PBXFrameworksBuildPhase is refering to existing files.
*/


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

import Foundation
import ObjectMapper

extension TextToSpeech {

    public struct Voice: Mappable {

        // URL for addressing the voice in a synthesize call
        public var url: String?

        // Gender of the voice
        public var gender: String?

        // Name of the voice
        public var name: String?

        // Language of the voice
        public var language: String?

        // Description of the voice
        public var description: String?

        public init?(_ map: Map) {}

        public mutating func mapping(map: Map) {
            url         <- map["url"]
            gender      <- map["gender"]
            name        <- map["name"]
            language    <- map["language"]
            description <- map["description"]
        }
    }
}

Update comments for TextToSpeech models

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

import Foundation
import ObjectMapper

extension TextToSpeech {

    public struct Voice: Mappable {

        /// URL for addressing the voice in a synthesize call
        public var url: String?

        /// Gender of the voice
        public var gender: String?

        /// Name of the voice
        public var name: String?

        /// Language of the voice
        public var language: String?

        /// Description of the voice
        public var description: String?

        /// Used internally to initialize a `Voice` from JSON.
        public init?(_ map: Map) {}

        /// Used internally to serialize and deserialize JSON.
        public mutating func mapping(map: Map) {
            url         <- map["url"]
            gender      <- map["gender"]
            name        <- map["name"]
            language    <- map["language"]
            description <- map["description"]
        }
    }
}


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

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

	func testNestedQuotation() {
		assert(Value.pi(.Type) { Value.pi(.Type, const($0)) }.quote, ==, Term.lambda(.type) { Term.lambda(.type, const($0)) })
	}

	func testQuotationMapsBoundVariablesToVariables() {
		assert(Value.Bound(1).quote, ==, Term(.Variable(-2)))
	}

	func testQuotationMapsNestedBoundVariablesToVariables() {
		assert(Value.Pi(Box(.Type)) { _ in Value.Pi(Box(.Type), unit) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Variable(1)))))))))
	}
}

import Assertions
import Box
import Manifold
import Prelude
import XCTest

Make the bound variable explicit.

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

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

	func testNestedQuotation() {
		assert(Value.pi(.Type) { Value.pi(.Type, const($0)) }.quote, ==, Term.lambda(.type) { x in Term.lambda(.type, const(x)) })
	}

	func testQuotationMapsBoundVariablesToVariables() {
		assert(Value.Bound(1).quote, ==, Term(.Variable(-2)))
	}

	func testQuotationMapsNestedBoundVariablesToVariables() {
		assert(Value.Pi(Box(.Type)) { _ in Value.Pi(Box(.Type), unit) }.quote, ==, Term(.Pi(0, Box(.type), Box(Term(.Pi(1, Box(.type), Box(Term(.Variable(1)))))))))
	}
}

import Assertions
import Box
import Manifold
import Prelude
import XCTest


/*
 |  _   ____   ____   _
 | ⎛ |‾|  ⚈ |-| ⚈  |‾| ⎞
 | ⎝ |  ‾‾‾‾| |‾‾‾‾  | ⎠
 |  ‾        ‾        ‾
 */

import UIKit

public class RotatingViewController: UIViewController {

    override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .All
    }

}

public class RotatingNavController: UINavigationController {

    override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .All
    }

}

Add support for adjusting status bar

/*
 |  _   ____   ____   _
 | ⎛ |‾|  ⚈ |-| ⚈  |‾| ⎞
 | ⎝ |  ‾‾‾‾| |‾‾‾‾  | ⎠
 |  ‾        ‾        ‾
 */

import UIKit

public class RotatingViewController: UIViewController {

    override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .All
    }

    @IBInspectable public var lightStatusBar: Bool = false {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    public override func preferredStatusBarStyle() -> UIStatusBarStyle {
        if lightStatusBar {
            return .LightContent
        }
        return .Default
    }

}

public class RotatingNavController: UINavigationController {

    override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .All
    }

    @IBInspectable public var lightStatusBar: Bool = false {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    public override func preferredStatusBarStyle() -> UIStatusBarStyle {
        if lightStatusBar {
            return .LightContent
        }
        return .Default
    }

}


// RUN: %target-typecheck-verify-swift -warn-long-expression-type-checking=1 -warn-long-function-bodies=1 %s

@_silgen_name("generic_foo")
func foo<T>(_ x: T) -> T

@_silgen_name("foo_of_int")
func foo(_ x: Int) -> Int

func test(m: Double) -> Int {
  // expected-warning@-1 {{global function 'test(m:)' took}}
  return Int(foo(Float(m) / 20) * 20 - 2) + 10
  // expected-warning@-1 {{expression took}}
}

Remove explicit filename argument in RUN line.

// RUN: %target-typecheck-verify-swift -warn-long-expression-type-checking=1 -warn-long-function-bodies=1

@_silgen_name("generic_foo")
func foo<T>(_ x: T) -> T

@_silgen_name("foo_of_int")
func foo(_ x: Int) -> Int

func test(m: Double) -> Int {
  // expected-warning@-1 {{global function 'test(m:)' took}}
  return Int(foo(Float(m) / 20) * 20 - 2) + 10
  // expected-warning@-1 {{expression took}}
}


import Vapor

class SampleMiddleware: Middleware {

	class func handle(handler: Request.Handler) -> Request.Handler {
		return { request in
			// You can manipulate the request before calling the handler
			// and abort early if necessary, a good injection point for
			// handling auth.

			// return Response(status: .Forbidden, text: "Permission denied")

			let response = try handler(request: request)

			// You can also manipulate the response to add headers
			// cookies, etc.

			return response
		}
	}

}

Update middleware to match new Vapor code

import Vapor

class SampleMiddleware: Middleware {

	class func handle(handler: Request.Handler, for application: Application) -> Request.Handler {
		return { request in
			// You can manipulate the request before calling the handler
			// and abort early if necessary, a good injection point for
			// handling auth.

			// return Response(status: .Forbidden, text: "Permission denied")

			let response = try handler(request: request)

			// You can also manipulate the response to add headers
			// cookies, etc.

			return response
		}
	}

}


import io;

(string output)
echo_filename(file input) "funcs" "0.0"
[ "set <<output>> <<input>>" ];

// SKIP-THIS-TEST: Issue #453
// Issue is filename substitution into Tcl
// This works:  [ lindex <<input>> 0 ]

main {
  file f = input_file("alice.txt");
  string s = echo_filename(f);
  printf("filename: %s", s);
}

Update test to be correct

import assert;
import io;

// Check that we can extract filename from file

(string output)
echo_filename(file input) "funcs" "0.0"
[ "set <<output>> [ turbine::local_file_path <<input>> ]" ];

main {
  file f = input_file("alice.txt");
  string s = echo_filename(f);
  printf("filename: %s", s);
  assertEqual(s, "alice.txt", "Filename correct");
}


extension String {
    /**
         Hydrates from environment if has leading `$`. If contains `:`, represents fallback.

            $PORT:8080

         Checks first if `PORT` env variable is set, then loads `8080`

         If no fallback, and no env value, returns nil
    */
    internal func hydratedEnv() -> String? {
        guard hasPrefix("$") else { return self }
        let components = self.makeBytes()
            .dropFirst()
            .split(separator: .colon, maxSplits: 1, omittingEmptySubsequences: true)
            .map({ $0.makeString() })

        return components.first.flatMap(Env.get)
            ?? components[safe: 1]
    }
}

Allow empty strings as fallback in configuration

extension String {
    /**
         Hydrates from environment if has leading `$`. If contains `:`, represents fallback.

            $PORT:8080

         Checks first if `PORT` env variable is set, then loads `8080`

         If no fallback, and no env value, returns nil
    */
    internal func hydratedEnv() -> String? {
        guard hasPrefix("$") else { return self }
        let components = self.makeBytes()
            .dropFirst()
            .split(separator: .colon, maxSplits: 1, omittingEmptySubsequences: false)
            .map({ $0.makeString() })

        return components.first.flatMap(Env.get)
            ?? components[safe: 1]
    }
}


// RUN: %incr-transfer-tree --expected-incremental-syntax-tree %S/Outputs/extend-identifier-at-eof.json %s

func foo() {}
_ = x<<<|||x>>>

Add warning not to add anything to the identifier-at-eof test

// RUN: %incr-transfer-tree --expected-incremental-syntax-tree %S/Outputs/extend-identifier-at-eof.json %s

func foo() {}
// ATTENTION: This file is testing the EOF token.
// DO NOT PUT ANYTHING AFTER THE CHANGE, NOT EVEN A NEWLINE
_ = x<<<|||x>>>


//
//  ResponseError.swift
//  SwiftSourceKit
//

import sourcekitd

public final class ResponseError: ErrorType {
    private let response: sourcekitd_response_t

    init(response: sourcekitd_response_t) {
        self.response = response
    }

    deinit {
        sourcekitd_response_dispose(response)
    }

    public var description: String {
        guard let str = String.fromCString(sourcekitd_response_error_get_description(response)) else {
            return ""
        }
        return str
    }

    public enum ErrorKind {
        case ConnectionInterrupted
        case RequestInvalid
        case RequestFailed
        case RequestCancelled
        case UnknownError
    }

    public var errorKind: ErrorKind {
        let kind = sourcekitd_response_error_get_kind(response)
        if kind == SOURCEKITD_ERROR_CONNECTION_INTERRUPTED { return .ConnectionInterrupted }
        else if kind == SOURCEKITD_ERROR_REQUEST_INVALID { return .RequestInvalid }
        else if kind == SOURCEKITD_ERROR_REQUEST_FAILED { return .RequestFailed }
        else if kind == SOURCEKITD_ERROR_REQUEST_CANCELLED { return .RequestCancelled }
        return .UnknownError
    }
}

Use switch to convert response error type

//
//  ResponseError.swift
//  SwiftSourceKit
//

import sourcekitd

public final class ResponseError: ErrorType {
    private let response: sourcekitd_response_t

    init(response: sourcekitd_response_t) {
        self.response = response
    }

    deinit {
        sourcekitd_response_dispose(response)
    }

    public var description: String {
        guard let str = String.fromCString(sourcekitd_response_error_get_description(response)) else {
            return ""
        }
        return str
    }

    public enum ErrorKind {
        case ConnectionInterrupted
        case RequestInvalid
        case RequestFailed
        case RequestCancelled
        case UnknownError
    }

    public var errorKind: ErrorKind {
        let kind = sourcekitd_response_error_get_kind(response)
        switch kind {
        case SOURCEKITD_ERROR_CONNECTION_INTERRUPTED: return .ConnectionInterrupted
        case SOURCEKITD_ERROR_REQUEST_INVALID: return .RequestInvalid
        case SOURCEKITD_ERROR_REQUEST_FAILED: return .RequestFailed
        case SOURCEKITD_ERROR_REQUEST_CANCELLED: return .RequestCancelled
        default:
            return .UnknownError
        }
    }
}


//
//  LectureHeaderView.swift
//  HTWDD
//
//  Created by Benjamin Herzog on 09/03/2017.
//  Copyright © 2017 HTW Dresden. All rights reserved.
//

import UIKit

class LectureHeaderView: CollectionReusableView, Identifiable {

	private let label = UILabel()

    var title: String? {
        get {
            return self.label.text
        }
        set {
            self.label.text = newValue?.uppercased()
        }
    }

	// MARK: - Init

    override func initialSetup() {
        self.backgroundColor = UIColor.htw.veryLightGrey

		self.label.frame = self.bounds
        self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
		self.label.font = .systemFont(ofSize: 16, weight: .semibold)
		self.label.textColor = UIColor.htw.mediumGrey
		self.label.textAlignment = .center
        self.addSubview(self.label)
    }

}

Clear bg on Schedule List header view

//
//  LectureHeaderView.swift
//  HTWDD
//
//  Created by Benjamin Herzog on 09/03/2017.
//  Copyright © 2017 HTW Dresden. All rights reserved.
//

import UIKit

class LectureHeaderView: CollectionReusableView, Identifiable {

	private let label = UILabel()

    var title: String? {
        get {
            return self.label.text
        }
        set {
            self.label.text = newValue?.uppercased()
        }
    }

	// MARK: - Init

    override func initialSetup() {
        self.backgroundColor = .clear

		self.label.frame = self.bounds
        self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
		self.label.font = .systemFont(ofSize: 16, weight: .semibold)
		self.label.textColor = UIColor.htw.mediumGrey
		self.label.textAlignment = .center
        self.addSubview(self.label)
    }

}


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

public enum Value: Printable {
	case Constant(Any)
	case Function(Any -> Any)

	public func destructure<T, U, V, W>(constant: T -> W, _ function: (U -> V) -> W) -> W {
		switch self {
		case let Constant(v):
			return constant(v as T)
		case let Function(f):
			return function(f as U -> Any as U -> V)
		}
	}

	// MARK: Printable

	public var description: String {
		switch self {
		case let Constant(c):
			return ".Constant(\(toString(c))"
		case let Function(f):
			return ".Function(f)"
		}
	}
}

Work around a runtime crash.

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

public enum Value: Printable {
	case Constant(Any)
	case Function(Any -> Any)

	public func destructure<T, U, V, W>(constant: T -> W, _ function: (U -> V) -> W) -> W? {
		switch self {
		case let Constant(v as T):
			return constant(v as T)
		case let Function(f):
			return function(f as U -> Any as U -> V)
		default:
			return nil
		}
	}

	// MARK: Printable

	public var description: String {
		switch self {
		case let Constant(c):
			return ".Constant(\(toString(c))"
		case let Function(f):
			return ".Function(f)"
		}
	}
}


//
//  BirthdayViewModelSpec.swift
//  AgeTests
//
//  Created by Julian Grosshauser on 09/04/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
import Age

class BirthdayViewModelSpec: QuickSpec {

    override func spec() {
        describe("BirthdayViewModel") {
            var birthdayViewModel: BirthdayViewModel!

            beforeEach {
                birthdayViewModel = BirthdayViewModel()
            }
        }
    }
}

Add examples for incrementDay and decrementDay

//
//  BirthdayViewModelSpec.swift
//  AgeTests
//
//  Created by Julian Grosshauser on 09/04/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import Quick
import Nimble
import Age

class BirthdayViewModelSpec: QuickSpec {

    override func spec() {
        describe("BirthdayViewModel") {
            describe("incrementDay") {
                context("day value is at bottom limit") {
                    it("increments day value") {
                        let birthdayViewModel = BirthdayViewModel(day: 1, month: 1, year: 2015)
                        birthdayViewModel.incrementDay()
                        expect(birthdayViewModel.day).to(equal(2))
                    }
                }

                context("day value is at upper limit") {
                    it("sets day value to bottom limit") {
                        let birthdayViewModel = BirthdayViewModel(day: 31, month: 1, year: 2015)
                        birthdayViewModel.incrementDay()
                        expect(birthdayViewModel.day).to(equal(1))
                    }
                }
            }

            describe("decrementDay") {
                context("day value is at bottom limit") {
                    it("sets day value to upper limit") {
                        let birthdayViewModel = BirthdayViewModel(day: 1, month: 1, year: 2015)
                        birthdayViewModel.decrementDay()
                        expect(birthdayViewModel.day).to(equal(31))
                    }
                }

                context("day value is at upper limit") {
                    it("decrements day value") {
                        let birthdayViewModel = BirthdayViewModel(day: 31, month: 1, year: 2015)
                        birthdayViewModel.decrementDay()
                        expect(birthdayViewModel.day).to(equal(30))
                    }
                }
            }
        }
    }
}


extension Request {
    /**
        Multipart encoded request data sent using
        the `multipart/form-data...` header.

        Used by web browsers to send files.
    */
    public var multipart: [String: Multipart]? {
        if let existing = storage["multipart"] as? [String: Multipart]? {
            return existing
        } else if let type = headers["Content-Type"] where type.contains("multipart/form-data") {
            guard case let .data(body) = body else { return nil }
            guard let boundary = try? Multipart.parseBoundary(contentType: type) else { return nil }
            let multipart = Multipart.parse(Data(body), boundary: boundary)
            storage["multipart"] = multipart
            return multipart
        } else {
            return nil
        }
    }
}

Fix request's multipart data getter

extension Request {
    /**
        Multipart encoded request data sent using
        the `multipart/form-data...` header.

        Used by web browsers to send files.
    */
    public var multipart: [String: Multipart]? {
        if let existing = storage["multipart"] as? [String: Multipart] {
            return existing
        } else if let type = headers["Content-Type"] where type.contains("multipart/form-data") {
            guard case let .data(body) = body else { return nil }
            guard let boundary = try? Multipart.parseBoundary(contentType: type) else { return nil }
            let multipart = Multipart.parse(Data(body), boundary: boundary)
            storage["multipart"] = multipart
            return multipart
        } else {
            return nil
        }
    }
}


import Foundation

/// The protocol used to define the specifications necessary for a `MoyaProvider`.
public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// The type of validation to perform on the request. Default is `.none`.
    var validationType: ValidationType { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {

    /// The type of validation to perform on the request. Default is `.none`.
    var validationType: ValidationType {
        return .none
    }
}

Make `sampleData` an optional property.

import Foundation

/// The protocol used to define the specifications necessary for a `MoyaProvider`.
public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing. Default is `Data()`.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// The type of validation to perform on the request. Default is `.none`.
    var validationType: ValidationType { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {

    /// The type of validation to perform on the request. Default is `.none`.
    var validationType: ValidationType { .none }

    /// Provides stub data for use in testing. Default is `Data()`.
    var sampleData: Data { Data() }
}


//  Created by Christos Koninis on 25/09/2019.

import Foundation
import SwiftCLI

// Task extentions to querry the limitations of the Task's argument list
extension Task {
    // Method to determent if the argument list is to long to pass to new process
    static func isArgumentListTooLong(_ argumentList: [String]) -> Bool {
        // Get maximum length of arguments for a new process (in Bytes) and the maximum count for the list for arguments. See
        // https://www.in-ulm.de/~mascheck/various/argmax/ for more info.
        guard
            let maxArgumentLength = resultForGetconfCommand("expr `getconf ARG_MAX` - `env|wc -c` - `env|wc -l` \\* 4 - 2048"),
            let maxArgumentCount = resultForGetconfCommand("expr `getconf _POSIX_ARG_MAX`")
            else {
            return false
        }

        let argumentListLength = argumentList.joined(separator: " ").utf8.count
        let isArgumentListLengthTooLong = maxArgumentLength < argumentListLength
        let isArgumentListCountTooLong = maxArgumentCount < argumentList.count + ProcessInfo.processInfo.environment.keys.count

        return isArgumentListLengthTooLong || isArgumentListCountTooLong
    }

    private static func resultForGetconfCommand(_ getconfCommand: String) -> Int? {
        guard let commandResult = try? Task.capture(bash: getconfCommand) else { return nil }

        return Int(commandResult.stdout)
    }
}

Update conditional logic for writing files to file argument plist

//  Created by Christos Koninis on 25/09/2019.

import Foundation
import SwiftCLI

// Task extentions to querry the limitations of the Task's argument list
extension Task {
    // Method to determent if the argument list is to long to pass to new process
    static func isArgumentListTooLong(_ argumentList: [String]) -> Bool {
        // Get maximum length of arguments for a new process (in Bytes) and the maximum count for the list for arguments. See
        // https://www.in-ulm.de/~mascheck/various/argmax/ for more info.
        guard
            let maxArgumentLength = resultForGetconfCommand("expr `getconf ARG_MAX` \\/ 2 - `env|wc -c` - `env|wc -l` \\* 4 - 2048"),
            let maxArgumentCount = resultForGetconfCommand("expr `getconf _POSIX_ARG_MAX`"),
            let argumentListData = argumentList.joined(separator: " ").data(using: .utf8)
            else {
            return true
        }

        let argumentListLength = argumentListData.count
        let isArgumentListLengthTooLong = maxArgumentLength < argumentListLength
        let isArgumentListCountTooLong = maxArgumentCount < argumentList.count

        return isArgumentListLengthTooLong || isArgumentListCountTooLong
    }

    private static func resultForGetconfCommand(_ getconfCommand: String) -> Int? {
        guard let commandResult = try? Task.capture(bash: getconfCommand) else { return nil }

        return Int(commandResult.stdout)
    }
}


//
//  This source file is part of the carousell/pickle open source project
//
//  Copyright © 2017 Carousell and the project authors
//  Licensed under Apache License v2.0
//
//  See https://github.com/carousell/pickle/blob/master/LICENSE for license information
//  See https://github.com/carousell/pickle/graphs/contributors for the list of project authors
//

import XCTest

class UITests: XCTestCase {

    private lazy var app: XCUIApplication = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app.launch()
    }

    func testLaunch() {
        app.tables.cells.staticTexts["Default appearance"].tap()

        addUIInterruptionMonitor(withDescription: "Pickle Example") { alert -> Bool in
            let button = alert.buttons["OK"]
            if button.exists {
                button.tap()
                return true
            }
            return false
        }

        // need to interact with the app for the handler to fire
        app.tap()
        app.navigationBars["Camera Roll"].buttons["Cancel"].tap()
    }

}

Test the default button states

//
//  This source file is part of the carousell/pickle open source project
//
//  Copyright © 2017 Carousell and the project authors
//  Licensed under Apache License v2.0
//
//  See https://github.com/carousell/pickle/blob/master/LICENSE for license information
//  See https://github.com/carousell/pickle/graphs/contributors for the list of project authors
//

import XCTest

class UITests: XCTestCase {

    private lazy var app: XCUIApplication = XCUIApplication()

    private var cancelButton: XCUIElement {
        return app.navigationBars["Camera Roll"].buttons["Cancel"]
    }

    private var doneButton: XCUIElement {
        return app.navigationBars["Camera Roll"].buttons["Done"]
    }

    // MARK: -

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app.launch()
    }

    private func showImagePicker(named name: String) {
        app.tables.cells.staticTexts[name].tap()

        addUIInterruptionMonitor(withDescription: "Pickle Example") { alert -> Bool in
            let button = alert.buttons["OK"]
            if button.exists {
                button.tap()
                return true
            }
            return false
        }

        // need to interact with the app for the handler to fire
        app.tap()
    }

    func testDefaultStates() {
        showImagePicker(named: "Default appearance")
        XCTAssertTrue(cancelButton.isEnabled)
        XCTAssertFalse(doneButton.isEnabled)
        cancelButton.tap()
    }

}


//
//  BaseUrlDebugSwitcher.swift
//  grooop
//
//  Created by David Sweetman on 10/27/16.
//  Copyright © 2016 smashing boxes. All rights reserved.
//

import UIKit

class BaseUrlDebugSwitcher: UIViewController
{
    @IBOutlet weak var protocolField: UITextField!
    @IBOutlet weak var domainField: UITextField!

    weak var baseUrl: BaseUrl?

    init(baseUrl: BaseUrl) {
        self.baseUrl = baseUrl
        super.init(nibName: "BaseUrlDebutSwitcher", bundle: nil)
    }

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

    @IBAction func usePreviousButtonPressed(sender: AnyObject?) {
        #if DEBUG || STAGING
            let previous = baseUrl?.retreivePrevious()
            baseUrl?.setDebug(domain: previous?.domain, urlProtocol: previous?.urlProtocol)
        #endif
    }

    @IBAction func doneButtonPressed(sender: AnyObject?) {
        #if DEBUG || STAGING
            dismiss(animated: true, completion: nil)
            baseUrl?.setDebug(domain: domainField.text, urlProtocol: protocolField.text)
        #endif
    }
}

Fix nib name spelling error

//
//  BaseUrlDebugSwitcher.swift
//  grooop
//
//  Created by David Sweetman on 10/27/16.
//  Copyright © 2016 smashing boxes. All rights reserved.
//

import UIKit

class BaseUrlDebugSwitcher: UIViewController
{
    @IBOutlet weak var protocolField: UITextField!
    @IBOutlet weak var domainField: UITextField!

    weak var baseUrl: BaseUrl?

    init(baseUrl: BaseUrl) {
        self.baseUrl = baseUrl
        super.init(nibName: "BaseUrlDebugSwitcher", bundle: nil)
    }

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

    @IBAction func usePreviousButtonPressed(sender: AnyObject?) {
        #if DEBUG || STAGING
            let previous = baseUrl?.retreivePrevious()
            baseUrl?.setDebug(domain: previous?.domain, urlProtocol: previous?.urlProtocol)
        #endif
    }

    @IBAction func doneButtonPressed(sender: AnyObject?) {
        #if DEBUG || STAGING
            dismiss(animated: true, completion: nil)
            baseUrl?.setDebug(domain: domainField.text, urlProtocol: protocolField.text)
        #endif
    }
}


import Foundation

class MFirebaseDUserItem:MFirebaseDProtocol
{
    let identifier:String?

    required init?(snapshot:Any?, identifier:String?)
    {
        self.identifier = identifier
    }
}

Add parent to user item

import Foundation

class MFirebaseDUserItem:MFirebaseDProtocol
{
    let identifier:String?

    var parent:MFirebaseDProtocol?
    {
        get
        {
            let userList:MFirebaseDUser? = MFirebaseDUser(
                snapshot:nil,
                identifier:nil)

            return userList
        }
    }

    required init?(snapshot:Any?, identifier:String?)
    {
        self.identifier = identifier
    }
}


//
//  DataError.swift
//  CoordinatorExample
//
//  Created by Aleksandar Vacić on 18.5.17..
//  Copyright © 2017. Radiant Tap. All rights reserved.
//

import Foundation
import Marshal

enum DataError: Error {
	case internalError
	case insufficientInput
	case missingData

	case ivkoServiceError(IvkoServiceError)
	case marshalError(MarshalError)
	case unknownColorCode(Int)
}

extension DataError: CustomStringConvertible {
	var description: String {
		switch self {
		case .internalError:
			return "Internal Error"
		case .insufficientInput:
			return "Insufficient input parameters"
		case .missingData:
			return "No data available at the moment"
		case .unknownColorCode(let code):
			return "Unhandled product color code: \( code )"
		case .ivkoServiceError, .marshalError:
			return "Internal error"
		}
	}
}

Mark this part as needed to fix with better error message

//
//  DataError.swift
//  CoordinatorExample
//
//  Created by Aleksandar Vacić on 18.5.17..
//  Copyright © 2017. Radiant Tap. All rights reserved.
//

import Foundation
import Marshal

enum DataError: Error {
	case internalError
	case insufficientInput
	case missingData

	case ivkoServiceError(IvkoServiceError)
	case marshalError(MarshalError)
	case unknownColorCode(Int)
}

extension DataError: CustomStringConvertible {
	var description: String {
		switch self {
		case .internalError:
			return "Internal Error"
		case .insufficientInput:
			return "Insufficient input parameters"
		case .missingData:
			return "No data available at the moment"
		case .unknownColorCode(let code):
			return "Unhandled product color code: \( code )"
		case .ivkoServiceError, .marshalError:	//TODO: improve this
			return "Internal error"
		}
	}
}


//
//  DrawingViewController.swift
//  Padiddle
//
//  Created by Zev Eisenberg on 9/12/15.
//  Copyright © 2015 Zev Eisenberg. All rights reserved.
//

import UIKit

class DrawingViewController: UIViewController {

    private let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .whiteColor()

        let width = CGRectGetWidth(UIScreen.mainScreen().bounds)
        let height = CGRectGetHeight(UIScreen.mainScreen().bounds)

        let longSide = max(width, height)

        view.widthAnchor.constraintEqualToConstant(longSide).active = true
        view.heightAnchor.constraintEqualToConstant(longSide).active = true

        label.text = "Drawing view will go here eventually"
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)

        label.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
        label.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
    }
}

Hide drawing view controller debug label unless a flag is set.

//
//  DrawingViewController.swift
//  Padiddle
//
//  Created by Zev Eisenberg on 9/12/15.
//  Copyright © 2015 Zev Eisenberg. All rights reserved.
//

import UIKit

let showDebugLabel = false

class DrawingViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .whiteColor()

        let width = CGRectGetWidth(UIScreen.mainScreen().bounds)
        let height = CGRectGetHeight(UIScreen.mainScreen().bounds)

        let longSide = max(width, height)

        view.widthAnchor.constraintEqualToConstant(longSide).active = true
        view.heightAnchor.constraintEqualToConstant(longSide).active = true

        if showDebugLabel {
            let label = UILabel()
            label.text = "Drawing view debug label"
            label.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(label)

            label.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
            label.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
        }
    }
}


//
//  SpelledPitch.swift
//  PitchSpellingTools
//
//  Created by James Bean on 5/1/16.
//
//

import Foundation
import Pitch

/**
 Structure that extends a `Pitch` with a `PitchSpelling`.
 */
public class SpelledPitch: Pitch {

    public let spelling: PitchSpelling

    public init(pitch: Pitch, spelling: PitchSpelling) {
        self.spelling = spelling
        super.init(pitch: pitch)
    }
}

/*
extension SpelledPitch: Equatable { }

public func == (lhs: SpelledPitch, rhs: SpelledPitch) -> Bool {
    return lhs.pitch == rhs.pitch
}

extension SpelledPitch: Comparable { }

public func < (lhs: SpelledPitch, rhs: SpelledPitch) -> Bool {
    return lhs.pitch < rhs.pitch
}
*/

Remove dead code, make spelling private

//
//  SpelledPitch.swift
//  PitchSpellingTools
//
//  Created by James Bean on 5/1/16.
//
//

import Foundation
import Pitch

/**
 Structure that extends a `Pitch` with a `PitchSpelling`.
 */
public class SpelledPitch: Pitch {

    private let spelling: PitchSpelling

    /**
     Create a `SpelledPitch` with a given `pitch` and `spelling`.
     */
    public init(pitch: Pitch, spelling: PitchSpelling) {
        self.spelling = spelling
        super.init(pitch: pitch)
    }
}


//
//  TouchableRenderer.swift
//  PortalView
//
//  Created by Guido Marucci Blas on 4/3/17.
//  Copyright © 2017 Guido Marucci Blas. All rights reserved.
//

import UIKit

internal struct TouchableRenderer<MessageType>: UIKitRenderer {

    let child: Component<MessageType>
    let gesture: Gesture<MessageType>

    func render(with layoutEngine: LayoutEngine, isDebugModeEnabled: Bool) -> Render<MessageType> {
        var result = child.render(with: layoutEngine, isDebugModeEnabled: isDebugModeEnabled)
        switch gesture {

        case .tap(let message):
            let dispatcher: MessageDispatcher<MessageType>
            if let mailbox = result.mailbox {
                dispatcher = MessageDispatcher(message: message, mailbox: mailbox)
            } else {
                dispatcher = MessageDispatcher(message: message)
                result = Render(view: result.view, mailbox: dispatcher.mailbox, executeAfterLayout: result.afterLayout)
            }
            result.view.register(dispatcher: dispatcher)
            let recognizer = UITapGestureRecognizer(target: dispatcher, action: #selector(MessageDispatcher<MessageType>.dispatch))
            result.view.addGestureRecognizer(recognizer)

        }
        return result
    }

}

Fix bug for touchable when using non interactives view

//
//  TouchableRenderer.swift
//  PortalView
//
//  Created by Guido Marucci Blas on 4/3/17.
//  Copyright © 2017 Guido Marucci Blas. All rights reserved.
//

import UIKit

internal struct TouchableRenderer<MessageType>: UIKitRenderer {

    let child: Component<MessageType>
    let gesture: Gesture<MessageType>

    func render(with layoutEngine: LayoutEngine, isDebugModeEnabled: Bool) -> Render<MessageType> {
        var result = child.render(with: layoutEngine, isDebugModeEnabled: isDebugModeEnabled)

        result.view.isUserInteractionEnabled = true

        switch gesture {

        case .tap(let message):
            let dispatcher: MessageDispatcher<MessageType>
            if let mailbox = result.mailbox {
                dispatcher = MessageDispatcher(message: message, mailbox: mailbox)
            } else {
                dispatcher = MessageDispatcher(message: message)
                result = Render(view: result.view, mailbox: dispatcher.mailbox, executeAfterLayout: result.afterLayout)
            }
            result.view.register(dispatcher: dispatcher)
            let recognizer = UITapGestureRecognizer(target: dispatcher, action: #selector(MessageDispatcher<MessageType>.dispatch))
            result.view.addGestureRecognizer(recognizer)

        }
        return result
    }

}


//
//  FirstViewController.swift
//  WhatTheColor
//
//  Created by Johan Sørensen on 24/02/16.
//  Copyright © 2016 Johan Sørensen. All rights reserved.
//

import UIKit
import WaddaColor

class FirstViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    let colors: [(name: String, rgba: RGBA)] = ColorThesaurusNames().map({ (name: $0, rgba: $1) })

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorStyle = .None
    }
}

extension FirstViewController: UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return colors.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("ColorCell", forIndexPath: indexPath)
        let color = colors[indexPath.row]
        cell.textLabel?.text = color.name
        cell.textLabel?.backgroundColor = color.rgba.color
        cell.contentView.backgroundColor = color.rgba.color
        return cell
    }
}

Change textcolor depending on color lightness in the example app

//
//  FirstViewController.swift
//  WhatTheColor
//
//  Created by Johan Sørensen on 24/02/16.
//  Copyright © 2016 Johan Sørensen. All rights reserved.
//

import UIKit
import WaddaColor

class FirstViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    let colors: [(name: String, rgba: RGBA)] = ColorThesaurusNames().map({ (name: $0, rgba: $1) })

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorStyle = .None
    }
}

extension FirstViewController: UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return colors.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("ColorCell", forIndexPath: indexPath)
        let color = colors[indexPath.row]
        cell.textLabel?.text = color.name
        let hsl = HSL(rgb: color.rgba)
        if hsl.isLight() {
            cell.textLabel?.textColor = UIColor.blackColor()
        } else {
            cell.textLabel?.textColor = UIColor.whiteColor()
        }
        cell.textLabel?.backgroundColor = color.rgba.color
        cell.contentView.backgroundColor = color.rgba.color
        return cell
    }
}


import Nimble
import RxSwift
import RxTest

/// A Nimble matcher that succeeds when the actual events emit an error
/// of any type.
public func throwError<T: Equatable>() -> Predicate<RecordedEvents<T>> {
    func extractError(_ recorded: RecordedEvents<T>?) -> [Error]? {
        func extractError<E>(_ recorded: Recorded<Event<E>>) -> Error? {
            return recorded.value.error
        }

        #if swift(>=4.1)
        return recorded?.compactMap(extractError)
        #else
        return recorded?.flatMap(extractError)
        #endif
    }

    return Predicate { actualEvents in
        var actualError: Error?
        do {
            let recordedEvents = try actualEvents.evaluate()
            if let error = extractError(recordedEvents)?.first {
                throw error
            }
        } catch {
            actualError = error
        }

        if let actualError = actualError {
            return PredicateResult(bool: true, message: .expectedCustomValueTo("throw any error", "<\(actualError)>"))
        } else {
            return PredicateResult(bool: false, message: .expectedCustomValueTo("throw any error", "no error"))
        }
    }
}

Fix breaking changes introduced in Nimble 9

import Nimble
import RxSwift
import RxTest

/// A Nimble matcher that succeeds when the actual events emit an error
/// of any type.
public func throwError<T: Equatable>() -> Predicate<RecordedEvents<T>> {
    func extractError(_ recorded: RecordedEvents<T>?) -> [Error]? {
        func extractError<E>(_ recorded: Recorded<Event<E>>) -> Error? {
            return recorded.value.error
        }

        #if swift(>=4.1)
        return recorded?.compactMap(extractError)
        #else
        return recorded?.flatMap(extractError)
        #endif
    }

    return Predicate { actualEvents in
        var actualError: Error?
        do {
            let recordedEvents = try actualEvents.evaluate()
            if let error = extractError(recordedEvents)?.first {
                throw error
            }
        } catch {
            actualError = error
        }

        if let actualError = actualError {
            return PredicateResult(bool: true, message: .expectedCustomValueTo("throw any error", actual: "<\(actualError)>"))
        } else {
            return PredicateResult(bool: false, message: .expectedCustomValueTo("throw any error", actual: "no error"))
        }
    }
}


//
//  Globals.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 07.06.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

/// Runs code with delay given in seconds. Uses the main thread if not otherwise specified.
///
/// - Parameters:
///   - delayTime: The duration of the delay. E.g. `.seconds(1)` or `.milliseconds(200)`.
///   - qosClass: The global QOS class to be used or `nil` to use the main thread. Defaults to `nil`.
///   - closure: The code to run with a delay.
public func delay(by delayTime: Timespan, qosClass: DispatchQoS.QoSClass? = nil, closure: @escaping () -> Void) {
    let dispatchQueue = qosClass != nil ? DispatchQueue.global(qos: qosClass!) : DispatchQueue.main
    dispatchQueue.asyncAfter(deadline: DispatchTime.now() + delayTime, execute: closure)
}

Make closure in delay method unnamed (for cleaner autocompletion)

//
//  Globals.swift
//  HandySwift
//
//  Created by Cihat Gündüz on 07.06.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

/// Runs code with delay given in seconds. Uses the main thread if not otherwise specified.
///
/// - Parameters:
///   - delayTime: The duration of the delay. E.g. `.seconds(1)` or `.milliseconds(200)`.
///   - qosClass: The global QOS class to be used or `nil` to use the main thread. Defaults to `nil`.
///   - closure: The code to run with a delay.
public func delay(by delayTime: Timespan, qosClass: DispatchQoS.QoSClass? = nil, _ closure: @escaping () -> Void) {
    let dispatchQueue = qosClass != nil ? DispatchQueue.global(qos: qosClass!) : DispatchQueue.main
    dispatchQueue.asyncAfter(deadline: DispatchTime.now() + delayTime, execute: closure)
}


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

import ReactiveCocoa
import Shirley

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

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

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

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

struct TestError: ErrorType
{
    let value: Int
}

Add "import Result" to tests using NoError.

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

import ReactiveCocoa
import Result
import Shirley

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

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

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

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

struct TestError: ErrorType
{
    let value: Int
}


//
//  PtModeFilter.swift
//  Pods
//
//  Created by Kilian Költzsch on 17/11/2016.
//
//

import Foundation

public extension ModesSupport {
    /// Struktur zum Filtern nach Verkehrsmitteltypen.
    public struct PtModeFilter {
        /// Indikator, ob die in der Liste angegebenen Verkehrsmittel ausgeschlossen (Wert true) oder als einzige verwendet werden sollen (Wert false). Vor- einstellung ist true.
        public let exclude: Bool

        /// ÖV-Verkehrsmitteltypen.
        public let ptMode: [PtMode]

        init(exclude: Bool = true, ptMode: [PtMode]) {
            self.exclude = exclude
            self.ptMode = ptMode
        }
    }
}

Add FIXME for missing property (or whatever)

//
//  PtModeFilter.swift
//  Pods
//
//  Created by Kilian Költzsch on 17/11/2016.
//
//

import Foundation

public extension ModesSupport {
    /// Struktur zum Filtern nach Verkehrsmitteltypen.
    public struct PtModeFilter {
        /// Indikator, ob die in der Liste angegebenen Verkehrsmittel ausgeschlossen (Wert true) oder als einzige verwendet werden sollen (Wert false). Vor- einstellung ist true.
        public let exclude: Bool

        /// ÖV-Verkehrsmitteltypen.
        public let ptMode: [PtMode]

        // FIXME: Insert PtSubmodeChoice as ÖV-Untertypen.

        init(exclude: Bool = true, ptMode: [PtMode]) {
            self.exclude = exclude
            self.ptMode = ptMode
        }
    }
}


import TSCBasic

extension Driver {
  mutating func mergeModuleJob(inputs: [InputFile]) throws -> Job {
    var commandLine: [Job.ArgTemplate] = []

    fatalError()
  }
}

Add stub job for merge module

import TSCBasic

extension Driver {
  mutating func mergeModuleJob(inputs: [InputFile]) throws -> Job {
    var commandLine: [Job.ArgTemplate] = []
    commandLine.appendFlag("-version")

    return Job(
      tool: .absolute(try toolchain.getToolPath(.swiftCompiler)),
      commandLine: commandLine,
      inputs: inputs.map{ $0.file },
      outputs: [.temporary("fake-merge-module-output.txt")]
    )
  }
}


//
//  NetworkActivityIndicatorManager.swift
//  JenkinsiOS
//
//  Created by Robert on 17.10.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import UIKit

class NetworkActivityIndicatorManager{

    /// The number of outstanding requests
    private var outstandingRequests = 0
    /// The central NetworkActivityIndicatorManager singleton
    static let manager = NetworkActivityIndicatorManager()

    private init(){}

    /// Set the activity indicator to active or inactive (once there are no outstanding requests)
    ///
    /// - parameter active: Whether or not to set the indicator to active
    func setActivityIndicator(active: Bool){
        outstandingRequests += (active) ? 1 : -1
        if outstandingRequests < 0{
            outstandingRequests = 0
        }

        #if !IS_EXTENSION
            UIApplication.shared.isNetworkActivityIndicatorVisible = (outstandingRequests > 0)
        #endif
    }

}

Fix issue where some code could be called on a non-main thread

//
//  NetworkActivityIndicatorManager.swift
//  JenkinsiOS
//
//  Created by Robert on 17.10.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import UIKit

class NetworkActivityIndicatorManager{

    /// The number of outstanding requests
    private var outstandingRequests = 0
    /// The central NetworkActivityIndicatorManager singleton
    static let manager = NetworkActivityIndicatorManager()

    private init(){}

    /// Set the activity indicator to active or inactive (once there are no outstanding requests)
    ///
    /// - parameter active: Whether or not to set the indicator to active
    func setActivityIndicator(active: Bool){
        outstandingRequests += (active) ? 1 : -1
        if outstandingRequests < 0{
            outstandingRequests = 0
        }

        #if !IS_EXTENSION
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = (self.outstandingRequests > 0)
            }
        #endif
    }

}


//
//  SwiftSnakeTests.swift
//  SwiftSnakeTests
//
//  Created by Ellen Shapiro (Vokal) on 9/24/15.
//  Copyright © 2015 Vokal. All rights reserved.
//

import XCTest
@testable import SwiftSnake

class SwiftSnakeTests: XCTestCase {

    override func setUp() {
        super.setUp()
        XCTFail("Y U NO WRITE TESTS?")
    }
}

Test the collsion detection stuff

//
//  SwiftSnakeTests.swift
//  SwiftSnakeTests
//
//  Created by Ellen Shapiro (Vokal) on 9/24/15.
//  Copyright © 2015 Vokal. All rights reserved.
//

import XCTest
import SpriteKit

@testable import SwiftSnake

class SwiftSnakeTests: XCTestCase {

    func testCollisionDetection() {
        let snakeHead = SKPhysicsBody()
        snakeHead.categoryBitMask = NodeBitmask.snakeHead
        let snakeBody = SKPhysicsBody()
        snakeBody.categoryBitMask = NodeBitmask.snakeBody
        let food = SKPhysicsBody()
        food.categoryBitMask = NodeBitmask.food

        //Ouroboros case
        XCTAssertTrue(CollisionHandler.isOuroboros(snakeHead, snakeBody))
        XCTAssertTrue(CollisionHandler.isOuroboros(snakeBody, snakeHead))
        XCTAssertFalse(CollisionHandler.isOuroboros(snakeBody, food))
        XCTAssertFalse(CollisionHandler.isOuroboros(food, snakeBody))
        XCTAssertFalse(CollisionHandler.isOuroboros(food, snakeHead))
        XCTAssertFalse(CollisionHandler.isOuroboros(snakeHead, food))

        //Eatin' case
        XCTAssertTrue(CollisionHandler.isEating(snakeHead, food))
        XCTAssertTrue(CollisionHandler.isEating(food, snakeHead))
        XCTAssertFalse(CollisionHandler.isEating(snakeHead, snakeBody))
        XCTAssertFalse(CollisionHandler.isEating(snakeBody, snakeHead))
        XCTAssertFalse(CollisionHandler.isEating(snakeBody, food))
        XCTAssertFalse(CollisionHandler.isEating(food, snakeBody))
    }
}


//
//  ChatControllerSocketConnectionHandler.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 17/12/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController: SocketConnectionHandler {

    func socketDidConnect(socket: SocketManager) {
        hideHeaderStatusView()

        DispatchQueue.main.async { [weak self] in
            if let subscription = self?.subscription {
                if subscription.isValid() {
                    self?.subscription = subscription
                }
            }

            if self?.subscription == nil {
                self?.subscription = .initialSubscription()
            }
        }

        rightButton.isEnabled = true
    }

    func socketDidDisconnect(socket: SocketManager) {
        showHeaderStatusView()

        chatHeaderViewStatus?.labelTitle.text = localized("connection.offline.banner.message")
        chatHeaderViewStatus?.buttonRefresh.isHidden = false
        chatHeaderViewStatus?.backgroundColor = .RCLightGray()
        chatHeaderViewStatus?.setTextColor(.RCDarkBlue())
    }

    func socketDidReturnError(socket: SocketManager, error: SocketError) {
        // Handle errors
    }

}

Make some other verifications in the subscription object

//
//  ChatControllerSocketConnectionHandler.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 17/12/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController: SocketConnectionHandler {

    func socketDidConnect(socket: SocketManager) {
        hideHeaderStatusView()

        DispatchQueue.main.async { [weak self] in
            if let subscription = self?.subscription, !subscription.isInvalidated, subscription.isValid() {
                self?.subscription = subscription
            } else {
                self?.subscription = .initialSubscription()
            }
        }

        rightButton.isEnabled = true
    }

    func socketDidDisconnect(socket: SocketManager) {
        showHeaderStatusView()

        chatHeaderViewStatus?.labelTitle.text = localized("connection.offline.banner.message")
        chatHeaderViewStatus?.buttonRefresh.isHidden = false
        chatHeaderViewStatus?.backgroundColor = .RCLightGray()
        chatHeaderViewStatus?.setTextColor(.RCDarkBlue())
    }

    func socketDidReturnError(socket: SocketManager, error: SocketError) {
        // Handle errors
    }

}


// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-protocols
// REQUIRES: tools-release,no_asserts

func test() {
  let x: UInt = 1 * 2 + 3 * 4 + 5 * 6 + 7 * 8 + 9 * 10 + 11 * 12 + 13 * 14
}

Fix release-build test failure due to unaccounted-for warning.

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-protocols
// REQUIRES: tools-release,no_asserts

func test() {
  let _: UInt = 1 * 2 + 3 * 4 + 5 * 6 + 7 * 8 + 9 * 10 + 11 * 12 + 13 * 14
}


//
//  PostsModels.swift
//  SwiftPress
//
//  Created by Basem Emara on 2018-05-30.
//

public enum PostsModels {

    public enum SearchScope {
        case all
        case title
        case content
        case terms
    }

    public struct SearchRequest {
        public let query: String
        public let scope: SearchScope
    }
}

Modify access control for search request

//
//  PostsModels.swift
//  SwiftPress
//
//  Created by Basem Emara on 2018-05-30.
//

public enum PostsModels {

    public enum SearchScope {
        case all
        case title
        case content
        case terms
    }

    public struct SearchRequest {
        let query: String
        let scope: SearchScope

        public init(query: String, scope: SearchScope) {
            self.query = query
            self.scope = scope
        }
    }
}


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

/// Combinator conforms to Printable.
extension Combinator : Printable {
	var description: String {
		return describe(self)
	}
}

/// Pretty-prints the language represented by a combinator.
func describe<Alphabet : Alphabet>(combinator: Combinator<Alphabet>) -> String {
	let describe: Combinator<Alphabet> -> String = fixpoint("S") { recur, combinator in
		switch combinator.language {
		case .Empty:
			return "∅"

		case let .Null(parses):
			let joined = join(" ", map(parses) { return $0.description })
			return "ε↓{\(joined)}"

		case let .Literal(c):
			return "'\(c)'"

		case let .Alternation(left, right):
			return "(\(recur(left)) ∪ \(recur(right)))"

		case let .Concatenation(first, second) where first == second:
			return "\(recur(first))+"

		case let .Concatenation(first, second):
			return "(\(recur(first)) ✕ \(recur(second)))"

//		case let .Intersection(left, right):
//			return "(\(recur(left)) ∩ \(recur(right)))"

		case let .Repetition(language):
			return "\(recur(language))*"

		case let .Reduction(language, _):
			return "\(recur(language)) → 𝑓"
		}
	}
	return describe(combinator)
}

Remove the obsolete reference to .Intersection.

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

/// Combinator conforms to Printable.
extension Combinator : Printable {
	var description: String {
		return describe(self)
	}
}

/// Pretty-prints the language represented by a combinator.
func describe<Alphabet : Alphabet>(combinator: Combinator<Alphabet>) -> String {
	let describe: Combinator<Alphabet> -> String = fixpoint("S") { recur, combinator in
		switch combinator.language {
		case .Empty:
			return "∅"

		case let .Null(parses):
			let joined = join(" ", map(parses) { return $0.description })
			return "ε↓{\(joined)}"

		case let .Literal(c):
			return "'\(c)'"

		case let .Alternation(left, right):
			return "(\(recur(left)) ∪ \(recur(right)))"

		case let .Concatenation(first, second) where first == second:
			return "\(recur(first))+"

		case let .Concatenation(first, second):
			return "(\(recur(first)) ✕ \(recur(second)))"

		case let .Repetition(language):
			return "\(recur(language))*"

		case let .Reduction(language, _):
			return "\(recur(language)) → 𝑓"
		}
	}
	return describe(combinator)
}


import Foundation

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

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

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

    public init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) {
        executor(fulfill)
    }

    private func fulfill(_ value: Value) {
        lock.lock()
        defer {
            lock.unlock()
        }
        if self.value == nil {
            self.value = value

            for handler in self.handlers {
                handler(value)
            }
            self.handlers.removeAll(keepingCapacity: false)
        }
    }

    public func map<T>(_ transform: @escaping (Value) -> T) -> Promise<T> {
        lock.lock()
        defer {
            lock.unlock()
        }

        if let value = self.value {
            return Promise<T>(transform(value))
        } else {
            return Promise<T> { fulfill in
                handlers.append { value in
                    fulfill(transform(value))
                }
            }
        }
    }

    public func flatMap<T>(_ transform: @escaping (Value) -> Promise<T>) -> Promise<T> {
        return Promise<T> { fulfill in self.get { transform($0).get { fulfill($0) } } }
    }

    public func get(_ handler: @escaping (Value) -> ()) {
        _ = map(handler)
    }
}

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

Move core implementations from `map` to `get`

import Foundation

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

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

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

    public init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) {
        executor(fulfill)
    }

    private func fulfill(_ value: Value) {
        lock.lock()
        defer {
            lock.unlock()
        }
        if self.value == nil {
            self.value = value

            for handler in self.handlers {
                handler(value)
            }
            self.handlers.removeAll(keepingCapacity: false)
        }
    }

    public func map<T>(_ transform: @escaping (Value) -> T) -> Promise<T> {
        return Promise<T> { fulfill in get { fulfill(transform($0)) } }
    }

    public func flatMap<T>(_ transform: @escaping (Value) -> Promise<T>) -> Promise<T> {
        return Promise<T> { fulfill in get { transform($0).get { fulfill($0) } } }
    }

    public func get(_ handler: @escaping (Value) -> ()) {
        lock.lock()
        defer {
            lock.unlock()
        }

        if let value = self.value {
            handler(value)
        } else {
            handlers.append(handler)
        }
    }
}

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


import Foundation
@testable import App
@testable import Vapor
import XCTest
import Testing
import FluentProvider
import MongoKitten

fileprivate let TEST_DB = "test_chuva_db"
fileprivate let DEV_DB = "chuva_db"

extension Droplet {
    static func testable() throws -> Droplet {
        let config = try Config(arguments: ["vapor", "--env=test"])
        try config.setup()
        let drop = try Droplet(config)

        _ = try Server("mongodb://localhost:27017")[TEST_DB].drop()
        _ = try Server("mongodb://localhost:27017")[DEV_DB].copy(toDatabase: TEST_DB)

        try drop.setup()
        return drop
    }
    func serveInBackground() throws {
        background {
            try! self.run()
        }
        console.wait(seconds: 0.5)
    }
}

class TestCase: XCTestCase {
    override func setUp() {
        _ = try! Server("mongodb://localhost:27017")[TEST_DB]
            .map { try $0.remove() }
        Node.fuzzy = [Row.self, JSON.self, Node.self]
        Testing.onFail = XCTFail
    }
}

Clear test db on teardown

import Foundation
@testable import App
@testable import Vapor
import XCTest
import Testing
import FluentProvider
import MongoKitten

fileprivate let TEST_DB = "test_chuva_db"
fileprivate let DEV_DB = "chuva_db"

extension Droplet {
    static func testable() throws -> Droplet {
        let config = try Config(arguments: ["vapor", "--env=test"])
        try config.setup()
        let drop = try Droplet(config)

        _ = try Server("mongodb://localhost:27017")[TEST_DB].drop()
        _ = try Server("mongodb://localhost:27017")[DEV_DB].copy(toDatabase: TEST_DB)

        try drop.setup()
        return drop
    }
    func serveInBackground() throws {
        background {
            try! self.run()
        }
        console.wait(seconds: 0.5)
    }
}

class TestCase: XCTestCase {
    override func setUp() {
        _ = try! Server("mongodb://localhost:27017")[TEST_DB]
            .map { try $0.remove() }
        Node.fuzzy = [Row.self, JSON.self, Node.self]
        Testing.onFail = XCTFail
    }

    override func tearDown() {
        _ = try! Server("mongodb://localhost:27017")[TEST_DB]
            .map { try $0.remove() }
        Node.fuzzy = [Row.self, JSON.self, Node.self]
        Testing.onFail = XCTFail
    }
}


import Foundation
import ReactiveCocoa

struct Settings {
  private static let serverAddressKey = "SceneLauncher.serverAddress"

  // TODO only let non-empty-values out?
  static let serverAddress = { () -> MutableProperty<String?> in
    let property = MutableProperty(NSUserDefaults.standardUserDefaults().stringForKey(serverAddressKey))
    let ignoreInitialValue: SignalProducer<String?, NoError> = property.producer |> skip(1)
    ignoreInitialValue.start(next: { println("Yes sir got \($0)") })
    return property
  }()

  // TODO remove
  static func getServerAddress() -> String? {
    return serverAddress.value
  }

  static func setServerAddress(newAddress: String) {
    serverAddress.put(newAddress)
    // TODO do this when serverAddress changes
    NSUserDefaults.standardUserDefaults().setObject(newAddress, forKey: serverAddressKey)
  }
}

Save server address when it changes

import Foundation
import ReactiveCocoa

struct Settings {
  private static let serverAddressKey = "SceneLauncher.serverAddress"

  // TODO only let non-empty-values out?
  static let serverAddress = { () -> MutableProperty<String?> in
    let property = MutableProperty(NSUserDefaults.standardUserDefaults().stringForKey(serverAddressKey))
    let ignoreInitialValue: SignalProducer<String?, NoError> = property.producer |> skip(1)
    // TODO compiler crashes if we do "producer |> skip |> start"
    ignoreInitialValue.start(next: {
      NSUserDefaults.standardUserDefaults().setObject($0, forKey: serverAddressKey)
    })
    return property
  }()

  // TODO remove
  static func getServerAddress() -> String? {
    return serverAddress.value
  }

  static func setServerAddress(newAddress: String) {
    serverAddress.put(newAddress)
  }
}


// RUN: %swift-ide-test -repl-code-completion -source-filename %s | FileCheck %s

// A smoketest for REPL code completion in Cocoa.

// REQUIRES: sdk
// REQUIRES: long_tests

// FIXME: iOS has no Cocoa.framework
// REQUIRES: OS=macosx

// CHECK: {{^}}CFArrayCreateCopy(allocator: CFAllocator?, theArray: CFArray?) -> CFArray!{{$}}
// CHECK: {{^}}FE_ALL_EXCEPT: CInt{{$}}

import Cocoa

Fix up the code completion test for Clang importer change

// RUN: %swift-ide-test -repl-code-completion -source-filename %s | FileCheck %s

// A smoketest for REPL code completion in Cocoa.

// REQUIRES: sdk
// REQUIRES: long_tests

// FIXME: iOS has no Cocoa.framework
// REQUIRES: OS=macosx

// CHECK: {{^}}CFArrayCreateCopy(allocator: CFAllocator?, theArray: CFArray?) -> CFArray!{{$}}
// CHECK: {{^}}FE_ALL_EXCEPT: Int32{{$}}

import Cocoa


//
//  Template.swift
//  Stencil
//
//  Created by Kyle Fuller on 23/10/2014.
//  Copyright (c) 2014 Cocode. All rights reserved.
//

import Foundation

public class Template {
    let parser:TokenParser

    public convenience init(named:String) {
        self.init(named:named, inBundle:nil)
    }

    public convenience init(named:String, inBundle bundle:NSBundle?) {
        var url:NSURL?

        if let bundle = bundle {
            url = bundle.URLForResource(named, withExtension: nil)
        } else {
            url = NSBundle.mainBundle().URLForResource(named, withExtension: nil)
        }

        self.init(URL:url!)
    }

    public convenience init(URL:NSURL) {
        var error:NSError?
        let templateString = NSString.stringWithContentsOfURL(URL, encoding: NSUTF8StringEncoding, error: &error)
        self.init(templateString:templateString)
    }

    public init(templateString:String) {
        let lexer = Lexer(templateString: templateString)
        let tokens = lexer.tokenize()
        parser = TokenParser(tokens: tokens)
    }

    public func render(context:Context) -> (string:String?, error:Error?) {
        let (nodes, error) = parser.parse()

        if let error = error {
            return (nil, error)
        } else if let nodes = nodes {
            return renderNodes(nodes, context)
        }

        return (nil, nil)
    }
}

Make use of failable initializers

//
//  Template.swift
//  Stencil
//
//  Created by Kyle Fuller on 23/10/2014.
//  Copyright (c) 2014 Cocode. All rights reserved.
//

import Foundation

public class Template {
    let parser:TokenParser

    public convenience init?(named:String) {
        self.init(named:named, inBundle:nil)
    }

    public convenience init?(named:String, inBundle bundle:NSBundle?) {
        var url:NSURL?

        if let bundle = bundle {
            url = bundle.URLForResource(named, withExtension: nil)
        } else {
            url = NSBundle.mainBundle().URLForResource(named, withExtension: nil)
        }

        self.init(URL:url!)
    }

    public convenience init?(URL:NSURL) {
        var error:NSError?
        let maybeTemplateString = NSString(contentsOfURL: URL, encoding: NSUTF8StringEncoding, error: &error)
        if let templateString = maybeTemplateString {
            self.init(templateString:templateString)
        } else {
            self.init(templateString:"")
            return nil
        }
    }

    public init(templateString:String) {
        let lexer = Lexer(templateString: templateString)
        let tokens = lexer.tokenize()
        parser = TokenParser(tokens: tokens)
    }

    public func render(context:Context) -> (string:String?, error:Error?) {
        let (nodes, error) = parser.parse()

        if let error = error {
            return (nil, error)
        } else if let nodes = nodes {
            return renderNodes(nodes, context)
        }

        return (nil, nil)
    }
}


//
//  TextAreaTableViewCell.swift
//  UsbongKit
//
//  Created by Joe Amanse on 12/02/2016.
//  Copyright © 2016 Usbong Social Systems, Inc. All rights reserved.
//

import UIKit

public class TextAreaTableViewCell: UITableViewCell, NibReusable {
    @IBOutlet weak var textView: UITextView!

    override public func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

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

        // Configure the view for the selected state
    }

}

Add input accessory view for text view

//
//  TextAreaTableViewCell.swift
//  UsbongKit
//
//  Created by Joe Amanse on 12/02/2016.
//  Copyright © 2016 Usbong Social Systems, Inc. All rights reserved.
//

import UIKit

public class TextAreaTableViewCell: UITableViewCell, NibReusable {
    @IBOutlet weak var textView: UITextView! {
        didSet {
            textView.inputAccessoryView = keyboardAccessoryView
        }
    }

    private static let accessoryViewHeight: CGFloat = 44
    private lazy var _keyboardAccessoryView: UIView? = {
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: self.dynamicType.accessoryViewHeight))

        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        let doneBarButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("didPressDone:"))

        toolbar.items = [flexibleSpace, doneBarButton]

        return toolbar
    }()

    public var keyboardAccessoryView: UIView? {
        get {
            return _keyboardAccessoryView
        }
        set {
            _keyboardAccessoryView = newValue
            textView.inputAccessoryView = _keyboardAccessoryView
        }
    }

    override public func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

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

        // Configure the view for the selected state
    }

    public func didPressDone(sender: AnyObject?) {
        // Ask delegate if should return
        let shouldReturn: Bool = textView.delegate?.textViewShouldEndEditing?(textView) ?? true

        if shouldReturn {
            textView.resignFirstResponder()
        }
    }

}