//
//  URLTableViewCell.swift
//  PhotoCollectionView
//
//  Created by Minh Luan Tran on 9/20/17.
//
//

import UIKit
import PhotoCollectionView

class URLTableViewCell: UITableViewCell {

    @IBOutlet weak var photoCollectionView: PhotoCollectionView!
    @IBOutlet weak var indexLabel: UILabel!
    @IBOutlet weak var photoCollectionViewHeight: NSLayoutConstraint!

    var urls: [String] = [] {
        didSet {
            if urls != oldValue {
                photoCollectionView.reloadData()
                photoCollectionViewHeight.constant = photoCollectionView.intrinsicContentSize.height
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        photoCollectionView.dataSource = self
    }

    func set(index: Int) {
        photoCollectionView.tag = index
        indexLabel.text = "Cell \(index)"
    }

}

extension URLTableViewCell: PhotoCollectionViewDataSource {

    func photoCollectionView(_ photoCollectionView: PhotoCollectionView, photoSource index: Int) -> PhotoSource {
        return .url(URL(string: urls[index]))
    }

    func numPhotos(in photoCollectionView: PhotoCollectionView) -> Int {
        return urls.count
    }

}

Fix bug table view didn't update height in demo project

//
//  URLTableViewCell.swift
//  PhotoCollectionView
//
//  Created by Minh Luan Tran on 9/20/17.
//
//

import UIKit
import PhotoCollectionView

class URLTableViewCell: UITableViewCell {

    @IBOutlet weak var photoCollectionView: PhotoCollectionView!
    @IBOutlet weak var indexLabel: UILabel!
    @IBOutlet weak var photoCollectionViewHeight: NSLayoutConstraint!

    var urls: [String] = [] {
        didSet {
            if urls != oldValue {
                photoCollectionView.reloadData()
            }
            photoCollectionViewHeight.constant = photoCollectionView.intrinsicContentSize.height
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        photoCollectionView.dataSource = self
    }

    func set(index: Int) {
        photoCollectionView.tag = index
        indexLabel.text = "Cell \(index)"
    }

}

extension URLTableViewCell: PhotoCollectionViewDataSource {

    func photoCollectionView(_ photoCollectionView: PhotoCollectionView, photoSource index: Int) -> PhotoSource {
        return .url(URL(string: urls[index]))
    }

    func numPhotos(in photoCollectionView: PhotoCollectionView) -> Int {
        return urls.count
    }

}


import Foundation

// Should be fixed: This reads in all of standard input
let standardInput = NSFileHandle.fileHandleWithStandardInput()
let input = standardInput.availableData
let text = String(data: input, encoding: NSUTF8StringEncoding)!

var counts = [String: Int]()

func isWordChar (c: Character) -> Bool {
    return "abcdefghijklmnopqrstuvwxyz'".rangeOfString("\(c)") != nil
}

for word in (text.lowercaseString.characters.split{!isWordChar($0)}.map(String.init)) {
    if let count = counts[word] {
        counts[word] = count + 1
    } else {
        counts[word] = 1
    }
}

for (word, count) in (counts.sort { $0.0 < $1.0 }) {
    print("\(word) \(count)")
}

Use ?? for accumulating dictionary counts

import Foundation

// Should be fixed: This reads in all of standard input
let standardInput = NSFileHandle.fileHandleWithStandardInput()
let input = standardInput.availableData
let text = String(data: input, encoding: NSUTF8StringEncoding)!

var counts = [String: Int]()

func isWordChar (c: Character) -> Bool {
    return "abcdefghijklmnopqrstuvwxyz'".rangeOfString("\(c)") != nil
}

for word in (text.lowercaseString.characters.split{!isWordChar($0)}.map(String.init)) {
    counts[word] = (counts[word] ?? 0) + 1
}

for (word, count) in (counts.sort { $0.0 < $1.0 }) {
    print("\(word) \(count)")
}


//
//  UIImage+qrCode.swift
//  QRCode
//
//  Created by luojie on 16/10/24.
//  Copyright © 2016年 LuoJie. All rights reserved.
//

import UIKit

extension UIImage {

    public static func qrCode(from text: String, length: CGFloat = 200) -> UIImage {
        let data = text.data(using: .isoLatin1)!
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        qrFilter.setDefaults()
        qrFilter.setValue(data, forKey: "inputMessage")
        qrFilter.setValue("H", forKey: "inputCorrectionLevel")
        let ciImage = qrFilter.outputImage!
        let scaleX = length / ciImage.extent.size.width
        let scaleY = length / ciImage.extent.size.height
        let transformedImage = ciImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
        return UIImage(ciImage: transformedImage)
    }
}

Add QR Code Tint Color.

//
//  UIImage+qrCode.swift
//  QRCode
//
//  Created by luojie on 16/10/24.
//  Copyright © 2016年 LuoJie. All rights reserved.
//

import UIKit

extension UIImage {

    public static func qrCode(from text: String, length: CGFloat = 200, tintColor: UIColor? = nil) -> UIImage {
        let data = text.data(using: .isoLatin1)!
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        qrFilter.setDefaults()
        qrFilter.setValue(data, forKey: "inputMessage")
        qrFilter.setValue("H", forKey: "inputCorrectionLevel")
        var ciImage = qrFilter.outputImage!

        if let tintColor = tintColor {
            let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: [
                "inputImage": ciImage,
                "inputColor0": tintColor.ciColor,
                "inputColor1": UIColor.white.ciColor
                ])!
            ciImage = colorFilter.outputImage!
        }

        let scaleX = length / ciImage.extent.size.width
        let scaleY = length / ciImage.extent.size.height
        let transformedImage = ciImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
        return UIImage(ciImage: transformedImage)
    }
}


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

// REQUIRES: CPU=x86_64

// FIXME: https://bugs.swift.org/browse/SR-2808
// XFAIL: resilient_stdlib

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

// CHECK: xor <2 x i64>

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

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

  return c
}

Disable IRGen test case that tests vectorization of arrays to unblock a bot

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

// REQUIRES: CPU=x86_64

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

// FIXME: https://bugs.swift.org/browse/SR-2808
// XFAIL: resilient_stdlib

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

// CHECK: xor <2 x i64>

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

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

  return c
}


//
//  String+OrangeLabel.swift
//  OrangeLabel
//
//  Created by Steve Kim on 09/04/2017.
//  Copyright © 2016 Steve Kim. All rights reserved.
//

import Foundation

extension String {
    func matches(pattern: String) throws -> [NSTextCheckingResult] {
        let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let range = NSRange(location: 0, length: self.characters.count)
        return regex.matches(in: self, options: .reportCompletion, range: range)
    }
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            else { return nil }
        return from ..< to
    }
}

Support to utf16 characters with regular expression

//
//  String+OrangeLabel.swift
//  OrangeLabel
//
//  Created by Steve Kim on 09/04/2017.
//  Copyright © 2016 Steve Kim. All rights reserved.
//

import Foundation

extension String {
    func matches(pattern: String) throws -> [NSTextCheckingResult] {
        let regex = try NSRegularExpression(pattern: pattern)
        return regex.matches(in: self, options: .reportCompletion, range: NSRange(0..<utf16.count))
    }
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            else { return nil }
        return from ..< to
    }
}


//
//  PageLinkParser.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import Foundation

struct PageLinks {
  let first: String?
  let previous: String?
  let next: String?
  let last: String?
}

final class PageLinkParser {

  private static let regex = try! NSRegularExpression(pattern: "<(?<url>[^>]*)>; ?rel=\"(?<rel>[^\"]*)\"")

  static func parse(linkString: String) -> PageLinks {
    let matches = regex.matches(in: linkString, range: NSRange(linkString.startIndex..., in: linkString))
    let relations = matches.map { String(linkString[Range($0.range(withName: "rel"), in: linkString)!]) }
    let urls = matches.map { String(linkString[Range($0.range(withName: "url"), in: linkString)!]) }
    let dictionary = Dictionary(uniqueKeysWithValues: zip(relations, urls))

    return PageLinks(first: dictionary["first"],
                     previous: dictionary["prev"],
                     next: dictionary["next"],
                     last: dictionary["last"])
  }
}

Use range(at:) for MacOS 10.12 compat

//
//  PageLinkParser.swift
//  GithubClient
//
//  Created by Eduardo Arenas on 2/18/18.
//  Copyright © 2018 GameChanger. All rights reserved.
//

import Foundation

struct PageLinks {
  let first: String?
  let previous: String?
  let next: String?
  let last: String?
}

final class PageLinkParser {

  private static let regex = try! NSRegularExpression(pattern: "<(?<url>[^>]*)>; ?rel=\"(?<rel>[^\"]*)\"")

  static func parse(linkString: String) -> PageLinks {
    let matches = regex.matches(in: linkString, range: NSRange(linkString.startIndex..., in: linkString))
    let relations = matches.map { String(linkString[Range($0.range(at: 2), in: linkString)!]) }
    let urls = matches.map { String(linkString[Range($0.range(at: 1), in: linkString)!]) }
    let dictionary = Dictionary(uniqueKeysWithValues: zip(relations, urls))

    return PageLinks(first: dictionary["first"],
                     previous: dictionary["prev"],
                     next: dictionary["next"],
                     last: dictionary["last"])
  }
}


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

import PackageDescription

let package = Package(
    name: "gotanda",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "gotanda",
            targets: ["gotanda"]),
    ],
    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: "gotanda",
            dependencies: [],
            path: "Sources"),
        .testTarget(
            name: "gotandaTests",
            dependencies: ["gotanda"]),
    ]
)

Update package name to Gotanda.

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

import PackageDescription

let package = Package(
    name: "Gotanda",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Gotanda",
            targets: ["gotanda"]),
    ],
    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: "gotanda",
            dependencies: [],
            path: "Sources"),
        .testTarget(
            name: "gotandaTests",
            dependencies: ["gotanda"]),
    ]
)


import HaCTML
import Foundation
import DotEnv

struct GAScript: Nodeable {
  let googleAnalyticsId = DotEnv.get("GOOGLE_ANALYTICS_ID")!
  var node: Node {
    return TextNode(
      """
      <!-- Global site tag (gtag.js) - Google Analytics -->
      <script async src=\"https://www.googletagmanager.com/gtag/js?id=\(googleAnalyticsId)\"></script>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', '\(googleAnalyticsId)');
      </script>
      """
    , escapeLevel: .unsafeRaw)
  }
}

Make google analytics id optional

import HaCTML
import Foundation
import DotEnv

struct GAScript: Nodeable {
  let googleAnalyticsId = DotEnv.get("GOOGLE_ANALYTICS_ID")
  var node: Node {
    guard let googleAnalyticsId = googleAnalyticsId else {
      return TextNode("")
    }
    return TextNode(
      """
      <!-- Global site tag (gtag.js) - Google Analytics -->
      <script async src=\"https://www.googletagmanager.com/gtag/js?id=\(googleAnalyticsId)\"></script>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', '\(googleAnalyticsId)');
      </script>
      """
    , escapeLevel: .unsafeRaw)
  }
}


/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation
import RxSwift

class OpenQuicklyReducer: ReducerType {

  typealias StateType = AppState
  typealias ActionType = OpenQuicklyWindow.Action

  let mainWindow = MainWindowReducer()

  func typedReduce(_ pair: ReduceTuple) -> ReduceTuple {
    var appState = pair.state

    switch pair.action {

    case let .setUsesVcsIgnores(usesVcsIgnores):
      guard let uuid = appState.currentMainWindowUuid else { return pair }
      appState.mainWindows[uuid]?.usesVcsIgnores = usesVcsIgnores

    case let .open(url):
      guard let uuid = appState.currentMainWindowUuid else { return pair }
      appState.mainWindows[uuid]?.urlsToOpen[url] = .newTab
      appState.openQuickly.open = false

    case .close:
      appState.openQuickly.open = false
      break

    }

    return (appState, pair.action, true)
  }

  class MainWindowReducer: ReducerType {

    typealias StateType = AppState
    typealias ActionType = UuidAction<MainWindow.Action>

    func typedReduce(_ pair: ReduceTuple) -> ReduceTuple {
      switch pair.action.payload {

      case .openQuickly:
        var appState = pair.state

        guard let uuid = appState.currentMainWindowUuid,
              appState.mainWindows[uuid]?.cwd != nil else { return pair }

        appState.openQuickly.open = true

        return (appState, pair.action, true)

      default:
        return pair

      }
    }
  }
}

Use default open mode for open quickly

/**
 * Tae Won Ha - http://taewon.de - @hataewon
 * See LICENSE
 */

import Foundation
import RxSwift

class OpenQuicklyReducer: ReducerType {

  typealias StateType = AppState
  typealias ActionType = OpenQuicklyWindow.Action

  let mainWindow = MainWindowReducer()

  func typedReduce(_ pair: ReduceTuple) -> ReduceTuple {
    var appState = pair.state

    switch pair.action {

    case let .setUsesVcsIgnores(usesVcsIgnores):
      guard let uuid = appState.currentMainWindowUuid else { return pair }
      appState.mainWindows[uuid]?.usesVcsIgnores = usesVcsIgnores

    case let .open(url):
      guard let uuid = appState.currentMainWindowUuid else { return pair }
      appState.mainWindows[uuid]?.urlsToOpen[url] = .default
      appState.openQuickly.open = false

    case .close:
      appState.openQuickly.open = false
      break

    }

    return (appState, pair.action, true)
  }

  class MainWindowReducer: ReducerType {

    typealias StateType = AppState
    typealias ActionType = UuidAction<MainWindow.Action>

    func typedReduce(_ pair: ReduceTuple) -> ReduceTuple {
      switch pair.action.payload {

      case .openQuickly:
        var appState = pair.state

        guard let uuid = appState.currentMainWindowUuid,
              appState.mainWindows[uuid]?.cwd != nil else { return pair }

        appState.openQuickly.open = true

        return (appState, pair.action, true)

      default:
        return pair

      }
    }
  }
}


/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import UIKit
import CatalogByConvention

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    let window = UIWindow(frame: UIScreen.main.bounds)
    self.window = window

    let rootViewController = CBCNodeListViewController(node: CBCCreateNavigationTree())
    rootViewController.title = "Material Motion streams for Apple devices"
    window.rootViewController = UINavigationController(rootViewController: rootViewController)

    window.makeKeyAndVisible()
    return true
  }
}

Fix title of catalog app.

/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import UIKit
import CatalogByConvention

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    let window = UIWindow(frame: UIScreen.main.bounds)
    self.window = window

    let rootViewController = CBCNodeListViewController(node: CBCCreateNavigationTree())
    rootViewController.title = "Reactive Motion examples"
    window.rootViewController = UINavigationController(rootViewController: rootViewController)

    window.makeKeyAndVisible()
    return true
  }
}


//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//

@_exported import Intents
import Foundation

#if os(iOS) || os(watchOS) || os(macOS)

public protocol _INIntentSetImageKeyPath { }

extension _INIntentSetImageKeyPath {

    @available(iOS 12.0, watchOS 5.0, macOS 10.14, *)
    public func setImage<Value>(_ image: INImage?, forParameterNamed parameterName: KeyPath<Self, Value>) {
        if let keyPathString = parameterName._kvcKeyPathString {
            (self as! INIntent).__setImage(image, forParameterNamed: keyPathString)
        }
    }

    @available(iOS 12.0, watchOS 5.0, macOS 10.14, *)
    public func image<Value>(forParameterNamed parameterName: KeyPath<Self, Value>) -> INImage? {
        if let keyPathString = parameterName._kvcKeyPathString {
            return (self as! INIntent).__image(forParameterNamed: keyPathString)
        } else {
            return nil
        }
    }
}

@available(iOS 10.0, watchOS 3.2, macOS 10.12, *)
extension INIntent : _INIntentSetImageKeyPath { }

#endif

Make APIs using INImage unavailable on macOS

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//

@_exported import Intents
import Foundation

#if os(iOS) || os(watchOS)

public protocol _INIntentSetImageKeyPath { }

extension _INIntentSetImageKeyPath {

    @available(iOS 12.0, watchOS 5.0, *)
    public func setImage<Value>(_ image: INImage?, forParameterNamed parameterName: KeyPath<Self, Value>) {
        if let keyPathString = parameterName._kvcKeyPathString {
            (self as! INIntent).__setImage(image, forParameterNamed: keyPathString)
        }
    }

    @available(iOS 12.0, watchOS 5.0, *)
    public func image<Value>(forParameterNamed parameterName: KeyPath<Self, Value>) -> INImage? {
        if let keyPathString = parameterName._kvcKeyPathString {
            return (self as! INIntent).__image(forParameterNamed: keyPathString)
        } else {
            return nil
        }
    }
}

@available(iOS 10.0, watchOS 3.2, *)
extension INIntent : _INIntentSetImageKeyPath { }

#endif


//
//  TodoCloudConfiguration.swift
//  Todos
//
//  Created by Andrew Shepard on 5/23/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import GROCloudStore

struct DefaultContainer: CloudContainerType {
    var Identifier: String {
        return "iCloud.org.andyshep.example.Todos"
    }

    var CustomZoneName: String {
        return "examplezonename"
    }
}

struct Subscription: SubscriptionType {
    var Default: [CKSubscription] {
        return []
    }
}

class TodoCloudConfiguration: Configuration {
    var Subscriptions: SubscriptionType {
        return Subscription()
    }

    var CloudContainer: CloudContainerType {
        return DefaultContainer()
    }
}

Add subscription to example configuration

//
//  TodoCloudConfiguration.swift
//  Todos
//
//  Created by Andrew Shepard on 5/23/16.
//  Copyright © 2016 Andrew Shepard. All rights reserved.
//

import Foundation
import GROCloudStore

struct DefaultContainer: CloudContainerType {
    var Identifier: String {
        return "iCloud.org.andyshep.example.Todos"
    }

    var CustomZoneName: String {
        return "examplezonename"
    }
}

struct Subscription: SubscriptionType {
    static let Todo = "iCloud.org.andyshep.example.Todos.subscription.Todo"

    var Default: [CKSubscription] {
        let subscriptionId = Subscription.Todo
        let zoneId = CKRecordZoneID(zoneName: DefaultContainer().CustomZoneName, ownerName: CKOwnerDefaultName)

        let options = CKSubscriptionOptions.FiresOnRecordCreation
        let subscription = CKSubscription(recordType: "Todo", predicate: NSPredicate(format: "TRUEPREDICATE"), subscriptionID: subscriptionId, options: options)
        subscription.zoneID = zoneId

        let notificationInfo = CKNotificationInfo()
        notificationInfo.shouldSendContentAvailable = true
        subscription.notificationInfo = notificationInfo

        return [subscription]
    }
}

class TodoCloudConfiguration: Configuration {
    var Subscriptions: SubscriptionType {
        return Subscription()
    }

    var CloudContainer: CloudContainerType {
        return DefaultContainer()
    }
}


//
//  MessageManager.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/14/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift

class MessageManager {

    static let historySize = 50

}

// MARK: Realm Data

extension MessageManager {

    static func allMessages(subscription: Subscription) -> Results<Message> {
        return try! Realm().objects(Message.self)
            .filter("subscription = %@", subscription)
            .sorted("createdAt", ascending: true)
    }

}

// MARK: History

extension MessageManager {

    static func fetchHistory(subscription: Subscription, completion: MessageCompletion) {
        let request = [
            "msg": "method",
            "method": "loadHistory",
            "params": ["\(subscription.rid)", NSNull(), historySize, [
                "$date": NSDate().timeIntervalSince1970 * 1000
            ]]
        ]

        SocketManager.send(request) { (response) in
            guard !response.isError() else {
                return print(response.result)
            }

            let messages = List<Message>()
            if let result = response.result["result"]["messages"].array {
                for obj in result {
                    let message = Message(object: obj)
                    message.subscription = subscription
                    messages.append(message)
                }
            }

            Realm.execute() { (realm) in
                realm.add(messages, update: true)
            }

            completion(response)
        }
    }

}

Remove unused method in manager

//
//  MessageManager.swift
//  Rocket.Chat
//
//  Created by Rafael K. Streit on 7/14/16.
//  Copyright © 2016 Rocket.Chat. All rights reserved.
//

import Foundation
import RealmSwift

class MessageManager {

    static let historySize = 50

}

// MARK: Realm Data

extension MessageManager {

}

// MARK: History

extension MessageManager {

    static func fetchHistory(subscription: Subscription, completion: MessageCompletion) {
        let request = [
            "msg": "method",
            "method": "loadHistory",
            "params": ["\(subscription.rid)", NSNull(), historySize, [
                "$date": NSDate().timeIntervalSince1970 * 1000
            ]]
        ]

        SocketManager.send(request) { (response) in
            guard !response.isError() else {
                return print(response.result)
            }

            let messages = List<Message>()
            if let result = response.result["result"]["messages"].array {
                for obj in result {
                    let message = Message(object: obj)
                    message.subscription = subscription
                    messages.append(message)
                }
            }

            Realm.execute() { (realm) in
                realm.add(messages, update: true)
            }

            completion(response)
        }
    }

}


import Commandant
import Foundation

struct ShowDocsCommand: CommandProtocol {
    let verb = "show-docs"
    let function = "Open `SwiftLint Framework Docs` on web browser"

    func run(_ options: NoOptions<CommandantError<()>>) -> Result<(), CommandantError<()>> {
        let url = URL(string: "https://realm.github.io/SwiftLint")!
        open(url)
        return .success(())
    }
}

private extension ShowDocsCommand {
    func open(_ url: URL) {
        let process = Process()
        process.launchPath = "/usr/bin/env"
        let command: String = {
            #if os(Linux)
            return "xdg-open"
            #else
            return "open"
            #endif
        }()
        process.arguments = [command, url.absoluteString]
        process.launch()
    }
}

Remove backquotes and "Framework" from the sentence

import Commandant
import Foundation

struct ShowDocsCommand: CommandProtocol {
    let verb = "show-docs"
    let function = "Open SwiftLint Docs on web browser"

    func run(_ options: NoOptions<CommandantError<()>>) -> Result<(), CommandantError<()>> {
        let url = URL(string: "https://realm.github.io/SwiftLint")!
        open(url)
        return .success(())
    }
}

private extension ShowDocsCommand {
    func open(_ url: URL) {
        let process = Process()
        process.launchPath = "/usr/bin/env"
        let command: String = {
            #if os(Linux)
            return "xdg-open"
            #else
            return "open"
            #endif
        }()
        process.arguments = [command, url.absoluteString]
        process.launch()
    }
}


// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode
// REQUIRES: objc_interop

import Foundation

@objc protocol P1 {
  @available(iOS, unavailable)
  func foo1()
  func foo2()
}

protocol P2 {
  func bar1()
  func bar2()
}

class C1 : P1, P2 {}
// expected-error@-1 {{type 'C1' does not conform to protocol 'P1'}}
// expected-error@-2 {{type 'C1' does not conform to protocol 'P2'}}
// expected-note@-3 {{do you want to add protocol stubs?}} {{20-20=\n    func foo2() {\n        <#code#>\n    \}\n\n    func bar1() {\n        <#code#>\n    \}\n\n    func bar2() {\n        <#code#>\n    \}\n}}

protocol P3 {
  associatedtype T1
  associatedtype T2
  associatedtype T3
}

protocol P4 : P3 {
  associatedtype T4 = T1
  associatedtype T5 = T2
  associatedtype T6 = T3
}

class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n    typealias T1 = <#type#>\n\n    typealias T2 = <#type#>\n\n    typealias T3 = <#type#>\n}}

Revert "Build fix: Update fix-it stub editor test"

// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode

protocol P1 {
  @available(iOS, unavailable)
  func foo1()
  func foo2()
}

protocol P2 {
  func bar1()
  func bar2()
}

class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n    func foo1() {\n        <#code#>\n    \}\n\n    func foo2() {\n        <#code#>\n    \}\n\n    func bar1() {\n        <#code#>\n    \}\n\n    func bar2() {\n        <#code#>\n    \}\n}}

protocol P3 {
  associatedtype T1
  associatedtype T2
  associatedtype T3
}

protocol P4 : P3 {
  associatedtype T4 = T1
  associatedtype T5 = T2
  associatedtype T6 = T3
}

class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n    typealias T1 = <#type#>\n\n    typealias T2 = <#type#>\n\n    typealias T3 = <#type#>\n}}


//
//  WebSocketTransportSpec.swift
//  WebSocketTransportSpec
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Quick
import Nimble
import WebSocketTransport
import JSONLib

class WebSocketTransportSpec: QuickSpec {

    override func spec() {

        describe("WebSocket transport") {

            describe("when receiving a message") {

                it("should be received in the runtime") {
                    let transport = WebSocketTransport()

                    let transportChannel = "channel"
                    let transportTopic = "topic"
                    let transportPayload = "{\"protocol\":\"channel\",\"command\":\"topic\",\"payload\":{\"key\":\"value\"}}"

                    var runtimeChannel: String!
                    var runtimeTopic: String!
                    var runtimePayload: JSON!

                    let runtime = FakeRuntime(transport) { (channel, topic, payload) in
                        runtimeChannel = channel
                        runtimeTopic = topic
                        runtimePayload = payload
                    }

                    // TODO: Receive a message in the transport

                    expect(runtimeChannel).to(equal(transportChannel))
                    expect(runtimeTopic).to(equal(transportTopic))

                    let json = JSON.parse(transportPayload).value
                    expect(runtimePayload).to(equal(json))
                }
            }
        }
    }
}

Add pending example for sending a message.

//
//  WebSocketTransportSpec.swift
//  WebSocketTransportSpec
//
//  Created by Paul Young on 28/08/2014.
//  Copyright (c) 2014 CocoaFlow. All rights reserved.
//

import Quick
import Nimble
import WebSocketTransport
import JSONLib

class WebSocketTransportSpec: QuickSpec {

    override func spec() {

        describe("WebSocket transport") {

            describe("when receiving a message") {

                it("should be received in the runtime") {
                    let transport = WebSocketTransport()

                    let transportChannel = "channel"
                    let transportTopic = "topic"
                    let transportPayload = "{\"protocol\":\"channel\",\"command\":\"topic\",\"payload\":{\"key\":\"value\"}}"

                    var runtimeChannel: String!
                    var runtimeTopic: String!
                    var runtimePayload: JSON!

                    let runtime = FakeRuntime(transport) { (channel, topic, payload) in
                        runtimeChannel = channel
                        runtimeTopic = topic
                        runtimePayload = payload
                    }

                    // TODO: Receive a message in the transport

                    expect(runtimeChannel).to(equal(transportChannel))
                    expect(runtimeTopic).to(equal(transportTopic))

                    let json = JSON.parse(transportPayload).value
                    expect(runtimePayload).to(equal(json))
                }
            }

            describe("when sent a message by the runtime") {

                pending("should send a message") {

                }
            }
        }
    }
}


import Foundation

public enum RequestBodyEntity {
    case Data(NSData)
    case InputStream(NSInputStream)
}

public protocol BodyParametersType {
    var contentType: String { get }
    var entity: RequestBodyEntity { get }
}

Use func for building entity to throw errors

import Foundation

public enum RequestBodyEntity {
    case Data(NSData)
    case InputStream(NSInputStream)
}

public protocol BodyParametersType {
    var contentType: String { get }

    func buildEntity() throws -> RequestBodyEntity
}


import XCTest

extension CGIContentOutputStreamTests {
    static let __allTests = [
        ("test_pathForUnexistingFile", test_pathForUnexistingFile),
    ]
}

extension CGIResponderTests {
    static let __allTests = [
        ("test_contentType", test_contentType),
        ("test_expectedStatus_Date", test_expectedStatus_Date),
        ("test_expectedStatus_ETag", test_expectedStatus_ETag),
        ("test_response", test_response),
    ]
}

extension ClientTests {
    static let __allTests = [
        ("test_cookies", test_cookies),
    ]
}

extension DataOutputStreamTests {
    static let __allTests = [
        ("test", test),
    ]
}

extension EnvironmentVariablesTests {
    static let __allTests = [
        ("test_accessor", test_accessor),
    ]
}

extension ErrorMessageTests {
    static let __allTests = [
        ("test_message", test_message),
    ]
}

extension ExportTests {
    static let __allTests = [
        ("test_HTTPETag", test_HTTPETag),
    ]
}

#if !os(macOS)
public func __allTests() -> [XCTestCaseEntry] {
    return [
        testCase(CGIContentOutputStreamTests.__allTests),
        testCase(CGIResponderTests.__allTests),
        testCase(ClientTests.__allTests),
        testCase(DataOutputStreamTests.__allTests),
        testCase(EnvironmentVariablesTests.__allTests),
        testCase(ErrorMessageTests.__allTests),
        testCase(ExportTests.__allTests),
    ]
}
#endif

Add test "test_queryItems" for Linux.

import XCTest

extension CGIContentOutputStreamTests {
    static let __allTests = [
        ("test_pathForUnexistingFile", test_pathForUnexistingFile),
    ]
}

extension CGIResponderTests {
    static let __allTests = [
        ("test_contentType", test_contentType),
        ("test_expectedStatus_Date", test_expectedStatus_Date),
        ("test_expectedStatus_ETag", test_expectedStatus_ETag),
        ("test_response", test_response),
    ]
}

extension ClientTests {
    static let __allTests = [
        ("test_cookies", test_cookies),
        ("test_queryItems", test_queryItems),
    ]
}

extension DataOutputStreamTests {
    static let __allTests = [
        ("test", test),
    ]
}

extension EnvironmentVariablesTests {
    static let __allTests = [
        ("test_accessor", test_accessor),
    ]
}

extension ErrorMessageTests {
    static let __allTests = [
        ("test_message", test_message),
    ]
}

extension ExportTests {
    static let __allTests = [
        ("test_HTTPETag", test_HTTPETag),
    ]
}

#if !os(macOS)
public func __allTests() -> [XCTestCaseEntry] {
    return [
        testCase(CGIContentOutputStreamTests.__allTests),
        testCase(CGIResponderTests.__allTests),
        testCase(ClientTests.__allTests),
        testCase(DataOutputStreamTests.__allTests),
        testCase(EnvironmentVariablesTests.__allTests),
        testCase(ErrorMessageTests.__allTests),
        testCase(ExportTests.__allTests),
    ]
}
#endif


//
//  VIMLiveHeartbeatTests.swift
//  VimeoNetworkingExample-iOS
//
//  Created by Nguyen, Van on 10/4/17.
//  Copyright © 2017 Vimeo. All rights reserved.
//

import XCTest

class VIMLiveHeartbeatTests: XCTestCase
{

}

Add test case for parsing `VIMLiveHeartbeat`

//
//  VIMLiveHeartbeatTests.swift
//  VimeoNetworkingExample-iOS
//
//  Created by Nguyen, Van on 10/4/17.
//  Copyright © 2017 Vimeo. All rights reserved.
//

import XCTest
import OHHTTPStubs
import VimeoNetworking

class VIMLiveHeartbeatTests: XCTestCase
{
    override func setUp()
    {
        super.setUp()

        VimeoClient.configureSharedClient(withAppConfiguration: AppConfiguration(clientIdentifier: "{CLIENT_ID}",
                                                                                clientSecret: "{CLIENT_SECRET}",
                                                                                scopes: [.Public, .Private, .Purchased, .Create, .Edit, .Delete, .Interact, .Upload],
                                                                                keychainService: "com.vimeo.keychain_service",
                                                                                apiVersion: "3.3.13"))
    }

    override func tearDown()
    {
        super.tearDown()

        OHHTTPStubs.removeAllStubs()
    }

    func testParsingLiveHeartbeatObject()
    {
        let request = Request<VIMVideo>(path: "/videos/224357160")

        stub(condition: isPath("/videos/224357160")) { _ in
            let stubPath = OHPathForFile("clip_live.json", type(of: self))
            return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"])
        }

        let expectation = self.expectation(description: "Network call expectation")

        _ = VimeoClient.sharedClient.request(request) { response in
            switch response
            {
            case .success(let result):
                let video = result.model

                let liveHeartbeat = video.playRepresentation?.hlsFile?.live

                XCTAssertNotNil(liveHeartbeat)
                XCTAssertEqual(liveHeartbeat?.heartbeatUrl, "https://api.vimeo.com/videos/236661678/heartbeat/hls/1507067883/3082903e82078a78bd146ca542899a124e1c47fe")

            case .failure(let error):
                XCTFail("\(error)")
            }

            expectation.fulfill()
        }

        self.waitForExpectations(timeout: 1.0) { error in
            if let unWrappedError = error
            {
                XCTFail("\(unWrappedError)")
            }
        }
    }
}


//
//  BothamAPIClientTests.swift
//  BothamNetworking
//
//  Created by Pedro Vicente Gomez on 23/11/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation
import Nimble
import BrightFutures
import Nocilla
@testable import BothamNetworking

class BothamAPIClientTests: NocillaTestCase {

    private let anyPath = "path"
    private let anyHTTPMethod = HTTPMethod.GET

    func shouldSendARequestToTheURLPassedAsArgument() {
        stubRequest("GET", anyPath)
        let bothamAPIClient = givenABothamAPIClient()

        let result = bothamAPIClient.sendRequest(anyHTTPMethod, path: anyPath)

        expect(result).toEventually(beSuccess())
    }

    func shouldSendARequestToTheURLPassedUsingParams() {
        stubRequest("GET", anyPath + "?k=v")
        let bothamAPIClient = givenABothamAPIClient()

        let result = bothamAPIClient.sendRequest(anyHTTPMethod, path: anyPath, params: ["k": "v"])

        expect(result).toEventually(beSuccess())
    }

    private func givenABothamAPIClient() -> BothamAPIClient {
        return BothamAPIClient(baseEndpoint: "www.anyhost.com", httpClient: NSHTTPClient())
    }

}

Refactor tests to improve readability

//
//  BothamAPIClientTests.swift
//  BothamNetworking
//
//  Created by Pedro Vicente Gomez on 23/11/15.
//  Copyright © 2015 GoKarumi S.L. All rights reserved.
//

import Foundation
import Nimble
import BrightFutures
import Nocilla
@testable import BothamNetworking

class BothamAPIClientTests: NocillaTestCase {

    private let anyPath = "path"
    private let anyHTTPMethod = HTTPMethod.GET

    func shouldSendARequestToTheURLPassedAsArgument() {
        stubRequest(anyHTTPMethod.rawValue, anyPath)
        let bothamAPIClient = givenABothamAPIClient()

        let result = bothamAPIClient.sendRequest(anyHTTPMethod, path: anyPath)

        expect(result).toEventually(beSuccess())
    }

    func shouldSendARequestToTheURLPassedUsingParams() {
        stubRequest(anyHTTPMethod.rawValue, anyPath + "?k=v")
        let bothamAPIClient = givenABothamAPIClient()

        let result = bothamAPIClient.sendRequest(anyHTTPMethod, path: anyPath, params: ["k": "v"])

        expect(result).toEventually(beSuccess())
    }

    private func givenABothamAPIClient() -> BothamAPIClient {
        return BothamAPIClient(baseEndpoint: "www.anyhost.com", httpClient: NSHTTPClient())
    }

}


//
//  ButtonStyleSelectableBase.swift
//  ButtonStyleKit
//
//  Created by keygx on 2016/08/04.
//  Copyright © 2016年 keygx. All rights reserved.
//

import UIKit

open class ButtonStyleSelectableBase: ButtonStyleKit {

    override public final var isEnabled: Bool {
        set {
            if newValue {
                currentState = .normal
            } else {
                currentState = .disabled
            }
        }
        get {
            return super.isEnabled
        }
    }

    override public final var isSelected: Bool {
        set {
            if newValue {
                currentState = .selected
            } else {
                currentState = .normal
            }
        }
        get {
            return super.isSelected
        }
    }

    public final var value: Bool = false {
        didSet {
            currentState = {
                if value {
                    return .selected
                } else {
                    return .normal
                }
            }()
        }
    }
}

Fix to reflect the value of isSelected in button value

//
//  ButtonStyleSelectableBase.swift
//  ButtonStyleKit
//
//  Created by keygx on 2016/08/04.
//  Copyright © 2016年 keygx. All rights reserved.
//

import UIKit

open class ButtonStyleSelectableBase: ButtonStyleKit {

    override public final var isEnabled: Bool {
        set {
            if newValue {
                currentState = .normal
            } else {
                currentState = .disabled
            }
        }
        get {
            return super.isEnabled
        }
    }

    override public final var isSelected: Bool {
        set {
            if newValue {
                value = true
            } else {
                value = false
            }
        }
        get {
            return super.isSelected
        }
    }

    public final var value: Bool = false {
        didSet {
            currentState = {
                if value {
                    return .selected
                } else {
                    return .normal
                }
            }()
        }
    }
}


//
//  sequenceOfBytesForFileAtPath.swift
//  KDJSwiftStdIO
//
//  Created by Kristopher Johnson on 7/19/14.
//  Copyright (c) 2014 Kristopher Johnson. All rights reserved.
//

import Foundation

// Return a sequence of Int32 values corresponding to bytes from a file.
//
// If an I/O error occurs, the value EOF (-1) will be the final value
// in the sequence.
//
// (Note that EOF will not appear in the sequence if the file is read
// from beginning to end without error.)
func sequenceOfBytesForFileAtPath(path: String) -> SequenceOf<Int32> {
    return SequenceOf({FileByteReaderGenerator(path: path)})
}

class FileByteReaderGenerator : Generator {
    var _finished: Bool
    var _file: UnsafePointer<FILE>

    init(path: String) {
        let pathAsCString = path.bridgeToObjectiveC().UTF8String
        _finished = false
        _file = fopen(pathAsCString, "rb")
    }

    deinit {
        if _file {
            fclose(_file)
        }
    }

    func next() -> Int32? {
        if _finished {
            return nil
        }

        if !_file {
            _finished = true
            return EOF
        }

        let ch = fgetc(_file)
        if ch != EOF {
            return ch
        }
        else if ferror(_file) != 0 {
            _finished = true
            return EOF
        }
        else {
            _finished = true
            return nil
        }
    }
}

Update for Xcode 6 beta 4

//
//  sequenceOfBytesForFileAtPath.swift
//  KDJSwiftStdIO
//
//  Created by Kristopher Johnson on 7/19/14.
//  Copyright (c) 2014 Kristopher Johnson. All rights reserved.
//

import Foundation

// Return a sequence of Int32 values corresponding to bytes from a file.
//
// If an I/O error occurs, the value EOF (-1) will be the final value
// in the sequence.
//
// (Note that EOF will not appear in the sequence if the file is read
// from beginning to end without error.)
public func sequenceOfBytesForFileAtPath(path: String) -> SequenceOf<Int32> {
    return SequenceOf({FileByteReaderGenerator(path: path)})
}

public class FileByteReaderGenerator : Generator {
    private var isFinished: Bool
    private var file: UnsafePointer<FILE>

    public init(path: String) {
        let pathAsCString = path.bridgeToObjectiveC().UTF8String
        isFinished = false
        file = fopen(pathAsCString, "rb")
    }

    deinit {
        if file {
            fclose(file)
        }
    }

    public func next() -> Int32? {
        if isFinished {
            return nil
        }

        if !file {
            isFinished = true
            return EOF
        }

        let ch = fgetc(file)
        if ch != EOF {
            return ch
        }
        else if ferror(file) != 0 {
            isFinished = true
            return EOF
        }
        else {
            isFinished = true
            return nil
        }
    }
}


//
//  RxWKUserContentController.swift
//  RxWebKit
//
//  Created by Jesse Hao on 2019/3/30.
//  Copyright © 2019 RxSwift Community. All rights reserved.
//

import WebKit
#if !RX_NO_MODULE
    import RxSwift
    import RxCocoa
#endif

extension WKUserContentController {
    fileprivate class MessageHandler : NSObject, WKScriptMessageHandler {
        typealias MessageReceiveHandler = (WKScriptMessage) -> Void
        private var messageReceiveHandler:MessageReceiveHandler?

        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            self.messageReceiveHandler?(message)
        }

        func onReceive(_ handler:@escaping MessageReceiveHandler) {
            self.messageReceiveHandler = handler
        }
    }
}

public extension Reactive where Base : WKUserContentController {
    /// Observable sequence of script message.
    ///
    /// - Parameter name: The name of the message handler
    /// - Returns: Observable sequence of script message.
    func scriptMessage(forName name:String) -> Observable<WKScriptMessage> {
        return Observable.create { [weak base] observer in
            let handler = WKUserContentController.MessageHandler()
            base?.add(handler, name: name)
            handler.onReceive {
                observer.onNext($0)
            }
            return Disposables.create {
                base?.removeScriptMessageHandler(forName: name)
            }
        }
    }
}

Adjust return type of scriptMessage(forName:)

//
//  RxWKUserContentController.swift
//  RxWebKit
//
//  Created by Jesse Hao on 2019/3/30.
//  Copyright © 2019 RxSwift Community. All rights reserved.
//

import WebKit
#if !RX_NO_MODULE
    import RxSwift
    import RxCocoa
#endif

extension WKUserContentController {
    fileprivate class MessageHandler : NSObject, WKScriptMessageHandler {
        typealias MessageReceiveHandler = (WKScriptMessage) -> Void
        private var messageReceiveHandler:MessageReceiveHandler?

        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            self.messageReceiveHandler?(message)
        }

        func onReceive(_ handler:@escaping MessageReceiveHandler) {
            self.messageReceiveHandler = handler
        }
    }
}

public extension Reactive where Base : WKUserContentController {
    /// Observable sequence of script message.
    ///
    /// - Parameter name: The name of the message handler
    /// - Returns: Observable sequence of script message.
    func scriptMessage(forName name:String) -> ControlEvent<WKScriptMessage> {
        return ControlEvent(events: Observable.create { [weak base] observer in
            let handler = WKUserContentController.MessageHandler()
            base?.add(handler, name: name)
            handler.onReceive {
                observer.onNext($0)
            }
            return Disposables.create {
                base?.removeScriptMessageHandler(forName: name)
            }
        })
    }
}


//
//  Store.swift
//  Habits
//
//  Created by Julian Grosshauser on 27/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import RealmSwift

typealias Habits = Results<Habit>

class Store {

    //MARK: Properties

    private let realm: Realm

    var habits: Habits {
        return realm.objects(Habit)
    }

    //MARK: Initialization

    init(realm: Realm) {
        self.realm = realm
    }

    //MARK: Managing Habits

    func addHabit(habit: Habit) {
        realm.write { [unowned self] in
            self.realm.add(habit)
        }
    }

    func deleteHabit(habit: Habit) {
        realm.write { [unowned self] in
            self.realm.delete(habit)
        }
    }
}

Create `Habit` object in `addHabit(_:)`

//
//  Store.swift
//  Habits
//
//  Created by Julian Grosshauser on 27/09/15.
//  Copyright © 2015 Julian Grosshauser. All rights reserved.
//

import RealmSwift

typealias Habits = Results<Habit>

class Store {

    //MARK: Properties

    private let realm: Realm

    var habits: Habits {
        return realm.objects(Habit)
    }

    //MARK: Initialization

    init(realm: Realm) {
        self.realm = realm
    }

    //MARK: Managing Habits

    func addHabit(name: String) {
        let habit = Habit(name: name)

        realm.write { [unowned self] in
            self.realm.add(habit)
        }
    }

    func deleteHabit(habit: Habit) {
        realm.write { [unowned self] in
            self.realm.delete(habit)
        }
    }
}


//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}
  /*
internal extension Collection {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript (safe index: Index) -> Generator.Element? {
    let val = self[index];
    return self.indices ~= index ? self[index] : nil;

    return indices.contains(index) ? self[index] : nil
  }
}
*/

Add Enum (with RawValue) and string extension.

//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

internal extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable where RawValue == String {
  init?(raw: String?) {
    guard let string = raw else {
      return nil
    }
    self.init(rawValue:string)
  }
}
internal extension RawRepresentable {
  init(raw: RawValue?,  defaultValue:Self) {
    if let value = raw  {
      self = Self.init(rawValue:value) ?? defaultValue
    }
    self = defaultValue
  }
}


//
//  Common.swift
//  AutoLayout
//
//  Created by Marc Baldwin on 11/03/2015.
//  Copyright (c) 2015 Marc Baldwin. All rights reserved.
//

import UIKit

public struct Views {
    let views: [UIView]

    init(_ views: [UIView]) {
        self.views = views
    }
}

public class Builder {
    var constraints = [NSLayoutConstraint]()
}

public extension Builder {

    public func activateConstraints(active: Bool) {
        for constraint in constraints {
            constraint.active = active
        }
    }
}

public func += (lhs: Builder, rhs: [NSLayoutConstraint]) {
    lhs.constraints += rhs
}

Add default init to Builder

//
//  Common.swift
//  AutoLayout
//
//  Created by Marc Baldwin on 11/03/2015.
//  Copyright (c) 2015 Marc Baldwin. All rights reserved.
//

import UIKit

public struct Views {
    let views: [UIView]

    init(_ views: [UIView]) {
        self.views = views
    }
}

public class Builder {
    var constraints = [NSLayoutConstraint]()

    init() {}
}

public extension Builder {

    public func activateConstraints(active: Bool) {
        for constraint in constraints {
            constraint.active = active
        }
    }
}

public func += (lhs: Builder, rhs: [NSLayoutConstraint]) {
    lhs.constraints += rhs
}


// RUN: %target-swift-frontend -import-objc-header %S/Inputs/huge_c_type.h %s -disable-llvm-optzns -emit-ir | %FileCheck %s
// Make sure that this does not crash during LLVM's ISel. It does not like huge
// llvm::IntegerTypes.
// RUN: %target-swift-frontend -import-objc-header %S/Inputs/huge_c_type.h %s -c

// CHECK-NOT:i9535616

public func doIt(a: Thing3) {
  print(a)
}

Test does not work on linux

// RUN: %target-swift-frontend -import-objc-header %S/Inputs/huge_c_type.h %s -disable-llvm-optzns -emit-ir | %FileCheck %s
// Make sure that this does not crash during LLVM's ISel. It does not like huge
// llvm::IntegerTypes.
// RUN: %target-swift-frontend -import-objc-header %S/Inputs/huge_c_type.h %s -c

// REQUIRES: OS=macosx || OS=ios

// CHECK-NOT:i9535616

public func doIt(a: Thing3) {
  print(a)
}


//
//  NewsRequest.swift
//  TOZ_iOS
//
//  Created by Rafal Gorczynski on 01.04.2017.
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation

final class NewsRequest: BackendAPIRequest {

    var endpoint: String {
        return "/news"
    }

    var method: NetworkService.Method {
        return .GET
    }

    var parameters: [String: Any]? {
        return nil
    }

    var headers: [String: String]? {
        return defaultJSONHeaders()
    }

    var queryItems: [URLQueryItem]? {
        return [URLQueryItem(name: "isOrdered", value: "true")]
    }
}

Refactor adding query item to request

//
//  NewsRequest.swift
//  TOZ_iOS
//
//  Created by Rafal Gorczynski on 01.04.2017.
//  Copyright © 2017 intive. All rights reserved.
//

import Foundation

final class NewsRequest: BackendAPIRequest {

    var endpoint: String {
        return "/news"
    }

    var method: NetworkService.Method {
        return .GET
    }

    var parameters: [String: Any]? {
        return ["isOrdered": "true"]
    }

    var headers: [String: String]? {
        return defaultJSONHeaders()
    }
}


//
//  Created by Tom Baranes on 14/07/16.
//  Copyright © 2016 Tom Baranes. All rights reserved.
//

import Foundation
import QuartzCore

public struct UnitTesting {

    public static var isRunning: Bool {
        return ProcessInfo.processInfo.environment["XCInjectBundle"] != nil
    }

    public static func measure(closure: () -> Void) -> Float {
        let start = CACurrentMediaTime()
        closure()

        let end = CACurrentMediaTime()
        return Float(end - start)
    }
}

Fix UnitTest isRunning on xcode8

//
//  Created by Tom Baranes on 14/07/16.
//  Copyright © 2016 Tom Baranes. All rights reserved.
//

import Foundation
import QuartzCore

public struct UnitTesting {

    public static var isRunning: Bool {
        return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
    }

    public static func measure(closure: () -> Void) -> Float {
        let start = CACurrentMediaTime()
        closure()

        let end = CACurrentMediaTime()
        return Float(end - start)
    }
}


import XCTest
@testable import CommandLine

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

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

Add test for simple running of commands

import XCTest
@testable import CommandLine

class CommandLineTests: XCTestCase {

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

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

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

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

}


//
//  AKScheduledAction.swift
//  AudioKit For iOS
//
//  Created by David Sweetman on 4/1/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import Foundation

class AKScheduledAction {

    private var interval: TimeInterval
    private var block: (() -> Void)
    private var timer: Timer?

    init(interval: TimeInterval, block: @escaping () -> Void) {
        self.interval = interval
        self.block = block
        start()
    }

    dynamic func start() {
        timer?.invalidate()
        timer = nil
        timer = Timer.scheduledTimer(withTimeInterval: interval,
                                     repeats: false,
                                     block: { [weak self] (timer) in
                                        guard timer.isValid else { return }
                                        self?.block()
        })
    }

    dynamic func stop() {
        timer?.invalidate()
        timer = nil
    }

    deinit {
        stop()
    }
}

Use delegate-based Timer initializer instead of block-based to meet iOS 9 req

//
//  AKScheduledAction.swift
//  AudioKit For iOS
//
//  Created by David Sweetman on 4/1/17.
//  Copyright © 2017 AudioKit. All rights reserved.
//

import Foundation

class AKScheduledAction {

    private var interval: TimeInterval
    private var block: (() -> Void)
    private var timer: Timer?

    init(interval: TimeInterval, block: @escaping () -> Void) {
        self.interval = interval
        self.block = block
        start()
    }

    func start() {
        timer?.invalidate()
        timer = Timer.scheduledTimer(timeInterval: interval,
                                     target: self,
                                     selector: #selector(fire(timer:)),
                                     userInfo: nil,
                                     repeats: false)
    }

    func stop() {
        timer?.invalidate()
        timer = nil
    }

    private dynamic func fire(timer: Timer) {
        guard timer.isValid else { return }
        self.block()
    }

    deinit {
        stop()
    }
}


// RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck %s

// rdar://problem/27781174
// XFAIL: *

// FIXME: Existential devirtualization needs to be updated to work with
// open_existential_addr instructions. rdar://problem/18506660

protocol Pingable {
 func ping(_ x : Int);
}
class Foo : Pingable {
  func ping(_ x : Int) { var t : Int }
}

// Everything gets devirtualized, inlined, and promoted to the stack.
//CHECK: @_TF24devirtualize_existential17interesting_stuffFT_T_
//CHECK-NOT: init_existential_addr
//CHECK-NOT: apply
//CHECK: return
func interesting_stuff() {
 var x : Pingable = Foo()
 x.ping(1)
}

Enable a previously disabled test.

// RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck %s

protocol Pingable {
 func ping(_ x : Int);
}
class Foo : Pingable {
  func ping(_ x : Int) { var t : Int }
}

// Everything gets devirtualized, inlined, and promoted to the stack.
//CHECK: @_TF24devirtualize_existential17interesting_stuffFT_T_
//CHECK-NOT: init_existential_addr
//CHECK-NOT: apply
//CHECK: return
public func interesting_stuff() {
 var x : Pingable = Foo()
 x.ping(1)
}


import Foundation
import Swish
import Result

struct FakeRequest: Request {
  typealias ResponseObject = String

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }

  func parse(_ data: Data) throws -> String {
    let body = try JSONDecoder().decode(FakeResponseBody.self, from: data)
    return body.text
  }
}

private struct FakeResponseBody: Codable {
  var text: String
}

struct FakeEmptyDataRequest: Request {
  typealias ResponseObject = EmptyResponse

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }
}

struct FakeStringRequest: Request {
  typealias ResponseObject = String

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }

  func parse(_ data: Data) throws -> String {
    if let string = String(data: data, encoding: .utf8) {
      return string
    } else {
      throw FakeError(message: "invalid UTF-8")
    }
  }
}

struct FakeError: Error {
  var message: String
}

Use an inline struct instead of fileprivate

import Foundation
import Swish
import Result

struct FakeRequest: Request {
  typealias ResponseObject = String

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }

  func parse(_ data: Data) throws -> String {
    struct Body: Codable { var text: String }
    let body = try JSONDecoder().decode(Body.self, from: data)
    return body.text
  }
}

struct FakeEmptyDataRequest: Request {
  typealias ResponseObject = EmptyResponse

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }
}

struct FakeStringRequest: Request {
  typealias ResponseObject = String

  func build() -> URLRequest {
    return URLRequest(url: URL(string: "http://example.com")!)
  }

  func parse(_ data: Data) throws -> String {
    if let string = String(data: data, encoding: .utf8) {
      return string
    } else {
      throw FakeError(message: "invalid UTF-8")
    }
  }
}

struct FakeError: Error {
  var message: String
}


import UIKit

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
  }

  public override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }
}

Set default tint color to red

import UIKit

public class DayViewController: UIViewController {

  lazy var dayView: DayView = DayView()

  override public func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = UIRectEdge.None
    view.addSubview(dayView)
    view.tintColor = UIColor.redColor()
  }

  public override func viewDidLayoutSubviews() {
    dayView.fillSuperview()
  }
}


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

extension Module {
	public static var churchList: Module {
		return Module("ChurchList", [])
	}
}

Add the type of encoded lists.

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

extension Module {
	public static var churchList: Module {
		let List: Recur = "List"
		let list = Declaration("List",
			type: .Type --> .Type,
			value: (.Type, .Type) => { A, B in (A --> List[A] --> B) --> (.UnitType --> B) --> B })

		return Module("ChurchList", [ list ])
	}
}


// REQUIRES OS=ios
// REQUIRES CPU=arm64
// RUN: %target-swift-frontend -typecheck %s -swift-version 3
// RUN: rm -rf %t && mkdir -p %t && cd %t && %swiftc_driver -c -update-code -target arm64-apple-ios10.3 -output-file-map %S/Inputs/no_duplicate_aarch64_use_tbi_ofm.json -swift-version 3 %s -v
// RUN: cd %t && %swiftc_driver -c -update-code -target arm64-apple-ios10.3 -output-file-map %S/Inputs/no_duplicate_aarch64_use_tbi_ofm.json -swift-version 3 %s -### > %t/driver_actions.txt
// RUN: %FileCheck --check-prefix=CHECK-REMAP %s < %t/no_duplicate_aarch64_use_tbi.remap
// RUN: %FileCheck --check-prefix=CHECK-ACTIONS %s < %t/driver_actions.txt

public func foo(_ f: (Void) -> ()) {}

// CHECK-REMAP: "offset": 671,
// CHECK-REMAP: "remove": 5,
// CHECK-REMAP: "text": "("

// CHECK-ACTIONS: -Xllvm -aarch64-use-tbi

Fix REQUIRES lines in test

// REQUIRES: OS=ios
// REQUIRES: CPU=arm64
// RUN: %target-swift-frontend -typecheck %s -swift-version 3
// RUN: rm -rf %t && mkdir -p %t && cd %t && %swiftc_driver -c -update-code -target arm64-apple-ios10.3 -output-file-map %S/Inputs/no_duplicate_aarch64_use_tbi_ofm.json -swift-version 3 %s -v
// RUN: cd %t && %swiftc_driver -c -update-code -target arm64-apple-ios10.3 -output-file-map %S/Inputs/no_duplicate_aarch64_use_tbi_ofm.json -swift-version 3 %s -### > %t/driver_actions.txt
// RUN: %FileCheck --check-prefix=CHECK-REMAP %s < %t/no_duplicate_aarch64_use_tbi.remap
// RUN: %FileCheck --check-prefix=CHECK-ACTIONS %s < %t/driver_actions.txt

public func foo(_ f: (Void) -> ()) {}

// CHECK-REMAP: "offset": 671,
// CHECK-REMAP: "remove": 5,
// CHECK-REMAP: "text": "("

// CHECK-ACTIONS: -Xllvm -aarch64-use-tbi


//
//  ViewController.swift
//  KonamiCode
//
//  Created by Sebastien Morel on 10/17/14.
//  Copyright (c) 2014 Plopix. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet var stateLabel : UILabel!;

    override func viewDidLoad() {
        super.viewDidLoad()
        let recognizer = PlopixKonamiGesture(target: self, action: "launchEasterEgg:")
        view.addGestureRecognizer(recognizer)
    }

    func launchEasterEgg(recognizer: UIGestureRecognizer) {
        if ( recognizer.state == .Ended ) {
            stateLabel.text = "Yeah you did it!"
        }
        if ( recognizer.state == .Failed || recognizer.state == .Cancelled ) {
            stateLabel.text = "Try again!"
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Fix swift 2.2 in standalone project

//
//  ViewController.swift
//  KonamiCode
//
//  Created by Sebastien Morel on 10/17/14.
//  Copyright (c) 2014 Plopix. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet var stateLabel : UILabel!;

    override func viewDidLoad() {
        super.viewDidLoad()
        let recognizer = PlopixKonamiGesture(target: self, action: #selector(ViewController.launchEasterEgg(_:)))
        view.addGestureRecognizer(recognizer)
    }

    func launchEasterEgg(recognizer: UIGestureRecognizer) {
        if ( recognizer.state == .Ended ) {
            stateLabel.text = "Yeah you did it!"
        }
        if ( recognizer.state == .Failed || recognizer.state == .Cancelled ) {
            stateLabel.text = "Try again!"
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


//
//  ResourceesClassGenerator.swift
//  SafeAsset
//
//  Created by Ido Mizrachi on 7/8/16.
//  Copyright © 2016 Ido Mizrachi. All rights reserved.
//

import Cocoa

class ResourceesClassGenerator {

    func generateClass(fromImages images : [ImageAssetMetadata], generatedFile : String) {
        var headerFile = ""
        var implementationFile = ""

        headerFile += "@import Foundation;\n\n"
        headerFile += "@interface \(generatedFile) : NSObject \n\n"

        implementationFile += "#import \"\(generatedFile).h\"\n"
        implementationFile += "@implementation \(generatedFile)\n"

        for metadata in images {
            headerFile += "+(NSString *)\(metadata.property);\n"
            implementationFile += "+(NSString *)\(metadata.property) {\n"
            implementationFile += "    return @\"\(metadata.imageNamed)\";\n"
            implementationFile += "}\n"
        }

        headerFile += "\n@end\n"

        implementationFile += "\n@end\n"

        do {
            try headerFile.writeToFile(generatedFile + ".h", atomically: false, encoding: NSUTF8StringEncoding)
            try implementationFile.writeToFile(generatedFile + ".m", atomically: false, encoding: NSUTF8StringEncoding)
        } catch let error {
            print("Error: \(error)")
        }
    }
}

Use struct instead of static methods

//
//  ResourceesClassGenerator.swift
//  SafeAsset
//
//  Created by Ido Mizrachi on 7/8/16.
//  Copyright © 2016 Ido Mizrachi. All rights reserved.
//

import Cocoa

class ResourceesClassGenerator {

    func generateClass(fromImages images : [ImageAssetMetadata], generatedFile : String) {
        var headerFile = ""
        var implementationFile = ""

        headerFile += "@import Foundation;\n\n"
        headerFile += "extern const struct \(generatedFile) {\n"

        implementationFile += "#import \"\(generatedFile).h\"\n"
        implementationFile += "const struct \(generatedFile) \(generatedFile) = {\n"

        for metadata in images {
            headerFile += "    __unsafe_unretained NSString *\(metadata.property);\n"
            implementationFile += "    .\(metadata.property) = @\"\(metadata.imageNamed)\",\n"

        }

        headerFile += "\n} \(generatedFile);\n"
        implementationFile += "\n};\n"

        do {
            try headerFile.writeToFile(generatedFile + ".h", atomically: false, encoding: NSUTF8StringEncoding)
            try implementationFile.writeToFile(generatedFile + ".m", atomically: false, encoding: NSUTF8StringEncoding)
        } catch let error {
            print("Error: \(error)")
        }
    }
}


import UIKit

extension UITableView {

    /// Register a cell type for reuse
    ///
    /// - parameter type: The type of cell that must be registered
    func register(_ type: CellType) {
        switch type {
        case .class(let cellClass):
            self.register(cellClass, forCellReuseIdentifier: type.reusableIdentifier)
        case .nib(let nib, _):
            self.register(nib, forCellReuseIdentifier: type.reusableIdentifier)
        }
    }

    /// Register a header/footer type for reuse
    ///
    /// - parameter type: The type of header/footer that must be registered
    func register(_ type: HeaderFooterType) {
        switch type {
        case .class(let cellClass):
            self.register(cellClass, forHeaderFooterViewReuseIdentifier: type.reusableIdentifier)
        case .nib(let nib, _):
            self.register(nib, forHeaderFooterViewReuseIdentifier: type.reusableIdentifier)
        }
    }

    func moveRows(at indexPaths: [IndexPath], to newIndexPaths: [IndexPath]) {
        for (index, _) in indexPaths.enumerated() {
            moveRow(at: indexPaths[index], to: newIndexPaths[index])
        }
    }

}

Change UITableView extension methods to public

import UIKit

extension UITableView {

    /// Register a cell type for reuse
    ///
    /// - parameter type: The type of cell that must be registered
    public func register(_ type: CellType) {
        switch type {
        case .class(let cellClass):
            self.register(cellClass, forCellReuseIdentifier: type.reusableIdentifier)
        case .nib(let nib, _):
            self.register(nib, forCellReuseIdentifier: type.reusableIdentifier)
        }
    }

    /// Register a header/footer type for reuse
    ///
    /// - parameter type: The type of header/footer that must be registered
    public func register(_ type: HeaderFooterType) {
        switch type {
        case .class(let cellClass):
            self.register(cellClass, forHeaderFooterViewReuseIdentifier: type.reusableIdentifier)
        case .nib(let nib, _):
            self.register(nib, forHeaderFooterViewReuseIdentifier: type.reusableIdentifier)
        }
    }

    public func moveRows(at indexPaths: [IndexPath], to newIndexPaths: [IndexPath]) {
        for (index, _) in indexPaths.enumerated() {
            moveRow(at: indexPaths[index], to: newIndexPaths[index])
        }
    }

}


//
//  ALUtilities.swift
//  ALCameraViewController
//
//  Created by Alex Littlejohn on 2015/06/25.
//  Copyright (c) 2015 zero. All rights reserved.
//

import UIKit

internal func SpringAnimation(animations: () -> Void) {
    UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.BeginFromCurrentState], animations: {
        animations()
        }, completion: nil)
}

internal func LocalizedString(key: String) -> String {
    return NSLocalizedString(key, tableName: "ALCameraView", bundle: NSBundle(forClass: ALCameraViewController.self), comment: key)
}

extension UIImage {
    func crop(frame: CGRect, scale: CGFloat) -> UIImage {

        let drawPoint = CGPointZero

        UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)

        let context = UIGraphicsGetCurrentContext()

        CGContextTranslateCTM(context, -frame.origin.x, -frame.origin.y)
        CGContextScaleCTM(context, scale, scale)
        drawAtPoint(drawPoint)

        let croppedImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext();

        return croppedImage
    }
}

Use screen scale to get a phone appropriate size for the cropped images

//
//  ALUtilities.swift
//  ALCameraViewController
//
//  Created by Alex Littlejohn on 2015/06/25.
//  Copyright (c) 2015 zero. All rights reserved.
//

import UIKit

internal func SpringAnimation(animations: () -> Void) {
    UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.BeginFromCurrentState], animations: {
        animations()
        }, completion: nil)
}

internal func LocalizedString(key: String) -> String {
    return NSLocalizedString(key, tableName: "ALCameraView", bundle: NSBundle(forClass: ALCameraViewController.self), comment: key)
}

extension UIImage {
    func crop(frame: CGRect, scale: CGFloat) -> UIImage {

        let screenScale = UIScreen.mainScreen().scale
        var mutableRect = frame

        mutableRect.origin.x *= screenScale
        mutableRect.origin.y *= screenScale
        mutableRect.size.width *= screenScale
        mutableRect.size.height *= screenScale

        let drawPoint = CGPointZero

        UIGraphicsBeginImageContextWithOptions(mutableRect.size, false, 0)

        let context = UIGraphicsGetCurrentContext()

        CGContextTranslateCTM(context, -mutableRect.origin.x, -mutableRect.origin.y)
        CGContextScaleCTM(context, scale * screenScale, scale * screenScale)
        drawAtPoint(drawPoint)

        let croppedImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext();

        return croppedImage
    }
}


//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

internal extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

internal extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable where RawValue == String {
  init?(raw: String?) {
    guard let string = raw else {
      return nil
    }
    self.init(rawValue: string)
  }
}
internal extension RawRepresentable {
  init(raw: RawValue?,  defaultValue: Self) {
    guard let value = raw  else {
      self = defaultValue
      return
    }
    self = Self.init(rawValue: value) ?? defaultValue
  }
}

Make a more generic extension, instead of the specialised one.

//
//  Utils.swift
//  IBAnimatableApp
//
//  Created by jason akakpo on 03/07/16.
//  Copyright © 2016 Jake Lin. All rights reserved.
//

import Foundation

extension Array {
  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  subscript(safe index: Int ) -> Element? {
    return indices.contains(index) ? self[index] : nil  /// Returns the element at the specified index iff it is within bounds, otherwise nil.
  }
}

extension String {
  func toDouble() -> Double? {
    return Double(self)
  }
  func toInt() -> Int? {
    return Int(self)
  }
}

internal extension RawRepresentable {

  init?(raw: RawValue?) {
    guard let raw = raw else {
      return nil
    }
    self.init(rawValue: raw)
  }

  init(raw: RawValue?,  defaultValue: Self) {
    guard let value = raw  else {
      self = defaultValue
      return
    }
    self = Self.init(rawValue: value) ?? defaultValue
  }
}


//
//  Action.swift
//  BoostRemote
//
//  Created by Shinichiro Oba on 2017/08/07.
//  Copyright © 2017 bricklife.com. All rights reserved.
//

import Foundation
import ReSwift

enum ConnectAction: Action {

    case scan
    case connect
    case disconnect
    case offline
    case unsupported
}

struct NotificationAction: Action {

    let notification: Notification
}

struct ActionCenter {

    static func startScan() {
        let action: Store<State>.ActionCreator = { state, store in
            MoveHubManager.shared.startScan()
            return ConnectAction.scan
        }
        store.dispatch(action)
    }

    static func stopScan() {
        MoveHubManager.shared.stopScan()
        store.dispatch(ConnectAction.disconnect)
    }

    static func disconnect() {
        MoveHubManager.shared.disconnect()
    }

    static func send(command: Command) {
        print(command)
        MoveHubManager.shared.write(data: command.data)
    }
}

Enable to cancel a discovering

//
//  Action.swift
//  BoostRemote
//
//  Created by Shinichiro Oba on 2017/08/07.
//  Copyright © 2017 bricklife.com. All rights reserved.
//

import Foundation
import ReSwift

enum ConnectAction: Action {

    case scan
    case connect
    case disconnect
    case offline
    case unsupported
}

struct NotificationAction: Action {

    let notification: Notification
}

struct ActionCenter {

    static func startScan() {
        let action: Store<State>.ActionCreator = { state, store in
            MoveHubManager.shared.startScan()
            return ConnectAction.scan
        }
        store.dispatch(action)
    }

    static func stopScan() {
        MoveHubManager.shared.stopScan()
        store.dispatch(ConnectAction.disconnect)
    }

    static func disconnect() {
        MoveHubManager.shared.disconnect()
        store.dispatch(ConnectAction.disconnect)
    }

    static func send(command: Command) {
        print(command)
        MoveHubManager.shared.write(data: command.data)
    }
}


/**
 * Question Link: https://leetcode.com/problems/longest-consecutive-sequence/
 * Primary idea: Iterate the array and check all neighbor numbers with the help of set
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class LongestConsecutiveSequence {
    func longestConsecutive(_ nums: [Int]) -> Int {
        var set = Set(nums)
        var longest = 0

        for num in nums {
            if set.contains(num) {
                set.remove(num)
                longest = max(1 + findConsecutive(&set, num, 1) + findConsecutive(&set, num, -1), longest)
            }
        }

        return longest
    }

    private func findConsecutive(_ set: inout Set<Int>, _ num: Int, _ step: Int) -> Int {
        var len = 0
        var num = num + step

        while set.contains(num) {
            set.remove(num)
            len += 1
            num += step
        }

        return len
    }
}

Update solution to Longest Consecutive Sequence

/**
 * Question Link: https://leetcode.com/problems/longest-consecutive-sequence/
 * Primary idea: Iterate the array and check all neighbor numbers with the help of set
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 */

class LongestConsecutiveSequence {
    func longestConsecutive(_ nums: [Int]) -> Int {
        var set = Set(nums), longest = 0

        for num in nums {
            if set.contains(num) {
                set.remove(num)
                let distance = 1 + findConsecutive(&set, num, 1) + findConsecutive(&set, num, -1)
                longest = max(longest, distance)
            }
        }

        return longest
    }

    fileprivate func findConsecutive(_ set: inout Set<Int>, _ num: Int, _ step: Int) -> Int {
        var len = 0, num = num + step

        while set.contains(num) {
            set.remove(num)
            len += 1
            num += step
        }

        return len
    }
}


// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

/// A type that represents an archive.
public protocol Archive {

    /// Unarchive data from the archive.
    static func unarchive(archive: Data) throws -> Data

}

/// A type that provides an implementation of a particular decompression algorithm.
public protocol DecompressionAlgorithm {

    /// Decompress data compressed with particular algorithm.
    static func decompress(data: Data) throws -> Data

}

/// A type that represents a container of files, directories and/or other data.
public protocol Container {

    /// Retrieve all the entries from the container.
    static func open(container: Data) throws -> [ContainerEntry]

}

/// A type that represents an entry from a container (file or directory) with attributes.
public protocol ContainerEntry {

    /// Retrieve name of the entry from the container.
    var name: String { get }

    /// Retrieve size of the entry's data from the container.
    var size: Int { get }

    /// Check if entry is a directory.
    var isDirectory: Bool { get }

    /**
     Provides a dictionary with various attributes of the entry.
     `FileAttributeKey` values are used as dictionary keys.

     - Note:
     Will be renamed to `attributes` in 4.0.
     */
    var entryAttributes: [FileAttributeKey: Any] { get }

    /// Retrieve entry's data from the container.
    func data() throws -> Data

}

Add isLink and linkPath properties to ContainerEntry protocol

// Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information

import Foundation

/// A type that represents an archive.
public protocol Archive {

    /// Unarchive data from the archive.
    static func unarchive(archive: Data) throws -> Data

}

/// A type that provides an implementation of a particular decompression algorithm.
public protocol DecompressionAlgorithm {

    /// Decompress data compressed with particular algorithm.
    static func decompress(data: Data) throws -> Data

}

/// A type that represents a container of files, directories and/or other data.
public protocol Container {

    /// Retrieve all the entries from the container.
    static func open(container: Data) throws -> [ContainerEntry]

}

/// A type that represents an entry from a container (file or directory) with attributes.
public protocol ContainerEntry {

    /// Retrieve name of the entry from the container.
    var name: String { get }

    /// Retrieve size of the entry's data from the container.
    var size: Int { get }

    /// Check if entry is a directory.
    var isDirectory: Bool { get }

    var isLink: Bool { get }
    var linkPath: String? { get }

    /**
     Provides a dictionary with various attributes of the entry.
     `FileAttributeKey` values are used as dictionary keys.

     - Note:
     Will be renamed to `attributes` in 4.0.
     */
    var entryAttributes: [FileAttributeKey: Any] { get }

    /// Retrieve entry's data from the container.
    func data() throws -> Data

}


import Foundation

enum LandingFeatures {
  /// Features in ascending order of date
  static let features: [LandingFeature?] = [
    LandingFeatures.introToProgramming1,
    LandingFeatures.introToProgramming2,
    LandingFeatures.bashWorkshop,
    LandingFeatures.gitWorkshop,
    LandingFeatures.introToProgramming3,
    LandingFeatures.programmingInRust,
    LandingFeatures.introToProgramming4,
    LandingFeatures.binaryExploitation,
    LandingFeatures.gamesWithLove,
    LandingFeatures.gameGig,
    LandingFeatures.introToUnity,
    LandingFeatures.continuousIntegrationWorkshop
  ]

  /// Gets the most currently appropriate feature
  static var currentFeature: LandingFeature? {
    let currentDate = Date()

    // We want to return the first non-nil LandingFeature whos expiry date is
    // after the current date. As the list itself is a list of optionals, we
    // need to safely unwrap the result at least once as features.first returns
    // a double optional.
    return (
      features.first { $0?.expiryDate ?? currentDate > currentDate }
      ?? nil
    )
  }
}

Make optional unwrapping for landing features less confusing

import Foundation

enum LandingFeatures {
  /// Features in ascending order of date
  static let features: [LandingFeature?] = [
    LandingFeatures.introToProgramming1,
    LandingFeatures.introToProgramming2,
    LandingFeatures.bashWorkshop,
    LandingFeatures.gitWorkshop,
    LandingFeatures.introToProgramming3,
    LandingFeatures.programmingInRust,
    LandingFeatures.introToProgramming4,
    LandingFeatures.binaryExploitation,
    LandingFeatures.gamesWithLove,
    LandingFeatures.gameGig,
    LandingFeatures.introToUnity,
    LandingFeatures.continuousIntegrationWorkshop
  ]

  /// Gets the most currently appropriate feature
  static var currentFeature: LandingFeature? {
    let currentDate = Date()

    // We want to return the first non-nil LandingFeature whos expiry date is
    // after the current date. As the list itself is a list of optionals, we
    // need to convert it to a list of non-optionals using flatMap first (as
    // otherwise a value of type double-optional is returned.)
    return  features.flatMap{ $0 }.first { $0.expiryDate > currentDate }
  }
}


//
//  BarItem.swift
//  goodbar
//
//  Created by Peter Hajas on 5/22/16.
//  Copyright © 2016 Peter Hajas. All rights reserved.
//

import Cocoa

struct BarItem {
    let script: String
    let color: NSColor

    init(script: String, color: NSColor) {
        self.script = script
        self.color = color
    }

    init(dictionaryRepresentation: NSDictionary) {
        let script = dictionaryRepresentation["script"] as! String
        var color = NSColor.orangeColor() // sane defaults

        if let colorStringFromFile = dictionaryRepresentation["color"] as? String {
            if let colorFromFile = NSColor.withCSSString(colorStringFromFile) {
                color = colorFromFile
            }
        }

        self.init(script: script, color: color)
    }

    func currentOutput() -> String {
        let task = NSTask()
        let pipe = NSPipe()

        let command = ((self.script as NSString).stringByExpandingTildeInPath) as String

        task.launchPath = "/bin/bash"
        task.arguments = ["-c", command]
        task.standardOutput = pipe

        task.launch()

        sleep(1)
        task.terminate()

        // Waiting seems busted right now...
//        task.waitUntilExit()

        let handle = pipe.fileHandleForReading
        let data = handle.readDataToEndOfFile()

        if let stringFromData = NSString(data: data, encoding: NSUTF8StringEncoding) {
            return stringFromData as String
        }
        else {
            return ""
        }
    }
}

Fix up the issue with sleeping - we can now just read until the end of the file

//
//  BarItem.swift
//  goodbar
//
//  Created by Peter Hajas on 5/22/16.
//  Copyright © 2016 Peter Hajas. All rights reserved.
//

import Cocoa

struct BarItem {
    let script: String
    let color: NSColor

    init(script: String, color: NSColor) {
        self.script = script
        self.color = color
    }

    init(dictionaryRepresentation: NSDictionary) {
        let script = dictionaryRepresentation["script"] as! String
        var color = NSColor.orangeColor() // sane defaults

        if let colorStringFromFile = dictionaryRepresentation["color"] as? String {
            if let colorFromFile = NSColor.withCSSString(colorStringFromFile) {
                color = colorFromFile
            }
        }

        self.init(script: script, color: color)
    }

    func currentOutput() -> String {
        let task = NSTask()
        let pipe = NSPipe()

        let command = ((self.script as NSString).stringByExpandingTildeInPath) as String

        task.launchPath = "/bin/bash"
        task.arguments = ["-c", command]
        task.standardOutput = pipe

        task.launch()

        let handle = pipe.fileHandleForReading
        let data = handle.readDataToEndOfFile()

        task.terminate()

        if let stringFromData = NSString(data: data, encoding: NSUTF8StringEncoding) {
            return stringFromData as String
        }
        else {
            return ""
        }
    }
}


import PackageDescription

let package = Package(
	name: "Swiftx",
	targets: [
		Target(name: "Swiftx"),
	],
	dependencies: [
		.Package(url: "https://github.com/typelift/Operadics.git", versions: Version(0,2,2)...Version(0,2,2))
	]
)

let libSwiftx = Product(name: "Swiftx", type: .Library(.Dynamic), modules: "Swiftx")
products.append(libSwiftx)

Remove products from the package manifest


import PackageDescription

let package = Package(
    name: "SwiftyImageIO"
)

Exclude not compatible GIF addition

import PackageDescription

let package = Package(
    name: "SwiftyImageIO",
    exclude: ["Sources/GIF.swift"]

)


//
//  SettingsAttributedStringView.swift
//  NetNewsWire-iOS
//
//  Created by Maurice Parker on 9/16/19.
//  Copyright © 2019 Ranchero Software. All rights reserved.
//

import SwiftUI

struct SettingsAttributedStringView: UIViewRepresentable {

	let string: NSAttributedString

    func makeUIView(context: Context) -> UITextView {
		let textView = UITextView()

		textView.attributedText = string
		textView.translatesAutoresizingMaskIntoConstraints = false
		textView.isEditable = false

		textView.adjustsFontForContentSizeCategory = true
		textView.font = .preferredFont(forTextStyle: .body)
		textView.textColor = UIColor.label
		textView.backgroundColor = UIColor.secondarySystemGroupedBackground

		return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
	}

}

Fix link tint color on about page

//
//  SettingsAttributedStringView.swift
//  NetNewsWire-iOS
//
//  Created by Maurice Parker on 9/16/19.
//  Copyright © 2019 Ranchero Software. All rights reserved.
//

import SwiftUI

struct SettingsAttributedStringView: UIViewRepresentable {

	let string: NSAttributedString

    func makeUIView(context: Context) -> UITextView {
		let textView = UITextView()

		textView.attributedText = string
		textView.translatesAutoresizingMaskIntoConstraints = false
		textView.isEditable = false

		textView.adjustsFontForContentSizeCategory = true
		textView.font = .preferredFont(forTextStyle: .body)
		textView.textColor = UIColor.label
		textView.tintColor = AppAssets.secondaryAccentColor
		textView.backgroundColor = UIColor.secondarySystemGroupedBackground

		return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
	}

}


// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk -abi -avoid-location
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable-abi.json -input-paths %t.tmp/current-stdlib.json -abi -o %t.tmp/changes.txt -v
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-abi.swift.expected -o - | sed '/^\s*$/d' | sort > %t.tmp/stability-stdlib-abi.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' | sort > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-abi.swift.expected %t.tmp/changes.txt.tmp

// The digester hasn't learned that we've stopped baking non-stored class member
// order into the ABI. rdar://problem/46617463
// The digester can incorrectly register a generic signature change when
// declarations are shuffled. rdar://problem/46618883
// UNSUPPORTED: swift_evolve

Remove comment citing fixed bug

// REQUIRES: OS=macosx
// RUN: %empty-directory(%t.tmp)
// mkdir %t.tmp/module-cache && mkdir %t.tmp/dummy.sdk
// RUN: %api-digester -dump-sdk -module Swift -o %t.tmp/current-stdlib.json -module-cache-path %t.tmp/module-cache -sdk %t.tmp/dummy.sdk -abi -avoid-location
// RUN: %api-digester -diagnose-sdk -input-paths %S/Inputs/stdlib-stable-abi.json -input-paths %t.tmp/current-stdlib.json -abi -o %t.tmp/changes.txt -v
// RUN: %clang -E -P -x c %S/Outputs/stability-stdlib-abi.swift.expected -o - | sed '/^\s*$/d' | sort > %t.tmp/stability-stdlib-abi.swift.expected
// RUN: %clang -E -P -x c %t.tmp/changes.txt -o - | sed '/^\s*$/d' | sort > %t.tmp/changes.txt.tmp
// RUN: diff -u %t.tmp/stability-stdlib-abi.swift.expected %t.tmp/changes.txt.tmp

// The digester can incorrectly register a generic signature change when
// declarations are shuffled. rdar://problem/46618883
// UNSUPPORTED: swift_evolve