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

import XCTest
import Set

final class MultisetSequenceTests: XCTestCase {
	func testGeneratorProducesEveryElement() {
		var multiset = Multiset<Int>()
		multiset.insert(0)
		multiset.insert(1)
		multiset.insert(2)
		XCTAssertEqual(sorted(map(multiset) { $0 }), [ 0, 1, 2 ])
	}

	func testGeneratorProducesElementsByMultiplicity() {
		var multiset = Multiset<Int>()
		multiset.insert(1)
		multiset.insert(1)
		multiset.insert(1)
		multiset.insert(2)
		multiset.insert(2)
		multiset.insert(3)
		XCTAssertEqual(reduce(multiset, 0, +), 10)
	}
}

Use the Array constructor instead of map.

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

import XCTest
import Set

final class MultisetSequenceTests: XCTestCase {
	func testGeneratorProducesEveryElement() {
		var multiset = Multiset<Int>()
		multiset.insert(0)
		multiset.insert(1)
		multiset.insert(2)
		XCTAssertEqual(sorted(Array(multiset)), [ 0, 1, 2 ])
	}

	func testGeneratorProducesElementsByMultiplicity() {
		var multiset = Multiset<Int>()
		multiset.insert(1)
		multiset.insert(1)
		multiset.insert(1)
		multiset.insert(2)
		multiset.insert(2)
		multiset.insert(3)
		XCTAssertEqual(reduce(multiset, 0, +), 10)
	}
}


//
//  MoreCommentCellView.swift
//  Breadit
//
//  Created by William Hester on 4/30/16.
//  Copyright © 2016 William Hester. All rights reserved.
//

import UIKit

class MoreCommentCellView: CommentCellView {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.uiLabel { v in
            v.text = "Load more comments..."
            v.fontSize = 12
            v.textColor = Colors.secondaryTextColor
        }.constrain { v in
            self.paddingConstraint = v.leftAnchor.constraintEqualToAnchor(self.contentView.leftAnchor)
            self.paddingConstraint.active = true
            v.rightAnchor.constraintEqualToAnchor(self.contentView.rightAnchor).active = true
            self.contentView.heightAnchor.constraintEqualToAnchor(v.heightAnchor, constant: 16).active = true
        }
    }

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

Remove padding from 'Load more comments' cells

//
//  MoreCommentCellView.swift
//  Breadit
//
//  Created by William Hester on 4/30/16.
//  Copyright © 2016 William Hester. All rights reserved.
//

import UIKit

class MoreCommentCellView: CommentCellView {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.uiLabel { v in
            v.text = "Load more comments..."
            v.fontSize = 12
            v.textColor = Colors.secondaryTextColor
        }.constrain { v in
            self.paddingConstraint = v.leftAnchor.constraintEqualToAnchor(self.contentView.leftAnchor)
            self.paddingConstraint.active = true
            v.rightAnchor.constraintEqualToAnchor(self.contentView.rightAnchor).active = true
            self.contentView.heightAnchor.constraintEqualToAnchor(v.heightAnchor).active = true
            self.heightAnchor.constraintEqualToAnchor(self.contentView.heightAnchor).active = true
            self.contentView.translatesAutoresizingMaskIntoConstraints = false
        }
    }

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


//
//  ReactiveCocoa+Additions.swift
//  MantleData
//
//  Created by Anders on 24/4/2016.
//  Copyright © 2016 Anders. All rights reserved.
//

import ReactiveCocoa

extension PropertyType {
	public func map<T>(transform: Value -> T) -> AnyProperty<T> {
		return AnyProperty<T>(initialValue: transform(value),
		                   producer: producer.map(transform))
	}
}

extension Observer {
	public func sendCompleted(with finalValue: Value) {
		sendNext(finalValue)
		sendCompleted()
	}
}

Remove `map(_:)` which has been implemented in RAC.

//
//  ReactiveCocoa+Additions.swift
//  MantleData
//
//  Created by Anders on 24/4/2016.
//  Copyright © 2016 Anders. All rights reserved.
//

import ReactiveCocoa

extension Observer {
	public func sendCompleted(with finalValue: Value) {
		sendNext(finalValue)
		sendCompleted()
	}
}


import Foundation

extension UIButton {
    fileprivate func wmf_configureForDynamicType(){
        if #available(iOS 10.0, *) {
            self.titleLabel!.adjustsFontForContentSizeCategory = true
            self.titleLabel!.textAlignment = .center
            self.titleLabel!.numberOfLines = 1
            self.titleLabel!.clipsToBounds = false
            self.titleLabel!.lineBreakMode = .byTruncatingTail
            self.titleLabel!.minimumScaleFactor = 0.25
            self.titleLabel!.adjustsFontSizeToFitWidth = true
        }
    }
}

extension UILabel {
    fileprivate func wmf_configureForDynamicType(){
        if #available(iOS 10.0, *) {
            self.adjustsFontForContentSizeCategory = true
        }
    }
}

extension UIView {
    func wmf_configureSubviewsForDynamicType() {
        if #available(iOS 10.0, *) {
            if self.isKind(of: UIButton.self) {
                (self as! UIButton).wmf_configureForDynamicType()
            }else if self.isKind(of: UILabel.self) {
                (self as! UILabel).wmf_configureForDynamicType()
            }
            for subview in self.subviews {
                subview.wmf_configureSubviewsForDynamicType()
            }
        }
    }
}

Update "wmf_configureSubviewsForDynamicType()" to handle UITextField.

import Foundation

extension UIButton {
    fileprivate func wmf_configureForDynamicType(){
        if #available(iOS 10.0, *) {
            self.titleLabel!.adjustsFontForContentSizeCategory = true
            self.titleLabel!.textAlignment = .center
            self.titleLabel!.numberOfLines = 1
            self.titleLabel!.clipsToBounds = false
            self.titleLabel!.lineBreakMode = .byTruncatingTail
            self.titleLabel!.minimumScaleFactor = 0.25
            self.titleLabel!.adjustsFontSizeToFitWidth = true
        }
    }
}

extension UILabel {
    fileprivate func wmf_configureForDynamicType(){
        if #available(iOS 10.0, *) {
            self.adjustsFontForContentSizeCategory = true
        }
    }
}

extension UITextField {
    fileprivate func wmf_configureForDynamicType(){
        if #available(iOS 10.0, *) {
            self.adjustsFontForContentSizeCategory = true
        }
    }
}

extension UIView {
    func wmf_configureSubviewsForDynamicType() {
        if #available(iOS 10.0, *) {
            if self.isKind(of: UIButton.self) {
                (self as! UIButton).wmf_configureForDynamicType()
            }else if self.isKind(of: UILabel.self) {
                (self as! UILabel).wmf_configureForDynamicType()
            }else if self.isKind(of: UITextField.self) {
                (self as! UITextField).wmf_configureForDynamicType()
            }
            for subview in self.subviews {
                subview.wmf_configureSubviewsForDynamicType()
            }
        }
    }
}


//
//  RangeReplaceableCollectionType+Extensions.swift
//  SwiftySwift
//
//  Created by Agustin De Cabrera on 5/18/16.
//  Copyright © 2016 Agustín de Cabrera. All rights reserved.
//

// MARK: - RangeReplaceableCollectionType

extension RangeReplaceableCollection {
    mutating public func remove(where predicate: (Iterator.Element) -> Bool) -> Iterator.Element? {
        return index(where: predicate).map { remove(at: $0) }
    }
}

extension RangeReplaceableCollection where Iterator.Element : Equatable {
    mutating public func remove(_ element: Iterator.Element) -> Iterator.Element? {
        return index(of: element).map { remove(at: $0) }
    }
}

Mark mutating methods as 'discardableResult'.

//
//  RangeReplaceableCollectionType+Extensions.swift
//  SwiftySwift
//
//  Created by Agustin De Cabrera on 5/18/16.
//  Copyright © 2016 Agustín de Cabrera. All rights reserved.
//

// MARK: - RangeReplaceableCollectionType

extension RangeReplaceableCollection {
    @discardableResult
    mutating public func remove(where predicate: (Iterator.Element) -> Bool) -> Iterator.Element? {
        return index(where: predicate).map { remove(at: $0) }
    }
}

extension RangeReplaceableCollection where Iterator.Element : Equatable {
    @discardableResult
    mutating public func remove(_ element: Iterator.Element) -> Iterator.Element? {
        return index(of: element).map { remove(at: $0) }
    }
}


/**
	Copyright (C) 2017 Quentin Mathe

	Author:  Quentin Mathe <quentin.mathe@gmail.com>
	Date:  June 2017
	License:  MIT
 */

import Foundation
import Dispatch

extension Stream {

	open func delay(_ seconds: TimeInterval) -> Stream<T> {
		let stream = Stream()

		_ = subscribe(stream) { event in
			switch event {
			case .error(_):
				stream.append(event)
			default:
				stream.queue.asyncAfter(deadline: .now() + seconds) {
					stream.append(event)
				}
			}
		}
		return stream
	}
}

Implement Map, Filter and Run operators

/**
	Copyright (C) 2017 Quentin Mathe

	Author:  Quentin Mathe <quentin.mathe@gmail.com>
	Date:  June 2017
	License:  MIT
 */

import Foundation
import Dispatch

extension Stream {

	public func map<V>(_ transform: @escaping (T) throws -> V) rethrows -> Stream<V> {
		let stream = Stream<V>()

		_ = subscribe(stream) { event in
			switch event {
			case .value(let value):
				if let mappedValue = try? transform(value) {
					stream.append(Stream<V>.Event<V>.value(mappedValue))
				}
			case .error(let error):
				stream.append(Stream<V>.Event<V>.error(error))
			case .completed:
				stream.append(Stream<V>.Event<V>.completed)
			}
		}
		return stream
	}

	open func filter(_ isIncluded: @escaping (T) throws -> Bool) rethrows -> Stream<T> {
		let stream = Stream()

		_ = subscribe(stream) { event in
			switch event {
			case .value(let value):
				if (try? isIncluded(value)) ?? false {
					stream.append(event)
				}
			default:
				stream.append(event)
			}
		}
		return stream
	}

	open func delay(_ seconds: TimeInterval) -> Stream<T> {
		let stream = Stream()

		_ = subscribe(stream) { event in
			switch event {
			case .error(_):
				stream.append(event)
			default:
				stream.queue.asyncAfter(deadline: .now() + seconds) {
					stream.append(event)
				}
			}
		}
		return stream
	}

	// NOTE: An alternative name could be switch(to queue).
	open func run(in queue: DispatchQueue) -> Stream<T> {
		let stream = Stream(queue: queue)

		_ = subscribe(stream) { event in
			stream.append(event)
		}
		return stream
	}
}


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

import Foundation

let ptr = UnsafeMutablePointer<UInt8>.init(allocatingCapacity: 10)
print(ptr)  // breakpoint
ptr[11] = 42

print("done")

Update this test for SE-0107.

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

import Foundation

let ptr = UnsafeMutablePointer<UInt8>.allocate(capacity: 10)
print(ptr)  // breakpoint
ptr[11] = 42

print("done")


//
//  SECGraphicStyle.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 11/02/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

public protocol SECGraphicStyle : SECShadowable {
    var fill: SECColor? { get set }
    var stroke: SECColor? { get set }
    var lineWidth: Float? { get set }
}

public struct SECCommonGraphicStyle : SECGraphicStyle {
    public var fill: SECColor?
    public var stroke: SECColor?
    public var lineWidth: Float?
    public var shadowBlur: Float?
    public var shadowOffsetX: Float?
    public var shadowOffsetY: Float?
    public var shadowColor: SECColor?
}

Make `SECCommonGraphicStyle` conform to `SECEnumable` an `SECMappable`

//
//  SECGraphicStyle.swift
//  SwiftyEcharts
//
//  Created by Pluto Y on 11/02/2017.
//  Copyright © 2017 com.pluto-y. All rights reserved.
//

public protocol SECGraphicStyle : SECShadowable {
    var fill: SECColor? { get set }
    var stroke: SECColor? { get set }
    var lineWidth: Float? { get set }
}

public struct SECCommonGraphicStyle : SECGraphicStyle {
    public var fill: SECColor?
    public var stroke: SECColor?
    public var lineWidth: Float?
    public var shadowBlur: Float?
    public var shadowOffsetX: Float?
    public var shadowOffsetY: Float?
    public var shadowColor: SECColor?

    public init() {}
}

extension SECCommonGraphicStyle : SECEnumable {
    public enum Enums {
        case fill(SECColor), stroke(SECColor), lineWidth(Float), shadowBlur(Float), shadowOffsetX(Float), shadowOffsetY(Float), shadowColor(SECColor)
    }

    public typealias ContentEnum = Enums

    public init(_ elements: Enums...) {
        for ele in elements {
            switch ele {
            case let .fill(fill):
                self.fill = fill
            case let .stroke(stroke):
                self.stroke = stroke
            case let .lineWidth(lineWidth):
                self.lineWidth = lineWidth
            case let .shadowBlur(shadowBlur):
                self.shadowBlur = shadowBlur
            case let .shadowOffsetX(shadowOffsetX):
                self.shadowOffsetX = shadowOffsetX
            case let .shadowOffsetY(shadowOffsetY):
                self.shadowOffsetY = shadowOffsetY
            case let .shadowColor(shadowColor):
                self.shadowColor = shadowColor
            }
        }
    }
}

extension SECCommonGraphicStyle : SECMappable {
    public func mapping(map: SECMap) {
        map["fill"] = fill
        map["stroke"] = stroke
        map["lineWidth"] = lineWidth
        map["shadowBlur"] = shadowBlur
        map["shadowOffsetX"] = shadowOffsetX
        map["shadowOffsetY"] = shadowOffsetY
        map["shadowColor"] = shadowColor
    }
}


import Alamofire

/// These functions are default mappings to `MoyaProvider`'s properties: endpoints, requests, manager, etc.
public extension MoyaProvider {
    public final class func defaultEndpointMapping(for target: Target) -> Endpoint<Target> {
        let url = target.baseURL.appendingPathComponent(target.path).absoluteString
        return Endpoint(
            url: url,
            sampleResponseClosure: { .networkResponse(200, target.sampleData) },
            method: target.method,
            parameters: target.parameters,
            parameterEncoding: target.parameterEncoding
        )
    }

    public final class func defaultRequestMapping(for endpoint: Endpoint<Target>, closure: RequestResultClosure) {
        if let urlRequest = endpoint.urlRequest {
            closure(.success(urlRequest))
        } else {
            closure(.failure(Error.requestMapping(endpoint.url)))
        }
    }

    public final class func defaultAlamofireManager() -> Manager {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders

        let manager = Manager(configuration: configuration)
        manager.startRequestsImmediately = false
        return manager
    }
}

Add Foundation import to fix SPM build error.

import Foundation
import Alamofire

/// These functions are default mappings to `MoyaProvider`'s properties: endpoints, requests, manager, etc.
public extension MoyaProvider {
    public final class func defaultEndpointMapping(for target: Target) -> Endpoint<Target> {
        let url = target.baseURL.appendingPathComponent(target.path).absoluteString
        return Endpoint(
            url: url,
            sampleResponseClosure: { .networkResponse(200, target.sampleData) },
            method: target.method,
            parameters: target.parameters,
            parameterEncoding: target.parameterEncoding
        )
    }

    public final class func defaultRequestMapping(for endpoint: Endpoint<Target>, closure: RequestResultClosure) {
        if let urlRequest = endpoint.urlRequest {
            closure(.success(urlRequest))
        } else {
            closure(.failure(Error.requestMapping(endpoint.url)))
        }
    }

    public final class func defaultAlamofireManager() -> Manager {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders

        let manager = Manager(configuration: configuration)
        manager.startRequestsImmediately = false
        return manager
    }
}


//
//  ViewController.swift
//  ImageScrollViewDemo
//
//  Created by Nguyen Cong Huy on 3/5/16.
//  Copyright © 2016 Nguyen Cong Huy. All rights reserved.
//

import UIKit
import ImageScrollView

class ViewController: UIViewController {

    @IBOutlet weak var imageScrollView: ImageScrollView!
    var images = [UIImage]()
    var index = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 0..<5 {
            if let image = UIImage(named: "dog-\(i).jpg") {
                images.append(image)
            }
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageScrollView.imageContentMode = .aspectFit
        imageScrollView.initialOffset = .center
        imageScrollView.display(image: images[index])
    }

    @IBAction func previousButtonTap(_ sender: AnyObject) {
        index = (index - 1 + images.count)%images.count
        imageScrollView.display(image: images[index])
    }

    @IBAction func nextButtonTap(_ sender: AnyObject) {
        index = (index + 1)%images.count
        imageScrollView.display(image: images[index])
    }

}

Update demo project for delegate

//
//  ViewController.swift
//  ImageScrollViewDemo
//
//  Created by Nguyen Cong Huy on 3/5/16.
//  Copyright © 2016 Nguyen Cong Huy. All rights reserved.
//

import UIKit
import ImageScrollView

class ViewController: UIViewController {

    @IBOutlet weak var imageScrollView: ImageScrollView!
    var images = [UIImage]()
    var index = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        imageScrollView.imageScrollViewDelegate = self

        for i in 0..<5 {
            if let image = UIImage(named: "dog-\(i).jpg") {
                images.append(image)
            }
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageScrollView.imageContentMode = .aspectFit
        imageScrollView.initialOffset = .center
        imageScrollView.display(image: images[index])
    }

    @IBAction func previousButtonTap(_ sender: AnyObject) {
        index = (index - 1 + images.count)%images.count
        imageScrollView.display(image: images[index])
    }

    @IBAction func nextButtonTap(_ sender: AnyObject) {
        index = (index + 1)%images.count
        imageScrollView.display(image: images[index])
    }

}

extension ViewController: UIScrollViewDelegate {
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        print("scrollViewDidEndZooming at scale \(scale)")
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("scrollViewDidScroll at offset \(scrollView.contentOffset)")
    }
}


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

extension Module {
	public static var churchBoolean: Module {
		let Boolean = Declaration("Boolean",
			type: .Type,
			value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) })

		return Module([ Boolean ])
	}
}

import Prelude

Add a Church-encoded `true` value.

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

extension Module {
	public static var churchBoolean: Module {
		let Boolean = Declaration("Boolean",
			type: .Type,
			value: Recur.lambda(.Type) { Recur.lambda($0, $0, const($0)) })

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

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

import Prelude


import io;
import unix;

(file o[]) task(file i, int n) "turbine" "0.1"
[
"""
set f [ swift_filename &<<i>> ]
exec ./317-array-build.task.sh $f <<n>>;
set L [ glob test-317-*.data ];
swift_array_build <<o>> $L file;
"""
 ];

main
{
  printf("OK");
  file i<"input.txt">;
  file o[];
  o = task(i, 10);
  foreach f in o
  {
    printf("output file: %s", filename(f));
  }
  i = touch();
}

Update test 317 for modified array_build syntax

import io;
import unix;

(file o[]) task(file i, int n) "turbine" "0.1"
[
"""
set f [ swift_filename &<<i>> ]
exec ./317-array-build.task.sh $f <<n>>;
set L [ glob test-317-*.data ];
set <<o>> swift_array_build $L file;
"""
 ];

main
{
  printf("OK");
  file i<"input.txt">;
  file o[];
  o = task(i, 10);
  foreach f in o
  {
    printf("output file: %s", filename(f));
  }
  i = touch();
}


//
//  DemoView.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 15/07/2016.
//
//

import Foundation

///
/// Click/drag to move the circle
///
class DemoView : ReactiveView {
    override func drawReactive() {
        if leftMouseDown.value {
            // Draw an oval centered on the current position
            let clickPos    = mousePosition.value;
            let ovalRect    = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -64, -64);

            NSColor.blueColor().set();
            NSBezierPath.init(ovalInRect: ovalRect).fill();
        }
    }
}

Update the demo view so that it starts track the mouse when the button is not held down

//
//  DemoView.swift
//  SwiftRebound
//
//  Created by Andrew Hunter on 15/07/2016.
//
//

import Foundation

///
/// Click/drag to move the circle
///
class DemoView : ReactiveView {
    override func drawReactive() {
        if leftMouseDown.value {
            // Draw an oval centered on the current position
            let clickPos    = mousePosition.value;
            let ovalRect    = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -64, -64);

            NSColor.blueColor().set();
            NSBezierPath.init(ovalInRect: ovalRect).fill();
        } else if mouseOver.value {
            // Draw an square centered on the current position
            let clickPos    = mousePosition.value;
            let square      = NSInsetRect(NSRect(origin: clickPos, size: NSSize(width: 0, height: 0)), -16, -16);

            NSColor.greenColor().set();
            NSRectFill(square);
        }
    }
}


//
//  DispatchSource+Fisticuffs.swift
//  Fisticuffs
//
//  Created by Maksym Korytko on 2016-12-22.
//  Copyright © 2016 theScore. All rights reserved.
//

import Foundation

extension DispatchSource {
    /**
     Creates a single use timer source and resumes it.
     Once the timer fires, it is automatically invalidated.
     - parameters:
        - queue: The dispatch queue that should be used to enque the handler.
        - interval: Timer interval since now when the handler should be invoked.
        - leeway: The handler may be called at any time between its scheduled time + leeway.
        - handler: A function that should be called when the timer fires.

     - returns: An instance of the DispatchSourceTimer protocol.
                The returned timer will be in the resumed state.
     */
    class func makeScheduledOneshotTimer(
        queue: DispatchQueue = .main,
        interval: DispatchTimeInterval,
        leeway: DispatchTimeInterval = .nanoseconds(0),
        handler: @escaping () -> Void) -> DispatchSourceTimer {

        let timer = DispatchSource.makeTimerSource(queue: queue)

        timer.setEventHandler(handler: handler)
        timer.scheduleOneshot(deadline: DispatchTime.now() + interval)
        timer.resume()

        return timer
    }
}

Fix a typo in the documentation

//
//  DispatchSource+Fisticuffs.swift
//  Fisticuffs
//
//  Created by Maksym Korytko on 2016-12-22.
//  Copyright © 2016 theScore. All rights reserved.
//

import Foundation

extension DispatchSource {
    /**
     Creates a single use timer source and resumes it.
     Once the timer fires, it is automatically invalidated.
     - parameters:
        - queue: The dispatch queue that should be used to enqueue the handler.
        - interval: Timer interval since now when the handler should be invoked.
        - leeway: The handler may be called at any time between its scheduled time + leeway.
        - handler: A function that should be called when the timer fires.

     - returns: An instance of the DispatchSourceTimer protocol.
                The returned timer will be in the resumed state.
     */
    class func makeScheduledOneshotTimer(
        queue: DispatchQueue = .main,
        interval: DispatchTimeInterval,
        leeway: DispatchTimeInterval = .nanoseconds(0),
        handler: @escaping () -> Void) -> DispatchSourceTimer {

        let timer = DispatchSource.makeTimerSource(queue: queue)

        timer.setEventHandler(handler: handler)
        timer.scheduleOneshot(deadline: DispatchTime.now() + interval)
        timer.resume()

        return timer
    }
}


//
//  Dependencies.swift
//  Whitelabel
//
//  Created by Martin Eberl on 27.02.17.
//  Copyright © 2017 Martin Eberl. All rights reserved.
//

import Foundation

class Dependencies {
    static let shared = Dependencies()

    let loader: ContentLoader?
    let locationProvider: LocationProvider?
    let timeStore: TimeStore

    private init() {
        if let urlString = Bundle.main.infoDictionary?["LOAD_PATH"] as? String,
            let url = URL(string: urlString) {
            loader = ContentLoader(url: url)
        } else {
            loader = nil
        }

        locationProvider = LocationProvider()
        timeStore = TimeStore()
    }
}

Use config instead of loading everything out of the config dictionary

//
//  Dependencies.swift
//  Whitelabel
//
//  Created by Martin Eberl on 27.02.17.
//  Copyright © 2017 Martin Eberl. All rights reserved.
//

import Foundation

class Dependencies {
    static let shared = Dependencies()

    let loader: ContentLoader?
    let locationProvider: LocationProvider?
    let timeStore: TimeStore

    private init() {
        if let urlString = Config.apiBasePath,
            let url = URL(string: urlString) {
            loader = ContentLoader(url: url)
        } else {
            loader = nil
        }

        locationProvider = LocationProvider()
        timeStore = TimeStore()
    }
}


//
//  DITypes.swift
//  DITranquillity
//
//  Created by Alexander Ivlev on 21/10/16.
//  Copyright © 2016 Alexander Ivlev. All rights reserved.
//

public typealias DIType = Any
public typealias DIMethodSignature = Any

public struct DIComponent {
  public let type: DIType
  public let file: String
  public let line: Int
}

public enum DILifeTime: Equatable {
  case single
  case lazySingle
  case perScope
  case perDependency
  case perRequest

  static var `default`: DILifeTime { return perScope }
}

Add description var for DIComponent

//
//  DITypes.swift
//  DITranquillity
//
//  Created by Alexander Ivlev on 21/10/16.
//  Copyright © 2016 Alexander Ivlev. All rights reserved.
//

public typealias DIType = Any
public typealias DIMethodSignature = Any

public struct DIComponent {
  public let type: DIType
  public let file: String
  public let line: Int
}

public extension DIComponent {
  public var description: String {
    return "<Registered component in file: \(file) on line: \(line) for type: \(String(describing: type))>"
  }
}

public enum DILifeTime: Equatable {
  case single
  case lazySingle
  case perScope
  case perDependency
  case perRequest

  static var `default`: DILifeTime { return perScope }
}


import assert;
import io;

main {

  float x[];

  x = [1.0:2.0];
  assertEqual(x[0], 1.0, "x[0]");
  assertEqual(x[1], 2.0, "x[1]");
  assertEqual(size(x), 2, "len(x)");

  trace("x", repr(x));

  foreach y in [1.0:10.0] {
    printf("y=%f", y);
  }

  foreach z in [0:1004.9:7.5] {
    printf("z=%f", z);
  }

  foreach a in [0:0.0:0.001] {
    printf("a=%f", a);
  }

  foreach b in [0:-1.0] {
    assert(false, "Range loop should not run");
  }
}

Extend floating point range test a bit

import assert;
import io;

main {

  float x[];

  x = [1.0:2.0];
  assertEqual(x[0], 1.0, "x[0]");
  assertEqual(x[1], 2.0, "x[1]");
  assertEqual(size(x), 2, "len(x)");

  trace("x", repr(x));

  foreach y in [1.0:10.0] {
    printf("y=%f", y);
  }

  y_range = [1.0:10.0];
  assertEqual(size(y_range), 10, "size(y)");
  assertEqual(y_range[0], 1.0, "y[0]");
  assertEqual(y_range[9], 10.0, "y[9]");

  foreach z in [0:1004.9:7.5] {
    printf("z=%f", z);
  }

  z_range = [0:1004.9:7.5];
  assertEqual(size(z_range), 134, "size(z)");
  assertEqual(z_range[0], 0.0, "z[0]");
  assertEqual(z_range[20], 150.0, "z[20]");

  foreach a in [95.5:95.51:0.1] {
    printf("a=%f", a);
  }

  a_range = [95.5:95.51:0.1];
  assertEqual(size(a_range), 1, "size(a)");
  assertEqual(a_range[0], 95.5, "a[0]");

  foreach b in [0:-1.0] {
    assert(false, "Range loop should not run");
  }

  b_range = [0:-1.0];
  assertEqual(size(b_range), 0, "size(b)");

}


//
//  AuthenticatedClient.swift
//  BetaSeriesKit
//
//  Created by Romain Pouclet on 2016-02-14.
//  Copyright © 2016 Perfectly-Cooked. All rights reserved.
//

import UIKit
import ReactiveCocoa

public class AuthenticatedClient: NSObject {

    public enum AuthenticatedClientError: ErrorType {
        case InternalError(actualError: RequestError)
    }

    private static let baseURL = NSURL(string: "https://api.betaseries.com")!

    let key: String
    public let token: String

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

    public func fetchShows() -> SignalProducer<Show, AuthenticatedClientError> {
        let request = FetchMemberInfos().send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)

        let showsSignalProducer = request.flatMap(.Latest, transform: { return SignalProducer(values: $0.shows) })

        return showsSignalProducer.flatMapError {
            return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
        }
    }

    public func fetchEpisodes(show: Show) -> SignalProducer<Episode, AuthenticatedClientError> {
        let request = FetchEpisodes(id: show.id)
            .send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)

        return request.flatMapError {
            return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
        }
    }

}

Use show id to fetch episodes

//
//  AuthenticatedClient.swift
//  BetaSeriesKit
//
//  Created by Romain Pouclet on 2016-02-14.
//  Copyright © 2016 Perfectly-Cooked. All rights reserved.
//

import UIKit
import ReactiveCocoa

public class AuthenticatedClient: NSObject {

    public enum AuthenticatedClientError: ErrorType {
        case InternalError(actualError: RequestError)
    }

    private static let baseURL = NSURL(string: "https://api.betaseries.com")!

    let key: String
    public let token: String

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

    public func fetchShows() -> SignalProducer<Show, AuthenticatedClientError> {
        let request = FetchMemberInfos().send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)

        let showsSignalProducer = request.flatMap(.Latest, transform: { return SignalProducer(values: $0.shows) })

        return showsSignalProducer.flatMapError {
            return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
        }
    }

    public func fetchEpisodes(id: Int) -> SignalProducer<Episode, AuthenticatedClientError> {
        let request = FetchEpisodes(id: id)
            .send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)

        return request.flatMapError {
            return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
        }
    }

}


//
//  ContentCollectionViewCell.swift
//  ICViewPager
//
//  Created by Ilter Cengiz on 18/5/18.
//  Copyright © 2018 Ilter Cengiz. All rights reserved.
//

import UIKit

final class ContentCollectionViewCell: UICollectionViewCell {

    private weak var contentViewController: UIViewController?

    // MARK: Public functions

    func configure(contentViewController: UIViewController) {
        self.contentViewController = contentViewController
    }

    // MARK: View controller containment

    func addContentViewController(to parentViewController: UIViewController) {

        guard let viewController = contentViewController else { return }

        parentViewController.addChildViewController(viewController)
        contentView.embed(viewController.view)
        viewController.didMove(toParentViewController: parentViewController)
        contentViewController = viewController
    }

    func removeContentViewController() {
        contentViewController?.willMove(toParentViewController: nil)
        contentViewController?.view.removeFromSuperview()
        contentViewController?.removeFromParentViewController()
        contentViewController = nil
    }
}

Fix for view controller embedding

//
//  ContentCollectionViewCell.swift
//  ICViewPager
//
//  Created by Ilter Cengiz on 18/5/18.
//  Copyright © 2018 Ilter Cengiz. All rights reserved.
//

import UIKit

final class ContentCollectionViewCell: UICollectionViewCell {

    private var contentViewController: UIViewController?

    // MARK: Public functions

    func configure(contentViewController: UIViewController) {
        self.contentViewController = contentViewController
    }

    // MARK: View controller containment

    func addContentViewController(to parentViewController: UIViewController) {

        guard let viewController = contentViewController else { return }

        parentViewController.addChildViewController(viewController)
        contentView.embed(viewController.view)
        viewController.didMove(toParentViewController: parentViewController)
        contentViewController = viewController
    }

    func removeContentViewController() {
        contentViewController?.willMove(toParentViewController: nil)
        contentViewController?.view.removeFromSuperview()
        contentViewController?.removeFromParentViewController()
    }
}


//
//  AppDelegate.swift
//  Age
//
//  Created by Julian Grosshauser on 14/03/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    //MARK: Properties

    lazy var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = UIColor.whiteColor()
        window.rootViewController = UINavigationController(rootViewController: AgeViewController())

        return window
    }()

    //MARK: UIApplicationDelegate

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // make UINavigationBar transparent
        UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
        UINavigationBar.appearance().shadowImage = UIImage()

        self.window?.makeKeyAndVisible()

        return true
    }
}

Set UINavigationBar tint color to white

//
//  AppDelegate.swift
//  Age
//
//  Created by Julian Grosshauser on 14/03/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    //MARK: Properties

    lazy var window: UIWindow? = {
        let window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = UIColor.whiteColor()
        window.rootViewController = UINavigationController(rootViewController: AgeViewController())

        return window
    }()

    //MARK: UIApplicationDelegate

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // make UINavigationBar transparent
        UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
        UINavigationBar.appearance().shadowImage = UIImage()

        UINavigationBar.appearance().tintColor = UIColor.whiteColor()

        self.window?.makeKeyAndVisible()

        return true
    }
}


protocol NominalType : MetadataType {
    var nominalTypeDescriptor: NominalTypeDescriptor { get }
}

extension NominalType {

    func fieldNamesAndTypes(for type: Any.Type) -> [(String, Any.Type)]? {
        return (0..<nominalTypeDescriptor.numberOfFields).map { index in
            var context: (String, Any.Type) = ("", Any.self)
            getFieldAt(type, index, { name, type, context in
                let context = context.assumingMemoryBound(to: (String, Any.Type).self)
                context.pointee = (
                    String(cString: name),
                    unsafeBitCast(type, to: Any.Type.self)
                )
            }, &context)
            return context
        }
    }

    var fieldOffsets: [Int]? {
        let vectorOffset = nominalTypeDescriptor.fieldOffsetVector
        guard vectorOffset != 0 else { return nil }
        return (0..<nominalTypeDescriptor.numberOfFields).map {
            return Int(UnsafePointer<Int32>(pointer)[vectorOffset + $0 + 2])
        }
    }

}

@_silgen_name("swift_getFieldAt")
private func getFieldAt(
    _ type: Any.Type,
    _ index: Int,
    _ callback: @convention(c) (
        _ mangledName: UnsafePointer<CChar>,
        _ type: UnsafeRawPointer,
        _ context: UnsafeMutableRawPointer
    ) -> Void,
    _ context: UnsafeMutableRawPointer
)

Fix bug for 32 bit platforms

protocol NominalType : MetadataType {
    var nominalTypeDescriptor: NominalTypeDescriptor { get }
}

extension NominalType {

    func fieldNamesAndTypes(for type: Any.Type) -> [(String, Any.Type)]? {
        return (0..<nominalTypeDescriptor.numberOfFields).map { index in
            var context: (String, Any.Type) = ("", Any.self)
            getFieldAt(type, index, { name, type, context in
                let context = context.assumingMemoryBound(to: (String, Any.Type).self)
                context.pointee = (
                    String(cString: name),
                    unsafeBitCast(type, to: Any.Type.self)
                )
            }, &context)
            return context
        }
    }

    var fieldOffsets: [Int]? {
        let vectorOffset = nominalTypeDescriptor.fieldOffsetVector
        guard vectorOffset != 0 else { return nil }
        return (0..<nominalTypeDescriptor.numberOfFields).map {
            return Int(UnsafePointer<Int32>(pointer)[vectorOffset + $0 + (is64BitPlatform ? 2 : 0)])
        }
    }

}

@_silgen_name("swift_getFieldAt")
private func getFieldAt(
    _ type: Any.Type,
    _ index: Int,
    _ callback: @convention(c) (
        _ mangledName: UnsafePointer<CChar>,
        _ type: UnsafeRawPointer,
        _ context: UnsafeMutableRawPointer
    ) -> Void,
    _ context: UnsafeMutableRawPointer
)


//
//  Util.swift
//  Few
//
//  Created by Josh Abernathy on 12/28/14.
//  Copyright (c) 2014 Josh Abernathy. All rights reserved.
//

import Foundation

func GET(URL: NSURL, fn: (NSDictionary!, NSURLResponse!, NSError!) -> ()) {
	NSURLSession.sharedSession().dataTaskWithURL(URL) { (data, response, error) in
		if data == nil {
			fn(nil, response, error)
			return
		}

		var JSONError: NSError?
		let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &JSONError) as? NSDictionary
		fn(result, response, JSONError)
	}.resume()
}

func uniqueKey(file: String = __FILE__, line: Int = __LINE__) -> String {
	return "\(file)+\(line)"
}

Include the column in the unique key.

//
//  Util.swift
//  Few
//
//  Created by Josh Abernathy on 12/28/14.
//  Copyright (c) 2014 Josh Abernathy. All rights reserved.
//

import Foundation

func GET(URL: NSURL, fn: (NSDictionary!, NSURLResponse!, NSError!) -> ()) {
	NSURLSession.sharedSession().dataTaskWithURL(URL) { (data, response, error) in
		if data == nil {
			fn(nil, response, error)
			return
		}

		var JSONError: NSError?
		let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &JSONError) as? NSDictionary
		fn(result, response, JSONError)
	}.resume()
}

func uniqueKey(file: String = __FILE__, line: Int = __LINE__, column: Int = __COLUMN__) -> String {
	return "\(file)+\(line)+\(column)"
}


//
//  K2AlertsTools.swift
//
//  Created by Kailen & Kathryne Engel on 3/2/16.
//  Copyright © 2016 K2. All rights reserved.
//
//  Alert & Notification utility functions
//

import UIKit

func makeAlertFor (
    forVC: UIViewController,
    title: String,
    message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let cancel = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
        alert.addAction(cancel)
        forVC.presentViewController(alert, animated: true, completion: nil)
}

func makeAlertWithActionsFor (
    forVC: UIViewController,
    title: String,
    message: String,
    addButtons: (title: String, block: (UIAlertAction->Void))...,
    withCancel: Bool = true) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

        for button in addButtons {
            let action = UIAlertAction(title: button.title, style: .Default, handler: button.block)
            alert.addAction(action)
        }

        if withCancel {
            let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            alert.addAction(cancel)
        }

        forVC.presentViewController(alert, animated: true, completion: nil)
}

Update to swift 3 style

//
//  K2AlertsTools.swift
//
//  Created by Kailen & Kathryne Engel on 3/2/16.
//  Copyright © 2016 K2. All rights reserved.
//
//  Alert & Notification utility functions
//

import UIKit

func makeAlert(
    for vc: UIViewController,
    title: String,
    message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let cancel = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
        alert.addAction(cancel)
        vc.presentViewController(alert, animated: true, completion: nil)
}

func makeAlertWithActions(
    for vc: UIViewController,
    title: String,
    message: String,
    addButtons: (title: String, block: (UIAlertAction->Void))...,
    withCancel: Bool = true) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

        for button in addButtons {
            let action = UIAlertAction(title: button.title, style: .Default, handler: button.block)
            alert.addAction(action)
        }

        if withCancel {
            let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            alert.addAction(cancel)
        }

        vc.presentViewController(alert, animated: true, completion: nil)
}


//
//  ChatControllerHeaderStatus.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 10/08/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController {

    func showHeaderStatusView() {
        chatHeaderViewStatus?.removeFromSuperview()

        if let headerView = ChatHeaderViewStatus.instantiateFromNib() {
            headerView.translatesAutoresizingMaskIntoConstraints = false
            headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)
            view.addSubview(headerView)
            chatHeaderViewStatus = headerView

            view.addConstraints(NSLayoutConstraint.constraints(
                withVisualFormat: "|-0-[headerView]-0-|",
                options: .alignAllLeft,
                metrics: nil,
                views: ["headerView": headerView])
            )

            view.addConstraints(NSLayoutConstraint.constraints(
                withVisualFormat: "V:|-0-[headerView(44)]",
                options: .alignAllLeft,
                metrics: nil,
                views: ["headerView": headerView])
            )
        }
    }

    func hideHeaderStatusView() {
        chatHeaderViewStatus?.removeFromSuperview()
    }

}

Add a nice shadow into the header status view

//
//  ChatControllerHeaderStatus.swift
//  Rocket.Chat
//
//  Created by Rafael Kellermann Streit on 10/08/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import UIKit

extension ChatViewController {

    func showHeaderStatusView() {
        chatHeaderViewStatus?.removeFromSuperview()

        if let headerView = ChatHeaderViewStatus.instantiateFromNib() {
            headerView.translatesAutoresizingMaskIntoConstraints = false
            headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)
            view.addSubview(headerView)
            chatHeaderViewStatus = headerView

            // Shadow of the view
            headerView.layer.masksToBounds = false
            headerView.layer.shadowColor = UIColor.black.cgColor
            headerView.layer.shadowOpacity = 0.5
            headerView.layer.shadowOffset = CGSize(width: 0, height: 0)
            headerView.layer.shadowRadius = 5

            view.addConstraints(NSLayoutConstraint.constraints(
                withVisualFormat: "|-0-[headerView]-0-|",
                options: .alignAllLeft,
                metrics: nil,
                views: ["headerView": headerView])
            )

            view.addConstraints(NSLayoutConstraint.constraints(
                withVisualFormat: "V:|-0-[headerView(44)]",
                options: .alignAllLeft,
                metrics: nil,
                views: ["headerView": headerView])
            )
        }
    }

    func hideHeaderStatusView() {
        chatHeaderViewStatus?.removeFromSuperview()
    }

}


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

final class IntExtensionTests: XCTestCase {
	func testThereIsOneDigitInZero() {
		assert(0.digits, ==, [0])
	}

	func testThereIsOneDigitInNine() {
		assert(9.digits, ==, [9])
	}

	func testThereAreTwoDigitsInTen() {
		assert(10.digits, ==, [1, 0])
	}

	func testThereAreTwoDigitsInNinetyNine() {
		assert(99.digits, ==, [9, 9])
	}

	func testThereAreThreeDigitsInOneHundredAndTwentyThree() {
		assert(123.digits, ==, [1, 2, 3])
	}

	func testBinaryDigits() {
		assert(4.digits(2), ==, [ 1, 0, 0 ])
		assert(7.digits(2), ==, [ 1, 1, 1 ])
	}

	func testHexDigits() {
		assert(0.digits(16), ==, [ 0 ])
		assert(255.digits(16), ==, [ 15, 15 ])
		assert(65535.digits(16), ==, [ 15, 15, 15, 15 ])
	}
}

import Assertions
@testable import Manifold
import XCTest

Test the `digits` method directly.

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

final class IntExtensionTests: XCTestCase {
	func testThereIsOneDigitInZero() {
		assert(0.digits(10), ==, [0])
	}

	func testThereIsOneDigitInNine() {
		assert(9.digits(10), ==, [9])
	}

	func testThereAreTwoDigitsInTen() {
		assert(10.digits(10), ==, [1, 0])
	}

	func testThereAreTwoDigitsInNinetyNine() {
		assert(99.digits(10), ==, [9, 9])
	}

	func testThereAreThreeDigitsInOneHundredAndTwentyThree() {
		assert(123.digits(10), ==, [1, 2, 3])
	}

	func testBinaryDigits() {
		assert(4.digits(2), ==, [ 1, 0, 0 ])
		assert(7.digits(2), ==, [ 1, 1, 1 ])
	}

	func testHexDigits() {
		assert(0.digits(16), ==, [ 0 ])
		assert(255.digits(16), ==, [ 15, 15 ])
		assert(65535.digits(16), ==, [ 15, 15, 15, 15 ])
	}
}

import Assertions
@testable import Manifold
import XCTest


// RUN: %target-swift-frontend %s -emit-ir -o -

func f() {
		enum NotAnError: Swift.Error {
			case nope(length: Int)
		}
}

Fix whitespace in a test


import Foundation

extension MConnectingSocketTcpMethodType
{
    private static func factoryMethod(
        type:MConnectingSocketTcpMethodType) -> MConnectingSocketTcpMethodProtocol.Type
    {
        switch type
        {
        case MConnectingSocketTcpMethodType.showpin:

            return MConnectingSocketTcpMethodShowpin.self

        case MConnectingSocketTcpMethodType.register:

            return MConnectingSocketTcpMethodRegister.self

        case MConnectingSocketTcpMethodType.registerResult:

            return MConnectingSocketTcpMethodRegisterResult.self

        case MConnectingSocketTcpMethodType.registerCancel:

            return MConnectingSocketTcpMethodRegisterCancel.self

        case MConnectingSocketTcpMethodType.connect:

            return MConnectingSocketTcpMethodConnect.self

        case MConnectingSocketTcpMethodType.standby:

            return MConnectingSocketTcpMethodStandby.self
        }
    }

    //MARK: internal

    static func factoryMethod(
        name:String,
        received:String) -> MConnectingSocketTcpMethodProtocol?
    {
        guard

            let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
                rawValue:name)

        else
        {
            return nil
        }

        let methodType:MConnectingSocketTcpMethodProtocol.Type = factoryMethod(
            type:type)
        let method:MConnectingSocketTcpMethodProtocol = methodType.init(
            received:received)

        return method
    }
}

Replace switch with method map

import Foundation

extension MConnectingSocketTcpMethodType
{
    private static let kMethodMap:[
        MConnectingSocketTcpMethodType:
        MConnectingSocketTcpMethodProtocol.Type] = [
            MConnectingSocketTcpMethodType.showpin:
                MConnectingSocketTcpMethodShowpin.self,
            MConnectingSocketTcpMethodType.register:
                MConnectingSocketTcpMethodRegister.self,
            MConnectingSocketTcpMethodType.registerResult:
                MConnectingSocketTcpMethodRegisterResult.self,
            MConnectingSocketTcpMethodType.registerCancel:
                MConnectingSocketTcpMethodRegisterCancel.self,
            MConnectingSocketTcpMethodType.connect:
                MConnectingSocketTcpMethodConnect.self,
            MConnectingSocketTcpMethodType.standby:
                MConnectingSocketTcpMethodStandby.self]

    //MARK: internal

    static func factoryMethod(
        name:String,
        received:String) -> MConnectingSocketTcpMethodProtocol?
    {
        guard

            let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
                rawValue:name),
            let methodType:MConnectingSocketTcpMethodProtocol.Type = kMethodMap[
                type]

        else
        {
            return nil
        }

        let method:MConnectingSocketTcpMethodProtocol = methodType.init(
            received:received)

        return method
    }
}


// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -I %S/Inputs/custom-modules %s

import Foundation

func variadicFunc2(A : Int32, _: Any...) -> Int { return 0 }

class C1 {}

func test_unavailable_because_variadic() {
  print(variadicFunc1(2, [3])) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, [3], C1())) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, 3, 3, 4)) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, 3, [3], 4)) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc2(2, [3])) // no-error
  print(variadicFunc2(2, 3)) // no-error
  print(variadicFunc2(2, 3, C1())) // no-error
  print(variadicFunc2(2, 3, 4, 5, 6)) // no-error
  print(variadicFunc2(2, [3], [4], 5, 6)) // no-error
}

Add requirement to avoid failure on linux bots.

// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -I %S/Inputs/custom-modules %s

// REQUIRES: OS=macosx

import Foundation

func variadicFunc2(A : Int32, _: Any...) -> Int { return 0 }

class C1 {}

func test_unavailable_because_variadic() {
  print(variadicFunc1(2, [3])) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, [3], C1())) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, 3, 3, 4)) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc1(2, 3, [3], 4)) // expected-error {{'variadicFunc1' is unavailable: Variadic function is unavailable}}
  print(variadicFunc2(2, [3])) // no-error
  print(variadicFunc2(2, 3)) // no-error
  print(variadicFunc2(2, 3, C1())) // no-error
  print(variadicFunc2(2, 3, 4, 5, 6)) // no-error
  print(variadicFunc2(2, [3], [4], 5, 6)) // no-error
}


//
//  OnboardingHeaderCellPresenter.swift
//  Ello
//
//  Created by Colin Gray on 5/14/2015.
//  Copyright (c) 2015 Ello. All rights reserved.
//

public struct OnboardingHeaderCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath,
        currentUser: User?)
    {
        if let cell = cell as? OnboardingHeaderCell,
            let (header, message) = streamCellItem.type.data as? (String, String)
        {
            cell.header = header
            cell.message = message

            if streamCellItem.type.oneColumnHeight != cell.height() || streamCellItem.calculatedOneColumnCellHeight == nil || streamCellItem.calculatedOneColumnCellHeight! != cell.height() {
                streamCellItem.calculatedOneColumnCellHeight = cell.height()
                streamCellItem.calculatedMultiColumnCellHeight = cell.height()
                postNotification(StreamNotification.UpdateCellHeightNotification, cell)
            }
        }
    }
}

Update to use static helper method.

//
//  OnboardingHeaderCellPresenter.swift
//  Ello
//
//  Created by Colin Gray on 5/14/2015.
//  Copyright (c) 2015 Ello. All rights reserved.
//

public struct OnboardingHeaderCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath,
        currentUser: User?)
    {
        if let cell = cell as? OnboardingHeaderCell,
            let (header, message) = streamCellItem.type.data as? (String, String)
        {
            cell.header = header
            cell.message = message

            if needsHeightUpdate(cell, streamCellItem: streamCellItem) {
                streamCellItem.calculatedOneColumnCellHeight = cell.height()
                streamCellItem.calculatedMultiColumnCellHeight = cell.height()
                postNotification(StreamNotification.UpdateCellHeightNotification, cell)
            }
        }
    }

    private static func needsHeightUpdate(cell: OnboardingHeaderCell, streamCellItem: StreamCellItem) -> Bool {
        return streamCellItem.type.oneColumnHeight != cell.height() || streamCellItem.calculatedOneColumnCellHeight == nil || streamCellItem.calculatedOneColumnCellHeight! != cell.height()
    }
}


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Conductor",
    products: [
        .executable(
            name: "Conductor",
            targets: ["Conductor"]
        ),
    ],
    dependencies: [
        .package(url: "https://github.com/danger/swift.git", from: "3.10.1"),
        .package(url: "https://github.com/kylef/Commander.git", from: "0.9.1"),
        .package(url: "https://github.com/davecom/SwiftGraph.git", .branch("master")),
        .package(url: "https://github.com/jmmaloney4/Squall.git", .branch("master")),
        .package(url: "https://github.com/jpsim/Yams.git", from: "4.0.6"),
        .package(url: "https://github.com/SwiftyBeaver/SwiftyBeaver.git", from: "1.9.5"),
        .package(url: "https://github.com/Wildchild9/LinkedList.git", .branch("master")),
    ],
    targets: [
        .target(
            name: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph", "Squall", "Yams", "SwiftyBeaver", "LinkedList"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)

Update dependency kylef/Commander to from: "0.9.2"

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Conductor",
    products: [
        .executable(
            name: "Conductor",
            targets: ["Conductor"]
        ),
    ],
    dependencies: [
        .package(url: "https://github.com/danger/swift.git", from: "3.10.1"),
        .package(url: "https://github.com/kylef/Commander.git", from: "0.9.2"),
        .package(url: "https://github.com/davecom/SwiftGraph.git", .branch("master")),
        .package(url: "https://github.com/jmmaloney4/Squall.git", .branch("master")),
        .package(url: "https://github.com/jpsim/Yams.git", from: "4.0.6"),
        .package(url: "https://github.com/SwiftyBeaver/SwiftyBeaver.git", from: "1.9.5"),
        .package(url: "https://github.com/Wildchild9/LinkedList.git", .branch("master")),
    ],
    targets: [
        .target(
            name: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph", "Squall", "Yams", "SwiftyBeaver", "LinkedList"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)


//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    internal static var classPath: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    internal static var className: String {
        return String(describing: self)
    }
    internal static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSONObject() -> JSON? {
        return toJSON()
    }
    internal static func getFirebaseModels(_ snapshot: DataSnapshot) -> [Self]? {
        let dataSnapshot = snapshot.children.allObjects as? [DataSnapshot]
        let keys = dataSnapshot?.map({$0.key})
        let arraySelf = dataSnapshot?.flatMap({Self.deserialize(from: $0.value as? NSDictionary)})
        if let firebaseModels = arraySelf {
            for firebaseModel in firebaseModels {keys?.forEach({firebaseModel.key = $0})}
        }
        return arraySelf
    }
}

Remove extra parentheses from functional operations

//
//  FirebaseModel+Extension.swift
//  FirebaseCommunity
//
//  Created by Victor Alisson on 15/08/17.
//

import Foundation
import FirebaseCommunity

public extension FirebaseModel {
    typealias JSON = [String: Any]

    internal static var classPath: DatabaseReference {
        return reference.child(Self.className)
    }
    static var reference: DatabaseReference {
        return Database.database().reference()
    }
    internal static var className: String {
        return String(describing: self)
    }
    internal static var autoId: String {
        return Self.reference.childByAutoId().key
    }
    func toJSONObject() -> JSON? {
        return toJSON()
    }
    internal static func getFirebaseModels(_ snapshot: DataSnapshot) -> [Self]? {
        let dataSnapshot = snapshot.children.allObjects as? [DataSnapshot]
        let keys = dataSnapshot?.map {$0.key}
        let firebaseModels = dataSnapshot?.flatMap {Self.deserialize(from: $0.value as? NSDictionary)}
        if let firebaseModels = firebaseModels {
            for firebaseModel in firebaseModels {keys?.forEach {firebaseModel.key = $0}}
        }
        return firebaseModels
    }
}


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

final class TermTests: XCTestCase {
	func testPiTypeDescription() {
		assert(identity.typecheck().right?.description, ==, "Π : Type . Π : a . a")
	}

	func testSigmaTypeDescription() {
		assert(Term.sigma(.unit, .unit).typecheck().right?.description, ==, "Σ Unit . Unit")
	}

	func testGlobalsPrintTheirNames() {
		assert(Term.free("Global").description, ==, "Global")
	}
}

private let identity = Term.pi(.type, .pi(0, 0))
private let constant = Term.pi(.type, .pi(.type, .pi(1, .pi(1, 1))))

import Assertions
import Manifold
import XCTest

Test that nullary sums are the unit type.

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

final class TermTests: XCTestCase {
	func testPiTypeDescription() {
		assert(identity.typecheck().right?.description, ==, "Π : Type . Π : a . a")
	}

	func testSigmaTypeDescription() {
		assert(Term.sigma(.unit, .unit).typecheck().right?.description, ==, "Σ Unit . Unit")
	}

	func testGlobalsPrintTheirNames() {
		assert(Term.free("Global").description, ==, "Global")
	}

	func testNullarySumsAreUnitType() {
		assert(Term.sum([]), ==, .unitType)
	}
}

private let identity = Term.pi(.type, .pi(0, 0))
private let constant = Term.pi(.type, .pi(.type, .pi(1, .pi(1, 1))))

import Assertions
import Manifold
import XCTest


// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -Ounchecked %s -emit-ir | %FileCheck %s

// REQUIRES: CPU=x86_64

// rdar://30579970
// REQUIRES: optimized_stdlib

// We were missing target transform info and not vectorizing the loop below.

// CHECK: xor <{{[2,4,8]}} x i64>

public func f(a: UnsafePointer<Int>, b: UnsafePointer<Int>, count: Int) -> Int {
  var c = 0

  for i in 0..<count {
    c = a[i] ^ b[i] ^ c
  }

  return c
}

Convert regex to idiomatic syntax

// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -Ounchecked %s -emit-ir | %FileCheck %s

// REQUIRES: CPU=x86_64

// rdar://30579970
// REQUIRES: optimized_stdlib

// We were missing target transform info and not vectorizing the loop below.

// CHECK: xor <{{(2|4|8)}} x i64>

public func f(a: UnsafePointer<Int>, b: UnsafePointer<Int>, count: Int) -> Int {
  var c = 0

  for i in 0..<count {
    c = a[i] ^ b[i] ^ c
  }

  return c
}


//: Example 98
//:
//: 题目：斐波那契数列
//:
//: 1.程序分析：
//:
//: 2.程序源代码：

import UIKit

func fibonacci(index: Int) -> Int {
    return (index > 2) ? fibonacci(index - 1) + fibonacci(index - 2) : 1
}

func fibonacciLoop(index: Int) -> Int {
    var a = [1, 1, 0]
    if index == 1 || index == 2 {
        a[2] = 1
    } else {
        for _ in 2 ..< index {
            a[2] = a[1] + a[0]
            a[0] = a[1]
            a[1] = a[2]
        }
    }
    return a[2]
}

fibonacciLoop(6)
fibonacci(6)

Add comments to an Example

//: Example 98
//:
//: 题目：斐波那契数列
//:
//: 1.程序分析：
//:
//: 2.程序源代码：

import UIKit

//  递归
func fibonacci(index: Int) -> Int {
    return (index > 2) ? fibonacci(index - 1) + fibonacci(index - 2) : 1
}

//  循环
func fibonacciLoop(index: Int) -> Int {
    var a = [1, 1, 0]
    if index == 1 || index == 2 {
        a[2] = 1
    } else {
        for _ in 2 ..< index {
            a[2] = a[1] + a[0]
            a[0] = a[1]
            a[1] = a[2]
        }
    }
    return a[2]
}

fibonacciLoop(6)
fibonacci(6)


//: Example 99
//:
//: 题目：辗转相除法
//:
//: 1.程序分析：
//:
//: 2.程序源代码：

import UIKit

//  循环
func gcd(a a: Int, b: Int) -> Int {
    var x = a, y = b
    var n = x % y
    while n != 0 {
        x = y
        y = n
        n = x % y
    }
    return y
}

gcd(a: 75, b: 100)

//  递归
func gcdRecursive(a a: Int, b: Int) -> Int {
    return b == 0 ? a : gcdRecursive(a: b, b: a % b)
}

gcdRecursive(a: 75, b: 100)

Update a comment in Example 99

//: Example 99
//:
//: 题目：辗转相除法求两个数的最大公约数
//:
//: 1.程序分析：
//:
//: 2.程序源代码：

import UIKit

//  循环
func gcd(a a: Int, b: Int) -> Int {
    var x = a, y = b
    var n = x % y
    while n != 0 {
        x = y
        y = n
        n = x % y
    }
    return y
}

gcd(a: 75, b: 100)

//  递归
func gcdRecursive(a a: Int, b: Int) -> Int {
    return b == 0 ? a : gcdRecursive(a: b, b: a % b)
}

gcdRecursive(a: 75, b: 100)


//
//  Channel.swift
//  Harekaze
//
//  Created by Yuki MIZUNO on 2016/07/10.
//  Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//

import RealmSwift
import ObjectMapper

class Channel: Object, Mappable {

	// MARK: - Managed instance fileds
	dynamic var channel: Int = 0
	dynamic var id: String = ""
	dynamic var name: String = ""
	dynamic var number: Int = 0
	dynamic var sid: Int = 0
	dynamic var type: String = ""

	// MARK: - Primary key definition
	override static func primaryKey() -> String? {
		return "id"
	}

	// MARK: - Class initialization
	required convenience init?(_ map: Map) {
		self.init()
		mapping(map)
	}

	// MARK: - JSON value mapping
	func mapping(map: Map) {
		channel <- map["channel"]
		id <- map["id"]
		name <- map["name"]
		number <- map["n"]
		sid <- map["sid"]
		type <- map["type"]
	}
}

Fix parsing sid field of JSON string value

//
//  Channel.swift
//  Harekaze
//
//  Created by Yuki MIZUNO on 2016/07/10.
//  Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//

import RealmSwift
import ObjectMapper

class Channel: Object, Mappable {

	// MARK: - Managed instance fileds
	dynamic var channel: Int = 0
	dynamic var id: String = ""
	dynamic var name: String = ""
	dynamic var number: Int = 0
	dynamic var sid: Int = 0
	dynamic var type: String = ""

	// MARK: - Primary key definition
	override static func primaryKey() -> String? {
		return "id"
	}

	// MARK: - Class initialization
	required convenience init?(_ map: Map) {
		self.init()
		mapping(map)
	}

	// MARK: - JSON value mapping
	func mapping(map: Map) {
		channel <- map["channel"]
		id <- map["id"]
		name <- map["name"]
		number <- map["n"]
		sid <- (map["sid"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
		type <- map["type"]
	}
}


/*
  I2.SWIFT

  The idea is to stuff all generated params combinations in a big
  array (params) indexed by the hash code of the params.  Then we pull
  out all the hash codes with keys(params) .  Then we can iterate over
  the hash codes, retrieve the params, and assign work to the ME_ranks
*/

import io;
import matrix;
import string;

int ME_ranks[];

string params[];

(string s) compute_string(int p)
{
  s = "my params are: " + int2string(p+5);
}

// Define ME_ranks
foreach i in [0:5]
{
  ME_ranks[i] = i;
}

// Compute all parameter strings
// Could be nested loops, whatever, the ordering does not matter
// because we have unique hashes
foreach i in [0:5]
{
  params_string = compute_string(i);
  int h = hash(params_string);
  // printf("hash: %i", h);
  params[h] = params_string;
}

// Get all hash codes in a contiguous array for looping
int K[] = keys_integer(params);

foreach hash_index, rank in K
{
  // printf("hash_index: %i", hash_index);
  params_string = params[hash_index];
  printf("run on ME rank: %i params: \"%s\"", rank, params_string);
}

Allow for remapping of ME ranks

/*
  I2.SWIFT

  The idea is to stuff all generated params combinations in a big
  array (params) indexed by the hash code of the params.  Then we pull
  out all the hash codes with keys(params) .  Then we can iterate over
  the hash codes, retrieve the params, and assign work to the ME_ranks
*/

import io;
import matrix;
import string;

int ME_ranks[];

string params[];

(string s) compute_string(int p)
{
  s = "my params are: " + int2string(p+5);
}

// Define ME_ranks
foreach i in [0:5]
{
  ME_ranks[i] = i;
}

// Compute all parameter strings
// Could be nested loops, whatever, the ordering does not matter
// because we have unique hashes
foreach i in [0:5]
{
  params_string = compute_string(i);
  int h = hash(params_string);
  // printf("hash: %i", h);
  params[h] = params_string;
}

// Get all hash codes in a contiguous array for looping
int K[] = keys_integer(params);

foreach hash_index, r in K
{
  // printf("hash_index: %i", hash_index);
  params_string = params[hash_index];
  rank = ME_ranks[r];
  printf("run on ME rank: %i params: \"%s\"", rank, params_string);
}


//  Created by dasdom on 13.04.20.
//
//

import Foundation

public class BirthdaysManager {
  public private(set) var all: [Birthday]

  public init() {
    all = []
    all = loadBirthdays()
  }

  public func add(_ birthday: Birthday) {
    all.append(birthday)
    save(birthdays: all)
  }

  public func birthdayCounts() -> [BirthdayCount] {
    all.map { BirthdayCount(birthday: $0) }.sorted(by: { $0.remainingDays < $1.remainingDays })
  }
}

public extension BirthdaysManager {
  func save(birthdays: [Birthday]) {
    do {
      let data = try JSONEncoder().encode(birthdays)
      try data.write(to: FileManager.default.birthdaysURL(), options: .atomic)
    } catch {
      print("error: \(error)")
    }
  }

  func loadBirthdays() -> [Birthday] {
    do {
      let data = try Data(contentsOf: FileManager.default.birthdaysURL())
      return try JSONDecoder().decode([Birthday].self, from: data)
    } catch {
      return []
    }
  }
}

Change birthdayCounts from method to property

//  Created by dasdom on 13.04.20.
//
//

import Foundation

public class BirthdaysManager {
  public private(set) var all: [Birthday] {
    didSet {
      birthdayCounts = all
        .map { BirthdayCount(birthday: $0) }
        .sorted(by: { $0.remainingDays < $1.remainingDays })
    }
  }
  public private(set) var birthdayCounts: [BirthdayCount]

  public init() {
    all = []
    all = loadBirthdays()

    birthdayCounts = all
    .map { BirthdayCount(birthday: $0) }
    .sorted(by: { $0.remainingDays < $1.remainingDays })
  }

  public func add(_ birthday: Birthday) {
    all.append(birthday)
    save(birthdays: all)
  }
}

public extension BirthdaysManager {
  func save(birthdays: [Birthday]) {
    do {
      let data = try JSONEncoder().encode(birthdays)
      try data.write(to: FileManager.default.birthdaysURL(), options: .atomic)
    } catch {
      print("error: \(error)")
    }
  }

  func loadBirthdays() -> [Birthday] {
    do {
      let data = try Data(contentsOf: FileManager.default.birthdaysURL())
      return try JSONDecoder().decode([Birthday].self, from: data)
    } catch {
      return []
    }
  }
}


import UIKit

extension UINavigationController {

	public override func viewDidLoad() {
		super.viewDidLoad()

		if let gradient = UIImage(named: "gradient") {
			let stretchableGradient = gradient.stretchableImageWithLeftCapWidth(0, topCapHeight: 0)
			self.navigationBar.setBackgroundImage(stretchableGradient, forBarMetrics: .Default)
			self.navigationBar.setBackgroundImage(stretchableGradient, forBarMetrics: .Compact)
			self.navigationBar.setBackgroundImage(stretchableGradient, forBarMetrics: .DefaultPrompt)
			self.navigationBar.setBackgroundImage(stretchableGradient, forBarMetrics: .CompactPrompt)
		}
	}

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

}

Use a generated gradient for navigation bars.

import UIKit

extension UINavigationController {

	public override func viewDidLoad() {
		super.viewDidLoad()

        let color = UIColor(red:0.122,  green:0.463,  blue:0.804, alpha:1)
        let gradient = self._gradient(color)

        self.navigationBar.barTintColor = color
        self.navigationBar.setBackgroundImage(gradient, forBarMetrics: .Default)
        self.navigationBar.setBackgroundImage(gradient, forBarMetrics: .Compact)
        self.navigationBar.setBackgroundImage(gradient, forBarMetrics: .DefaultPrompt)
        self.navigationBar.setBackgroundImage(gradient, forBarMetrics: .CompactPrompt)
	}

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

    // MARK: Utilities

    private func _gradient(color: UIColor) -> UIImage {
        var hue: CGFloat = 0
        var saturation: CGFloat = 0
        var brightness: CGFloat = 0
        var alpha: CGFloat = 0

        color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
        let topColor = UIColor(hue:hue, saturation:saturation, brightness:brightness+0.2, alpha:alpha)
        let bottomColor = UIColor(hue:hue, saturation:saturation, brightness:brightness-0.02, alpha:alpha)

        let size = CGSize(width: 900, height: 900)

        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations: [CGFloat] = [0.0, 1.0]

        let gradient = CGGradientCreateWithColors(colorSpace, [topColor.CGColor, bottomColor.CGColor], locations)

        let startPoint = CGPointMake(size.width / 2, 0)
        let endPoint = CGPointMake(size.width / 2, size.height)
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, [.DrawsBeforeStartLocation,.DrawsAfterEndLocation])

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage.stretchableImageWithLeftCapWidth(0, topCapHeight: 0)
    }

}


//
//  WKRReadyStates.swift
//  WKRKit
//
//  Created by Andrew Finke on 8/31/17.
//  Copyright © 2017 Andrew Finke. All rights reserved.
//

import Foundation

public struct WKRReadyStates: Codable {
    let players: [WKRPlayer]
    init(players: [WKRPlayer]) {
        self.players = players
    }

    public func isPlayerReady(_ player: WKRPlayer) -> Bool {
        guard let index = players.firstIndex(of: player) else { return false }
        return players[index].state == .readyForNextRound
    }

    var isReadyForNextRound: Bool {
        for player in players where player.state != .readyForNextRound {
            return false
        }
        return true
    }
    func areAllRacePlayersReady(racePlayers: [WKRPlayer]) -> Bool {
        let relevantPlayers = players.filter({ racePlayers.contains($0) })
        for player in relevantPlayers where player.state != .readyForNextRound {
            return false
        }
        return true
    }
}

Stop checking for quit players' ready states

//
//  WKRReadyStates.swift
//  WKRKit
//
//  Created by Andrew Finke on 8/31/17.
//  Copyright © 2017 Andrew Finke. All rights reserved.
//

import Foundation

public struct WKRReadyStates: Codable {
    let players: [WKRPlayer]
    init(players: [WKRPlayer]) {
        self.players = players
    }

    public func isPlayerReady(_ player: WKRPlayer) -> Bool {
        guard let index = players.firstIndex(of: player) else { return false }
        return players[index].state == .readyForNextRound
    }

    func areAllRacePlayersReady(racePlayers: [WKRPlayer]) -> Bool {
        let relevantPlayers = players.filter({ racePlayers.contains($0) && $0.state != .quit })
        for player in relevantPlayers where player.state != .readyForNextRound {
            return false
        }
        return true
    }
}


//
//  FunctorSpec.swift
//  swiftz
//
//  Created by Robert Widmann on 1/19/15.
//  Copyright (c) 2015 TypeLift. All rights reserved.
//

import XCTest
import Swiftz

class FunctorSpec : XCTestCase {
	func testConst() {
		let s = "Goodbye!"
		let x : Const<String, String> = Const(s)
		XCTAssert(x.runConst == s)

		let b : Const<String, String> = x.fmap({ "I don't know why you say " + $0 })
		XCTAssert(b.runConst == s)
	}

	func testConstBifunctor() {
		let x : Const<String, String> = Const("Hello!")
		let y : Const<String, String>  = x.bimap({ "Why, " + $0 }, identity)
		XCTAssert(x.runConst != y.runConst)
	}

	func testTupleBifunctor() {
		let t : (Int, String) = (20, "Bottles of beer on the wall.")
		let y = TupleBF(t).bimap({ $0 - 1 }, identity)
		XCTAssert(y.0 != t.0)
		XCTAssert(y.1 == t.1)
	}
}

Convert Functor spec to properties

//
//  FunctorSpec.swift
//  swiftz
//
//  Created by Robert Widmann on 1/19/15.
//  Copyright (c) 2015 TypeLift. All rights reserved.
//

import XCTest
import Swiftz
import SwiftCheck

class FunctorSpec : XCTestCase {
	func testProperties() {
		property["Const obeys the Functor identity law"] = forAll { (s : String) in
			let x = Const<String, String>(s)
			return (x.fmap(identity)).runConst == identity(x).runConst
		}

		property["Const obeys the Functor composition law"] = forAll { (f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in
			let x = Const<Int, Int>(5)
			return (x.fmap(f.getArrow • g.getArrow)).runConst == (x.fmap(g.getArrow).fmap(f.getArrow)).runConst
		}
	}

	func testConstBifunctor() {
		let x : Const<String, String> = Const("Hello!")
		let y : Const<String, String>  = x.bimap({ "Why, " + $0 }, identity)
		XCTAssert(x.runConst != y.runConst)
	}

	func testTupleBifunctor() {
		let t : (Int, String) = (20, "Bottles of beer on the wall.")
		let y = TupleBF(t).bimap({ $0 - 1 }, identity)
		XCTAssert(y.0 != t.0)
		XCTAssert(y.1 == t.1)
	}
}


//
//  SoftwareUpdateStatus.swift
//  Pods
//
//  Created by Marcel Dittmann on 22.04.16.
//
//

import Foundation
import Gloss

public enum UpdateState {

    case NoUpdate, Downloading, ReadyForInstall, Installed
}

public struct SoftwareUpdateStatus: Decodable {

    public let updatestate: UpdateState?

    /**
     Check for update flag of the bridge
     */
    public let checkforupdate: Bool?

    /**
     Details of device type specific updates available
     */
    public let devicetypes: SoftwareUpdateStatusDeviceTypes?

    /**
     Release Notes Url
    */
    public let url: String?

    /**
     Update Text
    */
    public let text: String?

    /**
     Flag that turns to true when update is available. Can only be updated when its state is true and it is being set to false. All other transitions are invalid and will return an error.
     Updating this flag constitutes acceptance by the app of notification of the firmware update
     */
    public let notify: Bool?

    public init?(json: JSON) {

        updatestate = "updatestate" <~~ json
        checkforupdate = "checkforupdate" <~~ json
        devicetypes = "devicetypes" <~~ json
        url = "url" <~~ json
        text = "text" <~~ json
        notify = "notify" <~~ json

    }
}

Add type Int for UpdateState

//
//  SoftwareUpdateStatus.swift
//  Pods
//
//  Created by Marcel Dittmann on 22.04.16.
//
//

import Foundation
import Gloss

public enum UpdateState: Int {

    case NoUpdate, Downloading, ReadyForInstall, Installed
}

public struct SoftwareUpdateStatus: Decodable {

    public let updatestate: UpdateState?

    /**
     Check for update flag of the bridge
     */
    public let checkforupdate: Bool?

    /**
     Details of device type specific updates available
     */
    public let devicetypes: SoftwareUpdateStatusDeviceTypes?

    /**
     Release Notes Url
    */
    public let url: String?

    /**
     Update Text
    */
    public let text: String?

    /**
     Flag that turns to true when update is available. Can only be updated when its state is true and it is being set to false. All other transitions are invalid and will return an error.
     Updating this flag constitutes acceptance by the app of notification of the firmware update
     */
    public let notify: Bool?

    public init?(json: JSON) {

        updatestate = "updatestate" <~~ json
        checkforupdate = "checkforupdate" <~~ json
        devicetypes = "devicetypes" <~~ json
        url = "url" <~~ json
        text = "text" <~~ json
        notify = "notify" <~~ json

    }
}


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

public struct Environment: DictionaryLiteralConvertible {
	public init(_ bindings: [Int: Scheme]) {
		self.bindings = bindings
	}

	public var freeVariables: Set<Variable> {
		return reduce(lazy(bindings.values).map { $0.freeVariables }, [], +)
	}

	// MARK: DictionaryLiteralConvertible

	public init(dictionaryLiteral elements: (Int, Scheme)...) {
		self.init([:] + elements)
	}

	private let bindings: [Int: Scheme]
}

// MARK: - Imports

import Set

Generalize types to schemes within an environment.

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

public struct Environment: DictionaryLiteralConvertible {
	public init(_ bindings: [Int: Scheme]) {
		self.bindings = bindings
	}

	public var freeVariables: Set<Variable> {
		return reduce(lazy(bindings.values).map { $0.freeVariables }, [], +)
	}

	public func generalize(type: Type) -> Scheme {
		return Scheme(type.freeVariables - freeVariables, type)
	}

	// MARK: DictionaryLiteralConvertible

	public init(dictionaryLiteral elements: (Int, Scheme)...) {
		self.init([:] + elements)
	}

	private let bindings: [Int: Scheme]
}

// MARK: - Imports

import Set


//
//  StreamImageCellPresenter.swift
//  Ello
//
//  Created by Sean on 2/18/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public struct StreamImageCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath)
    {
        if let cell = cell as? StreamImageCell {
            if let photoData = streamCellItem.data as! ImageRegion? {

                if let isGif = photoData.asset?.isGif {
                    if let photoURL = photoData.asset?.optimized?.url {
                        cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                        cell.setImageURL(photoURL)
                    }
                    else if let photoURL = photoData.url {
                        cell.setImageURL(photoURL)
                    }
                }
                else {
                    if let photoURL = photoData.asset?.hdpi?.url {
                        cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                        cell.setImageURL(photoURL)
                    }
                    else if let photoURL = photoData.url {
                        cell.setImageURL(photoURL)
                    }
                }
            }
        }
    }

}

Load smaller images in streams

//
//  StreamImageCellPresenter.swift
//  Ello
//
//  Created by Sean on 2/18/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

import Foundation

public struct StreamImageCellPresenter {

    static func configure(
        cell:UICollectionViewCell,
        streamCellItem:StreamCellItem,
        streamKind: StreamKind,
        indexPath: NSIndexPath)
    {
        if let cell = cell as? StreamImageCell {
            if let photoData = streamCellItem.data as! ImageRegion? {

                if let isGif = photoData.asset?.isGif {
                    if let photoURL = photoData.asset?.optimized?.url {
                        cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                        cell.setImageURL(photoURL)
                    }
                    else if let photoURL = photoData.url {
                        cell.setImageURL(photoURL)
                    }
                }
                else {
                    let photoToLoad = streamKind.isGridLayout ? photoData.asset?.ldpi?.url : photoData.asset?.mdpi?.url
                    if let photoURL = photoToLoad {
                        cell.serverProvidedAspectRatio = StreamCellItemParser.aspectRatioForImageBlock(photoData)
                        cell.setImageURL(photoURL)
                    }
                    else if let photoURL = photoData.url {
                        cell.setImageURL(photoURL)
                    }
                }
            }
        }
    }

}


import Foundation

extension Measurement where UnitType == UnitAngle {
  var radians: CGFloat {
    return CGFloat(self.converted(to: .radians).value)
  }

  var degrees: CGFloat {
    return CGFloat(self.converted(to: .degrees).value)
  }

  func f() {
    return //%self.expect('p self.radians', substrs=['is not convertible to'], error=True)
  }
}

let measure = Measurement<UnitAngle>(value: 100, unit: UnitAngle.degrees)
measure.f()

Adjust error message for failing member lookup test

import Foundation

extension Measurement where UnitType == UnitAngle {
  var radians: CGFloat {
    return CGFloat(self.converted(to: .radians).value)
  }

  var degrees: CGFloat {
    return CGFloat(self.converted(to: .degrees).value)
  }

  func f() {
    return //%self.expect('p self.radians', substrs=["property 'radians' requires the types 'UnitType' and 'UnitAngle' be equivalent"], error=True)
  }
}

let measure = Measurement<UnitAngle>(value: 100, unit: UnitAngle.degrees)
measure.f()


import XCTest
@testable import worldcities

class TestModelListSearch:XCTestCase
{
}

Create test for search items

import XCTest
@testable import worldcities

class TestModelListSearch:XCTestCase
{
    private let kWaitExpectation:TimeInterval = 90

    func testSearchItems()
    {
        let itemsExpectation:XCTestExpectation = expectation(
            description:"items loaded")

        let modelList:ModelList = ModelList()
        modelList.loadItems
        {
            itemsExpectation.fulfill()
        }

        waitForExpectations(timeout:kWaitExpectation)
        { [weak self] (error:Error?) in
        }
    }
}


//
//  ViewController.swift
//  DCDirectoryWatcherExample
//
//  Created by David Chavez on 2/11/15.
//  Copyright (c) 2015 David Chavez. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let directoryWatcher = DCDirectoryWatcher.watchDirectory(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String, completionClosure: {
            println("Directory changed!")
        })
    }

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

}

Print some description about example usage

//
//  ViewController.swift
//  DCDirectoryWatcherExample
//
//  Created by David Chavez on 2/11/15.
//  Copyright (c) 2015 David Chavez. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let directoryWatcher = DCDirectoryWatcher.watchDirectory(directory, completionClosure: {
            println("Directory changed!")
        })
        println("Watching '\(directory)'.")
    }

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

}


//
//  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.matchesInString(self.string, options: [], range: NSMakeRange(0, self.length)).enumerate().forEach { result in
            let (location, length) = (result.element.range.location, result.element.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))
        }
    }
}

Modify to use enumerateMatchesInString instead of matchesInString and enumerate

//
//  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))
        }
    }
}


//
//  {PROJECT}Tests.swift
//  {ORGANIZATION}
//
//  Created by {AUTHOR} on {TODAY}.
//  Copyright © {YEAR} {ORGANIZATION}. All rights reserved.
//

import Foundation
import XCTest
import {PROJECT}

class {PROJECT}Tests: XCTestCase {
    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        //// XCTAssertEqual({PROJECT}().text, "Hello, World!")
    }
}

#if os(Linux)
extension {PROJECT}Tests {
    static var allTests : [(String, ({PROJECT}Tests) -> () throws -> Void)] {
        return [
            ("testExample", testExample),
        ]
    }
}
#endif

Simplify `allTests` computed prop in Tests

//
//  {PROJECT}Tests.swift
//  {ORGANIZATION}
//
//  Created by {AUTHOR} on {TODAY}.
//  Copyright © {YEAR} {ORGANIZATION}. All rights reserved.
//

import Foundation
import XCTest
import {PROJECT}

class {PROJECT}Tests: XCTestCase {
    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        //// XCTAssertEqual({PROJECT}().text, "Hello, World!")
    }

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


import Foundation

// MARK: - File

/// A simple typealias for strings representing files
public typealias File = String

extension File {

    public var fileType: FileType? {
        return FileType(from: self)
    }

    public var name: String {
        return String(self)
    }

}

// MARK: - FileType

public enum FileType: String, Equatable {
    case h, json, m, markdown = "md", mm, pbxproj, plist, storyboard, swift, xcscheme, yaml, yml

    @available(swift, deprecated: 4.2, message: "Replace with CaseIterable conformance")
    static internal var allCases: [FileType] {
        return [.h, .json, .m, .markdown, .mm, .pbxproj, .plist, .storyboard, .swift, .xcscheme, yaml, yml]
    }
}

// MARK: - FileType extensions

extension FileType {

    public var `extension`: String {
        return rawValue
    }

    init?(from file: File) {
        let allCasesDelimited = FileType.allCases.map { $0.extension }.joined(separator: "|")

        guard
            let pattern = try? NSRegularExpression(pattern: "\\.(\(allCasesDelimited))$"),
            let match = pattern.firstMatchingString(in: file.name)
        else {
            return nil
        }

        let rawValue = match.replacingOccurrences(of: ".", with: "")
        self.init(rawValue: rawValue)
    }

}

Replace manual implementation of allCases w/ compiler provided one in CaseIterable

import Foundation

// MARK: - File

/// A simple typealias for strings representing files
public typealias File = String

extension File {

    public var fileType: FileType? {
        return FileType(from: self)
    }

    public var name: String {
        return String(self)
    }

}

// MARK: - FileType

public enum FileType: String, Equatable, CaseIterable {
    case h, json, m, markdown = "md", mm, pbxproj, plist, storyboard, swift, xcscheme, yaml, yml
}

// MARK: - FileType extensions

extension FileType {

    public var `extension`: String {
        return rawValue
    }

    init?(from file: File) {
        let allCasesDelimited = FileType.allCases.map { $0.extension }.joined(separator: "|")

        guard
            let pattern = try? NSRegularExpression(pattern: "\\.(\(allCasesDelimited))$"),
            let match = pattern.firstMatchingString(in: file.name)
        else {
            return nil
        }

        let rawValue = match.replacingOccurrences(of: ".", with: "")
        self.init(rawValue: rawValue)
    }

}


//
// Created by Raimundas Sakalauskas on 2019-06-10.
// Copyright (c) 2019 Particle. All rights reserved.
//

import Foundation

class DeviceTypeLabel: ParticleLabel {
    private var deviceType: ParticleDeviceType?

    override func awakeFromNib() {
        super.awakeFromNib()

        self.internalSetup()
    }

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

        self.internalSetup()
    }

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

        self.internalSetup()
    }

    func setDeviceType(_ type: ParticleDeviceType) {
        self.deviceType = type

        self.textColor = type.getIconColor()
        self.layer.borderColor = type.getIconColor().cgColor
        self.text = type.description
    }

    func internalSetup() {
        self.layer.cornerRadius = 12
        self.layer.masksToBounds = true
        self.layer.borderWidth = 1
        self.textAlignment = .center
        self.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.DetailSize, color: .white)

        NSLayoutConstraint.activate(
            [
                self.widthAnchor.constraint(equalToConstant: 95),
                self.heightAnchor.constraint(equalToConstant: 24)
            ]
        )
    }
}

Revert "expand device type pill icon in device list to accomodate long name of new som"

//
// Created by Raimundas Sakalauskas on 2019-06-10.
// Copyright (c) 2019 Particle. All rights reserved.
//

import Foundation

class DeviceTypeLabel: ParticleLabel {
    private var deviceType: ParticleDeviceType?

    override func awakeFromNib() {
        super.awakeFromNib()

        self.internalSetup()
    }

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

        self.internalSetup()
    }

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

        self.internalSetup()
    }

    func setDeviceType(_ type: ParticleDeviceType) {
        self.deviceType = type

        self.textColor = type.getIconColor()
        self.layer.borderColor = type.getIconColor().cgColor
        self.text = type.description
    }

    func internalSetup() {
        self.layer.cornerRadius = 12
        self.layer.masksToBounds = true
        self.layer.borderWidth = 1
        self.textAlignment = .center
        self.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.DetailSize, color: .white)

        NSLayoutConstraint.activate(
            [
                self.widthAnchor.constraint(equalToConstant: 80),
                self.heightAnchor.constraint(equalToConstant: 24)
            ]
        )
    }
}


//
//  Point.swift
//  PathTools
//
//  Created by James Bean on 1/7/17.
//
//

/// Representation of a point.
///
/// - TODO: Consider making generic over `SignedNumber`.
public struct Point {

    public let x: Double
    public let y: Double

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

extension Point {

    // MARK: - `Equatable`

    public static func == (lhs: Point, rhs: Point) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}

Make conformance to Equatable explicit

//
//  Point.swift
//  PathTools
//
//  Created by James Bean on 1/7/17.
//
//

/// Representation of a point.
///
/// - TODO: Consider making generic over `SignedNumber`.
public struct Point {

    public let x: Double
    public let y: Double

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

extension Point: Equatable {

    // MARK: - `Equatable`

    public static func == (lhs: Point, rhs: Point) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}