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

extension Expression where Recur: TermType {
	public static var boolean: Module<Recur> {
		let Boolean = Declaration("Boolean",
			type: .Type(0),
			value: lambda(.Type) { A in Recur.lambda(A, A, const(A)) })

		let `true` = Declaration("true",
			type: Boolean.ref.out,
			value: lambda(.Type) { A in Recur.lambda(A, A) { a, _ in a } })

		let `false` = Declaration("false",
			type: Boolean.ref.out,
			value: lambda(.Type) { A in Recur.lambda(A, A) { _, a in a } })

		let not = Declaration("not",
			type: FunctionType(Boolean.ref, Boolean.ref),
			value: lambda(Boolean.ref, .Type) { b, A in Recur.lambda(A, A) { t, f in b[A, f, t] } })

		let `if` = Declaration("if",
			type: lambda(.Type, Boolean.ref) { t, _ in .FunctionType(t, t, t) },
			value: lambda(.Type, Boolean.ref) { t, condition in Recur.lambda(t, t) { condition[$0, $1] } })

		return Module([ Boolean, `true`, `false`, not, `if` ])
	}
}

import Prelude

Revert "Add an `if` binding."

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

extension Expression where Recur: TermType {
	public static var boolean: Module<Recur> {
		let Boolean = Declaration("Boolean",
			type: .Type(0),
			value: lambda(.Type) { A in Recur.lambda(A, A, const(A)) })

		let `true` = Declaration("true",
			type: Boolean.ref.out,
			value: lambda(.Type) { A in Recur.lambda(A, A) { a, _ in a } })

		let `false` = Declaration("false",
			type: Boolean.ref.out,
			value: lambda(.Type) { A in Recur.lambda(A, A) { _, a in a } })

		let not = Declaration("not",
			type: FunctionType(Boolean.ref, Boolean.ref),
			value: lambda(Boolean.ref, .Type) { b, A in Recur.lambda(A, A) { t, f in b[A, f, t] } })

		return Module([ Boolean, `true`, `false`, not ])
	}
}

import Prelude


import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    var modelList:ModelList?

    override func setUp()
    {
        super.setUp()
        modelList = ModelList()
    }

    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }

    func testLoadData()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl()

        else
        {
            return
        }

        let data:Data? = modelList?.loadData(url:url)
        XCTAssertNotNil(data, "failed loading data from url")
    }
}

Create test for load json

import XCTest
@testable import worldcities

class TestModelListParser:XCTestCase
{
    var modelList:ModelList?

    override func setUp()
    {
        super.setUp()
        modelList = ModelList()
    }

    func testFactoryResourceUrl()
    {
        let url:URL? = ModelList.factoryResourceUrl()
        XCTAssertNotNil(url, "failed creating resource url")
    }

    func testLoadData()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl()

        else
        {
            return
        }

        let data:Data? = modelList?.loadData(url:url)
        XCTAssertNotNil(data, "failed loading data from url")
    }

    func testLoadJson()
    {
        guard

            let url:URL = ModelList.factoryResourceUrl(),
            let data:Data = modelList?.loadData(url:url)

        else
        {
            return
        }

        let json:Any? = modelList?.loadJson(data:data)
        XCTAssertNotNil(json, "failed loading json from data")
    }
}


//
// Copyright 2020 New Vector Ltd
//
// 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 UIKit

/// Dialpad action button type
@objc enum DialpadActionButtonType: Int {
    case backspace
    case call
}

/// Action button class for Dialpad screen
class DialpadActionButton: DialpadButton {

    var type: DialpadActionButtonType = .backspace

    override func update(theme: Theme) {
        switch type {
        case .backspace:
            backgroundColor = .clear
            tintColor = theme.noticeSecondaryColor
        case .call:
            backgroundColor = theme.tintColor
            tintColor = .white
        }
    }

}

Update bg color for backspace button

//
// Copyright 2020 New Vector Ltd
//
// 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 UIKit

/// Dialpad action button type
@objc enum DialpadActionButtonType: Int {
    case backspace
    case call
}

/// Action button class for Dialpad screen
class DialpadActionButton: DialpadButton {

    var type: DialpadActionButtonType = .backspace

    override func update(theme: Theme) {
        switch type {
        case .backspace:
            backgroundColor = .clear
            if theme.identifier == ThemeIdentifier.light.rawValue {
                tintColor = theme.textSecondaryColor
            } else {
                tintColor = theme.textTertiaryColor
            }
        case .call:
            backgroundColor = theme.tintColor
            tintColor = .white
        }
    }

}


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

extension Module {
	public static var maybe: Module {
		return Module("Maybe", [
			Declaration.Datatype("Maybe", .Argument(.Type, {
				[
					"just": .Argument($0, const(.End)),
					"nothing": .End
				]
			}))
		])
	}
}

import Prelude

Break the Maybe declaration out into a temporary.

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

extension Module {
	public static var maybe: Module {
		let Maybe = Declaration.Datatype("Maybe", .Argument(.Type, {
			[
				"just": .Argument($0, const(.End)),
				"nothing": .End
			]
		}))
		return Module("Maybe", [ Maybe ])
	}
}

import Prelude


//
//  JsonObject.swift
//  LibStorj
//
//  Created by Koray Koska on 07/09/2017.
//
//

import Foundation
import JSON
import CLibStorj

/**
 * JsonObject extension is a converter which basically wraps json-c around the JSON implementation
 * from vapor. (see: https://github.com/vapor/json)
 *
 * **Please be careful with this implementation!**
 *
 * Currently this wrapper is far away from being fast. It is really just meant for internal use
 * as json objects aren't heavily or intensively used in this library.
 *
 * If you use this implementation outside of the context of this library please understand
 * the following points:
 *
 * - You don't get any support regarding the json-c wrapper
 * - This implementation may at any point have breaking changes
 * - For intensive json serializing and deserializing or heavy
 *   usage this implementation **will** be a bottleneck!
 */
public extension JSON {

    public init?(jsonString: String) {
        try? self.init(json: JSON(bytes: jsonString.bytes))
    }

    init?(jsonObject: OpaquePointer) {
        guard let str = json_object_to_json_string(jsonObject) else {
            return nil
        }

        self.init(jsonString: String(cString: str))
    }

    func jsonObject() -> OpaquePointer? {
        guard let s = try? serialize().makeString() else {
            return nil
        }

        return json_tokener_parse(s)
    }
}

Make initializer for JSOn internal

//
//  JsonObject.swift
//  LibStorj
//
//  Created by Koray Koska on 07/09/2017.
//
//

import Foundation
import JSON
import CLibStorj

/**
 * JsonObject extension is a converter which basically wraps json-c around the JSON implementation
 * from vapor. (see: https://github.com/vapor/json)
 *
 * **Please be careful with this implementation!**
 *
 * Currently this wrapper is far away from being fast. It is really just meant for internal use
 * as json objects aren't heavily or intensively used in this library.
 *
 * If you use this implementation outside of the context of this library please understand
 * the following points:
 *
 * - You don't get any support regarding the json-c wrapper
 * - This implementation may at any point have breaking changes
 * - For intensive json serializing and deserializing or heavy
 *   usage this implementation **will** be a bottleneck!
 */
public extension JSON {

    init?(jsonString: String) {
        try? self.init(json: JSON(bytes: jsonString.bytes))
    }

    init?(jsonObject: OpaquePointer) {
        guard let str = json_object_to_json_string(jsonObject) else {
            return nil
        }

        self.init(jsonString: String(cString: str))
    }

    func jsonObject() -> OpaquePointer? {
        guard let s = try? serialize().makeString() else {
            return nil
        }

        return json_tokener_parse(s)
    }
}


import Foundation
import Alamofire

public func request
    (config: Config)
    (_ endpoint: Endpoint, params: [Param], finish: (error: NSError?, data: [String: AnyObject]?) -> Void)
{
    Alamofire.request(buildRequest(config, endpoint, params))
        .validate()
        .response { request, response, data, error in
            if let data = data {
                finish(error: nil, data: processResponse(data, endpoint))
            } else {
                finish(error: error, data: nil)
            }
        }
}

Add helpers to assist web login

import Foundation
import Alamofire

public typealias FinishClosure = (error: NSError?, data: [String: AnyObject]?) -> Void

public func request
    (config: Config)
    (_ endpoint: Endpoint, _ params: [Param], _ finish: FinishClosure)
{
    Alamofire.request(buildRequest(config, endpoint, params))
        .validate()
        .response { request, response, data, error in
            if let data = data {
                finish(error: nil, data: processResponse(data, endpoint))
            } else {
                finish(error: error, data: nil)
            }
        }
}

public func requestWebAuthUrl(config: Config)(_ callbackUrl: String, finish: (error: NSError?, url: NSURL?) -> Void) {
    request(config)(.OauthRequestToken, [.OauthCallback(callbackUrl)]) { error, data in
        let token = data?["oauth_token"] as? String
        let url = NSURL(string: "https://api.twitter.com/oauth/authenticate?oauth_token=\(token)")
        finish(error: error, url: url)
    }
}

public func requestAccessToken(config: Config)(_ oauthReturnUrl: NSURL, finish: FinishClosure) {
    let dict = parseQueryParams(oauthReturnUrl.query!)

    if let verifier = dict["oauth_verifier"] where dict["oauth_token"] != nil {
        request(config)(.OauthAccessToken, [.OauthVerifier(verifier)], finish)
    } else {
        let error = NSError(
            domain: "com.daiweilu.LarryBird",
            code: 0,
            userInfo: [
                "description": "OAuth return does not contain any verifier",
                "provided_url": oauthReturnUrl.URLString
            ])
        finish(error: error, data: nil)
    }
}


//
//  AuthSettings.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 06/10/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyJSON

final class AuthSettings: BaseModel {
    dynamic var siteURL: String?
}

Add settings that RC supports for S3

//
//  AuthSettings.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 06/10/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyJSON

final class AuthSettings: BaseModel {
    dynamic var siteURL: String?

    // File upload
    dynamic var uploadStorageType: String?

    // Amazon S3 settings
    dynamic var AWSS3Bucket: String?
    dynamic var AWSS3BucketURL: String?
    dynamic var AWSS3ACL: String?
    dynamic var AWSS3AccessKey: String?
    dynamic var AWSS3SecretKey: String?
    dynamic var AWSS3CDN: String?
    dynamic var AWSS3Region: String?
}


//
//  ObservableProperty.swift
//  ReSwiftRx
//
//  Created by Charlotte Tortorella on 29/11/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

public final class ObservableProperty<ValueType>: ObservablePropertyType {
    internal typealias ObservablePropertySubscriptionReferenceType =
        ObservablePropertySubscriptionReference<ValueType>
    internal var subscriptions = [ObservablePropertySubscriptionReferenceType : (ValueType) -> ()]()
    private var subscriptionToken: Int = 0
    public var value: ValueType {
        didSet {
            subscriptions.forEach { $0.value(value) }
        }
    }

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

    @discardableResult
    public func subscribe(_ function: @escaping (ValueType) -> Void) -> SubscriptionReferenceType? {
        defer { subscriptionToken += 1 }
        defer { function(value) }
        let reference = ObservablePropertySubscriptionReferenceType(key: String(subscriptionToken),
                                                            stream: self)
        subscriptions.updateValue(function, forKey: reference)
        return reference
    }

    internal func unsubscribe(reference: ObservablePropertySubscriptionReferenceType) {
        subscriptions.removeValue(forKey: reference)
    }
}

Add a self reference variable to ensure that an observable does not deallocate while being observed

//
//  ObservableProperty.swift
//  ReSwiftRx
//
//  Created by Charlotte Tortorella on 29/11/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

public final class ObservableProperty<ValueType>: ObservablePropertyType {
    internal typealias ObservablePropertySubscriptionReferenceType =
        ObservablePropertySubscriptionReference<ValueType>
    internal var subscriptions = [ObservablePropertySubscriptionReferenceType : (ValueType) -> ()]()
    private var subscriptionToken: Int = 0
    private var retainReference: ObservableProperty<ValueType>?
    public var value: ValueType {
        didSet {
            subscriptions.forEach { $0.value(value) }
        }
    }

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

    @discardableResult
    public func subscribe(_ function: @escaping (ValueType) -> Void) -> SubscriptionReferenceType? {
        defer { subscriptionToken += 1 }
        retainReference = self
        function(value)
        let reference = ObservablePropertySubscriptionReferenceType(key: String(subscriptionToken),
                                                            stream: self)
        subscriptions.updateValue(function, forKey: reference)
        return reference
    }

    internal func unsubscribe(reference: ObservablePropertySubscriptionReferenceType) {
        subscriptions.removeValue(forKey: reference)
        if subscriptions.count == 0 {
            retainReference = nil
        }
    }
}


// RUN: %target-typecheck-verify-swift -enable-experimental-variadic-generics

protocol P {}

protocol P1 {
  associatedtype A... // expected-error {{associated types cannot be variadic}}
  associatedtype B<U>...
  // expected-error@-1 {{associated types cannot be variadic}}
  // expected-error@-2 {{associated types must not have a generic parameter list}}
}

typealias Alias<T...> = (T...)

struct S1<T...> {}
struct S2<T, U...> {}
struct S3<T..., U> {}

struct S4<T...:P, U> {}
struct S5<T... :P, U> {}
struct S6<T...: P> {}
struct S7<T... : P> {}

func foo<T...>(_ x: T...) {}

func bar<T...:P>(_ x: T...) {}
func baz<T... :P>(_ x: T...) {}
func qux<T... : P>(_ x: T...) {}
func quux<T...: P>(_ x: T...) {}

func foobar<T, U, V...>(x: T, y: U, z: V...) { }
func foobaz<T, U..., V>(x: T, y: U..., z: V) { }
func fooqux<T..., U..., V...>(x: T..., y: U..., z: V...) { }

Add extra variadic generic test

// RUN: %target-typecheck-verify-swift -enable-experimental-variadic-generics

protocol P {}

protocol P1 {
  associatedtype A... // expected-error {{associated types cannot be variadic}}
  associatedtype B<U>...
  // expected-error@-1 {{associated types cannot be variadic}}
  // expected-error@-2 {{associated types must not have a generic parameter list}}
}

typealias Alias<T...> = (T...)

struct S1<T...> {}
struct S2<T, U...> {}
struct S3<T..., U> {}

struct S4<T...:P, U> {}
struct S5<T... :P, U> {}
struct S6<T...: P> {}
struct S7<T... : P> {}

func foo<T...>(_ x: T...) {}

func bar<T...:P>(_ x: T...) {}
func baz<T... :P>(_ x: T...) {}
func qux<T... : P>(_ x: T...) {}
func quux<T...: P>(_ x: T...) {}

func foobar<T, U, V...>(x: T, y: U, z: V...) { }
func foobaz<T, U..., V>(x: T, y: U..., z: V) { }
func fooqux<T..., U..., V...>(x: T..., y: U..., z: V...) { }

// We allow whitespace between the generic parameter and the '...', this is
// consistent with regular variadic parameters.
func withWhitespace<T ...>(_ x: T ...) -> (T ...) {}


//
//  ConsulKeyValuePair.swift
//  ConsulSwift
//
//  Created by Christoph Pageler on 19.06.17.
//

import Foundation
import Quack
import SwiftyJSON

public class ConsulKeyValuePair: QuackModel {

    public var key: String
    public var value: String

    public required init?(json: JSON) {
        guard
            let jsonArray = json.array,
            let firstJsonEntry = jsonArray.first,
            let key = firstJsonEntry["Key"].string,
            let value = firstJsonEntry["Value"].string
        else { return nil }

        self.key = key
        self.value = value
    }

    public func decodedValue() -> String? {
        guard let decodedData = NSData(base64Encoded: value) as Data? else { return nil }
        return NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) as String?
    }

}

Update Consul KeyValuePair to Linux Swift

//
//  ConsulKeyValuePair.swift
//  ConsulSwift
//
//  Created by Christoph Pageler on 19.06.17.
//

import Foundation
import Quack
import SwiftyJSON

public class ConsulKeyValuePair: QuackModel {

    public var key: String
    public var value: String

    public required init?(json: JSON) {
        guard
            let jsonArray = json.array,
            let firstJsonEntry = jsonArray.first,
            let key = firstJsonEntry["Key"].string,
            let value = firstJsonEntry["Value"].string
        else { return nil }

        self.key = key
        self.value = value
    }

    public func decodedValue() -> String? {
        guard let decodedData = Data(base64Encoded: value) else { return nil }
        return String(data: decodedData, encoding: String.Encoding.utf8)
    }

}


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

import Tesseract
import XCTest

final class TypeTests: XCTestCase {
	func testConstantTermHasConstantType() {
		XCTAssertEqual(typeof(.Constant(.Integer(0))), Type.Integer)
	}
}

Test against the unwrapped type.

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

import Prelude
import Tesseract
import XCTest

final class TypeTests: XCTestCase {
	func testConstantTermHasConstantType() {
		XCTAssertEqual(typeof(.Constant(.Integer(0))).either(const(.Boolean), id), Type.Integer)
	}
}


//
//  UserToken.swift
//
//
//  Created by Vladislav Fitc on 20/03/2020.
//

import Foundation

public struct UserToken: StringWrapper, URLEncodable {

  public let rawValue: String

  private let allowedCharacters: CharacterSet = CharacterSet.alphanumerics.union(.init(charactersIn: "_-"))

  public init(rawValue: String) {
    assert(!rawValue.isEmpty, "UserToken can't be empty")
    assert(rawValue.count <= 64, "UserToken length can't be superior to 64 characters. Input: \(rawValue)")
    let containsOnlyAllowedCharacters = rawValue.trimmingCharacters(in: allowedCharacters).isEmpty
    assert(containsOnlyAllowedCharacters, "UserToken allows only characters of type [a-zA-Z0-9_-]. Input: \(rawValue)")
    self.rawValue = rawValue
  }

}

Add point as allowed character in user token

//
//  UserToken.swift
//
//
//  Created by Vladislav Fitc on 20/03/2020.
//

import Foundation

public struct UserToken: StringWrapper, URLEncodable {

  public let rawValue: String

  private let allowedCharacters: CharacterSet = CharacterSet.alphanumerics.union(.init(charactersIn: "._-"))

  public init(rawValue: String) {
    assert(!rawValue.isEmpty, "UserToken can't be empty")
    assert(rawValue.count <= 64, "UserToken length can't be superior to 64 characters. Input: \(rawValue)")
    let containsOnlyAllowedCharacters = rawValue.trimmingCharacters(in: allowedCharacters).isEmpty
    assert(containsOnlyAllowedCharacters, "UserToken allows only characters of type [a-zA-Z0-9_-.]. Input: \(rawValue)")
    self.rawValue = rawValue
  }

}


/// SANE uses fixed point numbers with a 16 bit shift for decimal numbers
fileprivate let shift = Double(0b1 << 16)

extension Int32 {
  /**
    Converts a SANE fixed point number into a floating point number

    - parameter shift: The shift value which `self` is divided by, defaults to 2^16
    - returns: `self` as a floating point number
  */
  public func unfixed(by shift: Double = shift) -> Double {
    return Double(self)/shift
  }
}

extension Double {
  /**
    Converts a floating point number into a SANE fixed point number

    - parameter shift: The shift value which `self` is multiplied by, defaults to 2^16
    - returns: `self` as a SANE compatible fixed point number
  */
 public func fixed(by shift: Double = shift) -> Int32 {
    return Int32(self*shift)
  }
}

Make fixed point extensions internal and use SANE_Fixed type

import Clibsane

/// SANE uses fixed point numbers with a 16 bit shift for decimal numbers
fileprivate let shift = Double(0b1 << SANE_FIXED_SCALE_SHIFT)

extension SANE_Fixed {
  /**
    Converts a SANE fixed point number into a floating point number

    - parameter shift: The shift value which `self` is divided by, defaults to 2^16
    - returns: `self` as a floating point number
  */
  func unfixed(by shift: Double = shift) -> Double {
    return Double(self)/shift
  }
}

extension Double {
  /**
    Converts a floating point number into a SANE fixed point number

    - parameter shift: The shift value which `self` is multiplied by, defaults to 2^16
    - returns: `self` as a SANE compatible fixed point number
  */
 func fixed(by shift: Double = shift) -> SANE_Fixed {
    return SANE_Fixed(self*shift)
  }
}


//
//  SubscriptionCollection.swift
//  Pods
//
//  Created by Lim, Jennifer on 1/20/17.
//
//

/// Represents all the subscriptions with extra informations
public class SubscriptionCollection: VIMModelObject
{
    // MARK: - Properties

    /// Represents the uri
    public var uri: String?

    /// Represents the modified time
    public var modifiedTime: Date?

    /// Represents the subscription
    public var subscription: Subscription?

    // MARK: - VIMMappable

    public override func getObjectMapping() -> Any
    {
        return ["modified_time": "modifiedTime",
                "subscriptions": "subscription"]
    }

    public override func getClassForObjectKey(_ key: String!) -> AnyClass!
    {
        if key == "subscriptions"
        {
            return Subscription.self
        }

        return nil
    }
}

Remove modifiedTime property. Add migrated property.

//
//  SubscriptionCollection.swift
//  Pods
//
//  Created by Lim, Jennifer on 1/20/17.
//
//

/// Represents all the subscriptions with extra informations
public class SubscriptionCollection: VIMModelObject
{
    // MARK: - Properties

    /// Represents the uri
    public var uri: String?

    /// Represents the subscription
    public var subscription: Subscription?

    /// Represents the migration that indicates whether the user has migrated from the old system `VIMTrigger` to new new system `Localytics`.
    public var migrated: NSNumber?

    // MARK: - VIMMappable

    public override func getObjectMapping() -> Any
    {
        return ["subscriptions": "subscription"]
    }

    public override func getClassForObjectKey(_ key: String!) -> AnyClass!
    {
        if key == "subscriptions"
        {
            return Subscription.self
        }

        return nil
    }
}


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

enum Hey {
  case listen
}

func test() {
  switch Hey.listen {
  case nil: // expected-warning {{type 'Hey' is not optional, value can never be nil}}
    break
  default:
    break
  }
}

Augment Test for Confusing ExpressibleByNilLiteral Case

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

enum Hey {
  case listen
}

func test() {
  switch Hey.listen {
  case nil: // expected-warning {{type 'Hey' is not optional, value can never be nil}}
    break
  default:
    break
  }
}

struct Nilable: ExpressibleByNilLiteral {
  init(nilLiteral: ()) {}
}

func testNil() {
  // N.B. A deeply confusing case as no conversion is performed on the `nil`
  // literal. Instead, the match subject is converted to `Nilable?` and compared
  // using ~=.
  switch Nilable(nilLiteral: ()) {
  case nil: // expected-warning {{type 'Nilable' is not optional, value can never be nil}}
    break
  default:
    break
  }
}


//
//  LTVPNDomainsViewController.swift
//  VPNOn
//
//  Created by Lex Tang on 1/28/15.
//  Copyright (c) 2015 LexTang.com. All rights reserved.
//

import UIKit
import VPNOnKit

@objc protocol LTVPNDomainsViewControllerDelegate {
    optional func didTapSaveDomainsWithText(text: String)
}

class LTVPNDomainsViewController: UITableViewController
{
    weak var delegate: LTVPNDomainsViewControllerDelegate?

    @IBOutlet weak var saveButton: UIBarButtonItem!
    @IBOutlet weak var textView: UITextView!

    @IBAction func save(sender: AnyObject?) {
        VPNManager.sharedManager().onDemandDomains = textView.text

        if let d = delegate {
            d.didTapSaveDomainsWithText?(textView.text)
        }
        popDetailViewController()
    }

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

        textView.text = VPNManager.sharedManager().onDemandDomains
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        delegate = nil
    }

    // MARK: - Navigation

    func popDetailViewController() {
        let topNavigationController = splitViewController!.viewControllers.last! as UINavigationController
        topNavigationController.popViewControllerAnimated(true)
    }
}

Set background color of domains view controller.

//
//  LTVPNDomainsViewController.swift
//  VPNOn
//
//  Created by Lex Tang on 1/28/15.
//  Copyright (c) 2015 LexTang.com. All rights reserved.
//

import UIKit
import VPNOnKit

@objc protocol LTVPNDomainsViewControllerDelegate {
    optional func didTapSaveDomainsWithText(text: String)
}

class LTVPNDomainsViewController: UITableViewController
{
    weak var delegate: LTVPNDomainsViewControllerDelegate?

    @IBOutlet weak var saveButton: UIBarButtonItem!
    @IBOutlet weak var textView: UITextView!

    @IBAction func save(sender: AnyObject?) {
        VPNManager.sharedManager().onDemandDomains = textView.text

        if let d = delegate {
            d.didTapSaveDomainsWithText?(textView.text)
        }
        popDetailViewController()
    }

    override func loadView() {
        super.loadView()

        let backgroundView = LTViewControllerBackground()
        tableView.backgroundView = backgroundView
    }

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

        textView.text = VPNManager.sharedManager().onDemandDomains
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        delegate = nil
    }

    // MARK: - Navigation

    func popDetailViewController() {
        let topNavigationController = splitViewController!.viewControllers.last! as UINavigationController
        topNavigationController.popViewControllerAnimated(true)
    }
}


//
//  Created by Jake Lin on 3/1/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import UIKit
import IBAnimatable

class TransitionViewController: AnimatableViewController {
  var animationType: String?

  @IBOutlet var presentButton: AnimatableButton!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Transition animations start with `System` do not support Present transition, so hide it
    if let animationType = animationType where animationType.hasPrefix("System") {
        presentButton.alpha = 0
    }
  }

  @IBAction func presentButtonDidTap(sender: AnyObject) {
    guard let toViewController = storyboard?.instantiateViewControllerWithIdentifier("PresentedFirstViewController") as? AnimatableViewController, animationType = animationType else {
      return
    }

    toViewController.transitionAnimationType = animationType
    let segueName = "IBAnimatable.Present" + animationType + "Segue"
    guard let segueClass = NSClassFromString(segueName) as? UIStoryboardSegue.Type else {
      return
    }

    let segue = segueClass.init(identifier: segueName, source: self, destination: toViewController)
    prepareForSegue(segue, sender: self)
    segue.perform()
  }
}

Fix the present Explode segue in demo app.

//
//  Created by Jake Lin on 3/1/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import UIKit
import IBAnimatable

class TransitionViewController: AnimatableViewController {
  var animationType: String?

  @IBOutlet var presentButton: AnimatableButton!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Transition animations start with `System` do not support Present transition, so hide it
    if let animationType = animationType where animationType.hasPrefix("System") {
      // Cannot use `hidden` here because of `UIStackView`
      presentButton.alpha = 0
    }
  }

  @IBAction func presentButtonDidTap(sender: AnyObject) {
    guard let toViewController = storyboard?.instantiateViewControllerWithIdentifier("PresentedFirstViewController") as? AnimatableViewController, animationType = animationType else {
      return
    }

    toViewController.transitionAnimationType = animationType
    let segueName = "IBAnimatable.Present" + extractAnimationType(animationType) + "Segue"
    guard let segueClass = NSClassFromString(segueName) as? UIStoryboardSegue.Type else {
      return
    }

    let segue = segueClass.init(identifier: segueName, source: self, destination: toViewController)
    prepareForSegue(segue, sender: self)
    segue.perform()
  }

  // To extract the type without parameters
  private func extractAnimationType(animationType: String) -> String {
    if let range = animationType.rangeOfString("(") {
      return animationType.substringToIndex(range.startIndex)
    }
    return animationType
  }
}


//
//  NSMutableAttributedString+Extension.swift
//  KernLabel
//
//  Created by ikai on 2016/05/26.
//  Copyright © 2016年 Taishi Ikai. All rights reserved.
//

import UIKit

extension NSMutableAttributedString {
    func kerning(regexp: NSRegularExpression?) -> Self {
        guard let regexp = regexp else {
            return self
        }
        let defaultFont = UIFont.systemFontOfSize(UIFont.systemFontSize())
        regexp.enumerateMatchesInString(self.string, options: [], range: NSMakeRange(0, self.length)) { (result, _, _) in
            guard let result = result else { return }
            let (location, length) = (result.range.location, result.range.length)
            let curAttrs = self.attributesAtIndex(location, effectiveRange: nil)
            let font = curAttrs[NSFontAttributeName] as? UIFont ?? defaultFont
            self.addAttribute(NSKernAttributeName, value: font.pointSize * -0.5, range: NSMakeRange(location, length - 1))
        }
        return self
    }

    override var attributes: [String : AnyObject]? {
        get {
            return super.attributes
        }
        set {
            guard let newValue = newValue else {
                return
            }
            self.addAttributes(newValue, range: NSMakeRange(0, self.length))
        }
    }
}

Remove risk of memory leak

//
//  NSMutableAttributedString+Extension.swift
//  KernLabel
//
//  Created by ikai on 2016/05/26.
//  Copyright © 2016年 Taishi Ikai. All rights reserved.
//

import UIKit

extension NSMutableAttributedString {
    func kerning(regexp: NSRegularExpression?) -> Self {
        guard let regexp = regexp else {
            return self
        }
        let defaultFont = UIFont.systemFontOfSize(UIFont.systemFontSize())
        regexp.enumerateMatchesInString(self.string, options: [], range: NSMakeRange(0, self.length)) { [weak self] (result, _, _) in
            guard let result = result, this = self else { return }
            let (location, length) = (result.range.location, result.range.length)
            let curAttrs = this.attributesAtIndex(location, effectiveRange: nil)
            let font = curAttrs[NSFontAttributeName] as? UIFont ?? defaultFont
            this.addAttribute(NSKernAttributeName, value: font.pointSize * -0.5, range: NSMakeRange(location, length - 1))
        }
        return self
    }

    override var attributes: [String : AnyObject]? {
        get {
            return super.attributes
        }
        set {
            guard let newValue = newValue else {
                return
            }
            self.addAttributes(newValue, range: NSMakeRange(0, self.length))
        }
    }
}


//
//  Extensions.swift
//  Typist-Demo
//
//  Created by Lasha Efremidze on 12/2/17.
//  Copyright © 2017 Toto Tvalavadze. All rights reserved.
//

import UIKit

extension UIViewAnimationOptions {
    init(curve: UIViewAnimationCurve) {
        switch curve {
        case .easeIn:
            self = .curveEaseIn
        case .easeOut:
            self = .curveEaseOut
        case .easeInOut:
            self = .curveEaseInOut
        case .linear:
            self = .curveLinear
        }
    }
}

Add better(?) sintax for OptionSet assignmenet

//
//  Extensions.swift
//  Typist-Demo
//
//  Created by Lasha Efremidze on 12/2/17.
//  Copyright © 2017 Toto Tvalavadze. All rights reserved.
//

import UIKit

extension UIViewAnimationOptions {
    init(curve: UIViewAnimationCurve) {
        switch curve {
        case .easeIn:
            self = [.curveEaseIn]
        case .easeOut:
            self = [.curveEaseOut]
        case .easeInOut:
            self = [.curveEaseInOut]
        case .linear:
            self = [.curveLinear]
        }
    }
}


/**
 * 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

extension Dialog {

    internal struct Constants {

        static let serviceURL = "https://gateway.watsonplatform.net/dialog/api"
        static let errorDoman = "com.watsonplatform.dialog"

        // MARK: Content Operations
        static func content(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/content"
        }
        static let dialogs = "/v1/dialogs"
        static func dialogID(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)"
        }

        // MARK: Conversation Operations
        static func conversation(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/conversation"
        }

        // MARK: Profile Opeations
        static func profile(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/profile"
        }
    }
}

Add missing token url to Dialog's constants

/**
 * 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

extension Dialog {

    internal struct Constants {

        static let serviceURL = "https://gateway.watsonplatform.net/dialog/api"
        static let tokenURL = "https://gateway.watsonplatform.net/authorization/api/v1/token"
        static let errorDoman = "com.watsonplatform.dialog"

        // MARK: Content Operations
        static func content(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/content"
        }
        static let dialogs = "/v1/dialogs"
        static func dialogID(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)"
        }

        // MARK: Conversation Operations
        static func conversation(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/conversation"
        }

        // MARK: Profile Opeations
        static func profile(dialogID: DialogID) -> String {
            return "/v1/dialogs/\(dialogID)/profile"
        }
    }
}


//
//  AuthViewControllerAuthenticationHandler.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 3/26/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

extension AuthViewController {
    internal func handleAuthenticationResponse(_ response: SocketResponse) {
        if response.isError() {
            stopLoading()

            if let error = response.result["error"].dictionary {
                // User is using 2FA
                if error["error"]?.string == "totp-required" {
                    performSegue(withIdentifier: "TwoFactor", sender: nil)
                    return
                }

                Alert(
                    key: "error.socket.default_error"
                    ).present()
            }

            return
        }

        API.current()?.fetch(MeRequest()) { [weak self] response in
            switch response {
            case .resource(let resource):
                guard let strongSelf = self else { return }

                SocketManager.removeConnectionHandler(token: strongSelf.socketHandlerToken)

                if let user = resource.user {
                    BugTrackingCoordinator.identifyCrashReports(withUser: user)

                    if user.username != nil {
                        DispatchQueue.main.async {
                            strongSelf.dismiss(animated: true, completion: nil)
                            AppManager.reloadApp()
                        }
                    } else {
                        DispatchQueue.main.async {
                            strongSelf.performSegue(withIdentifier: "RequestUsername", sender: nil)
                        }
                    }
                } else {
                    self?.stopLoading()
                    Alert(
                        key: "error.socket.default_error"
                        ).present()
                }
            case .error:
                self?.stopLoading()
            }
        }
    }
}

Remove duplicated call on BugTracking since ReloadApp will call it

//
//  AuthViewControllerAuthenticationHandler.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 3/26/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import Foundation

extension AuthViewController {
    internal func handleAuthenticationResponse(_ response: SocketResponse) {
        if response.isError() {
            stopLoading()

            if let error = response.result["error"].dictionary {
                // User is using 2FA
                if error["error"]?.string == "totp-required" {
                    performSegue(withIdentifier: "TwoFactor", sender: nil)
                    return
                }

                Alert(key: "error.socket.default_error").present()
            }

            return
        }

        API.current()?.fetch(MeRequest()) { [weak self] response in
            switch response {
            case .resource(let resource):
                guard let strongSelf = self else { return }

                SocketManager.removeConnectionHandler(token: strongSelf.socketHandlerToken)

                if let user = resource.user {
                    if user.username != nil {
                        DispatchQueue.main.async {
                            strongSelf.dismiss(animated: true, completion: nil)
                            AppManager.reloadApp()
                        }
                    } else {
                        DispatchQueue.main.async {
                            strongSelf.performSegue(withIdentifier: "RequestUsername", sender: nil)
                        }
                    }
                } else {
                    self?.stopLoading()
                    Alert(key: "error.socket.default_error").present()
                }
            case .error:
                self?.stopLoading()
            }
        }
    }
}


//
//  NightNight.swift
//  Pods
//
//  Created by Draveness on 6/30/16.
//
//

import UIKit
import ObjectiveC

public let NightNightThemeChangeNotification = "NightNightThemeChangeNotification"
private let NightNightThemeKey = "NightNightThemeKey"

open class NightNight {
    fileprivate static var currentTheme = Theme(rawValue: UserDefaults.standard.integer(forKey: NightNightThemeKey)) ?? Theme.normal

    public enum Theme: Int {
        case normal
        case night
    }

    open static var theme: Theme {
        get { return currentTheme }
        set {
            currentTheme = newValue
            UserDefaults.standard.set(currentTheme.rawValue, forKey: NightNightThemeKey)
            NotificationCenter.default.post(name: Notification.Name(rawValue: NightNightThemeChangeNotification), object: nil)
        }
    }
}

Add a handy function to toggle between Night and Normal themes. Useful for controlling the Night Mode setting with a UISwitch.

//
//  NightNight.swift
//  Pods
//
//  Created by Draveness on 6/30/16.
//
//

import UIKit
import ObjectiveC

public let NightNightThemeChangeNotification = "NightNightThemeChangeNotification"
private let NightNightThemeKey = "NightNightThemeKey"

open class NightNight {
    fileprivate static var currentTheme = Theme(rawValue: UserDefaults.standard.integer(forKey: NightNightThemeKey)) ?? Theme.normal

    public enum Theme: Int {
        case normal
        case night
    }

    open static var theme: Theme {
        get { return currentTheme }
        set {
            currentTheme = newValue
            UserDefaults.standard.set(currentTheme.rawValue, forKey: NightNightThemeKey)
            NotificationCenter.default.post(name: Notification.Name(rawValue: NightNightThemeChangeNotification), object: nil)
        }
    }

    open class func toggleNightTheme() {
        theme = currentTheme == .night ? .normal : .night
    }
}


import Foundation

extension Optional where Wrapped: Collection {
    /// Return `true` if `self` is empty or nil
    public var isEmpty: Bool {
        switch self {
        case .none:
            return true
        case .some(let value):
            return value.isEmpty
        }
    }
}

extension Collection {
    /// Return object at index if inside bounds, `nil` otherwise
    public subscript(safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Collection where Index: Strideable, Index.Stride: SignedInteger {
    /// Return objects in given range
    public subscript(safe range: CountableRange<Index>) -> Array<Element> {
        return range.compactMap { self[safe: $0] }
    }
}

Add additional isEmpty logic for collections.

import Foundation

extension Optional where Wrapped: Collection {
    /// Return `true` if `self` is empty or nil
    public var isEmpty: Bool {
        switch self {
        case .none:
            return true
        case .some(let value):
            return value.isEmpty
        }
    }

    /// Return `true` if `self` is not empty and not nil
    public var isNotEmpty: Bool {
        switch self {
        case .none:
            return false
        case .some(let value):
            return !value.isEmpty
        }
    }

    /// Return `self` if it is not empty and not nil, otherwise return nil
    var nonEmpty: Wrapped? {
        return self?.isEmpty == true ? nil : self
    }
}

extension Collection {
    /// Return object at index if inside bounds, `nil` otherwise
    public subscript(safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }

    /// Return `true` if `self¨ is not empty
    public var isNotEmpty: Bool {
        return !isEmpty
    }
}

extension Collection where Index: Strideable, Index.Stride: SignedInteger {
    /// Return objects in given range
    public subscript(safe range: CountableRange<Index>) -> Array<Element> {
        return range.compactMap { self[safe: $0] }
    }
}


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

public enum Symbol: Hashable, Printable {
	public static func named(name: String, _ type: Term) -> Symbol {
		return Named(name, type)
	}

	public static func index(index: Int, _ type: Term) -> Symbol {
		return Index(index, type)
	}

	case Named(String, Term)
	case Index(Int, Term)

	public var name: String {
		switch self {
		case let Named(name, _):
			return name
		case let Index(index, _):
			return index.description
		}
	}

	public var type: Term {
		switch self {
		case let Named(_, type):
			return type
		case let Index(_, type):
			return type
		}
	}

	// MARK: Hashable

	public var hashValue: Int {
		return
			name.hashValue
		^	type.hashValue
	}

	// MARK: Printable

	public var description: String {
		let comma = ", "
		return "\(name) :: \(type)"
	}
}

public func == (left: Symbol, right: Symbol) -> Bool {
	return
		left.name == right.name
	&&	left.type == right.type
}

// MARK: - Imports

import Manifold

Add an IndexType to symbols.

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

public enum Symbol: Hashable, Printable {
	public static func named(name: String, _ type: Term) -> Symbol {
		return Named(name, type)
	}

	public static func index(index: Int, _ type: Term) -> Symbol {
		return Index(index, type)
	}

	case Named(String, Term)
	case Index(Int, Term)

	public typealias IndexType = (Int, Term)

	public var name: String {
		switch self {
		case let Named(name, _):
			return name
		case let Index(index, _):
			return index.description
		}
	}

	public var type: Term {
		switch self {
		case let Named(_, type):
			return type
		case let Index(_, type):
			return type
		}
	}

	// MARK: Hashable

	public var hashValue: Int {
		return
			name.hashValue
		^	type.hashValue
	}

	// MARK: Printable

	public var description: String {
		let comma = ", "
		return "\(name) :: \(type)"
	}
}

public func == (left: Symbol, right: Symbol) -> Bool {
	return
		left.name == right.name
	&&	left.type == right.type
}

// MARK: - Imports

import Manifold


//
//  MahjongFaceCell.swift
//  Stage1st
//
//  Created by Zheng Li on 2018/10/1.
//  Copyright © 2018 Renaissance. All rights reserved.
//

import Alamofire
import Kingfisher

final class MahjongFaceCell: UICollectionViewCell {
    let imageView = UIImageView(frame: .zero)

    static let placeholderImage = UIImage(named: "MahjongFacePlaceholder")

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

        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.center.equalTo(self.contentView)
        }
    }

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

    override func prepareForReuse() {
        self.imageView.kf.cancelDownloadTask()
    }

    func configure(with item: MahjongFaceInputView.Category.Item) {
        imageView.kf.setImage(with: item.url, placeholder: MahjongFaceCell.placeholderImage)
        imageView.snp.remakeConstraints { (make) in
            make.center.equalTo(contentView)
            make.width.equalTo(item.width)
            make.height.equalTo(item.height)
        }
    }
}

Fix mahjong face image in keyboard.

//
//  MahjongFaceCell.swift
//  Stage1st
//
//  Created by Zheng Li on 2018/10/1.
//  Copyright © 2018 Renaissance. All rights reserved.
//

import Alamofire
import Kingfisher

final class MahjongFaceCell: UICollectionViewCell {
    let imageView = UIImageView(frame: .zero)

    static let placeholderImage = UIImage(named: "MahjongFacePlaceholder")

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

        imageView.contentMode = .scaleAspectFit
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.center.equalTo(self.contentView)
        }
    }

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

    override func prepareForReuse() {
        self.imageView.kf.cancelDownloadTask()
    }

    func configure(with item: MahjongFaceInputView.Category.Item) {
        imageView.kf.setImage(with: .provider(LocalFileImageDataProvider(fileURL: item.url)), placeholder: MahjongFaceCell.placeholderImage)
        imageView.snp.remakeConstraints { (make) in
            make.center.equalTo(contentView)
            make.width.equalTo(item.width)
            make.height.equalTo(item.height)
        }
    }
}


//
//  CommandSpec.swift
//  Commandant
//
//  Created by Syo Ikeda on 1/5/16.
//  Copyright © 2016 Carthage. All rights reserved.
//

import Commandant
import Nimble
import Quick
import Result

class CommandWrapperSpec: QuickSpec {
	override func spec() {
		describe("CommandWrapper.usage") {
			it("should not crash for a command with NoOptions") {
				let command = NoOptionsCommand()

				let registry = CommandRegistry<CommandantError<()>>()
				registry.register(command)

				let wrapper = registry[command.verb]
				expect(wrapper).notTo(beNil())
				expect(wrapper?.usage()).to(beNil())
			}
		}
	}
}

struct NoOptionsCommand: CommandProtocol {
	var verb: String { return "verb" }
	var function: String { return "function" }

	func run(_ options: NoOptions<CommandantError<()>>) -> Result<(), CommandantError<()>> {
		return .success()
	}
}

Fix a Swift 4 build error

//
//  CommandSpec.swift
//  Commandant
//
//  Created by Syo Ikeda on 1/5/16.
//  Copyright © 2016 Carthage. All rights reserved.
//

import Commandant
import Nimble
import Quick
import Result

class CommandWrapperSpec: QuickSpec {
	override func spec() {
		describe("CommandWrapper.usage") {
			it("should not crash for a command with NoOptions") {
				let command = NoOptionsCommand()

				let registry = CommandRegistry<CommandantError<()>>()
				registry.register(command)

				let wrapper = registry[command.verb]
				expect(wrapper).notTo(beNil())
				expect(wrapper?.usage()).to(beNil())
			}
		}
	}
}

struct NoOptionsCommand: CommandProtocol {
	var verb: String { return "verb" }
	var function: String { return "function" }

	func run(_ options: NoOptions<CommandantError<()>>) -> Result<(), CommandantError<()>> {
		return .success(())
	}
}


//
//  GenStringsCommander.swift
//  BartyCrouch
//
//  Created by Cihat Gündüz on 03.05.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

/// Sends `genstrings` commands with specified input/output paths to bash.
public class GenStringsCommander {

    // MARK: - Stored Class Properties

    public static let sharedInstance = GenStringsCommander()

    // MARK: - Instance Methods

    public func export(stringsFilesToPath stringsFilePath: String, fromCodeInDirectoryPath codeDirectoryPath: String) -> Bool {
        let findFilesResult = Commander.sharedInstance.run("/usr/bin/find", arguments:
            [codeDirectoryPath, "-name", "'*.[hm]'", "-o", "-name", "'*.mm'", "-o", "-name", "'*.swift'", "-print"])
        let exportFileResult = Commander.sharedInstance.run("/usr/bin/genstrings", arguments: findFilesResult.outputs + ["-o", stringsFilePath])

        if findFilesResult.exitCode == 0 && exportFileResult.exitCode == 0 {
            return true
        } else {
            return false
        }
    }

}

Fix tests for whitespaces in paths

//
//  GenStringsCommander.swift
//  BartyCrouch
//
//  Created by Cihat Gündüz on 03.05.16.
//  Copyright © 2016 Flinesoft. All rights reserved.
//

import Foundation

/// Sends `genstrings` commands with specified input/output paths to bash.
public class GenStringsCommander {

    // MARK: - Stored Class Properties

    public static let sharedInstance = GenStringsCommander()

    // MARK: - Instance Methods

    public func export(stringsFilesToPath stringsFilePath: String, fromCodeInDirectoryPath codeDirectoryPath: String) -> Bool {
        let findFilesResult = Commander.sharedInstance.run("/usr/bin/find", arguments:
            [codeDirectoryPath, "-name", "*.[hm]", "-o", "-name", "*.mm", "-o", "-name", "*.swift"])

        let exportFileResult = Commander.sharedInstance.run("/usr/bin/genstrings", arguments: findFilesResult.outputs + ["-o", stringsFilePath])

        if findFilesResult.exitCode == 0 && exportFileResult.exitCode == 0 {
            return true
        } else {
            return false
        }
    }

}


//
//  SwinjectStoryboardOption.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 2/28/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

import Swinject

#if os(iOS) || os(OSX) || os(tvOS)
internal struct SwinjectStoryboardOption: ServiceKeyOptionType {
    internal let controllerType: String

    internal init(controllerType: Container.Controller.Type) {
        self.controllerType = String(reflecting: controllerType)
    }

    internal func isEqualTo(_ another: ServiceKeyOptionType) -> Bool {
        guard let another = another as? SwinjectStoryboardOption else {
            return false
        }

        return self.controllerType == another.controllerType
    }

    internal var hashValue: Int {
        return controllerType.hashValue
    }

    internal var description: String {
        return "Storyboard: \(controllerType)"
    }
}
#endif

Fix a protocol name renamed in Swinject 2.0.0-beta.3.

//
//  SwinjectStoryboardOption.swift
//  Swinject
//
//  Created by Yoichi Tagaya on 2/28/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

import Swinject

#if os(iOS) || os(OSX) || os(tvOS)
internal struct SwinjectStoryboardOption: ServiceKeyOption {
    internal let controllerType: String

    internal init(controllerType: Container.Controller.Type) {
        self.controllerType = String(reflecting: controllerType)
    }

    internal func isEqualTo(_ another: ServiceKeyOption) -> Bool {
        guard let another = another as? SwinjectStoryboardOption else {
            return false
        }

        return self.controllerType == another.controllerType
    }

    internal var hashValue: Int {
        return controllerType.hashValue
    }

    internal var description: String {
        return "Storyboard: \(controllerType)"
    }
}
#endif


/**
 * `undefined()` pretends to be able to produce a value of any type `T` which can
 * be very useful whilst writing a program. It happens that you need a value
 * (which can be a function as well) of a certain type but you can't produce it
 * just yet. However, you can always temporarily replace it by `undefined()`.
 *
 * Inspired by Haskell's
 * [undefined](http://hackage.haskell.org/package/base-4.7.0.2/docs/Prelude.html#v:undefined).
 *
 * Invoking `undefined()` will crash your program.
 *
 * Some examples:
 *
 *  - `let x : String = undefined()`
 *  - `let f : String -> Int? = undefined("string to optional int function")`
 *  - `return undefined() /* in any function */`
 *  - `let x : String = (undefined() as Int -> String)(42)`
 *  - ...
 *
 * What a crash looks like:
 *
 * `fatal error: undefined: main.swift, line 131`
 *
 */
func undefined<T>(_ hint:String="", file:StaticString=__FILE__, line:UWord=__LINE__) -> T {
    let message = hint == "" ? "" : ": \(hint)"
    fatalError("undefined \(T.self)\(message)", file:file, line:line)
}

Update for Swift 2.0 beta 5

/**
 * `undefined()` pretends to be able to produce a value of any type `T` which can
 * be very useful whilst writing a program. It happens that you need a value
 * (which can be a function as well) of a certain type but you can't produce it
 * just yet. However, you can always temporarily replace it by `undefined()`.
 *
 * Inspired by Haskell's
 * [undefined](http://hackage.haskell.org/package/base-4.7.0.2/docs/Prelude.html#v:undefined).
 *
 * Invoking `undefined()` will crash your program.
 *
 * Some examples:
 *
 *  - `let x : String = undefined()`
 *  - `let f : String -> Int? = undefined("string to optional int function")`
 *  - `return undefined() /* in any function */`
 *  - `let x : String = (undefined() as Int -> String)(42)`
 *  - ...
 *
 * What a crash looks like:
 *
 * `fatal error: undefined: main.swift, line 131`
 *
 */
func undefined<T>(hint: String = "", file: StaticString = __FILE__, line: UInt = __LINE__) -> T {
    let message = hint == "" ? "" : ": \(hint)"
    fatalError("undefined \(T.self)\(message)", file:file, line:line)
}


// swift-tools-version:5.0
import PackageDescription

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

Use a static enum rather than string literal for platform version

// swift-tools-version:5.0
import PackageDescription

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


import LlamaKit
import Runes

let AccountLinkedNotificationName = "PoppinsAccountLinked"
let ServiceKey = "PoppinsService"

class LinkManager: LinkableService {
    var service: LinkableService

    var type: Service {
        return service.type
    }

    var client: SyncClient {
        return service.client
    }

    init(service: LinkableService) {
        self.service = service
    }

    func setService(service: LinkableService) {
        self.service = service
    }

    func initiateAuthentication<T>(meta: T) {
        service.initiateAuthentication(meta)
    }

    func finalizeAuthentication(url: NSURL) -> Bool {
        let handled = service.finalizeAuthentication(url)
        if handled {
            NSNotificationCenter.defaultCenter().postNotificationName(AccountLinkedNotificationName, object: .None)
        }
        return handled
    }

    func setup() {
        service.setup()
    }

    func isLinked() -> Bool {
        return service.isLinked()
    }

    func unLink() {
        service.unLink()
    }
}

Send account linked notification only if is linked

import LlamaKit
import Runes

let AccountLinkedNotificationName = "PoppinsAccountLinked"
let ServiceKey = "PoppinsService"

class LinkManager: LinkableService {
    var service: LinkableService

    var type: Service {
        return service.type
    }

    var client: SyncClient {
        return service.client
    }

    init(service: LinkableService) {
        self.service = service
    }

    func setService(service: LinkableService) {
        self.service = service
    }

    func initiateAuthentication<T>(meta: T) {
        service.initiateAuthentication(meta)
    }

    func finalizeAuthentication(url: NSURL) -> Bool {
        let handled = service.finalizeAuthentication(url)
        if handled && isLinked() {
            NSNotificationCenter.defaultCenter().postNotificationName(AccountLinkedNotificationName, object: .None)
        }
        return handled
    }

    func setup() {
        service.setup()
    }

    func isLinked() -> Bool {
        return service.isLinked()
    }

    func unLink() {
        service.unLink()
    }
}


//
//  AppDelegate.swift
//  Sample
//
//  Created by Igor Fereira on 25/01/2016.
//  Copyright © 2016 Future Workshops. All rights reserved.
//

import UIKit
import Keys
import FWTNotifiable

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var notifiableManager:FWTNotifiableManager!

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

        let keys = SampleKeys()
        self.notifiableManager = FWTNotifiableManager(url: "http://fw-notifiable-staging2.herokuapp.com/", accessId: keys.fWTAccessID(), andSecretKey: keys.fWTSecretKey())

        self.getMainViewController()?.manager = self.notifiableManager

        if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject:AnyObject] {
            self.application(application, didReceiveRemoteNotification: remoteNotification)
        }

        return true
    }

    func getMainViewController() -> ViewController?
    {
        guard let navigationController = window?.rootViewController as? UINavigationController else {
            return nil
        }

        if let mainViewController = navigationController.viewControllers[0] as? ViewController {
            return mainViewController
        } else {
            return nil
        }
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        self.notifiableManager.applicationDidReceiveRemoteNotification(userInfo);
    }
}

Change the way that the application finds the main view controller

//
//  AppDelegate.swift
//  Sample
//
//  Created by Igor Fereira on 25/01/2016.
//  Copyright © 2016 Future Workshops. All rights reserved.
//

import UIKit
import Keys
import FWTNotifiable

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var notifiableManager:FWTNotifiableManager!

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

        let keys = SampleKeys()
        self.notifiableManager = FWTNotifiableManager(url: "http://fw-notifiable-staging2.herokuapp.com/", accessId: keys.fWTAccessID(), andSecretKey: keys.fWTSecretKey())

        self.getMainViewController()?.manager = self.notifiableManager

        if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject:AnyObject] {
            self.application(application, didReceiveRemoteNotification: remoteNotification)
        }

        return true
    }

    func getMainViewController() -> ViewController?
    {
        guard let navigationController = window?.rootViewController as? UINavigationController else {
            return nil
        }

        if let mainViewController = navigationController.topViewController as? ViewController {
            return mainViewController
        } else {
            return nil
        }
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        self.notifiableManager.applicationDidReceiveRemoteNotification(userInfo);
    }
}


//
//  OmnibarViewController.swift
//  Caturlog
//
//  Created by Jonathon Rubin on 7/18/14.
//  Copyright (c) 2014 Jonathon Rubin. All rights reserved.
//

import Cocoa

class OmnibarViewController :NSViewController, NSTextFieldDelegate {

    @IBOutlet var omnibar: NSTokenField!
    @IBOutlet var caturlogWindowControler :CaturlogWindowController!

    override func controlTextDidEndEditing(obj: NSNotification!) {
        var textField = obj.object as NSTextField

        if(textField.isEqualTo(omnibar)) {
            let tokenField = textField as NSTokenField
            let tokens = tokenField.objectValue as Array<String>

            caturlogWindowControler.viewModel?.omnibarTokensChanged(tokens)
        }
    }

}

Update continuously upon text input instead of only on return. This way you get live search results. Results of someone typing in a url would be disastrous. Probably need to recode this so URLs and tag associations only get parsed on return while tags also get parsed as typed (for searching).

//
//  OmnibarViewController.swift
//  Caturlog
//
//  Created by Jonathon Rubin on 7/18/14.
//  Copyright (c) 2014 Jonathon Rubin. All rights reserved.
//

import Cocoa

class OmnibarViewController :NSViewController, NSTextFieldDelegate {

    @IBOutlet var omnibar: NSTokenField!
    @IBOutlet var caturlogWindowControler :CaturlogWindowController!

    override func controlTextDidChange(obj: NSNotification!) {
        var textField = obj.object as NSTextField

        if(textField.isEqualTo(omnibar)) {
            let tokenField = textField as NSTokenField
            let tokens = tokenField.objectValue as Array<String>

            caturlogWindowControler.viewModel?.omnibarTokensChanged(tokens)
        }
    }

}


import XCTest
@testable import CommandLine

class CommandLineTests: XCTestCase {

    func testRunCommand() {
        let runExpectation = expectation(description: "Run <ls> to see files in current directory.")

        let commandLine = CommandLine()
        let command = "/usr/bin/env"
        let arguments = [ "ls" ]
        let result = commandLine.execute(command, with: arguments)

        switch result {
        case .output(let output):
            print(output)
            runExpectation.fulfill()
        case .error(let message):
            print("Error: \(message)")
        }
    }

    static var allTests : [(String, (CommandLineTests) -> () throws -> Void)] {
        return [
            ("testRunCommand", testRunCommand)
        ]
    }

}

Reset summarising test dictionary for Linux

import XCTest
@testable import CommandLine

class CommandLineTests: XCTestCase {

    func testRunCommand() {
        let runExpectation = expectation(description: "Run <ls> to see files in current directory.")

        let commandLine = CommandLine()
        let command = "/usr/bin/env"
        let arguments = [ "ls" ]
        let result = commandLine.execute(command, with: arguments)

        switch result {
        case .output(let output):
            print(output)
            runExpectation.fulfill()
        case .error(let message):
            print("Error: \(message)")
        }
    }

    static var allTests : [(String, (CommandLineTests) -> () throws -> Void)] {
        return [
            ("testRunCommand", testRunCommand),
        ]
    }

}


import Foundation

public typealias Id = UUID
public typealias Date = Foundation.Date

public struct ToDo {
    internal let id: Id
    public let title: String
    public let done: Bool
    public let due: Date?
    public let notes: String
    public let tags: [Tag]

    internal init(
        id: Id = Id(),
        title: String,
        done: Bool = false,
        due: Date?,
        notes: String,
        tags: [Tag]
    ) {
        self.id = id
        self.title = title
        self.done = done
        self.due = due
        self.notes = notes
        self.tags = tags
    }

}

public struct Tag {
    public let name: String

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

Tag need no public init

import Foundation

public typealias Id = UUID
public typealias Date = Foundation.Date

public struct ToDo {
    internal let id: Id
    public let title: String
    public let done: Bool
    public let due: Date?
    public let notes: String
    public let tags: [Tag]

    internal init(
        id: Id = Id(),
        title: String,
        done: Bool = false,
        due: Date?,
        notes: String,
        tags: [Tag]
    ) {
        self.id = id
        self.title = title
        self.done = done
        self.due = due
        self.notes = notes
        self.tags = tags
    }

}

public struct Tag {
    public let name: String
}


import Glibc

public class Mutex {

  var id = pthread_mutex_t()

  public init() {
    pthread_mutex_init(&id, nil)
  }

  public func lock() {
    pthread_mutex_lock(&id)
  }

  public func unlock() {
    pthread_mutex_unlock(&id)
  }

}

var registerThreadMutex = Mutex()
var registerThreadCallback: (() -> Void)?

func runPthread(ctx: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> {
  registerThreadCallback!()
  return ctx
}

func createPthread(inout id: UInt, fn: () -> Void) {
  registerThreadMutex.lock()
  registerThreadCallback = fn
  defer {
    registerThreadMutex.unlock()
  }
  pthread_create(&id, nil, runPthread, nil)
}

public class Thread {

  public var threadId = pthread_t()

  // Just a default initializer. Callback can be passed by a later call to #run
  init() { }

  init(fn: () -> Void) {
    run(fn)
  }

  public func run(fn: () -> Void) {
    createPthread(&threadId, fn: fn)
  }

  public func join() {
    pthread_join(threadId, nil)
  }

}

Fix for setting up the Thread callback.

import Glibc

public class Mutex {

  var id = pthread_mutex_t()

  public init() {
    pthread_mutex_init(&id, nil)
  }

  public func lock() {
    pthread_mutex_lock(&id)
  }

  public func unlock() {
    pthread_mutex_unlock(&id)
  }

}

var registerThreadMutex = Mutex()
var threadCallbacks: [pthread_t: () -> Void] = [:]

func runPthread(ctx: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> {
  let id = pthread_self()
  var fn = threadCallbacks[id]
  while fn == nil {
    // Yield to master thread so it can set up the callback for us.
    IO.sleep(0.000000001)
    fn = threadCallbacks[id]
  }
  fn!()
  threadCallbacks[id] = nil
  return ctx
}

func createPthread(inout id: UInt, fn: () -> Void) {
  registerThreadMutex.lock()
  defer {
    registerThreadMutex.unlock()
  }
  pthread_create(&id, nil, runPthread, nil)
  threadCallbacks[id] = fn
}

public class Thread {

  public var threadId = pthread_t()

  // Just a default initializer. Callback can be passed by a later call to #run
  init() { }

  init(fn: () -> Void) {
    run(fn)
  }

  public func run(fn: () -> Void) {
    createPthread(&threadId, fn: fn)
  }

  public func join() {
    pthread_join(threadId, nil)
  }

}


//
//  Check.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 1/19/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

/// The interface to the SwiftCheck testing mechanism. To test a proposition one subscripts into
/// this variable with a description of the property being tested like so:
///
/// property["Integer Equality is Reflexive"] = forAll { (i : Int8) in
///	    return i == i
/// }
///
public var property : QuickCheck = QuickCheck()

public struct QuickCheck {
	public subscript(s : String) -> Testable {
		get {
			fatalError("Proposition '\(s)' has an undefined test case")
		}
		set(test) {
			quickCheck(test, name: s)
		}
	}
}

Add support for asserting properties

//
//  Check.swift
//  SwiftCheck
//
//  Created by Robert Widmann on 1/19/15.
//  Copyright (c) 2015 Robert Widmann. All rights reserved.
//

import XCTest

/// The main interface for the SwiftCheck testing mechanism. To test a program property one
/// subscripts into this variable with a description of the property being tested like so:
///
/// property["Integer Equality is Reflexive"] = forAll { (i : Int8) in
///	    return i == i
/// }
///
public var property : QuickCheck = QuickCheck()

public struct QuickCheck {
	public subscript(s : String) -> Testable {
		get {
			fatalError("Proposition '\(s)' has an undefined test case")
		}
		set(test) {
			quickCheck(test, name: s)
		}
	}
}

/// The main interface for the Assertive SwiftCheck testing mechanism.  Assertive checks test
/// program properties that will fail in XCTest and not just print failures to the console.
public var assertProperty : AssertiveQuickCheck = AssertiveQuickCheck()

public struct AssertiveQuickCheck {
	public subscript(s : String) -> Testable {
		get {
			fatalError("Assertive proposition '\(s)' has an undefined test case")
		}
		set(test) {
			switch quickCheckWithResult(stdArgs(name: s), test) {
			case let .Failure(numTests, numShrinks, usedSeed, usedSize, reason, labels, output):
				XCTFail(reason)
			default:
				return
			}
		}
	}
}


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

// Round NSTimeInterval to seconds and milliseconds double

import Foundation
import UIKit

let cal = Calendar.current
let dateComponents = NSDateComponents()
dateComponents.day = 1
let tomorrow = cal.nextDate(after: Date(), matchingHour: 0, minute: 1, second: 0, options: .matchNextTime)

Add snippets for showing alert from error

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

// Round NSTimeInterval to seconds and milliseconds double

import Foundation
import UIKit

let cal = Calendar.current
let date = Date()
let morning = cal.startOfDay(for: date as Date)

// Show Alert
let error = NSError.init(coder: NSCoder()
let alert = UIAlertController(title: error?.localizedDescription, message: error?.localizedFailureReason, preferredStyle: .Alert)
let ok = UIAlertAction(title: NSLocalizedString("OK", comment: "alert button"), style: .Default, handler: nil)
alert.addAction(ok)
self.presentViewController(alert, animated: true, completion: nil)

// Main

dispatch_async(dispatch_get_main_queue(),{
    // Code...
})


// RUN: %swiftc_driver_plain -target %target-triple -module-cache-path %t -typecheck -Xfrontend -verify %s

// This test should be updated to match the expected default Swift version
// when swiftc is invoked directly.
// It should /not/ follow the version specified when invoking lit, which means
// it can't use the %swiftc_driver or %target-build-swift substitutions.

#if swift(>=3)
asdf // expected-error {{use of unresolved identifier}}
#else
jkl
#endif

#if swift(>=3.1)
asdf // expected-error {{use of unresolved identifier}}
#else
jkl
#endif

#if swift(>=4)
aoeu
#else
htn // expected-error {{use of unresolved identifier}}
#endif

#if swift(>=4.1)
aoeu
#else
htn // expected-error {{use of unresolved identifier}}
#endif

#if swift(>=5)
aoeu
#else
htn // expected-error {{use of unresolved identifier}}
#endif

Update test to reflect new default is -swift-version 4.

// RUN: %swiftc_driver_plain -target %target-triple -module-cache-path %t -typecheck -Xfrontend -verify %s

// This test should be updated to match the expected default Swift version
// when swiftc is invoked directly.
// It should /not/ follow the version specified when invoking lit, which means
// it can't use the %swiftc_driver or %target-build-swift substitutions.

#if swift(>=3)
asdf // expected-error {{use of unresolved identifier}}
#else
jkl
#endif

#if swift(>=3.1)
asdf // expected-error {{use of unresolved identifier}}
#else
jkl
#endif

#if swift(>=4)
aoeu // expected-error {{use of unresolved identifier}}
#else
htn
#endif

#if swift(>=4.1)
aoeu
#else
htn // expected-error {{use of unresolved identifier}}
#endif

#if swift(>=5)
aoeu
#else
htn // expected-error {{use of unresolved identifier}}
#endif


//
//  NSString+IDNA.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-18.
//

import Foundation

@objc public extension NSString {
	@objc(IDNAEncodedString) var idnaEncoded: String? { (self as String).idnaEncoded }
	@objc(IDNADecodedString) var idnaDecoded: String? { (self as String).idnaDecoded }
	var encodedURLString: String? { (self as String).encodedURLString}
	var decodedURLString: String? { (self as String).encodedURLString }
}

@objc public extension NSURL {
	@objc(URLWithUnicodeString:) static func urlWithUnicodeString(_ unicodeString: String) -> URL? {
		return URL(unicodeString: unicodeString)
	}

	var decodedURLString: String? {
		return (self as URL).decodedURLString
	}

	@objc(URLWithUnicodeString:relativeToURL:) static func urlWithUnicodeString(_ unicodeString: String, relativeTo url: URL) -> URL? {
		return URL(unicodeString: unicodeString, relativeTo: url)
	}
}

Fix decodedURLString in the NSString overlay

//
//  NSString+IDNA.swift
//  PunyCocoa Swift
//
//  Created by Nate Weaver on 2020-04-18.
//

import Foundation

@objc public extension NSString {
	@objc(IDNAEncodedString) var idnaEncoded: String? { (self as String).idnaEncoded }
	@objc(IDNADecodedString) var idnaDecoded: String? { (self as String).idnaDecoded }
	var encodedURLString: String? { (self as String).encodedURLString }
	var decodedURLString: String? { (self as String).decodedURLString }
}

@objc public extension NSURL {
	@objc(URLWithUnicodeString:) static func urlWithUnicodeString(_ unicodeString: String) -> URL? {
		return URL(unicodeString: unicodeString)
	}

	var decodedURLString: String? {
		return (self as URL).decodedURLString
	}

	@objc(URLWithUnicodeString:relativeToURL:) static func urlWithUnicodeString(_ unicodeString: String, relativeTo url: URL) -> URL? {
		return URL(unicodeString: unicodeString, relativeTo: url)
	}
}


// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=scudo -o %t_scudo-binary
// RUN: not %target-run %t_scudo-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: OS=linux-gnu
// REQUIRES: scudo_runtime

let allocated = UnsafeMutableRawPointer.allocate(byteCount: 128, alignment: 1)
allocated.deallocate()
allocated.deallocate()

// CHECK: ERROR: invalid chunk state

Enhance Scudo test to tolerate GWP-Asan.

// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=scudo -o %t_scudo-binary
// RUN: not %target-run %t_scudo-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: OS=linux-gnu
// REQUIRES: scudo_runtime

let allocated = UnsafeMutableRawPointer.allocate(byteCount: 128, alignment: 1)
allocated.deallocate()
allocated.deallocate()

// CHECK: {{ERROR: invalid chunk state|\*\*\* GWP-ASan detected a memory error \*\*\*}}


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

import Foundation

class JobList: CustomStringConvertible{

    var jobs: [Job] = []

    init(data: Any) throws{
        guard let json = data as? [String: AnyObject]
            else { throw ParsingError.DataNotCorrectFormatError }
        guard let jsonJobs = json["jobs"] as? [[String: AnyObject]]
            else{ throw ParsingError.KeyMissingError(key: "jobs") }

        for jsonJob in jsonJobs{
            if let job = Job(json: jsonJob, minimalVersion: true){
                jobs.append(job)
            }
        }
    }

    var description: String{
        return "{\n" + jobs.reduce("", { (result, job) -> String in
            return "\(result) Name: \(job.name), Description: \(job.description) \n"
        }) + "}"
    }
}

Configure the job list to take in views

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

import Foundation

class JobList: CustomStringConvertible{

    var jobs: [Job] = []
    var views: [View]?

    //FIXME: Init with different tree
    init(data: Any) throws{
        guard let json = data as? [String: AnyObject]
            else { throw ParsingError.DataNotCorrectFormatError }
        guard let jsonJobs = json["jobs"] as? [[String: AnyObject]]
            else{ throw ParsingError.KeyMissingError(key: "jobs") }

        for jsonJob in jsonJobs{
            if let job = Job(json: jsonJob, minimalVersion: true){
                jobs.append(job)
            }
        }

        if let jsonViews = json["views"] as? [[String: AnyObject]]{
            views = []
            for jsonView in jsonViews{
                if let view = View(json: jsonView){
                    views?.append(view)
                }
            }
        }
    }

    var description: String{
        return "{\n" + jobs.reduce("", { (result, job) -> String in
            return "\(result) Name: \(job.name), Description: \(job.description) \n"
        }) + (views?.reduce("Views: ", { (result, view) -> String in
            return "\(result)\(view)\n"
        }) ?? "No views") + "}"
    }
}


import Foundation

/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {

    /// Returns a value that can be stored in the database.
    public var databaseValue: DatabaseValue {
        var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
        return uuidBytes.withUnsafeMutableBufferPointer { buffer in
            getBytes(buffer.baseAddress)
            return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
        }
    }

    /// Returns an NSUUID initialized from *dbValue*, if possible.
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
        guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
            return nil
        }
        return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
    }
}

/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }

Fix compilation with Xcode 9 in compatibilty mode

import Foundation

/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {

    /// Returns a value that can be stored in the database.
    public var databaseValue: DatabaseValue {
        var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
        return uuidBytes.withUnsafeMutableBufferPointer { buffer in
            getBytes(buffer.baseAddress!)
            return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
        }
    }

    /// Returns an NSUUID initialized from *dbValue*, if possible.
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
        guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
            return nil
        }
        return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
    }
}

/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }


// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "StringScanner"
)

Add explicit target to package manifest

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "StringScanner",
    targets: [
        .target(
            name: "StringScanner",
            path: "Sources")
    ]
)


//
//  Libgit2.swift
//  SwiftGit2
//
//  Created by Matt Diephouse on 1/11/15.
//  Copyright (c) 2015 GitHub, Inc. All rights reserved.
//

import libgit2

func == (lhs: git_otype, rhs: git_otype) -> Bool {
	return lhs.rawValue == rhs.rawValue
}

extension git_strarray {
	func filter(_ isIncluded: (String) -> Bool) -> [String] {
		return map { $0 }.filter(isIncluded)
	}

	func map<T>(_ transform: (String) -> T) -> [T] {
		return (0..<self.count).map {
			let string = String(validatingUTF8: self.strings[$0]!)!
			return transform(string)
		}
	}
}

Use default == implementation for git_otype

//
//  Libgit2.swift
//  SwiftGit2
//
//  Created by Matt Diephouse on 1/11/15.
//  Copyright (c) 2015 GitHub, Inc. All rights reserved.
//

import libgit2

extension git_strarray {
	func filter(_ isIncluded: (String) -> Bool) -> [String] {
		return map { $0 }.filter(isIncluded)
	}

	func map<T>(_ transform: (String) -> T) -> [T] {
		return (0..<self.count).map {
			let string = String(validatingUTF8: self.strings[$0]!)!
			return transform(string)
		}
	}
}


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

public enum AnnotatedTerm<Annotation>: TermContainerType {
	indirect case Unroll(Annotation, Scoping<AnnotatedTerm>)

	public var annotation: Annotation {
		get {
			return destructure.0
		}
		set {
			self = .Unroll(newValue, out)
		}
	}

	public var destructure: (Annotation, Scoping<AnnotatedTerm>) {
		switch self {
		case let .Unroll(all):
			return all
		}
	}

	// MARK: TermContainerType

	public var out: Scoping<AnnotatedTerm> {
		return destructure.1
	}

	public var freeVariables: Set<Name> {
		return []
	}
}

public func == <Annotation: Equatable> (left: AnnotatedTerm<Annotation>, right: AnnotatedTerm<Annotation>) -> Bool {
	return left.annotation == right.annotation && Scoping.equal(==)(left.out, right.out)
}

Correct the set of free variables in annotated terms.

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

public enum AnnotatedTerm<Annotation>: TermContainerType {
	indirect case Unroll(Annotation, Scoping<AnnotatedTerm>)

	public var annotation: Annotation {
		get {
			return destructure.0
		}
		set {
			self = .Unroll(newValue, out)
		}
	}

	public var destructure: (Annotation, Scoping<AnnotatedTerm>) {
		switch self {
		case let .Unroll(all):
			return all
		}
	}

	// MARK: TermContainerType

	public var out: Scoping<AnnotatedTerm> {
		return destructure.1
	}

	public var freeVariables: Set<Name> {
		switch out {
		case let .Identity(expression):
			return expression.foldMap { $0.freeVariables }
		case let .Variable(name):
			return [ name ]
		case let .Abstraction(name, scope):
			return scope.freeVariables.subtract([ name ])
		}
	}
}

public func == <Annotation: Equatable> (left: AnnotatedTerm<Annotation>, right: AnnotatedTerm<Annotation>) -> Bool {
	return left.annotation == right.annotation && Scoping.equal(==)(left.out, right.out)
}


import UIKit
import DATAStack
import Sync

class Networking {
    let AppNetURL = "https://api.app.net/posts/stream/global"
    let dataStack: DATAStack

    required init(dataStack: DATAStack) {
        self.dataStack = dataStack
    }

    func fetchItems(completion: (NSError?) -> Void) {

        if let urlAppNet = NSURL(string: AppNetURL) {
            let request = NSURLRequest(URL: urlAppNet)
            let operationQueue = NSOperationQueue()

            NSURLConnection.sendAsynchronousRequest(request, queue: operationQueue) { [unowned self] _, data, error in
                if let data = data, json = (try? NSJSONSerialization.JSONObjectWithData(data,
                    options: NSJSONReadingOptions.MutableContainers)) as? Dictionary<String, AnyObject> {
                        Sync.changes(json["data"] as! Array,
                            inEntityNamed: "Data",
                            dataStack: self.dataStack,
                            completion: { error in
                                completion(error)
                        })
                } else {
                    completion(error)
                }
            }
        }
    }
}

Use NSURLSession instead of NSURLConnection

import UIKit
import DATAStack
import Sync

class Networking {
    let AppNetURL = "https://api.app.net/posts/stream/global"
    let dataStack: DATAStack

    required init(dataStack: DATAStack) {
        self.dataStack = dataStack
    }

    func fetchItems(completion: (NSError?) -> Void) {
        let session = NSURLSession.sharedSession()
        let request = NSURLRequest(URL: NSURL(string: AppNetURL)!)
        session.dataTaskWithRequest(request, completionHandler: { data, response, error in
            if let data = data, json = (try? NSJSONSerialization.JSONObjectWithData(data, options: [])) as? [String: AnyObject] {
                Sync.changes(json["data"] as! Array,
                    inEntityNamed: "Data",
                    dataStack: self.dataStack,
                    completion: { error in
                        completion(error)
                })
            } else {
                completion(error)
            }
        }).resume()
    }
}


//
//  RxTests.swift
//  ReSwiftRx
//
//  Created by Charlotte Tortorella on 25/11/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

@testable import ReSwiftRx
import XCTest

class RxTests: XCTestCase {

    func testObservablePropertySendsNewValues() {
        let property = ObservableProperty(10)
        XCTAssertEqual(property.value, 10)
        property.value = 20
        XCTAssertEqual(property.value, 20)
        property.value = 30
        XCTAssertEqual(property.value, 30)
    }

    func testObservablePropertyDisposesOfReferences() {
        let property = ObservableProperty(())
        let reference = property.subscribe({})
        XCTAssertEqual(property.subscriptions.count, 1)
        reference?.dispose()
        XCTAssertEqual(property.subscriptions.count, 0)
    }

    func testSubscriptionBagDisposesOfReferences() {
        let property = ObservableProperty(())
        let bag = SubscriptionReferenceBag()
        bag += property.subscribe({})
        bag += property.subscribe({})
        XCTAssertEqual(property.subscriptions.count, 2)
        bag.dispose()
        XCTAssertEqual(property.subscriptions.count, 0)
    }

    func testThatDisposingOfAReferenceTwiceIsOkay() {
        let property = ObservableProperty(())
        let reference = property.subscribe({})
        reference?.dispose()
        reference?.dispose()
    }

}

Edit tests to prove that the current value is sent on subscription

//
//  RxTests.swift
//  ReSwiftRx
//
//  Created by Charlotte Tortorella on 25/11/16.
//  Copyright © 2016 Benjamin Encz. All rights reserved.
//

@testable import ReSwiftRx
import XCTest

class RxTests: XCTestCase {

    func testObservablePropertySendsNewValues() {
        let values = (10, 20, 30)
        var receivedValue: Int?
        let property = ObservableProperty(values.0)
        property.subscribe {
            receivedValue = $0
        }
        XCTAssertEqual(receivedValue, values.0)
        property.value = values.1
        XCTAssertEqual(receivedValue, values.1)
        property.value = values.2
        XCTAssertEqual(receivedValue, values.2)
    }

    func testObservablePropertyDisposesOfReferences() {
        let property = ObservableProperty(())
        let reference = property.subscribe({})
        XCTAssertEqual(property.subscriptions.count, 1)
        reference?.dispose()
        XCTAssertEqual(property.subscriptions.count, 0)
    }

    func testSubscriptionBagDisposesOfReferences() {
        let property = ObservableProperty(())
        let bag = SubscriptionReferenceBag()
        bag += property.subscribe({})
        bag += property.subscribe({})
        XCTAssertEqual(property.subscriptions.count, 2)
        bag.dispose()
        XCTAssertEqual(property.subscriptions.count, 0)
    }

    func testThatDisposingOfAReferenceTwiceIsOkay() {
        let property = ObservableProperty(())
        let reference = property.subscribe({})
        reference?.dispose()
        reference?.dispose()
    }

}


import UIKit

extension UIViewController {
    // Adds a peekable view controller on top of another view controller. Since the view controller is the one we want to show when the user peeks through, we're saving time by loading it behind the peekable view controller.
    @objc func wmf_setupPeekable(_ peekableViewController: UIViewController, on viewController: UIViewController, with articleURL: URL) -> UIViewController {
        viewController.addChildViewController(peekableViewController)
        peekableViewController.view.frame = viewController.view.frame
        viewController.view.wmf_addSubviewWithConstraintsToEdges(peekableViewController.view)
        peekableViewController.didMove(toParentViewController: viewController)
        return viewController
    }

    @objc func wmf_removePeekable(_ peekableViewController: UIViewController, from viewController: UIViewController) {
        peekableViewController.view.removeFromSuperview()
        peekableViewController.removeFromParentViewController()
    }
}

Add a func to set up Peekable with self

import UIKit

extension UIViewController {
    // Adds a peekable view controller on top of another view controller. Since the view controller is the one we want to show when the user peeks through, we're saving time by loading it behind the peekable view controller.
    @objc func wmf_setupPeekable(_ peekableViewController: UIViewController, with articleURL: URL) -> UIViewController {
        self.addChildViewController(peekableViewController)
        peekableViewController.view.frame = self.view.frame
        self.view.wmf_addSubviewWithConstraintsToEdges(peekableViewController.view)
        peekableViewController.didMove(toParentViewController: self)
        return self
    }

    @objc func wmf_setupPeekable(_ peekableViewController: UIViewController, on viewController: UIViewController, with articleURL: URL) -> UIViewController {
        viewController.addChildViewController(peekableViewController)
        peekableViewController.view.frame = viewController.view.frame
        viewController.view.wmf_addSubviewWithConstraintsToEdges(peekableViewController.view)
        peekableViewController.didMove(toParentViewController: viewController)
        return viewController
    }

    @objc func wmf_removePeekable(_ peekableViewController: UIViewController) {
        peekableViewController.view.removeFromSuperview()
        peekableViewController.removeFromParentViewController()
    }
}


// RUN: %target-swift-frontend -typecheck -verify %S/Inputs/keypath.swift -primary-file %s -swift-version 5

struct S {
  let i: Int

  init() {
    let _: WritableKeyPath<S, Int> = \.i // expected-error {{type of expression is ambiguous without more context}}
  }
}

func test() {
  let _: WritableKeyPath<C, Int> = \.i // expected-error {{type of expression is ambiguous without more context}}
}

Add keypath write test for -swift-version 5.

// RUN: %target-swift-frontend -typecheck -verify %S/Inputs/keypath.swift -primary-file %s -swift-version 5

struct S {
  let i: Int

  init() {
    let _: WritableKeyPath<S, Int> = \.i // expected-error {{type of expression is ambiguous without more context}}

    S()[keyPath: \.i] = 1
    // expected-error@-1 {{cannot assign to immutable expression}}
  }
}

func test() {
  let _: WritableKeyPath<C, Int> = \.i // expected-error {{type of expression is ambiguous without more context}}

  C()[keyPath: \.i] = 1
  // expected-error@-1 {{cannot assign to immutable expression}}

  let _ = C()[keyPath: \.i] // no warning for a read
}


import Foundation

extension DPlan
{
    //MARK: private

    private func reconnectOrigin(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {
        guard

            let previousStop:DPlanStop = stop.originTravel?.origin

        else
        {
            reconnectDestination(
                database:database,
                stop:stop,
                completion:completion)

            return
        }

        database.create
        { [weak self] (travel:DPlanTravel) in

            self?.newOrigin(
                database:database,
                stop:stop,
                origin:previousStop,
                travel:travel,
                completion:completion)
        }
    }

    private func reconnectDestination(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {

    }

    private func newOrigin(
        database:Database,
        stop:DPlanStop,
        origin:DPlanStop,
        travel:DPlanTravel,
        completion:@escaping(() -> ()))
    {
        travel.origin = origin
        travel.destination = stop

        if let travelMode:DPlanTravelMode = stop.originTravel?.mode
        {
            travel.mode = travelMode
        }

        reconnectDestination(
            database:database,
            stop:stop,
            completion:completion)
    }

    //MARK: internal

    func disconnect(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {
        stop.plan = nil

        reconnectOrigin(
            database:database,
            stop:stop,
            completion:completion)
    }
}

Change travel origin to destination

import Foundation

extension DPlan
{
    //MARK: private

    private func reconnectOrigin(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {
        guard

            let previousStop:DPlanStop = stop.destinationTravel?.origin

        else
        {
            reconnectDestination(
                database:database,
                stop:stop,
                completion:completion)

            return
        }

        database.create
        { [weak self] (travel:DPlanTravel) in

            self?.newOrigin(
                database:database,
                stop:stop,
                origin:previousStop,
                travel:travel,
                completion:completion)
        }
    }

    private func reconnectDestination(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {

    }

    private func newOrigin(
        database:Database,
        stop:DPlanStop,
        origin:DPlanStop,
        travel:DPlanTravel,
        completion:@escaping(() -> ()))
    {
        travel.origin = origin
        travel.destination = stop

        if let travelMode:DPlanTravelMode = stop.originTravel?.mode
        {
            travel.mode = travelMode
        }

        reconnectDestination(
            database:database,
            stop:stop,
            completion:completion)
    }

    //MARK: internal

    func disconnect(
        database:Database,
        stop:DPlanStop,
        completion:@escaping(() -> ()))
    {
        stop.plan = nil

        reconnectOrigin(
            database:database,
            stop:stop,
            completion:completion)
    }
}