extension Optional where Wrapped == String {

    var intValue: Int? {
        if let self = self {
            return Int(self)
        } else {
            return nil
        }
    }

    var doubleValue: Double? {
        if let self = self {
            return Double(self)
        } else {
            return nil
        }
    }

}

Add color from string extension

import UIKit

extension Optional where Wrapped == String {

    var intValue: Int? {
        if let self = self {
            return Int(self)
        } else {
            return nil
        }
    }

    var doubleValue: Double? {
        if let self = self {
            return Double(self)
        } else {
            return nil
        }
    }

}

extension String {

    var color: UIColor {
        var total: Int = 0

        for u in unicodeScalars {
            total += Int(UInt32(u))
        }

        srand48(total * 200)
        let red = CGFloat(drand48())

        srand48(total)
        let green = CGFloat(drand48())

        srand48(total / 200)
        let blue = CGFloat(drand48())

        return UIColor(red: red, green: green, blue: blue, alpha: 1)
    }

}


// The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).

import XCTest
@testable import Nuke

#if !os(macOS)
    import UIKit
#endif

class ImageProcessorsAnonymousTests: XCTestCase {

    func testAnonymousProcessorsHaveDifferentIdentifiers() {
        XCTAssertEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier,
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier
        )
        XCTAssertNotEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier,
            ImageProcessors.Anonymous(id: "2", { $0 }).identifier
        )
    }

    func testAnonymousProcessorsHaveDifferentHashableIdentifiers() {
        XCTAssertEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier,
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier
        )
        XCTAssertNotEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier,
            ImageProcessors.Anonymous(id: "2", { $0 }).hashableIdentifier
        )
    }

    func testAnonymousProcessorIsApplied() throws {
        // Given
        let processor = ImageProcessors.Anonymous(id: "1") {
            $0.nk_test_processorIDs = ["1"]
            return $0
        }

        // When
        let image = try processor.process(Test.image)

        // Then
        XCTAssertEqual(image.nk_test_processorIDs ?? [], ["1"])
    }
}

Fix warnings in unit tests

// The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).

import XCTest
@testable import Nuke

#if !os(macOS)
    import UIKit
#endif

class ImageProcessorsAnonymousTests: XCTestCase {

    func testAnonymousProcessorsHaveDifferentIdentifiers() {
        XCTAssertEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier,
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier
        )
        XCTAssertNotEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).identifier,
            ImageProcessors.Anonymous(id: "2", { $0 }).identifier
        )
    }

    func testAnonymousProcessorsHaveDifferentHashableIdentifiers() {
        XCTAssertEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier,
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier
        )
        XCTAssertNotEqual(
            ImageProcessors.Anonymous(id: "1", { $0 }).hashableIdentifier,
            ImageProcessors.Anonymous(id: "2", { $0 }).hashableIdentifier
        )
    }

    func testAnonymousProcessorIsApplied() throws {
        // Given
        let processor = ImageProcessors.Anonymous(id: "1") {
            $0.nk_test_processorIDs = ["1"]
            return $0
        }

        // When
        let image = try processor.process(Test.image)

        // Then
        XCTAssertEqual(image.nk_test_processorIDs, ["1"])
    }
}


//
//  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) })?
            .enumerated()
            .flatMap { offset, element -> Self in element.key = keys?[offset]; return element }
        return firebaseModels
    }
}

Refactor names of clojure parameters in deserialization functional operation

//
//  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) })?
            .enumerated()
            .flatMap { index, model -> Self in model.key = keys?[index]; return model }
        return firebaseModels
    }
}


import Foundation
import WMF

class TalkPageFetcher: Fetcher {

}

Add new TalkPAge response objects

import Foundation
import WMF

class TalkPageResponse: Codable {
    let pageinfo: [TalkPageThreadItems]

    enum CodingKeys: String, CodingKey {
        case pageinfo = "discussiontoolspageinfo"
    }
}

class TalkPageThreadItems: Codable {
    let threadItemsHTML: [TalkPageItem]

    enum CodingKeys: String, CodingKey {
        case threadItemsHTML = "threaditemshtml"
    }
}

class TalkPageItem: Codable {
    let type: String
    let level: Int
    let id: String
    let html: String
    let headingLevel: Int
    let placeholderHeading: Bool
    let replies: [TalkPageItem]
}

class TalkPageFetcher: Fetcher {

}


struct Config: FlyConfig {
    var environment = Environment.Development
}

class UserController {
    class func newUser(request: FlyRequest, response: FlyResponse) -> FlyResponse {
        return "New User Form"
    }

    class func createUser(request: FlyRequest, response: FlyResponse) -> FlyResponse {
        return "Creating a new user!"
    }
}

extension App {
    func setup() {
        router.route("/users/new", action: UserController.newUser)
        router.route("/users/create", method: .POST, action: UserController.createUser)

        router.route("/") { request, response in
            var response = response
            response.body = "Home page!"
            return response
        }

        // not sure I like this:
        router.GET("/welcome") { request, response in
            return "Welcome to our web page"
        }

        router.route("/welcome", method: .POST) { request, response in
            return "Why are you posting to /welcome?"
        }
    }
}

Use HTML5 template for root route

struct Config: FlyConfig {
    var environment = Environment.Development
}

class UserController {
    class func newUser(request: FlyRequest, response: FlyResponse) -> FlyResponse {
        return "New User Form"
    }

    class func createUser(request: FlyRequest, response: FlyResponse) -> FlyResponse {
        return "Creating a new user!"
    }
}

extension App {
    func setup() {
        router.route("/users/new", action: UserController.newUser)
        router.route("/users/create", method: .POST, action: UserController.createUser)

        router.route("/") { request, response in
            var response = response
            response.body = HTML5([Tag(.Div, "Home page!")]).htmlString
            return response
        }

        // not sure I like this:
        router.GET("/welcome") { request, response in
            return "Welcome to our web page"
        }

        router.route("/welcome", method: .POST) { request, response in
            return "Why are you posting to /welcome?"
        }
    }
}


//
//  Store+Dispatch.swift
//  TDRedux
//
//  Created by Nicholas Tian on 20/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {
    public typealias Dispatch = (Action) -> ()
    public typealias AsyncAction = (@escaping Store.Dispatch) -> ()

    public func dispatch(asyncAction action: AsyncAction) {
        action(dispatch)
    }
}

Add docs for things in Dispatch extension

//
//  Store+Dispatch.swift
//  TDRedux
//
//  Created by Nicholas Tian on 20/10/2016.
//  Copyright © 2016 nicktd. All rights reserved.
//

extension Store {

    /// Dispatches the given *Action* to its binded *Store*
    ///
    /// - parameter action: An Action dispatched to the Store
    ///
    /// - returns: Void
    public typealias Dispatch = (_ action: Action) -> ()

    /// Async actions which will call the dispatch function
    ///
    /// - parameter dispatch: a Dispatch function
    ///
    /// - returns: Void
    public typealias AsyncAction = (_ dispath: @escaping Store.Dispatch) -> ()

    /// Dispatches *AsyncActions*
    ///
    /// - parameter action: An AsyncAction
    public func dispatch(asyncAction action: AsyncAction) {
        action(dispatch)
    }
}


//
//  InstanceStorage.swift
//  Swinject
//
//  Created by Jakub Vaňo on 11/11/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

/// Storage provided by `ObjectScope`. It is used by `Container` to persist resolved instances.
public protocol InstanceStorage: AnyObject {
    var instance: Any? { get set }
}

/// Persists stored instance until it is explicitly discarded.
public final class PermanentStorage: InstanceStorage {
    public var instance: Any?

    public init() {}
}

/// Does not persist stored instance.
public final class TransientStorage: InstanceStorage {
    public var instance: Any? {
        get { return nil }
        set {}
    }

    public init() {}
}

/// Does not persist value types.
/// Persists reference types as long as there are strong references to given instance.
public final class WeakStorage: InstanceStorage {
    private weak var object: AnyObject?

    public var instance: Any? {
        get { return object }
        set { object = newValue as AnyObject? }
    }

    public init () {}
}

Fix Any to AnyObject cast for linux environment

//
//  InstanceStorage.swift
//  Swinject
//
//  Created by Jakub Vaňo on 11/11/16.
//  Copyright © 2016 Swinject Contributors. All rights reserved.
//

/// Storage provided by `ObjectScope`. It is used by `Container` to persist resolved instances.
public protocol InstanceStorage: AnyObject {
    var instance: Any? { get set }
}

/// Persists stored instance until it is explicitly discarded.
public final class PermanentStorage: InstanceStorage {
    public var instance: Any?

    public init() {}
}

/// Does not persist stored instance.
public final class TransientStorage: InstanceStorage {
    public var instance: Any? {
        get { return nil }
        set {}
    }

    public init() {}
}

/// Does not persist value types.
/// Persists reference types as long as there are strong references to given instance.
public final class WeakStorage: InstanceStorage {
    private weak var object: AnyObject?

    #if os(Linux)
    public var instance: Any? {
        get { return object }
        set { object = newValue.flatMap { $0 as? AnyObject } }
    }
    #else
    public var instance: Any? {
        get { return object }
        set { object = newValue as AnyObject? }
    }
    #endif

    public init () {}
}


import Foundation

/// A Nimble matcher that succeeds when the actual value is Void.
public func beVoid() -> Predicate<()> {
    return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
        failureMessage.postfixMessage = "be void"
        let actualValue: ()? = try actualExpression.evaluate()
        return actualValue != nil
    }
}

public func == (lhs: Expectation<()>, rhs: ()) {
    lhs.to(beVoid())
}

public func != (lhs: Expectation<()>, rhs: ()) {
    lhs.toNot(beVoid())
}

Refactor `beVoid` matcher using `Predicate.simpleNilable`

import Foundation

/// A Nimble matcher that succeeds when the actual value is Void.
public func beVoid() -> Predicate<()> {
    return Predicate.simpleNilable("be void") { actualExpression in
        let actualValue: ()? = try actualExpression.evaluate()
        return PredicateStatus(bool: actualValue != nil)
    }
}

public func == (lhs: Expectation<()>, rhs: ()) {
    lhs.to(beVoid())
}

public func != (lhs: Expectation<()>, rhs: ()) {
    lhs.toNot(beVoid())
}


//
//  DocumentTableCellView.swift
//  SampleCodeStalker
//
//  Created by Thomas Krajacic on 23.1.2016.
//  Copyright © 2016 Thomas Krajacic. All rights reserved.
//

import Cocoa

class DocumentTableCellView: NSTableCellView {

    static let dateFormatter : NSDateFormatter = {
        let df = NSDateFormatter()
        df.dateStyle = .MediumStyle
        df.timeStyle = .NoStyle
        return df
    }()

    @IBOutlet weak var nameTextField: NSTextField!
    @IBOutlet weak var dateTextField: NSTextField!
    @IBOutlet weak var topicTextField: NSTextField!
    @IBOutlet weak var frameworkTextField: NSTextField!
    @IBOutlet weak var updateSizeTextField: NSTextField!

    var document : CDDocument? {
        didSet {
        guard let document = document else { return }
            nameTextField.stringValue = document.name
            dateTextField.stringValue = DocumentTableCellView.dateFormatter.stringFromDate(document.date)
            topicTextField.stringValue = "\(document.topic?.name ?? "") / \(document.subTopic?.name ?? "")"
            frameworkTextField.stringValue = document.framework?.name ?? ""
            updateSizeTextField.stringValue = "\(document.updateSize.rawValue)"
        }

    }

}

Improve optional subtopic display code

//
//  DocumentTableCellView.swift
//  SampleCodeStalker
//
//  Created by Thomas Krajacic on 23.1.2016.
//  Copyright © 2016 Thomas Krajacic. All rights reserved.
//

import Cocoa

class DocumentTableCellView: NSTableCellView {

    static let dateFormatter : NSDateFormatter = {
        let df = NSDateFormatter()
        df.dateStyle = .MediumStyle
        df.timeStyle = .NoStyle
        return df
    }()

    @IBOutlet weak var nameTextField: NSTextField!
    @IBOutlet weak var dateTextField: NSTextField!
    @IBOutlet weak var topicTextField: NSTextField!
    @IBOutlet weak var frameworkTextField: NSTextField!
    @IBOutlet weak var updateSizeTextField: NSTextField!

    var document : CDDocument? {
        didSet {
        guard let document = document else { return }
            nameTextField.stringValue = document.name
            dateTextField.stringValue = DocumentTableCellView.dateFormatter.stringFromDate(document.date)
            topicTextField.stringValue = "\(document.topic?.name ?? "")" + (document.subTopic.flatMap({" / \($0.name)"}) ?? "")
            frameworkTextField.stringValue = document.framework?.name ?? ""
            updateSizeTextField.stringValue = "\(document.updateSize.rawValue)"
        }

    }

}


//
//  NoteEditorTextViewDelegate.swift
//  RichTextExample
//
//  Created by Clay Tinnell on 7/27/15.
//  Copyright (c) 2015 Clay Tinnell. All rights reserved.
//

import UIKit
import Foundation

class NoteEditorTextViewDelegate: NSObject {

    func characterIsAWordTerminator(text: String) -> Bool {
        return text == " " || text == "." || text == "," || text == ":" || text == ";" || text == "\n" || text == "!" || text == "?"
    }

    func stripSpecialCharacters(text: String) -> [String]? {
        let strippedLowerCaseText = " ".join(text.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)).lowercaseString
        let trimmedWhiteSpace = strippedLowerCaseText.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!isEmpty($0)})
        return trimmedWhiteSpace
    }

}

extension NoteEditorTextViewDelegate : UITextViewDelegate {
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

        println("text changed: \(text)")
        if characterIsAWordTerminator(text) {
            println("word terminator")
            if let strippedText = stripSpecialCharacters(textView.text) {
                println(",".join(strippedText))
            }
        }
        return true
    }
}

Refactor functions into String extension

//
//  NoteEditorTextViewDelegate.swift
//  RichTextExample
//
//  Created by Clay Tinnell on 7/27/15.
//  Copyright (c) 2015 Clay Tinnell. All rights reserved.
//

import UIKit
import Foundation

class NoteEditorTextViewDelegate: NSObject {

}

extension NoteEditorTextViewDelegate : UITextViewDelegate {

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if text.isAWordTerminator() {
            println(textView.text.stripSpecialCharacters().trimExtraWhiteSpace())
        }
        return true
    }
}

private extension String {
    func isAWordTerminator() -> Bool {
        return self == " " || self == "." || self == "," || self == ":" || self == ";" || self == "\n" || self == "!" || self == "?"
    }

    func stripSpecialCharacters() -> String {
        return " ".join(self.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)).lowercaseString
    }

    func componentsSeparatedByWhiteSpace() -> [String] {
        return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    func trimExtraWhiteSpace() -> String {
        return " ".join(self.componentsSeparatedByWhiteSpace().filter({!$0.isEmpty}))
    }
}


//
//  WebMPlayerViewController.swift
//  KomicaViewer
//
//  Created by Craig Zheng on 2/11/16.
//  Copyright © 2016 Craig. All rights reserved.
//

import UIKit

import OGVKit

class WebMPlayerViewController: UIViewController {

    var webMSourceURL: NSURL!

    @IBOutlet weak var playerView: OGVPlayerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        playerView.delegate = self
        playerView.sourceURL = webMSourceURL
        playerView.play()
    }

    @IBAction func doneAction(sender: AnyObject) {
        navigationController?.popViewControllerAnimated(true)
        dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func safariAction(sender: AnyObject) {
        if webMSourceURL != nil {
            UIApplication.sharedApplication().openURL(webMSourceURL)
        }
    }

}

extension WebMPlayerViewController: OGVPlayerDelegate {

}

Stop the webM player upon tapping the done button.

//
//  WebMPlayerViewController.swift
//  KomicaViewer
//
//  Created by Craig Zheng on 2/11/16.
//  Copyright © 2016 Craig. All rights reserved.
//

import UIKit

import OGVKit

class WebMPlayerViewController: UIViewController {

    var webMSourceURL: NSURL!

    @IBOutlet weak var playerView: OGVPlayerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        playerView.delegate = self
        playerView.sourceURL = webMSourceURL
        playerView.play()
    }

    @IBAction func doneAction(sender: AnyObject) {
        playerView.pause()
        navigationController?.popViewControllerAnimated(true)
        dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func safariAction(sender: AnyObject) {
        if webMSourceURL != nil {
            UIApplication.sharedApplication().openURL(webMSourceURL)
        }
    }

}

extension WebMPlayerViewController: OGVPlayerDelegate {

}


//
//  EditViewController.swift
//  Noted
//
//  Created by Michael Andrew Auer on 1/23/16.
//  Copyright © 2016 Usonia LLC. All rights reserved.
//

import UIKit

class EditViewController: UIViewController {

    @IBOutlet weak var noteTextField: UITextView!

    var selectedValue: Note!
    let dataInterface = DataInterface()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Get rid of that blank space at the top of the text view
        self.automaticallyAdjustsScrollViewInsets = false
        // Set the value of the text field to the note that we clicked on in the table view
        noteTextField.text = selectedValue?.note

        // Hide the back button
        self.navigationItem.setHidesBackButton(true, animated: false)
    }

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

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "save") {
            // If we have a note object update it, if not create a new one
            if (selectedValue == nil) {
                dataInterface.create("Note", properties: [
                    "note": noteTextField.text!
                ])
            } else {
                selectedValue?.note = noteTextField.text!
                dataInterface.update(selectedValue)
            }
        }
    }
}

Change title of edit view controller based on context

//
//  EditViewController.swift
//  Noted
//
//  Created by Michael Andrew Auer on 1/23/16.
//  Copyright © 2016 Usonia LLC. All rights reserved.
//

import UIKit

class EditViewController: UIViewController {

    @IBOutlet weak var noteTextField: UITextView!

    var selectedValue: Note!
    let dataInterface = DataInterface()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Get rid of that blank space at the top of the text view
        self.automaticallyAdjustsScrollViewInsets = false

        if (selectedValue != nil) {
            // Set the value of the text field to the note that we clicked on in the table view
            noteTextField.text = selectedValue?.note
            self.navigationController?.topViewController!.title = "Edit Note"
        } else {
            self.navigationController?.topViewController!.title = "New Note"
        }
        // Hide the back button
        self.navigationItem.setHidesBackButton(true, animated: false)
    }

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

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "save") {
            // If we have a note object update it, if not create a new one
            if (selectedValue == nil) {
                dataInterface.create("Note", properties: [
                    "note": noteTextField.text!
                ])
            } else {
                selectedValue?.note = noteTextField.text!
                dataInterface.update(selectedValue)
            }
        }
    }
}


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

import CoreGraphics

extension CGRect {

    var diagonal: CGFloat {

        let widthSquared = width * width
        let heightSquared = height * height

        let diagonal = sqrt(widthSquared + heightSquared)

        return diagonal

    }

}

Use "pow" function to calculate squared values

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

import CoreGraphics

extension CGRect {

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

}


/**
 * Question Link: https://leetcode.com/problems/balanced-binary-tree/
 * Primary idea: use the idea of maximum depth of a binary tree
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */

class BalancedBinaryTree {
    func isBalanced(root: TreeNode?) -> Bool {
        guard let root = root else {
            return true
        }

        if _checkHeight(root) == -1 {
            return false
        }

        return true
    }

    private func _checkHeight(root: TreeNode?) -> Int {
        guard let root = root else {
            return 0
        }

        // check left and right subtree
        var leftHeight = _checkHeight(root.left)
        if leftHeight == -1 {
            return -1
        }
        var rightHeight = _checkHeight(root.right)
        if rightHeight == -1 {
            return -1
        }

        // check current
        if abs(leftHeight - rightHeight) > 1 {
            return -1
        }

        return max(leftHeight, rightHeight) + 1
    }
}

Optimize solution to Balanced Binary Tree

/**
 * Question Link: https://leetcode.com/problems/balanced-binary-tree/
 * Primary idea: use the idea of maximum depth of a binary tree
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */

class BalancedBinaryTree {
    func isBalanced(_ root: TreeNode?) -> Bool {
        return checkHeight(root) != -1
    }

    private func checkHeight(_ root: TreeNode?) -> Int {
        guard let root = root else {
            return 0
        }

        let left = checkHeight(root.left), right = checkHeight(root.right)

        if left == -1 || right == -1 {
            return -1
        }

        if abs(left - right) > 1 {
            return -1
        }

        return max(left, right) + 1
    }
}


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

// RUN: not %target-swift-frontend %s -emit-ir
// REQUIRES: asserts
{lazy var E

Remove "REQUIRES: asserts" from fixed crasher.

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

// RUN: not %target-swift-frontend %s -emit-ir
{lazy var E


//
//  CoreDataKit.swift
//  CoreDataKit
//
//  Created by Mathijs Kadijk on 23-06-14.
//  Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//

import CoreData

public class CoreDataKit : NSObject
{
    private struct DefaultCoordinator {
        static var instance: NSPersistentStoreCoordinator?
    }

    public class var persistentStoreCoordinator: NSPersistentStoreCoordinator! {
        get {
            return DefaultCoordinator.instance
        }

        set {
            DefaultCoordinator.instance = newValue
        }
    }

    public class var rootContext: NSManagedObjectContext {
        struct Singleton {
            static let instance = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType, persistentStoreCoordinator: CoreDataKit.persistentStoreCoordinator!)
        }

        return Singleton.instance
    }

    public class var mainThreadContext: NSManagedObjectContext {
        struct Singleton {
            static let instance = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType, parentContext: CoreDataKit.rootContext)
        }

        return Singleton.instance
    }
}

Make coordinator optional so checks are foced by the compiler

//
//  CoreDataKit.swift
//  CoreDataKit
//
//  Created by Mathijs Kadijk on 23-06-14.
//  Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//

import CoreData

public class CoreDataKit : NSObject
{
    private struct DefaultCoordinator {
        static var instance: NSPersistentStoreCoordinator?
    }

    public class var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
        get {
            return DefaultCoordinator.instance
        }

        set {
            DefaultCoordinator.instance = newValue
        }
    }

    public class var rootContext: NSManagedObjectContext {
        struct Singleton {
            static let instance = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType, persistentStoreCoordinator: CoreDataKit.persistentStoreCoordinator!)
        }

        return Singleton.instance
    }

    public class var mainThreadContext: NSManagedObjectContext {
        struct Singleton {
            static let instance = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType, parentContext: CoreDataKit.rootContext)
        }

        return Singleton.instance
    }
}


import EurofurenceModel
import UserNotifications

struct UserNotificationsScheduler: NotificationScheduler {

    func scheduleNotification(forEvent identifier: EventIdentifier,
                              at dateComponents: DateComponents,
                              title: String,
                              body: String,
                              userInfo: [ApplicationNotificationKey: String]) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.userInfo = userInfo.xpcSafeDictionary

        let soundName = UNNotificationSoundName(rawValue: "personal_notification.caf")
        content.sound = UNNotificationSound(named: soundName)

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
        let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("Failed to add notification with error: \(error)")
            }
        }
    }

    func cancelNotification(forEvent identifier: EventIdentifier) {
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
    }

}

private extension Dictionary where Key == ApplicationNotificationKey, Value == String {

    var xpcSafeDictionary: [String: String] {
        let stringPairs: [(String, String)] = map({ (key, value) -> (String, String) in
            return (key.rawValue, value)
        })

        var dictionary = [String: String]()
        for (key, value) in stringPairs {
            dictionary[key] = value
        }

        return dictionary
    }

}

Mark event reminders as time sensitive

import EurofurenceModel
import UserNotifications

struct UserNotificationsScheduler: NotificationScheduler {

    func scheduleNotification(forEvent identifier: EventIdentifier,
                              at dateComponents: DateComponents,
                              title: String,
                              body: String,
                              userInfo: [ApplicationNotificationKey: String]) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.userInfo = userInfo.xpcSafeDictionary

        if #available(iOS 15.0, *) {
            content.interruptionLevel = .timeSensitive
        }

        let soundName = UNNotificationSoundName(rawValue: "personal_notification.caf")
        content.sound = UNNotificationSound(named: soundName)

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
        let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("Failed to add notification with error: \(error)")
            }
        }
    }

    func cancelNotification(forEvent identifier: EventIdentifier) {
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
    }

}

private extension Dictionary where Key == ApplicationNotificationKey, Value == String {

    var xpcSafeDictionary: [String: String] {
        let stringPairs: [(String, String)] = map({ (key, value) -> (String, String) in
            return (key.rawValue, value)
        })

        var dictionary = [String: String]()
        for (key, value) in stringPairs {
            dictionary[key] = value
        }

        return dictionary
    }

}


import Foundation

extension String: DefaultConstructible {}

Add a bunch of DefaultConstructible extensions

import Foundation

extension Array : DefaultConstructible {}
extension AutoreleasingUnsafeMutablePointer : DefaultConstructible {}
extension Bool : DefaultConstructible {}
extension COpaquePointer : DefaultConstructible {}
extension ContiguousArray : DefaultConstructible {}
extension Dictionary : DefaultConstructible {}
extension Double : DefaultConstructible {}
extension EmptyCollection : DefaultConstructible {}
extension EmptyGenerator : DefaultConstructible {}
extension Float : DefaultConstructible {}
extension Float80 : DefaultConstructible {}
extension Int : DefaultConstructible {}
extension Int16 : DefaultConstructible {}
extension Int32 : DefaultConstructible {}
extension Int64 : DefaultConstructible {}
extension Int8 : DefaultConstructible {}
extension StaticString : DefaultConstructible {}
extension String : DefaultConstructible {}
extension UInt : DefaultConstructible {}
extension UInt16 : DefaultConstructible {}
extension UInt32 : DefaultConstructible {}
extension UInt64 : DefaultConstructible {}
extension UInt8 : DefaultConstructible {}
extension UTF16 : DefaultConstructible {}
extension UTF32 : DefaultConstructible {}
extension UTF8 : DefaultConstructible {}
extension UnicodeScalar : DefaultConstructible {}
extension UnsafeMutablePointer : DefaultConstructible {}
extension UnsafePointer : DefaultConstructible {}


import Foundation
import SwiftyGPIO
import led

class Blink {

    let led: LED

    // This will work for a LED attached to GPIO pin 17 on a Raspberry Pi 3
    init() {
        let gpios = SwiftyGPIO.GPIOs(for:.RaspberryPi3)
        self.led = LED(gpioPin: .P17, swiftyGPIOs: gpios)
    }

    // Blink 3 times
    func start() {
        for _ in 1...3 {
            // Light up LED by setting value to 1
            self.led.value = 1
            sleep(1)

            // Turn the LED off by setting value to 0
            self.led.value = 0
            sleep(1)
        }
    }

}

// Main program starts here
Blink().start()

Simplify by using the convenience initializer on LED.

import Foundation
import SwiftyGPIO
import led

class Blink {

    let led: LED

    // This will work for a LED attached to GPIO pin 17 on a Raspberry Pi 3
    init() {
        self.led = LED(gpioPin: .P17)
    }

    // Blink 3 times
    func start() {
        for _ in 1...3 {
            // Light up LED by setting value to 1
            self.led.value = 1
            sleep(1)

            // Turn the LED off by setting value to 0
            self.led.value = 0
            sleep(1)
        }
    }

}

// Main program starts here
Blink().start()


//
//  JSONProtocols.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 14/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public enum JSONModelError: Error {
    case jsonIsNotAnObject
    case invalidElement
}

public protocol PropertiesContaining {
    associatedtype PropertyKey: RawRepresentable, Hashable
}

public protocol JSONObjectInitializable: PropertiesContaining, JSONInitializable {
    init(object: JSONObject<PropertyKey>) throws
}

public protocol JSONObjectRepresentable: PropertiesContaining, JSONRepresentable {
    var dictValue: [PropertyKey: JSONRepresentable] { get }
}

public protocol JSONModelType: JSONObjectInitializable, JSONObjectRepresentable {}

public extension JSONObjectInitializable where PropertyKey.RawValue == String {
    init(json: JSON) throws {
        let jsonObject = try JSONObject<PropertyKey>(json: json)
        try self.init(object: jsonObject)
    }
}

public extension JSONObjectRepresentable where PropertyKey.RawValue == String {
    var jsonValue: JSON {
        return JSONObject<PropertyKey>(dictValue).jsonValue
    }
}

Add recursive error case for value for key

//
//  JSONProtocols.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 14/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public indirect enum JSONModelError: Error {
    case jsonIsNotAnObject
    case invalidElement
    case invalidValueFor(key: String, JSONModelError)
}
}

public protocol PropertiesContaining {
    associatedtype PropertyKey: RawRepresentable, Hashable
}

public protocol JSONObjectInitializable: PropertiesContaining, JSONInitializable {
    init(object: JSONObject<PropertyKey>) throws
}

public protocol JSONObjectRepresentable: PropertiesContaining, JSONRepresentable {
    var dictValue: [PropertyKey: JSONRepresentable] { get }
}

public protocol JSONModelType: JSONObjectInitializable, JSONObjectRepresentable {}

public extension JSONObjectInitializable where PropertyKey.RawValue == String {
    init(json: JSON) throws {
        let jsonObject = try JSONObject<PropertyKey>(json: json)
        try self.init(object: jsonObject)
    }
}

public extension JSONObjectRepresentable where PropertyKey.RawValue == String {
    var jsonValue: JSON {
        return JSONObject<PropertyKey>(dictValue).jsonValue
    }
}


//
//  Plotting.swift
//  SwiftNum
//
//  Created by Donald Pinckney on 12/27/16.
//
//

import Foundation

func plot(_ xs: [Double], toFile: String? = nil) {
    let plotCommand = "plot '<cat' with impulses"
    let code: String
    if let file = toFile {
        code = "set terminal png; set output \"\(file)\";" + plotCommand
    } else {
        code = plotCommand
    }

    let inputPipe = Pipe()
    var inputFile = inputPipe.fileHandleForWriting

    let gnuplot = Process()
    gnuplot.launchPath = "/usr/local/bin/gnuplot"
    gnuplot.arguments = ["-p", "-e", code]
    gnuplot.standardInput = inputPipe
    gnuplot.launch()

    let plotData = xs.map { $0.description }.joined(separator: "\n")
    print(plotData, to: &inputFile)
    inputFile.closeFile()
}

Change plotting to normal line, until we write much better plotting

//
//  Plotting.swift
//  SwiftNum
//
//  Created by Donald Pinckney on 12/27/16.
//
//

import Foundation

public func plot(_ xs: [Double], toFile: String? = nil) {
    let plotCommand = "plot '<cat' with lines"
    let code: String
    if let file = toFile {
        code = "set terminal png; set output \"\(file)\";" + plotCommand
    } else {
        code = plotCommand
    }

    let inputPipe = Pipe()
    var inputFile = inputPipe.fileHandleForWriting

    let gnuplot = Process()
    gnuplot.launchPath = "/usr/local/bin/gnuplot"
    gnuplot.arguments = ["-p", "-e", code]
    gnuplot.standardInput = inputPipe
    gnuplot.launch()

    let plotData = xs.map { $0.description }.joined(separator: "\n")
    print(plotData, to: &inputFile)
    inputFile.closeFile()
}


/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/
class Problem01 {

    let MAX = 1000                              // Upperbound
    let factors:Array<Int> = [3,5]              // Factors to check for multiples

    /*
        Iterates through the given Natural numbers collection.
        If an element of the Natural numbers collections is a multiple
        of the given factors, add it to the current sum.
    */
    func findSum() {
        var sumOfMultiples:Int = 0              // Initialize and set sum to 0

        for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
            for j in factors {                  // Iterate over given factors.
                if i % j == 0 {                 // If current factor is a multiple of current element of the collection N,
                    sumOfMultiples += i         // add the current element to the current sum.
                    break
                }
            }
        }

        print(sumOfMultiples)                   // Return summated result of found factor multiples.
    }

}

Remove class definition from solution

/**
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
    multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
*/

let MAX = 1000                              // Upperbound
let factors:Array<Int> = [3,5]              // Factors to check for multiples

/*
    Iterates through the given Natural numbers collection.
    If an element of the Natural numbers collections is a multiple
    of the given factors, add it to the current sum.
*/

func findSum() {
    var sumOfMultiples:Int = 0              // Initialize and set sum to 0

    for i in factors.minElement()!..<MAX {  // Iterate from lowerbound to upperbound.
        for j in factors {                  // Iterate over given factors.
            if i % j == 0 {                 // If current factor is a multiple of current element of the collection N,
                sumOfMultiples += i         // add the current element to the current sum.
                break
            }
        }
    }

    print(sumOfMultiples)                   // Return summated result of found factor multiples.
}


/**
    A `Driver` execute queries
    and returns an array of results.
    It is responsible for interfacing
    with the data store powering Fluent.
*/
public protocol Driver: Executor {
    /**
        The string value for the
        default identifier key.

        The `idKey` will be used when
        `Model.find(_:)` or other find
        by identifier methods are used.
    */
    var idKey: String { get }

    /**
        Creates a connection for executing
        queries. This method is used to
        automatically create a connection
        if any Executor methods are called on
        the Driver.
    */
    func makeConnection() throws -> Connection
}

// MARK: Executor

extension Driver {
    @discardableResult
    public func query<T: Entity>(_ query: Query<T>) throws -> Node {
        return try makeConnection().query(query)
    }

    public func schema(_ schema: Schema) throws {
        return try makeConnection().schema(schema)
    }

    @discardableResult
    public func raw(_ raw: String, _ values: [Node]) throws -> Node {
        return try makeConnection().raw(raw, values)
    }
}

// MARK: Deprecated

enum DriverError: Error {
    case connectionsNotSupported(String)
}

extension Driver {
    public func makeConnection() throws -> Connection {
        throw DriverError.connectionsNotSupported("Please update your database driver package to be compatible with Fluent 1.4.")
    }
}

Document 'overridability' of idKey property on the database driver file by individual entities

/**
    A `Driver` execute queries
    and returns an array of results.
    It is responsible for interfacing
    with the data store powering Fluent.
*/
public protocol Driver: Executor {
    /**
        The string value for the
        default identifier key.

        The `idKey` will be used when
        `Model.find(_:)` or other find
        by identifier methods are used.

        This value is overriden by
        entities that implement the
        `Entity.idKey` static property.
    */
    var idKey: String { get }

    /**
        Creates a connection for executing
        queries. This method is used to
        automatically create a connection
        if any Executor methods are called on
        the Driver.
    */
    func makeConnection() throws -> Connection
}

// MARK: Executor

extension Driver {
    @discardableResult
    public func query<T: Entity>(_ query: Query<T>) throws -> Node {
        return try makeConnection().query(query)
    }

    public func schema(_ schema: Schema) throws {
        return try makeConnection().schema(schema)
    }

    @discardableResult
    public func raw(_ raw: String, _ values: [Node]) throws -> Node {
        return try makeConnection().raw(raw, values)
    }
}

// MARK: Deprecated

enum DriverError: Error {
    case connectionsNotSupported(String)
}

extension Driver {
    public func makeConnection() throws -> Connection {
        throw DriverError.connectionsNotSupported("Please update your database driver package to be compatible with Fluent 1.4.")
    }
}


//
//  PodTestsTests.swift
//  PodTestsTests
//
//  Created by doof nugget on 4/18/16.
//  Copyright © 2016 letvargo. All rights reserved.
//

import XCTest
import LVGUtilities

class PodTestsTests: XCTestCase {

    class TestClass {
        var value = 0
    }

    var obj = TestClass()

    func testEqualityAfterBridgeRetained() {
        let objBridged = bridgeRetained(obj)
        let objUnbridged: TestClass = bridgeTransfer(objBridged)
        XCTAssert(obj === objUnbridged)
    }

    func testEqualityAfterBridge() {
        let objBridged = bridge(obj)
        let objUnbridged: TestClass = bridge(objBridged)
        XCTAssert(obj === objUnbridged)
    }
}

Change name of bridging functions test class

//
//  PodTestsTests.swift
//  PodTestsTests
//
//  Created by doof nugget on 4/18/16.
//  Copyright © 2016 letvargo. All rights reserved.
//

import XCTest
import LVGUtilities

class CBridgingFunctionTests: XCTestCase {

    class TestClass {
        var value = 0
    }

    var obj = TestClass()

    func testEqualityAfterBridgeRetained() {
        let objBridged = bridgeRetained(obj)
        let objUnbridged: TestClass = bridgeTransfer(objBridged)
        XCTAssert(obj === objUnbridged)
    }

    func testEqualityAfterBridge() {
        let objBridged = bridge(obj)
        let objUnbridged: TestClass = bridge(objBridged)
        XCTAssert(obj === objUnbridged)
    }
}


//
//  MangasViewModel.swift
//  Yomu
//
//  Created by Sendy Halim on 7/3/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import RxCocoa
import RxMoya
import RxSwift
import Swiftz

struct MangaCollectionViewModel {
  private let _mangaById = Variable(Set<Manga>())
  private let provider = RxMoyaProvider<MangaEdenAPI>()

  var mangas: Driver<List<Manga>> {
    return _mangaById.asDriver().map {
      return List(fromArray: $0.flatMap(identity))
    }
  }

  func fetch(id: String) -> Disposable {
    let api = MangaEdenAPI.MangaDetail(id)

    return provider
      .request(api)
      .filterSuccessfulStatusCodes()
      .map(Manga.self)
      .subscribeNext {
        var manga = $0
        manga.id = id

        // Manga already in collection
        if self._mangaById.value.contains(manga) {
          return
        }

        self._mangaById.value.insert(manga)
      }
  }
}

Add subscript and count computed properties

//
//  MangasViewModel.swift
//  Yomu
//
//  Created by Sendy Halim on 7/3/16.
//  Copyright © 2016 Sendy Halim. All rights reserved.
//

import RxCocoa
import RxMoya
import RxSwift
import Swiftz

struct MangaCollectionViewModel {
  private let _mangas = Variable(Set<Manga>())
  private let provider = RxMoyaProvider<MangaEdenAPI>()

  var mangas: Driver<List<Manga>> {
    return _mangas.asDriver().map {
      return List(fromArray: $0.flatMap(identity))
    }
  }

  var count: Int {
    return _mangas.value.count
  }

  subscript(index: Int) -> Manga {
    let mangas = _mangas.value
    let _index = mangas.startIndex.advancedBy(index)

    return mangas[_index]
  }

  func fetch(id: String) -> Disposable {
    let api = MangaEdenAPI.MangaDetail(id)

    return provider
      .request(api)
      .filterSuccessfulStatusCodes()
      .map(Manga.self)
      .subscribeNext {
        var manga = $0
        manga.id = id

        // Manga already in collection
        if self._mangas.value.contains(manga) {
          return
        }

        self._mangas.value.insert(manga)
      }
  }
}


/**
 Anything that has default value
*/
public protocol DefaultType {
  static var defaultValue: Self { get }
}

extension String: DefaultType {
  public static var defaultValue: String {
    return ""
  }
}

extension Int: DefaultType {
  public static var defaultValue: Int {
    return 0
  }
}

extension Float: DefaultType {
  public static var defaultValue: Float {
    return 0
  }
}

extension Bool: DefaultType {
  public static var defaultValue: Bool {
    return false
  }
}

extension Array: DefaultType {
  public static var defaultValue: Array {
    return []
  }
}

extension Dictionary: DefaultType {
  public static var defaultValue: Dictionary {
    return [:]
  }
}

Add missing extension on Double

/**
 Anything that has default value
*/
public protocol DefaultType {
  static var defaultValue: Self { get }
}

extension String: DefaultType {
  public static var defaultValue: String {
    return ""
  }
}

extension Int: DefaultType {
  public static var defaultValue: Int {
    return 0
  }
}

extension Double: DefaultType {
  public static var defaultValue: Double {
    return 0
  }
}

extension Float: DefaultType {
  public static var defaultValue: Float {
    return 0
  }
}

extension Bool: DefaultType {
  public static var defaultValue: Bool {
    return false
  }
}

extension Array: DefaultType {
  public static var defaultValue: Array {
    return []
  }
}

extension Dictionary: DefaultType {
  public static var defaultValue: Dictionary {
    return [:]
  }
}


import Foundation

class MOptionWhistlesVsZombiesWhistle
{

}

Create required init for whistle model

import SpriteKit

class MOptionWhistlesVsZombiesWhistle
{
    private weak var textures:MOptionWhistlesVsZombiesWhistleTextures!

    required init(textures:MOptionWhistlesVsZombiesWhistleTextures)
    {
        self.textures = textures
    }
}


//
// main.swift
//
// This file containing the example code is in public domain.
// Feel free to copy-paste it and edit it in any way you like.
//

import Foundation
import TelegramBot

let environment = NSProcessInfo.processInfo().environment
guard let token = environment["HELLO_BOT_TOKEN"] else {
    fatalError("Please set HELLO_BOT_TOKEN environment variable")
}

let bot = TelegramBot(token: token)

let router = Router()

router.addPath([Command("help")]) { () -> () in
    let helpText = "Usage: /greet"
    bot.respondPrivatelyAsync(helpText,
        groupText: "\(bot.lastMessage.from.firstName), please find usage instructions in a personal message.")
}

router.addPath([Command("greet")]) { () -> () in
    bot.respondAsync("Hello, \(bot.lastMessage.from.firstName)!")
}

// Default handler
router.addPath([RestOfString("text")]) { (args: Arguments) -> () in
    let text = args["text"].stringValue
    bot.respondAsync("I don't understand \(text).\n" +
        "Usage: /greet")
}

print("Ready to accept commands")
while let command = bot.nextCommandSync() {
    print("--- updateId: \(bot.lastUpdate!.updateId)")
    print("message: \(bot.lastMessage.prettyPrint)")
    try router.processString(command)
}
fatalError("Server stopped due to error: \(bot.lastError)")

Use new API in hello-bot sample

//
// main.swift
//
// This file containing the example code is in public domain.
// Feel free to copy-paste it and edit it in any way you like.
//

import Foundation
import TelegramBot

let environment = NSProcessInfo.processInfo().environment
guard let token = environment["HELLO_BOT_TOKEN"] else {
    fatalError("Please set HELLO_BOT_TOKEN environment variable")
}

let bot = TelegramBot(token: token)

let router = Router()

router.add(Command("help")) { () -> () in
    let helpText = "Usage: /greet"
    bot.respondPrivatelyAsync(helpText,
        groupText: "\(bot.lastMessage.from.first_name), please find usage instructions in a personal message.")
}

router.add(Command("greet")) { () -> () in
    bot.respondAsync("Hello, \(bot.lastMessage.from.first_name)!")
}

// Default handler
router.fallbackHandler = .NonCancellableHandlerWithArguments({ (args: ArgumentScanner) -> () in
    let text = args.scanRestOfString()
    bot.respondAsync("I don't understand \(text).\n" +
        "Usage: /greet")
})

print("Ready to accept commands")
while let message = bot.nextMessageSync() {
	print("--- update_id: \(bot.lastUpdate!.update_id)")
	print("message: \(message.debugDescription)")
	print("command: \(bot.lastCommand.unwrapOptional)")

	if let command = bot.lastCommand {
		try router.process(command)
	}
}
fatalError("Server stopped due to error: \(bot.lastError)")


/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

import swiftra

#if os(Linux)
    import Glibc
#endif

get("/abc") { req in
    return Response("/abc was requested with GET")
}

post("/abc") { req in
    return "/abc was requested with POST, body = \(req.body)"
}

get("/def") { req in
    return "/def was was requested with GET"
}

serve(8080)

Update to print decoded text

/*
 The MIT License (MIT)

 Copyright (c) 2015 Shun Takebayashi

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

import swiftra

#if os(Linux)
    import Glibc
#endif

get("/abc") { req in
    return Response("/abc was requested with GET")
}

post("/abc") { req in
    return "/abc was requested with POST, body = \(String(req.bodyString))"
}

get("/def") { req in
    return "/def was was requested with GET"
}

serve(8080)


//
//  CollectThemAllModuleBuilder.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class CollectThemAllModuleBuilder {

    private var sceneFactory: CollectThemAllSceneFactory
    private var service: CollectThemAllService

    init() {
        struct DummyCollectThemAllService: CollectThemAllService {
            func subscribe(_ observer: CollectThemAllURLObserver) {

            }
        }

        sceneFactory = StoryboardCollectThemAllSceneFactory()
        service = DummyCollectThemAllService()
    }

    @discardableResult
    func with(_ sceneFactory: CollectThemAllSceneFactory) -> CollectThemAllModuleBuilder {
        self.sceneFactory = sceneFactory
        return self
    }

    @discardableResult
    func with(_ service: CollectThemAllService) -> CollectThemAllModuleBuilder {
        self.service = service
        return self
    }

    func build() -> CollectThemAllModuleProviding {
        return CollectThemAllModule(sceneFactory: sceneFactory, service: service)
    }

}

Use concrete collect them all service

//
//  CollectThemAllModuleBuilder.swift
//  Eurofurence
//
//  Created by Thomas Sherwood on 24/06/2018.
//  Copyright © 2018 Eurofurence. All rights reserved.
//

import UIKit

class CollectThemAllModuleBuilder {

    private var sceneFactory: CollectThemAllSceneFactory
    private var service: CollectThemAllService

    init() {
        sceneFactory = StoryboardCollectThemAllSceneFactory()
        service = EurofurenceApplication.shared
    }

    @discardableResult
    func with(_ sceneFactory: CollectThemAllSceneFactory) -> CollectThemAllModuleBuilder {
        self.sceneFactory = sceneFactory
        return self
    }

    @discardableResult
    func with(_ service: CollectThemAllService) -> CollectThemAllModuleBuilder {
        self.service = service
        return self
    }

    func build() -> CollectThemAllModuleProviding {
        return CollectThemAllModule(sceneFactory: sceneFactory, service: service)
    }

}


//
//  Currency.swift
//  FinanceKit
//
//  Created by Christian Mitteldorf on 17/05/2017.
//  Copyright © 2017 Christian Mitteldorf. All rights reserved.
//

import Foundation

public enum CurrencyCode: String, CaseIterable, Codable {
    #warning("get all currencies and sort by name")
    case dkk
    case USD
    case EUR
    case GBP
    case AUD
    case NOK
    case SEK

    public var currencyCodeString: String {
        self.rawValue.uppercased()
    }

    var currencyName: String {
        switch self {
        default:
            return ""
        }
    }
}

public struct Currency: Codable {

    public let code: CurrencyCode
    public let name: String

    init(code currencyCode: CurrencyCode) {
        code = currencyCode
        name = currencyCode.currencyName
    }
}

Add unknown case for currency

//
//  Currency.swift
//  FinanceKit
//
//  Created by Christian Mitteldorf on 17/05/2017.
//  Copyright © 2017 Christian Mitteldorf. All rights reserved.
//

import Foundation

public enum CurrencyCode: String, CaseIterable, Codable {
    #warning("get all currencies and sort by name")
    case unknown
    case dkk
    case USD
    case EUR
    case GBP
    case AUD
    case NOK
    case SEK

    public var currencyCodeString: String {
        self.rawValue.uppercased()
    }

    public var currencyName: String {
        switch self {
        default:
            return ""
        }
    }
}

public struct Currency: Codable {

    public let code: CurrencyCode
    public let name: String

    public init(code currencyCode: CurrencyCode) {
        code = currencyCode
        name = currencyCode.currencyName
    }
}


//
//  RoundedBorderButton.swift
//  Swiftlier
//
//  Created by Andrew J Wagner on 5/29/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

#if os(iOS)
import UIKit

@IBDesignable class RoundedBorderButton: UIButton {
    @IBInspectable var borderColor: UIColor = UIColor.clear {
        didSet {
            self.update()
        }
    }

    @IBInspectable var borderSize: CGFloat = 1 / UIScreen.main.scale {
        didSet {
            self.update()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 10 {
        didSet {
            self.update()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.update()
    }
}

private extension RoundedBorderButton {
    func update() {
        self.layer.borderWidth = self.borderSize
        self.layer.borderColor = self.borderColor.cgColor
        self.layer.cornerRadius = self.cornerRadius
    }
}
#endif

Make rounded border button public

//
//  RoundedBorderButton.swift
//  Swiftlier
//
//  Created by Andrew J Wagner on 5/29/16.
//  Copyright © 2016 Drewag LLC. All rights reserved.
//

#if os(iOS)
import UIKit

@IBDesignable
public class RoundedBorderButton: UIButton {

    @IBInspectable
    public  var borderColor: UIColor = UIColor.clear {
        didSet {
            self.update()
        }
    }

    @IBInspectable
    public var borderSize: CGFloat = 1 / UIScreen.main.scale {
        didSet {
            self.update()
        }
    }

    @IBInspectable
    public var cornerRadius: CGFloat = 10 {
        didSet {
            self.update()
        }
    }

    open override func awakeFromNib() {
        super.awakeFromNib()

        self.update()
    }
}

private extension RoundedBorderButton {
    func update() {
        self.layer.borderWidth = self.borderSize
        self.layer.borderColor = self.borderColor.cgColor
        self.layer.cornerRadius = self.cornerRadius
    }
}
#endif


// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "GraphQL",

    products: [
        .library(name: "GraphQL", targets: ["GraphQL"]),
    ],

    dependencies: [
        .package(url: "https://github.com/wickwirew/Runtime.git", from: "0.5.0"),
    ],

    targets: [
        .target(name: "GraphQL", dependencies: ["Runtime"]),

        .testTarget(name: "GraphQLTests", dependencies: ["GraphQL"]),
    ]
)

Update to Runtime library 0.6.0

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "GraphQL",

    products: [
        .library(name: "GraphQL", targets: ["GraphQL"]),
    ],

    dependencies: [
        .package(url: "https://github.com/wickwirew/Runtime.git", from: "0.6.0"),
    ],

    targets: [
        .target(name: "GraphQL", dependencies: ["Runtime"]),

        .testTarget(name: "GraphQLTests", dependencies: ["GraphQL"]),
    ]
)


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

import PackageDescription

let package = Package(
    name: "CGPointVector",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "CGPointVector",
            targets: ["CGPointVector"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "CGPointVector",
            dependencies: [],
            path: "Sources"),
        .testTarget(
            name: "CGPointVectorTests",
            dependencies: ["CGPointVector"]),
    ]
)

Support only Swift 5.0 and later

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

import PackageDescription

let package = Package(
    name: "CGPointVector",
    platforms: [
        .iOS(.v8),
        .macOS(.v10_10),
        .tvOS(.v9),
        .watchOS(.v2),
    ],
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "CGPointVector",
            targets: ["CGPointVector"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "CGPointVector",
            dependencies: [],
            path: "Sources"),
        .testTarget(
            name: "CGPointVectorTests",
            dependencies: ["CGPointVector"]),
    ],
    swiftLanguageVersions: [.v5]
)


// 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", .upToNextMajor(from: "1.9.0")),
    ],
    targets: [
        .target(
            name: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph", "Squall", "Yams", "SwiftyBeaver"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)

Update dependency SwiftyBeaver/SwiftyBeaver to from: "1.9.4"

// 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.4"),
    ],
    targets: [
        .target(
            name: "Conductor",
            dependencies: ["Danger", "Commander", "SwiftGraph", "Squall", "Yams", "SwiftyBeaver"]
        ),
    ],
    swiftLanguageVersions: [.v5]
)


//
//  Calendars.swift
//  Eatery
//
//  Created by Eric Appel on 5/5/15.
//  Copyright (c) 2015 CUAppDev. All rights reserved.
//

import Foundation
import SwiftyJSON

internal let kFrameworkBundle = NSBundle(identifier: "org.cuappdev.DiningStack")!

/// Hardcoded menus for those which would not normally have them
internal let kEateryGeneralMenus = JSON(data: NSData(contentsOfURL: kFrameworkBundle.URLForResource("hardcodedMenus", withExtension: "json")!) ?? NSData()).dictionaryValue

Use NSBundle's forClass to get around CocoaPods

//
//  Calendars.swift
//  Eatery
//
//  Created by Eric Appel on 5/5/15.
//  Copyright (c) 2015 CUAppDev. All rights reserved.
//

import Foundation
import SwiftyJSON

internal let kFrameworkBundle = NSBundle(forClass: DataManager.self)

/// Hardcoded menus for those which would not normally have them
internal let kEateryGeneralMenus = JSON(data: NSData(contentsOfURL: kFrameworkBundle.URLForResource("hardcodedMenus", withExtension: "json")!) ?? NSData()).dictionaryValue


//
//  CoreBluetooth.swift
//  SwiftySensors
//
//  https://github.com/kinetic-fit/sensors-swift
//
//  Copyright © 2017 Kinetic. All rights reserved.
//

import CoreBluetooth

extension CBCharacteristic {

    /**
     Enable / Disable Notifications for Characteristic

     - parameter enabled: Notification Flag
     */
    public func notify(_ enabled: Bool) {
        service.peripheral.setNotifyValue(enabled, for: self)
    }

    /// Read the value of the Characteristic
    public func read() {
        service.peripheral.readValue(for: self)
    }

    /**
     Write Data to the Characteristic

     - parameter data: Data to write
     - parameter writeType: BLE Write Type
     */
    public func write(_ data: Data, writeType: CBCharacteristicWriteType) {
        service.peripheral.writeValue(data, for: self, type: writeType)
    }

}

Check peripheral state before trying to write

//
//  CoreBluetooth.swift
//  SwiftySensors
//
//  https://github.com/kinetic-fit/sensors-swift
//
//  Copyright © 2017 Kinetic. All rights reserved.
//

import CoreBluetooth

extension CBCharacteristic {

    /**
     Enable / Disable Notifications for Characteristic

     - parameter enabled: Notification Flag
     */
    public func notify(_ enabled: Bool) {
        service.peripheral.setNotifyValue(enabled, for: self)
    }

    /// Read the value of the Characteristic
    public func read() {
        service.peripheral.readValue(for: self)
    }

    /**
     Write Data to the Characteristic

     - parameter data: Data to write
     - parameter writeType: BLE Write Type
     */
    public func write(_ data: Data, writeType: CBCharacteristicWriteType) {
        if service.peripheral.state == .connected {
            service.peripheral.writeValue(data, for: self, type: writeType)
        }
    }

}


//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String?
    var issuer: String?
    var type: TokenType?
    var secret: NSData?
    var algorithm: Algorithm?
    var digits: Int?

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}

Declare immutable token properties as non-optional constants

//
//  OTPToken.swift
//  OneTimePassword
//
//  Created by Matt Rubin on 6/10/14.
//  Copyright (c) 2014 Matt Rubin. All rights reserved.
//

class OTPToken: NSObject {
    var name: String?
    var issuer: String?
    let type: TokenType
    let secret: NSData
    let algorithm: Algorithm
    let digits: Int

    init(type: TokenType, secret: NSData, algorithm: Algorithm, digits: Int) {
        self.type = type
        self.secret = secret
        self.algorithm = algorithm
        self.digits = digits
    }

    enum TokenType {
        case Counter, Timer
    }

    enum Algorithm {
        case SHA1, SHA256, SHA512
    }
}


//
//  EventsSpec.swift
//  SwiftHub
//
//  Created by Ben Chatelain on 8/5/15.
//  Copyright © 2015 phatblat. All rights reserved.
//

@testable import SwiftHub
import Quick
import Nimble

class EventsSpec: QuickSpec {
    var events: [String]?

    override func spec() {
        describe("events list") {
            it("can be retrieved") {
                guard let semaphore = dispatch_semaphore_create(0)
                else { fatalError("Failed to create semaphore") }

                Events.list() { (events: [String]?) in
                    expect(events).toNot(beNil())
                    print("events \(events)")
                    self.events = events

                    dispatch_semaphore_signal(semaphore)
                }

                let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_SEC))
                dispatch_semaphore_wait(semaphore, timeout)

                expect(self.events).toNot(beNil())
                expect(self.events?.count).to(equal(30))
            }
        }
    }
}

Use Nocilla to serve up test json file

//
//  EventsSpec.swift
//  SwiftHub
//
//  Created by Ben Chatelain on 8/5/15.
//  Copyright © 2015 phatblat. All rights reserved.
//

@testable import SwiftHub
import Quick
import Nimble
import Nocilla

class EventsSpec: QuickSpec {
    var events: [String]?

    override func spec() {
        beforeEach {
            LSNocilla.sharedInstance().start()
        }
        afterEach {
            LSNocilla.sharedInstance().stop()
        }

        describe("events list") {
            afterEach {
                LSNocilla.sharedInstance().clearStubs()
            }

            it("can be retrieved") {
                let baseURLString = "https://api.github.com"
//                let emptyParameters = [:]
//                let service = makeJSONWebService(baseURLString: baseURLString, defaultParameters: emptyParameters)
//                stubRequest("GET", baseURLString + "/users/phatblat/events").andReturn(200).withBody("{\"ok\":1}")

                let path = NSBundle(forClass: EventsSpec.self).pathForResource("events", ofType: "json")!
                let payload = NSData(contentsOfFile: path)

                stubRequest("GET", baseURLString + "/users/phatblat/events")
                    .withHeaders(["Accept": "application/vnd.github.v3+json"])
                    .andReturnRawResponse(payload)

                guard let semaphore = dispatch_semaphore_create(0)
                else { fatalError("Failed to create semaphore") }

                Events.list() { (events: [String]?) in
                    expect(events).toNot(beNil())
                    print("events \(events)")
                    self.events = events

                    dispatch_semaphore_signal(semaphore)
                }

                let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_SEC))
                dispatch_semaphore_wait(semaphore, timeout)

                expect(self.events).toNot(beNil())
                expect(self.events?.count).to(equal(1))
            }
        }
    }
}


import io;
import files;
import sys;

//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
  file s[];
  s = glob(argv("S"));
  foreach f in s
  {
    printf("file: %s", filename(f));
  }
}

Extend test for empty globs

import io;
import files;
import sys;
import assert;

//usage: stc 563-glob.swift -S=/home/zzhang/*.swift
main
{
  file s[];
  s = glob(argv("S"));
  foreach f in s
  {
    printf("file: %s", filename(f));
  }

  file t[];
  t = glob("A.pattern.that.does.not.match.anything.*");
  assertEqual(size(t), 0, "size(t)");
}


//
//  NotificationPost.swift
//  ESNotification
//
//  Created by Tomohiro Kumagai on H27/10/15.
//  Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//

import Foundation

public protocol Postable : NotificationProtocol {

}

extension Postable {

	/// Post the `notification`.
	public func post() {

		let notificationCenter = NSNotificationCenter.defaultCenter()
		let rawNotification = self.makeRawNotificationForNativePost()

		notificationCenter.postNotification(rawNotification)
	}

	/// Create an NSNotification from the `notification`.
	func makeRawNotificationForNativePost() -> NSNotification {

		if let notification = self as? RawNotificationType {

			return notification.rawNotification
		}
		else {

			let name = self.dynamicType.notificationIdentifier
			let object = self

			return NSNotification(name: name, object: object, userInfo:nil)
		}
	}
}

Rename a private method name to 'makeRawNotification' and can now public access.

//
//  NotificationPost.swift
//  ESNotification
//
//  Created by Tomohiro Kumagai on H27/10/15.
//  Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//

import Foundation

public protocol Postable : NotificationProtocol {

}

extension Postable {

	/// Post the `notification`.
	public func post() {

		let notificationCenter = NSNotificationCenter.defaultCenter()
		let rawNotification = self.makeRawNotification()

		notificationCenter.postNotification(rawNotification)
	}

	/// Create an NSNotification from the `notification`.
	public func makeRawNotification() -> NSNotification {

		if let notification = self as? RawNotificationType {

			return notification.rawNotification
		}
		else {

			let name = self.dynamicType.notificationIdentifier
			let object = self

			return NSNotification(name: name, object: object, userInfo:nil)
		}
	}
}


//
//  NopImplStubTemplate.swift
//  CuckooGeneratorFramework
//
//  Created by Tadeas Kriz on 11/14/17.
//

extension Templates {
    static let noImplStub = """
{{container.accessibility}} class {{ container.name }}Stub: {{ container.name }} {
    {% for property in container.properties %}
    {{ property.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %} var {{ property.name }}: {{ property.type }} {
        get {
            return DefaultValueRegistry.defaultValue(for: ({{property.type|genericSafe}}).self)
        }
        {% ifnot property.isReadOnly %}
        set { }
        {% endif %}
    }
    {% endfor %}

    {% for initializer in container.initializers %}
    {{ initializer.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %}{% if initializer.@type == "ProtocolMethod" %} required{%endif%} init({{initializer.parameterSignature}}) {
        {% if container.@type == "ClassDeclaration" %}
        super.init({{initializer.call}})
        {% endif %}
    }
    {% endfor %}

    {% for method in container.methods %}
    {{ method.accessibility }}{% if container.@type == "ClassDeclaration" and method.isOverriding %} override{% endif %} func {{ method.name }}({{ method.parameterSignature }}) {{ method.returnSignature }} {
        return DefaultValueRegistry.defaultValue(for: {{method.returnType}}.self)
    }
    {% endfor %}
}
"""
}

Transform IUO return value as well.

//
//  NopImplStubTemplate.swift
//  CuckooGeneratorFramework
//
//  Created by Tadeas Kriz on 11/14/17.
//

extension Templates {
    static let noImplStub = """
{{container.accessibility}} class {{ container.name }}Stub: {{ container.name }} {
    {% for property in container.properties %}
    {{ property.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %} var {{ property.name }}: {{ property.type }} {
        get {
            return DefaultValueRegistry.defaultValue(for: ({{property.type|genericSafe}}).self)
        }
        {% ifnot property.isReadOnly %}
        set { }
        {% endif %}
    }
    {% endfor %}

    {% for initializer in container.initializers %}
    {{ initializer.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %}{% if initializer.@type == "ProtocolMethod" %} required{%endif%} init({{initializer.parameterSignature}}) {
        {% if container.@type == "ClassDeclaration" %}
        super.init({{initializer.call}})
        {% endif %}
    }
    {% endfor %}

    {% for method in container.methods %}
    {{ method.accessibility }}{% if container.@type == "ClassDeclaration" and method.isOverriding %} override{% endif %} func {{ method.name }}({{ method.parameterSignature }}) {{ method.returnSignature }} {
        return DefaultValueRegistry.defaultValue(for: {{method.returnType|genericSafe}}.self)
    }
    {% endfor %}
}
"""
}


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

#if swift(>=4.0)
  print("Hello, Swift 4!")
#endif

import Cocoa

var set = Multiset<String>()

set.add("Foo")
set.add("Foo")
set.add("Bar")
set.add("Baz")

set.count
set.count(for: "Foo")

set.allItems

var set2 = Multiset<String>()
set2.add("Foo")
set2.add("Foo")

set2.isSubSet(of: set) // true
set.isSubSet(of: set2) // false

// Convenience constructor: pass a Collection of Hashables to the constructor
var cacti = Multiset<Character>("cacti")
cacti.allItems
var tactical = Multiset<Character>("tactical")
cacti.isSubSet(of: tactical) // true
tactical.isSubSet(of: cacti) // false

// Test ExpressibleByArrayLiteral protocol
let set3: Multiset<String> = ["foo", "bar"]
set3.count(for: "foo")

// Test Equatable protocol
let set4 = Multiset<String>(set3.allItems)
set4 == set3 // true
set4 == set // false

Update Multiset to Swift 4.2

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

import Cocoa

var set = Multiset<String>()

set.add("Foo")
set.add("Foo")
set.add("Bar")
set.add("Baz")

set.count
set.count(for: "Foo")

set.allItems

var set2 = Multiset<String>()
set2.add("Foo")
set2.add("Foo")

set2.isSubSet(of: set) // true
set.isSubSet(of: set2) // false

// Convenience constructor: pass a Collection of Hashables to the constructor
var cacti = Multiset<Character>("cacti")
cacti.allItems
var tactical = Multiset<Character>("tactical")
cacti.isSubSet(of: tactical) // true
tactical.isSubSet(of: cacti) // false

// Test ExpressibleByArrayLiteral protocol
let set3: Multiset<String> = ["foo", "bar"]
set3.count(for: "foo")

// Test Equatable protocol
let set4 = Multiset<String>(set3.allItems)
set4 == set3 // true
set4 == set // false


struct GLib {}

Add convenience factories for MainContext and MainLoop

import CGLib

public extension MainContextRef {
    /// Return a MainContext reference to the default context singleton.
    ///
    /// This is a convenience factory method that returns the global default
    /// main context, i.e. the main context used for main loop functions
    /// when a main loop is not explicitly specified, and corresponds to
    /// the "main" main loop. See also g_main_context_get_thread_default().
    public static func sharedContext() -> MainContextRef {
        return MainContextRef(opaquePointer: g_main_context_default()!)
    }
}

public extension MainContext {
    /// Return a MainContext that references the default context singleton.
    ///
    /// This is a convenience factory method that returns the global default
    /// main context, i.e. the main context used for main loop functions
    /// when a main loop is not explicitly specified, and corresponds to
    /// the "main" main loop. See also g_main_context_get_thread_default().
    public static func sharedContext() -> MainContext {
        let context = MainContext(opaquePointer: g_main_context_default()!)
        context.ref()
        return context
    }
}

public extension MainLoopRef {
    /// Convenience initialiser that returns a retained reference to the
    /// default main loop.  See also g_main_loop_unref()
    public init() {
        self.ptr = UnsafeMutablePointer(g_main_loop_new(g_main_context_default()!, 0)!)
    }
}

public extension MainLoop {
    /// Convenience initialiser that creates and returns the
    /// default main loop.
    public convenience init() {
        self.init(opaquePointer: g_main_loop_new(g_main_context_default()!, 0))
    }
}


//
//  AirRivet
//
//  Created by Stijn Willems on 07/04/16.
//  2016 iCapps. MIT Licensed.
//

import Foundation
/**
Use class functions to easily change queue's.
*/
public class dispatch {

    public class async {
        public class func bg(block: dispatch_block_t) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block)
        }

        public class func main(block: dispatch_block_t) {
            dispatch_async(dispatch_get_main_queue(), block)
        }
    }

	public class sync {
		public class func bg(block: dispatch_block_t) {
            dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block)
        }

        public class func main(block: dispatch_block_t) {
            if NSThread.isMainThread() {
                block()
            }
            else {
                dispatch_sync(dispatch_get_main_queue(), block)
            }
        }
    }

    public class func after(seconds:CGFloat,_ block: dispatch_block_t) {
        let dispatchTime = Int64(seconds * CGFloat(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, dispatchTime), dispatch_get_main_queue(), block)
    }
}

Remove the usage of CGFloat.

//
//  AirRivet
//
//  Created by Stijn Willems on 07/04/16.
//  2016 iCapps. MIT Licensed.
//

import Foundation
/**
Use class functions to easily change queue's.
*/
public class dispatch {

    public class async {
        public class func bg(block: dispatch_block_t) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block)
        }

        public class func main(block: dispatch_block_t) {
            dispatch_async(dispatch_get_main_queue(), block)
        }
    }

	public class sync {
		public class func bg(block: dispatch_block_t) {
            dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block)
        }

        public class func main(block: dispatch_block_t) {
            if NSThread.isMainThread() {
                block()
            }
            else {
                dispatch_sync(dispatch_get_main_queue(), block)
            }
        }
    }

    public class func after(seconds: Float,_ block: dispatch_block_t) {
        let dispatchTime = Int64(seconds * Float(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, dispatchTime), dispatch_get_main_queue(), block)
    }
}


//
//  StatusBarConfiguration.swift
//  PRODUCTNAME
//
//  Created by Zev Eisenberg on 4/3/18.
//  Copyright © 2018 ORGANIZATION. All rights reserved.
//

#if targetEnvironment(simulator)
    import SimulatorStatusMagic
#endif

struct StatusBarConfiguration: AppLifecycle {

    var isEnabled: Bool {
        return ProcessInfo.isRunningUITests
    }

    func onDidLaunch(application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        #if targetEnvironment(simulator)
            SDStatusBarManager.sharedInstance().enableOverrides()
        #endif
    }

}

Add additional check that we are on a debug build for SimulatorStatusMagic

//
//  StatusBarConfiguration.swift
//  PRODUCTNAME
//
//  Created by Zev Eisenberg on 4/3/18.
//  Copyright © 2018 ORGANIZATION. All rights reserved.
//

#if targetEnvironment(simulator) && DEBUG
    import SimulatorStatusMagic
#endif

struct StatusBarConfiguration: AppLifecycle {

    var isEnabled: Bool {
        return ProcessInfo.isRunningUITests
    }

    func onDidLaunch(application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        #if targetEnvironment(simulator) && DEBUG
            SDStatusBarManager.sharedInstance().enableOverrides()
        #endif
    }

}


// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// REQUIRES: CPU=i386
class Obj {}

enum MyError : Error {
  case Simple
  case WithObj(Obj)
}

// i386 does not pass swifterror in a register. To support debugging of the
// thrown error we create a shadow stack location holding the address of the
// location that holds the pointer to the error instead.
func simple(_ placeholder: Int64) throws -> () {
  // CHECK: define {{.*}}void @"$s8ErrorVar6simpleyys5Int64VKF"(i64, %swift.refcounted* swiftself, %swift.error** noalias nocapture dereferenceable(4))
  // CHECK: call void @llvm.dbg.declare
  // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata !DIExpression(DW_OP_deref))
  // CHECK: ![[ERRTY:.*]] = !DICompositeType({{.*}}identifier: "$ss5Error_pD"
  // CHECK: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2,
  // CHECK-SAME:                          type: ![[ERRTY]],
  // CHECK-SAME:                          flags: DIFlagArtificial)
  throw MyError.Simple
}

func obj() throws -> () {
  throw MyError.WithObj(Obj())
}

public func foo() {
  do {
    try simple(1)
    try obj()
  }
  catch {}
}

Update testcase for upstream LLVM changes.

// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// REQUIRES: CPU=i386
class Obj {}

enum MyError : Error {
  case Simple
  case WithObj(Obj)
}

// i386 does not pass swifterror in a register. To support debugging of the
// thrown error we create a shadow stack location holding the address of the
// location that holds the pointer to the error instead.
func simple(_ placeholder: Int64) throws -> () {
  // CHECK: define {{.*}}void @"$s8ErrorVar6simpleyys5Int64VKF"(
  // CHECK-SAME: i64
  // CHECK-SAME: %swift.refcounted* {{.*}}swiftself
  // CHECK-SAME: %swift.error** noalias nocapture dereferenceable(4)
  // CHECK: call void @llvm.dbg.declare
  // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata !DIExpression(DW_OP_deref))
  // CHECK: ![[ERRTY:.*]] = !DICompositeType({{.*}}identifier: "$ss5Error_pD"
  // CHECK: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2,
  // CHECK-SAME:                          type: ![[ERRTY]],
  // CHECK-SAME:                          flags: DIFlagArtificial)
  throw MyError.Simple
}

func obj() throws -> () {
  throw MyError.WithObj(Obj())
}

public func foo() {
  do {
    try simple(1)
    try obj()
  }
  catch {}
}


//
//  JSONObjectType.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 19/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public struct JSONObject<PropertyType: RawRepresentable & Hashable>: JSONInitializable {
    fileprivate let json: JSON

    public init(json: JSON) throws {
        guard json.type == .dictionary else {
            throw JSONModelError.invalidJSON
        }
        self.json = json
    }
}

extension JSONObject: JSONRepresentable {
    public var jsonValue: JSON {
        return json
    }
}

public extension JSONObject where PropertyType.RawValue == String {
    public init(_ jsonDict: [PropertyType: JSONRepresentable]) {
        var dict = [String: JSON]()

        for (key, value) in jsonDict {
            dict[key.rawValue] = value.jsonValue
        }

        json = JSON(dict)
    }

    public func value<T: JSONInitializable>(for key: PropertyType) throws -> T {
        return try T(json: json[key.rawValue])
    }

    public func value<T: JSONInitializable>(for key: PropertyType) -> T? {
        return try? value(for: key)
    }
}

Add methods to get array for key

//
//  JSONObjectType.swift
//  SwiftyJSONModel
//
//  Created by Oleksii on 19/09/16.
//  Copyright © 2016 Oleksii Dykan. All rights reserved.
//

import Foundation
import SwiftyJSON

public struct JSONObject<PropertyType: RawRepresentable & Hashable>: JSONInitializable {
    fileprivate let json: JSON

    public init(json: JSON) throws {
        guard json.type == .dictionary else {
            throw JSONModelError.invalidJSON
        }
        self.json = json
    }
}

extension JSONObject: JSONRepresentable {
    public var jsonValue: JSON {
        return json
    }
}

public extension JSONObject where PropertyType.RawValue == String {
    public init(_ jsonDict: [PropertyType: JSONRepresentable]) {
        var dict = [String: JSON]()

        for (key, value) in jsonDict {
            dict[key.rawValue] = value.jsonValue
        }

        json = JSON(dict)
    }

    public func value<T: JSONInitializable>(for key: PropertyType) throws -> T {
        return try T(json: json[key.rawValue])
    }

    public func value<T>(for key: PropertyType) throws -> [T] where T: JSONInitializable & JSONRepresentable {
        return try JSONArray<T>(json: json[key.rawValue]).array
    }

    public func value<T: JSONInitializable>(for key: PropertyType) -> T? {
        return try? value(for: key)
    }

    public func value<T>(for key: PropertyType) -> [T]? where T: JSONInitializable & JSONRepresentable {
        return try? value(for: key)
    }
}


//
//  Response.swift
//  Search
//
//  Created by Dave Hardiman on 11/03/2016
//  Copyright (c) Ordnance Survey. All rights reserved.
//

import Foundation
import OSJSON

public final class Response: NSObject {

    // MARK: Properties
    public let results: [SearchResult]
    public let header: Header

    init(results: [SearchResult], header: Header) {
        self.results = results
        self.header = header
    }

    //MARK: JSON initialiser
    convenience init?(json: JSON) {
        guard let results = json.jsonArrayForKey(Response.ResultsKey),
            headerJSON = json.jsonForKey(Response.HeaderKey),
            header = Header(json: headerJSON)
        else {
            return nil
        }

        let nestedResults = results.flatMap(resultForJson)

        self.init(
            results: nestedResults,
            header: header
        )
    }
}

func resultForJson(json: OSJSON) -> SearchResult? {
    guard let dpaJson = json.jsonForKey(Results.SearchResultKey) else {
        return nil
    }
    let result = SearchResult.init(json: dpaJson)
    return result
}

extension Response {
    // MARK: Declaration for string constants to be used to decode and also serialize.
    @nonobjc internal static let ResultsKey: String = "results"
    @nonobjc internal static let HeaderKey: String = "header"
}

Tidy up resultForJson: return value

//
//  Response.swift
//  Search
//
//  Created by Dave Hardiman on 11/03/2016
//  Copyright (c) Ordnance Survey. All rights reserved.
//

import Foundation
import OSJSON

public final class Response: NSObject {

    // MARK: Properties
    public let results: [SearchResult]
    public let header: Header

    init(results: [SearchResult], header: Header) {
        self.results = results
        self.header = header
    }

    //MARK: JSON initialiser
    convenience init?(json: JSON) {
        guard let results = json.jsonArrayForKey(Response.ResultsKey),
            headerJSON = json.jsonForKey(Response.HeaderKey),
            header = Header(json: headerJSON)
        else {
            return nil
        }

        let nestedResults = results.flatMap(resultForJson)

        self.init(
            results: nestedResults,
            header: header
        )
    }
}

func resultForJson(json: OSJSON) -> SearchResult? {
    guard let dpaJson = json.jsonForKey(Results.SearchResultKey) else {
        return nil
    }
    return SearchResult.init(json: dpaJson)
}

extension Response {
    // MARK: Declaration for string constants to be used to decode and also serialize.
    @nonobjc internal static let ResultsKey: String = "results"
    @nonobjc internal static let HeaderKey: String = "header"
}


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

public enum Name {
	// MARK: Destructors

	public var value: Int {
		switch self {
		case let .Local(n):
			return n
		case let .Free(n):
			return n
		}
	}
	// MARK: Cases

	case Local(Int)
	case Free(Int)
}

Rename the Free case to Quote.

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

public enum Name {
	// MARK: Destructors

	public var value: Int {
		switch self {
		case let .Local(n):
			return n
		case let .Quote(n):
			return n
		}
	}
	// MARK: Cases

	case Local(Int)
	case Quote(Int)
}


//
//  ShadowStyle.swift
//  Nori
//
//  Created by yukiasai on 11/22/16.
//  Copyright © 2016 yukiasai. All rights reserved.
//

public class ShadowStyle {
    var offset: CGSize?
    var color: UIColor?
    var radius: CGFloat?
    var opacity: Float?

    public init() { }

    public convenience init(closure: (ShadowStyle) -> Void) {
        self.init()
        closure(self)
    }
}

Access control of properties to public

//
//  ShadowStyle.swift
//  Nori
//
//  Created by yukiasai on 11/22/16.
//  Copyright © 2016 yukiasai. All rights reserved.
//

public class ShadowStyle {
    public var offset: CGSize?
    public var color: UIColor?
    public var radius: CGFloat?
    public var opacity: Float?

    public init() { }

    public convenience init(closure: (ShadowStyle) -> Void) {
        self.init()
        closure(self)
    }
}