//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: {
                let oldState = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)

                self.rootViewController = viewController

                UIView.setAnimationsEnabled(oldState)
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}

Add animation option to animate rootViewController in UIWindow

//
//  UIWindow+RootViewController.swift
//  Swiftilities
//
//  Created by Nicholas Bonatsakis on 2/5/16.
//  Copyright © 2016 Raizlabs. All rights reserved.
//

import UIKit

/**
 *  UIWindow extension for setting the rootViewController on a UIWindow instance in a safe and animatable way.
 */
public extension UIWindow {

    /**
     Set the rootViewController on this UIWindow instance.

     - parameter viewController: The view controller to set
     - parameter animated:       Whether or not to animate the transition, animation is a cross-fade
     - parameter completion:     Completion block to be invoked after the transition finishes
     */
    @nonobjc
    func setRootViewController(_ viewController: UIViewController, animated: Bool, duration: TimeInterval = 0.3, options: UIView.AnimationOptions = [.transitionCrossDissolve], completion: ((Bool) -> Void)? = nil) {
        if animated {
            UIView.transition(with: self, duration: duration, options: options, animations: {
                self.rootViewController = viewController
            }, completion: completion)
        } else {
            self.rootViewController = viewController
        }
    }
}


// RUN: %target-run-simple-swift
// REQUIRES: executable_test

import StdlibUnittest

// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif

var StringOrderRelationTestSuite = TestSuite("StringOrderRelation")

StringOrderRelationTestSuite.test("StringOrderRelation/ASCII/NullByte") {
  let baseString = "a"
  let nullbyteString = "a\0"
  expectTrue(baseString < nullbyteString)
  expectTrue(baseString <= nullbyteString)
  expectFalse(baseString > nullbyteString)
  expectFalse(baseString >= nullbyteString)
  expectFalse(baseString == nullbyteString)
  expectTrue(baseString != nullbyteString)
}

runAllTests()

Add .xfail for platforms without Objc runtime (FreeBSD and Linux)

// RUN: %target-run-simple-swift
// REQUIRES: executable_test

import StdlibUnittest

// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif

var StringOrderRelationTestSuite = TestSuite("StringOrderRelation")

StringOrderRelationTestSuite.test("StringOrderRelation/ASCII/NullByte")
  .xfail(.LinuxAny(reason: "String comparison: ICU vs. Foundation"))
  .xfail(.FreeBSDAny(reason: "String comparison: ICU vs. Foundation"))
  .code {
  let baseString = "a"
  let nullbyteString = "a\0"
  expectTrue(baseString < nullbyteString)
  expectTrue(baseString <= nullbyteString)
  expectFalse(baseString > nullbyteString)
  expectFalse(baseString >= nullbyteString)
  expectFalse(baseString == nullbyteString)
  expectTrue(baseString != nullbyteString)
}

runAllTests()


//
//  FlingChallengeUITests.swift
//  FlingChallengeUITests
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import XCTest

class FlingChallengeUITests: XCTestCase {

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

  override func tearDown() {
    super.tearDown()
  }

  func testExample() {
  }

}

Add a simple UI test that items are loaded

//
//  FlingChallengeUITests.swift
//  FlingChallengeUITests
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

import XCTest

class FlingChallengeUITests: XCTestCase {

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

  func testShowsContent() {
    let app = XCUIApplication()
    let collectionView = app.collectionViews
    XCTAssert(collectionView.cells.count > 0)
  }

}


//
//  AuthClient.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 5/5/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import RealmSwift

struct AuthClient: APIClient {
    let api: AnyAPIFetcher

    func login(params: LoginParams, completion: @escaping (APIResponse<LoginResource>) -> Void) {
        api.fetch(LoginRequest(params: params)) { response in
            switch response {
            case .resource(let resource):
                guard resource.status == "success" else {
                    return completion(.resource(.init(raw: ["error": resource.error ?? ""])))
                }

                let auth = Auth()
                auth.internalFirstChannelOpened = false
                auth.lastSubscriptionFetchWithLastMessage = nil
                auth.lastRoomFetchWithLastMessage = nil
                auth.lastAccess = Date()
                auth.serverURL = (self.api as? API)?.host.absoluteString ?? ""
                auth.token = resource.authToken
                auth.userId = resource.userId

                AuthManager.persistAuthInformation(auth)
                DatabaseManager.changeDatabaseInstance()

                Realm.executeOnMainThread({ (realm) in
                    // Delete all the Auth objects, since we don't
                    // support multiple-server per database
                    realm.delete(realm.objects(Auth.self))

                    PushManager.updatePushToken()
                    realm.add(auth)
                })

                SocketManager.sharedInstance.isUserAuthenticated = true
                ServerManager.timestampSync()
                completion(response)
            case .error:
                completion(response)
            }
        }
    }
}

Stop setting websocket connection as authenticated on LoginRequest callback because it doesn't authenticate the websocket connection

//
//  AuthClient.swift
//  Rocket.Chat
//
//  Created by Matheus Cardoso on 5/5/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//

import RealmSwift

struct AuthClient: APIClient {
    let api: AnyAPIFetcher

    func login(params: LoginParams, completion: @escaping (APIResponse<LoginResource>) -> Void) {
        api.fetch(LoginRequest(params: params)) { response in
            switch response {
            case .resource(let resource):
                guard resource.status == "success" else {
                    return completion(.resource(.init(raw: ["error": resource.error ?? ""])))
                }

                let auth = Auth()
                auth.internalFirstChannelOpened = false
                auth.lastSubscriptionFetchWithLastMessage = nil
                auth.lastRoomFetchWithLastMessage = nil
                auth.lastAccess = Date()
                auth.serverURL = (self.api as? API)?.host.absoluteString ?? ""
                auth.token = resource.authToken
                auth.userId = resource.userId

                AuthManager.persistAuthInformation(auth)
                DatabaseManager.changeDatabaseInstance()

                Realm.executeOnMainThread({ (realm) in
                    // Delete all the Auth objects, since we don't
                    // support multiple-server per database
                    realm.delete(realm.objects(Auth.self))

                    PushManager.updatePushToken()
                    realm.add(auth)
                })

                ServerManager.timestampSync()
                completion(response)
            case .error:
                completion(response)
            }
        }
    }
}


//
//  CircleViewController.swift
//  RotatingDials
//
//  Created by Ben Chatelain on 6/19/15.
//  Copyright (c) 2015 Ben Chatelain. All rights reserved.
//

import CoreGraphics
import UIKit

class CircleViewController: UIViewController {

    @IBOutlet weak var orangeCircle: UIView!
    @IBOutlet weak var greenCircle: UIView!
    @IBOutlet weak var blueCircle: UIView!

    let diameter: CGFloat = 250

    override func viewDidLoad() {
        super.viewDidLoad()

        orangeCircle.layer.cornerRadius = diameter / 2
        greenCircle.layer.cornerRadius = diameter / 2
        blueCircle.layer.cornerRadius = diameter / 2
    }

    @IBAction func didTapCircleContainerView(sender: AnyObject) {
        println("didTapCircleContainerView")

        UIView.animateWithDuration(0.5) { () -> Void in

            let radians = self.degreesToRadians(120)
            let transform = CGAffineTransformRotate(self.view.transform, CGFloat(radians))
            // CGAffineTransformMakeRotation(M_PI);
            self.view.transform = transform

        }

    }

    private func degreesToRadians(angle: Double) -> Double {
        return angle / 180.0 * M_PI
    }
}

Adjust anchorPoint so rotation is more natural

//
//  CircleViewController.swift
//  RotatingDials
//
//  Created by Ben Chatelain on 6/19/15.
//  Copyright (c) 2015 Ben Chatelain. All rights reserved.
//

import CoreGraphics
import UIKit

class CircleViewController: UIViewController {

    @IBOutlet weak var orangeCircle: UIView!
    @IBOutlet weak var greenCircle: UIView!
    @IBOutlet weak var blueCircle: UIView!

    let diameter: CGFloat = 250

    override func viewDidLoad() {
        super.viewDidLoad()

        orangeCircle.layer.cornerRadius = diameter / 2
        greenCircle.layer.cornerRadius = diameter / 2
        blueCircle.layer.cornerRadius = diameter / 2

        let anchorPoint = view.layer.anchorPoint
        println("anchorPoint: \(anchorPoint)")
        view.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5666)
    }

    @IBAction func didTapCircleContainerView(sender: AnyObject) {
        println("didTapCircleContainerView")

        UIView.animateWithDuration(0.5) { () -> Void in

            let radians = self.degreesToRadians(120)
            let transform = CGAffineTransformRotate(self.view.transform, CGFloat(radians))
            self.view.transform = transform

        }

    }

    private func degreesToRadians(angle: Double) -> Double {
        return angle / 180.0 * M_PI
    }
}


import AVFoundation

public class Recording {
    var recorder: AVAudioRecorder!
    var player: AVAudioPlayer!
    var session: AVAudioSession!
    var delegate: AVAudioRecorderDelegate!

    var directory: NSString {
        return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    }

    var url: NSURL!

    let settings = [
        AVFormatIDKey: kAudioFormatAppleLossless,
        AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue,
        AVEncoderBitRateKey: 32000,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey: 44100.0
    ]

    public init(to: NSString, on: AVAudioRecorderDelegate)
    {
        self.delegate = on
        self.session = AVAudioSession.sharedInstance()
        self.url = NSURL(fileURLWithPath: directory.stringByAppendingPathComponent(to))
    }

    public func record()
    {
        self.session.setCategory(AVAudioSessionCategoryRecord, error: nil)

        self.recorder = AVAudioRecorder(URL: url, settings: settings, error: nil)
        recorder.delegate = delegate

        recorder.record()
    }

    public func stop()
    {
        recorder.stop()
    }

    public func play()
    {
        self.session.setCategory(AVAudioSessionCategoryPlayback, error: nil)

        self.player = AVAudioPlayer(contentsOfURL: url, error: nil)
        player.play()
    }

}

Allow configuration of recording settings

import AVFoundation

public class Recording {
    var recorder: AVAudioRecorder!
    var player: AVAudioPlayer!
    var session: AVAudioSession!
    var delegate: AVAudioRecorderDelegate!

    var directory: NSString {
        return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    }

    var url: NSURL!

    var bitRate = 192000
    var sampleRate = 44100.0
    var channels = 1

    public init(to: NSString, on: AVAudioRecorderDelegate)
    {
        self.delegate = on
        self.session = AVAudioSession.sharedInstance()
        self.url = NSURL(fileURLWithPath: directory.stringByAppendingPathComponent(to))
    }

    public func record()
    {
        self.session.setCategory(AVAudioSessionCategoryRecord, error: nil)

        self.recorder = AVAudioRecorder(URL: url, settings: [
            AVFormatIDKey: kAudioFormatAppleLossless,
            AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue,
            AVEncoderBitRateKey: bitRate,
            AVNumberOfChannelsKey: channels,
            AVSampleRateKey: sampleRate
        ]
        , error: nil)

        recorder.delegate = delegate

        recorder.record()
    }

    public func stop()
    {
        recorder.stop()
    }

    public func play()
    {
        self.session.setCategory(AVAudioSessionCategoryPlayback, error: nil)

        self.player = AVAudioPlayer(contentsOfURL: url, error: nil)
        player.play()
    }

}


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

import UIKit

public protocol SegueHandling {
    associatedtype SegueIdentifier: RawRepresentable
}

public extension SegueHandling where Self: UIViewController, SegueIdentifier.RawValue == String {

    public func performSegueWithIdentifier(_ segueIdentifier: SegueIdentifier, sender: AnyObject?) {
        performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
    }

    public func segueIdentifierForSegue(_ segue: UIStoryboardSegue) -> SegueIdentifier {
        guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier)
            else { fatalError("Invalid segue identifier \(segue.identifier).") }
        return segueIdentifier
    }

}

Rename segue API calls for better Swift 3 feel

/*
 |  _   ____   ____   _
 | | |‾|  ⚈ |-| ⚈  |‾| |
 | | |  ‾‾‾‾| |‾‾‾‾  | |
 |  ‾        ‾        ‾
 */

import UIKit

public protocol SegueHandling {
    associatedtype SegueIdentifier: RawRepresentable
}

public extension SegueHandling where Self: UIViewController, SegueIdentifier.RawValue == String {

    public func performSegue(with segueIdentifier: SegueIdentifier, sender: AnyObject?) {
        performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
    }

    public func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier {
        guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier)
            else { fatalError("Invalid segue identifier \(segue.identifier).") }
        return segueIdentifier
    }

}


//
//  LayerView.swift
//  BFWControls
//
//  Created by Tom Brodhurst-Hill on 9/01/2016.
//  Copyright © 2016 BareFeetWare.
//  Free to use at your own risk, with acknowledgement to BareFeetWare.
//

import UIKit

extension UIView {

    var rotationDegrees: CGFloat {
        get {
            // TODO: Reverse engineer angle from transform.
            return 0.0
        }
        set {
            transform = CGAffineTransform(rotationAngle: .pi / 180.0 * newValue)
        }
    }

}

Fix UIView Rotation Degrees TODO

//
//  LayerView.swift
//  BFWControls
//
//  Created by Tom Brodhurst-Hill on 9/01/2016.
//  Copyright © 2016 BareFeetWare.
//  Free to use at your own risk, with acknowledgement to BareFeetWare.
//

import UIKit

extension UIView {

    var rotationDegrees: CGFloat {
        get {
            let angleInRadians = atan2(transform.b, transform.a)
            return angleInRadians * 180.0 / CGFloat(M_PI)
        }
        set {
            transform = CGAffineTransform(rotationAngle: .pi / 180.0 * newValue)
        }
    }

}


//
//  ContactsViewController.swift
//  V
//
//  Created by Dulio Denis on 7/5/16.
//  Copyright © 2016 Dulio Denis. All rights reserved.
//

import UIKit
import CoreData
import Contacts
import ContactsUI

class ContactsViewController: UIViewController, ContextViewController {

    // in order to fulfill the ContextVC Protocol
    var context: NSManagedObjectContext?

    private let tableView = UITableView(frame: CGRectZero, style: .Plain)
    private let cellIdentifier = "ContactCell"

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "All Contacts"
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "add"), style: .Plain, target: self, action: "newContact")

        // Account for the Navigation Bar
        automaticallyAdjustsScrollViewInsets = false
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.tableFooterView = UIView(frame: CGRectZero)

        fillViewWith(tableView)
    }

    func newContact() {
        print("New Contact")
    }

}

Set the title to the ContactsVC

//
//  ContactsViewController.swift
//  V
//
//  Created by Dulio Denis on 7/5/16.
//  Copyright © 2016 Dulio Denis. All rights reserved.
//

import UIKit
import CoreData
import Contacts
import ContactsUI

class ContactsViewController: UIViewController, ContextViewController {

    // in order to fulfill the ContextVC Protocol
    var context: NSManagedObjectContext?

    private let tableView = UITableView(frame: CGRectZero, style: .Plain)
    private let cellIdentifier = "ContactCell"

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.navigationBar.topItem?.title = "All Contacts"
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "add"), style: .Plain, target: self, action: "newContact")

        // Account for the Navigation Bar
        automaticallyAdjustsScrollViewInsets = false
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.tableFooterView = UIView(frame: CGRectZero)

        fillViewWith(tableView)
    }

    func newContact() {
        print("New Contact")
    }

}


// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop
//
// REQUIRES: OS=macosx || OS=linux-gnu

import CustomSequence
import Cxx

// === SimpleSequence ===

extension SimpleSequence.ConstIterator: UnsafeCxxInputIterator {}
extension SimpleSequence: CxxSequence {}

func checkSimpleSequence() {
  let seq = SimpleSequence()
  let contains = seq.contains(where: { $0 == 3 })
  print(contains)

  for item in seq {
    print(item)
  }
}

// === SimpleArrayWrapper ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually UnsafePointers here.
extension SimpleArrayWrapper: CxxSequence {}

// === SimpleArrayWrapperNullableIterators ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually optional UnsafePointers here.
extension SimpleArrayWrapperNullableIterators: CxxSequence {}

// === SimpleEmptySequence ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually optional UnsafePointers here.
extension SimpleEmptySequence: CxxSequence {}

Enable a test on Windows

// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop

import CustomSequence
import Cxx

// === SimpleSequence ===

extension SimpleSequence.ConstIterator: UnsafeCxxInputIterator {}
extension SimpleSequence: CxxSequence {}

func checkSimpleSequence() {
  let seq = SimpleSequence()
  let contains = seq.contains(where: { $0 == 3 })
  print(contains)

  for item in seq {
    print(item)
  }
}

// === SimpleArrayWrapper ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually UnsafePointers here.
extension SimpleArrayWrapper: CxxSequence {}

// === SimpleArrayWrapperNullableIterators ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually optional UnsafePointers here.
extension SimpleArrayWrapperNullableIterators: CxxSequence {}

// === SimpleEmptySequence ===
// No UnsafeCxxInputIterator conformance required, since the iterators are actually optional UnsafePointers here.
extension SimpleEmptySequence: CxxSequence {}


import Foundation
import Wall
import Faker

class DetailViewController: WallController {

  let faker = Faker()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = post!.text

    let delayTime = dispatch_time(DISPATCH_TIME_NOW,
      Int64(0.1 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
      self.posts = self.generatePosts(1, to: 3)
    }
  }

  func generatePosts(from: Int, to: Int) -> [Post] {
    var posts = [Post]()
    var startFrom = self.posts.count

    for i in from...to {
      let sencenceCount = Int(arc4random_uniform(8) + 1)
      posts.append(Post(text: faker.lorem.sentences(amount: sencenceCount),
        date: NSDate()))
    }
    return posts
  }

}

Add user to dummy comments

import Foundation
import Wall
import Faker

class DetailViewController: WallController {

  let faker = Faker()

  override func viewDidLoad() {
    super.viewDidLoad()

    title = post!.text

    let delayTime = dispatch_time(DISPATCH_TIME_NOW,
      Int64(0.1 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
      self.posts = self.generatePosts(1, to: 3)
    }
  }

  func generatePosts(from: Int, to: Int) -> [Post] {
    var posts = [Post]()
    var startFrom = self.posts.count

    for i in from...to {
      let user = User(
        name: faker.name.name(),
        avatar: Image("http://lorempixel.com/%d/%d/"))

      let sencenceCount = Int(arc4random_uniform(8) + 1)
      posts.append(Post(text: faker.lorem.sentences(amount: sencenceCount),
        date: NSDate(), author: user))
    }
    return posts
  }

}


// RUN: %target-swift-frontend -Ounchecked %s -emit-ir | FileCheck %s

// REQUIRES: CPU=x86_64

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

// CHECK: xor <2 x i64>

func f() -> Int {
  var a : Int = 10
  var b : Int = 15
  var c : Int = 0

  for _ in 0..<100000 {
    for _ in 0..<1000000 {
      c = a ^ b ^ c
    }
  }

  return c
}

var c = f()

Make the test more robust so that it passes with stronger optimizations in the new LLVM

// RUN: %target-swift-frontend -Ounchecked %s -emit-ir | FileCheck %s

// REQUIRES: CPU=x86_64

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


// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts

// expected-no-diagnostics

let a: [Double] = []
_ = a.map { $0 - 1.0 }
     .map { $0 * $0 }
     .reduce(0, +) / Double(a.count)

Disable timing-sensitive test that's periodically failing in CI, rdar://38378503.

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
// REQUIRES: rdar38378503

// expected-no-diagnostics

let a: [Double] = []
_ = a.map { $0 - 1.0 }
     .map { $0 * $0 }
     .reduce(0, +) / Double(a.count)


//
//  TimelineItemStatusView.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 7/1/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI

struct TimelineItemStatusView: View {

	var status: TimelineItemStatus

	@ViewBuilder var statusView: some View {
		switch status {
		case .showUnread:
			AppAssets.timelineUnread
				.resizable()
				.frame(width: 8, height: 8, alignment: .center)
				.padding(.all, 2)
		case .showStar:
			AppAssets.timelineStarred
				.resizable()
				.frame(width: 10, height: 10, alignment: .center)
		case .showNone:
			AppAssets.timelineUnread
				.resizable()
				.frame(width: 8, height: 8, alignment: .center)
				.padding(.all, 2)
				.opacity(0)
		}
	}

    var body: some View {
		statusView
			.padding(.top, 4)
			.padding(.leading, 4)
    }

}

Fix the width of the indicator so that it would stop reflowing the cell when changed to star

//
//  TimelineItemStatusView.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 7/1/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import SwiftUI

struct TimelineItemStatusView: View {

	var status: TimelineItemStatus

	@ViewBuilder var statusView: some View {
		ZStack {
			Spacer().frame(width: 12)
			switch status {
			case .showUnread:
				AppAssets.timelineUnread
					.resizable()
					.frame(width: 8, height: 8, alignment: .center)
					.padding(.all, 2)
			case .showStar:
				AppAssets.timelineStarred
					.resizable()
					.frame(width: 10, height: 10, alignment: .center)
			case .showNone:
				AppAssets.timelineUnread
					.resizable()
					.frame(width: 8, height: 8, alignment: .center)
					.padding(.all, 2)
					.opacity(0)
			}
		}
	}

    var body: some View {
		statusView
			.padding(.top, 4)
			.padding(.leading, 4)
    }

}


//
//  PreferencesWindow.swift
//  WeatherBar
//
//  Created by Brad Greenlee on 3/20/15.
//  Copyright (c) 2015 Etsy. All rights reserved.
//

import Cocoa

protocol PreferencesWindowDelegate {
    func preferencesDidUpdate()
}

class PreferencesWindow: NSWindowController, NSWindowDelegate {

    @IBOutlet weak var cityTextField: NSTextField!
    var delegate: PreferencesWindowDelegate?

    override var windowNibName : String! {
        return "PreferencesWindow"
    }

    override func windowDidLoad() {
        super.windowDidLoad()
        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        self.window?.center()
        self.window?.makeKeyAndOrderFront(nil)

        let defaults = NSUserDefaults.standardUserDefaults()
        let city = defaults.stringForKey("city") ?? DEFAULT_CITY
        cityTextField.stringValue = city
    }

    func windowWillClose(notification: NSNotification) {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setValue(cityTextField.stringValue, forKey: "city")
        delegate?.preferencesDidUpdate()
    }

}

Bring app to foreground when showing preferences

//
//  PreferencesWindow.swift
//  WeatherBar
//
//  Created by Brad Greenlee on 3/20/15.
//  Copyright (c) 2015 Etsy. All rights reserved.
//

import Cocoa

protocol PreferencesWindowDelegate {
    func preferencesDidUpdate()
}

class PreferencesWindow: NSWindowController, NSWindowDelegate {

    @IBOutlet weak var cityTextField: NSTextField!
    var delegate: PreferencesWindowDelegate?

    override var windowNibName : String! {
        return "PreferencesWindow"
    }

    override func windowDidLoad() {
        super.windowDidLoad()

        let defaults = NSUserDefaults.standardUserDefaults()
        let city = defaults.stringForKey("city") ?? DEFAULT_CITY
        cityTextField.stringValue = city

        self.window?.center()
        self.window?.makeKeyAndOrderFront(nil)
        NSApp.activateIgnoringOtherApps(true)
    }

    func windowWillClose(notification: NSNotification) {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setValue(cityTextField.stringValue, forKey: "city")
        delegate?.preferencesDidUpdate()
    }

}


//
//  PBXBuildStyle.swift
//  XcodeProjKit
//
//  Created by phimage on 30/07/2017.
//  Copyright © 2017 phimage (Eric Marchand). All rights reserved.
//

import Foundation

public class PBXBuildStyle: PBXProjectItem {

    public enum PBXKeys: PBXKey {
        case buildSettings
    }

    #if LAZY
    public lazy var buildSettings: [String: Any]? = dictionary(PBXKeys.buildSettings)
    #else
    public var buildSettings: [String: Any]? { dictionary(PBXKeys.buildSettings) }
    #endif

}

Allow to modify build settings

//
//  PBXBuildStyle.swift
//  XcodeProjKit
//
//  Created by phimage on 30/07/2017.
//  Copyright © 2017 phimage (Eric Marchand). All rights reserved.
//

import Foundation

public class PBXBuildStyle: PBXProjectItem {

    public enum PBXKeys: PBXKey {
        case buildSettings
    }

    #if LAZY
    public lazy var buildSettings: [String: Any]? = dictionary(PBXKeys.buildSettings)
    #else
    public var buildSettings: [String: Any]? {
        get {
            dictionary(PBXKeys.buildSettings)
        }
        set {
            self.fields[PBXKeys.buildSettings.rawValue] = newValue
        }
    }
    #endif

}


//
//  Layout.swift
//  components-swift
//
//  Created by Oliver Rickard on 10/9/17.
//  Copyright © 2017 Oliver Rickard. All rights reserved.
//

import UIKit

public struct LayoutChild {
  let layout: Layout;
  let position: CGPoint;
}

public struct Layout {
  let component: Component;
  let size: CGSize;
  let children: [LayoutChild];
}

Add an optional extra param to allow passing data from layout to mount

//
//  Layout.swift
//  components-swift
//
//  Created by Oliver Rickard on 10/9/17.
//  Copyright © 2017 Oliver Rickard. All rights reserved.
//

import UIKit

public struct LayoutChild {
  let layout: Layout;
  let position: CGPoint;
}

public struct Layout {
  let component: Component;
  let size: CGSize;
  let children: [LayoutChild];

  /*
   Can be used to pass data from layout to mount. Useful if you want to pre-compute something, and then use the
   result.

   Canonical example is rendering text. You may want to pass the text artifacts from layout to mount so you don't have
   to do the work of laying out the text again when mounting as an optimization.

   The framework will always leave this value nil. You can fill it with whatever you want.
  */
  let extra: Any?

  init(component: Component,
       size: CGSize,
       children: [LayoutChild],
       extra: Any? = nil) {
    self.component = component;
    self.size = size;
    self.children = children;
    self.extra = extra;
  }
}


//
//  TimeilneToolbarModifier.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 7/5/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import Foundation

import SwiftUI

struct TimelineToolbarModifier: ViewModifier {

	func body(content: Content) -> some View {
		content
			.toolbar {
				#if os(iOS)
				ToolbarItem {
					Button(action: {
					}, label: {
						AppAssets.markAllAsReadImage
							.foregroundColor(.accentColor)
					}).help("Mark All As Read")
				}
				ToolbarItem {
					Spacer()
				}
				ToolbarItem(placement: .automatic) {
					RefreshProgressView()
				}
				ToolbarItem {
					Spacer()
				}
				ToolbarItem {
					Button(action: {
					}, label: {
						AppAssets.nextUnreadArticleImage
							.resizable()
							.scaledToFit()
							.frame(width: 22, height: 22, alignment: .center)
					})
				}
				#endif
			}
	}

}

Change how next unread image is scaled up

//
//  TimeilneToolbarModifier.swift
//  NetNewsWire
//
//  Created by Maurice Parker on 7/5/20.
//  Copyright © 2020 Ranchero Software. All rights reserved.
//

import Foundation

import SwiftUI

struct TimelineToolbarModifier: ViewModifier {

	func body(content: Content) -> some View {
		content
			.toolbar {
				#if os(iOS)
				ToolbarItem {
					Button(action: {
					}, label: {
						AppAssets.markAllAsReadImage
							.foregroundColor(.accentColor)
					}).help("Mark All As Read")
				}
				ToolbarItem {
					Spacer()
				}
				ToolbarItem(placement: .automatic) {
					RefreshProgressView()
				}
				ToolbarItem {
					Spacer()
				}
				ToolbarItem {
					Button(action: {
					}, label: {
						AppAssets.nextUnreadArticleImage
							.font(.title3)
					}).help("Next Unread")
				}
				#endif
			}
	}

}


//
//  FirebaseStorable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation
import FirebaseCommunity

public protocol FirebaseStorable: Storable {

}

public extension FirebaseStorable {
    public typealias Reference = StorageReference

    public static var reference: StorageReference {
        return Storage.storage().reference()
    }
}

public extension FirebaseStorable {
    public func upload(with name: String) {
        guard let data = data else {
            return
        }

        let uploadTask = Self.reference.child("images/decentPath").putData(data, metadata: StorageMetadata()) { (metadata, error) in

            if let error = error{
                print(error.localizedDescription as Any)
            }
            else {
                guard let urlStorage = metadata?.downloadURL()!.absoluteString else {
                    fatalError("couldn't generate the storage url")
                }
                let result = (name: name, path: urlStorage)
                //TODO: return the result
            }
            if let error = error {
                //TODO: Return an error
            }
        }
        uploadTask.resume()
    }
}

Update reference type association with the brand new swift 4 sintax

//
//  FirebaseStorable.swift
//  FirebaseCommunity
//
//  Created by David Sanford on 15/08/17.
//

import Foundation
import FirebaseCommunity

public protocol FirebaseStorable: Storable {

}

public extension FirebaseStorable where Reference == StorageReference {

    public static var reference: StorageReference {
        return Storage.storage().reference()
    }
}

public extension FirebaseStorable {
    public func upload(with name: String) {
        guard let data = data else {
            return
        }

        let uploadTask = Self.reference.child("images/decentPath").putData(data, metadata: StorageMetadata()) { (metadata, error) in

            if let error = error{
                print(error.localizedDescription as Any)
            }
            else {
                guard let urlStorage = metadata?.downloadURL()!.absoluteString else {
                    fatalError("couldn't generate the storage url")
                }
                let result = (name: name, path: urlStorage)
                //TODO: return the result
            }
            if let error = error {
                //TODO: Return an error
            }
        }
        uploadTask.resume()
    }
}


import Combine
import Foundation

extension CacheLevel {
  /**
   Composes two cache levels

   - parameter cache: The second cache level

   - returns: A new cache level that is the result of the composition of the two cache levels
   */
  public func compose<A: CacheLevel>(_ cache: A) -> BasicCache<A.KeyType, A.OutputType> where A.KeyType == KeyType, A.OutputType == OutputType {
    BasicCache(
      getClosure: { key in
        self.get(key)
          .catch { _ -> AnyPublisher<OutputType, Error> in
            Logger.log("Composed| error on getting value for key \(key) on cache \(String(describing: self)).", .info)

            return cache.get(key)
              .flatMap { value -> AnyPublisher<(OutputType, Void), Error> in
                let get = Just(value).setFailureType(to: Error.self)
                let set = self.set(value, forKey: key)
                return Publishers.Zip(get, set)
                  .eraseToAnyPublisher()
              }
              .map(\.0)
              .eraseToAnyPublisher()
          }.eraseToAnyPublisher()
      },
      setClosure: { value, key in
        Publishers.Merge(
          self.set(value, forKey: key),
          cache.set(value, forKey: key)
        )
        .eraseToAnyPublisher()
      },
      clearClosure: {
        self.clear()
        cache.clear()
      },
      memoryClosure: {
        self.onMemoryWarning()
        cache.onMemoryWarning()
      }
    )
  }
}

Fix issue when composed cache receive value was called twice

import Combine
import Foundation

extension CacheLevel {
  /**
   Composes two cache levels

   - parameter cache: The second cache level

   - returns: A new cache level that is the result of the composition of the two cache levels
   */
  public func compose<A: CacheLevel>(_ cache: A) -> BasicCache<A.KeyType, A.OutputType> where A.KeyType == KeyType, A.OutputType == OutputType {
    BasicCache(
      getClosure: { key in
        self.get(key)
          .catch { _ -> AnyPublisher<OutputType, Error> in
            Logger.log("Composed| error on getting value for key \(key) on cache \(String(describing: self)).", .info)

            return cache.get(key)
              .flatMap { value -> AnyPublisher<(OutputType, Void), Error> in
                let get = Just(value).setFailureType(to: Error.self)
                let set = self.set(value, forKey: key)
                return Publishers.Zip(get, set)
                  .eraseToAnyPublisher()
              }
              .map(\.0)
              .eraseToAnyPublisher()
          }.eraseToAnyPublisher()
      },
      setClosure: { value, key in
        Publishers.Zip(
          self.set(value, forKey: key),
          cache.set(value, forKey: key)
        )
        .map { _ in () }
        .eraseToAnyPublisher()
      },
      clearClosure: {
        self.clear()
        cache.clear()
      },
      memoryClosure: {
        self.onMemoryWarning()
        cache.onMemoryWarning()
      }
    )
  }
}


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

import ArgumentParser

/// Encapsulates `--version` flag behavior.
struct VersionOptions: ParsableArguments {
  @Flag(name: .shortAndLong, help: "Print the version and exit")
  var version: Bool = false

  func validate() throws {
    if version {
      // TODO: Automate updates to this somehow.
      print("0.50200.1")
      throw ExitCode.success
    }
  }
}

Update the version number printed by `-v`.

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

import ArgumentParser

/// Encapsulates `--version` flag behavior.
struct VersionOptions: ParsableArguments {
  @Flag(name: .shortAndLong, help: "Print the version and exit")
  var version: Bool = false

  func validate() throws {
    if version {
      // TODO: Automate updates to this somehow.
      print("0.50500.0")
      throw ExitCode.success
    }
  }
}


import Foundation

class FDatabaseCountriesItemUser:FDatabaseProtocol
{
    var identifier:String?
    var parent:FDatabaseProtocol?

    init(
        parent:FDatabaseProtocol,
        identifier:String)
    {
        self.parent = parent
        self.identifier = identifier
    }

    required init?(json:Any)
    {
        return nil
    }
}

Add latitude and longitude to location

import Foundation

class FDatabaseCountriesItemUser:FDatabaseProtocol
{
    static let kKeyLatitude:String = "latitude"
    static let kKeyLongitude:String = "longitude"

    var identifier:String?
    var parent:FDatabaseProtocol?
    let latitude:Double
    let longitude:Double

    init(
        parent:FDatabaseProtocol,
        identifier:String,
        latitude:Double,
        longitude:Double)
    {
        self.parent = parent
        self.identifier = identifier
        self.latitude = latitude
        self.longitude = longitude
    }

    required init?(json:Any)
    {
        return nil
    }
}


//
//  Paging.swift
//  GeneratedResults
//
//  Created by Marcin Krzyzanowski on 22/06/15.
//  Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved.
//

import Foundation

//MARK: Generator

protocol AsyncGeneratorType {
    typealias Element
    typealias Fetch
    mutating func next(fetchNextBatch: Fetch, onFinish: ((Element) -> Void)?)
}

/// Generator is the class because struct is captured in asynchronous operations so offset won't update.
class PagingGenerator<T>: AsyncGeneratorType {
    typealias Element = Array<T>
    typealias Fetch = (offset: Int, limit: Int, completion: (result: Element) -> Void) -> Void

    var offset:Int
    let limit: Int

    init(startOffset: Int = 0, limit: Int = 25) {
        self.offset = startOffset
        self.limit = limit
    }

    func next(fetchNextBatch: Fetch, onFinish: ((Element) -> Void)? = nil) {
        fetchNextBatch(offset: offset, limit: limit) { [unowned self] (items) in
            onFinish?(items)
            self.offset += items.count
        }
    }
}

Migrate typealias to associatedtype due to typealias deprecation

//
//  Paging.swift
//  GeneratedResults
//
//  Created by Marcin Krzyzanowski on 22/06/15.
//  Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved.
//

import Foundation

//MARK: Generator

protocol AsyncGeneratorType {
    associatedtype Element
    associatedtype Fetch
    mutating func next(fetchNextBatch: Fetch, onFinish: ((Element) -> Void)?)
}

/// Generator is the class because struct is captured in asynchronous operations so offset won't update.
class PagingGenerator<T>: AsyncGeneratorType {
    typealias Element = Array<T>
    typealias Fetch = (offset: Int, limit: Int, completion: (result: Element) -> Void) -> Void

    var offset:Int
    let limit: Int

    init(startOffset: Int = 0, limit: Int = 25) {
        self.offset = startOffset
        self.limit = limit
    }

    func next(fetchNextBatch: Fetch, onFinish: ((Element) -> Void)? = nil) {
        fetchNextBatch(offset: offset, limit: limit) { [unowned self] (items) in
            onFinish?(items)
            self.offset += items.count
        }
    }
}


// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts

2...100.reversed().filter({ $0 % 11 == 0 }).map {
  // expected-error@-1 {{value of type 'Int' has no member 'reversed'}}
  "\($0) bottles of beer on the wall, \($0) bottles of beer;\n"
  + "  take eleven down, pass 'em around, \($0-11) bottles of beer on the wall!"
}

Fix type checker performance test to compile successfully.

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts

_ = (2...100).reversed().filter({ $0 % 11 == 0 }).map {
  "\($0) bottles of beer on the wall, \($0) bottles of beer;\n"
  + "  take eleven down, pass 'em around, \($0-11) bottles of beer on the wall!"
}


// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
extension Collection {
  func foo(_ x: Iterator.Element) {
    print(x) //%self.expect('frame variable -d run -- x', substrs=['key = 2', 'value = 2'])
  }
}

func main() {
  var a = [2: 2]
  for element in a {
    a.foo(element)
  }
}

main()

Make this test case compile again

// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
extension Collection {
  func foo(_ x: Iterator.Element) {
    print(x) //%self.expect('frame variable -d run -- x', substrs=['key = 2', 'value = 2'])
  }
}

func main() {
  var a = [2: 2]
  for element in a {
    a.foo((key: element.key, value: element.value))
  }
}

main()


//
//  SClockItem.swift
//  Pock
//
//  Created by Pierluigi Galdi on 23/02/2019.
//  Copyright © 2019 Pierluigi Galdi. All rights reserved.
//

import Foundation

class SClockItem: StatusItem {

    /// UI
    private let clockLabel: NSTextField!

    init() {
        clockLabel = NSTextField()
        clockLabel.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 44))
        clockLabel.font = NSFont.systemFont(ofSize: 13)
        clockLabel.backgroundColor = .clear
        clockLabel.isBezeled = false
        clockLabel.isEditable = false
        clockLabel.sizeToFit()
        reload()
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(reload), userInfo: nil, repeats: true)
    }

    var title: String  { return "clock" }

    var view: NSView { return clockLabel }

    func action() {
        print("[Pock]: Clock Status icon tapped!")
    }

    @objc func reload() {
        let formatter = DateFormatter()
        formatter.dateFormat = "EE dd MMM HH:mm"
        clockLabel.stringValue = formatter.string(from: Date())
        clockLabel.sizeToFit()
    }

}

Use Locale in clock item

//
//  SClockItem.swift
//  Pock
//
//  Created by Pierluigi Galdi on 23/02/2019.
//  Copyright © 2019 Pierluigi Galdi. All rights reserved.
//

import Foundation

class SClockItem: StatusItem {

    /// UI
    private let clockLabel: NSTextField!

    init() {
        clockLabel = NSTextField()
        clockLabel.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 44))
        clockLabel.font = NSFont.systemFont(ofSize: 13)
        clockLabel.backgroundColor = .clear
        clockLabel.isBezeled = false
        clockLabel.isEditable = false
        clockLabel.sizeToFit()
        reload()
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(reload), userInfo: nil, repeats: true)
    }

    var title: String  { return "clock" }

    var view: NSView { return clockLabel }

    func action() {
        print("[Pock]: Clock Status icon tapped!")
    }

    @objc func reload() {
        let formatter = DateFormatter()
        formatter.dateFormat = "EE dd MMM HH:mm"
        formatter.locale = Locale(identifier: Locale.preferredLanguages.first ?? "en_US_POSIX")
        clockLabel.stringValue = formatter.string(from: Date())
        clockLabel.sizeToFit()
    }

}


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

import Foundation

class CallVCPresentOperation: AsyncOperation {

    private var presenter: CallPresenter
    private var callVC: UIViewController
    private var completion: (() -> Void)?

    init(presenter: CallPresenter,
         callVC: UIViewController,
         completion: (() -> Void)? = nil) {
        self.presenter = presenter
        self.callVC = callVC
        self.completion = completion
    }

    override func main() {
        presenter.delegate?.callPresenter(presenter, presentCallViewController: callVC, completion: {
            self.finish()
            self.completion?()
        })
    }

}

Fix PiP state when presenting a call screen

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

import Foundation

class CallVCPresentOperation: AsyncOperation {

    private var presenter: CallPresenter
    private var callVC: UIViewController
    private var completion: (() -> Void)?

    init(presenter: CallPresenter,
         callVC: UIViewController,
         completion: (() -> Void)? = nil) {
        self.presenter = presenter
        self.callVC = callVC
        self.completion = completion
    }

    override func main() {
        if let pipable = callVC as? PictureInPicturable {
            pipable.willExitPiP?()
        }
        presenter.delegate?.callPresenter(presenter, presentCallViewController: callVC, completion: {
            self.finish()
            if let pipable = self.callVC as? PictureInPicturable {
                pipable.didExitPiP?()
            }
            self.completion?()
        })
    }

}


//
//  SwiftSampleCollectionViewController.swift
//  HTKDynamicResizingCellDemo
//
//  Created by Ben on 04/12/2014.
//  Copyright (c) 2014 bcylin. All rights reserved.
//

import UIKit

let reuseIdentifier = "Cell"

@objc class SwiftSampleCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Swift Collection View"

        // Register cell classes
        self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: - UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 0
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 0
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
        // Configure the cell
        return cell
    }

}

Fix collection view controller's NSInvalidArgumentException on a nil layout parameter

//
//  SwiftSampleCollectionViewController.swift
//  HTKDynamicResizingCellDemo
//
//  Created by Ben on 04/12/2014.
//  Copyright (c) 2014 bcylin. All rights reserved.
//

import UIKit

let reuseIdentifier = "Cell"

@objc class SwiftSampleCollectionViewController: UICollectionViewController {

    override init() {
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Swift Collection View"

        // Register cell classes
        self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView!.backgroundColor = UIColor.lightGrayColor()
    }

    // MARK: - UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 0
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 0
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
        // Configure the cell
        return cell
    }

}


//
// Created by Alexander Tkachenko on 9/9/17.
//

import UIKit

final class ImageLoadableView: UIView, ImageLoadable {
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var placeholderView: UIView!
    @IBInspectable var animated: Bool = true

    private var image: UIImage?
    private var dirty: Bool { return image != imageView.image }

    func load(imageURL: URL?) {
        guard let url = imageURL else {
            image = nil
            return
        }

        imageLoader.load(with: url, into: self) {
            [weak self] result in
            self?.image = result.image
            self?.updateSubviews()
        }
    }

    func prepareForReuse() {
        image = nil
        imageView.image = nil
        imageView.alpha = 0
    }

    private func updateSubviews() {
        guard dirty else { return }
        let newAlpha: CGFloat = image == nil ? 0 : 1
        if animated {
            imageView.image = image
            UIView.animate(withDuration: 0.3,
                           delay: 0,
                           options: [.allowUserInteraction, .beginFromCurrentState],
                           animations: {
                            self.imageView.alpha = newAlpha
            },
                           completion: nil)
        }
        else {
            imageView.alpha = newAlpha
            imageView.image = image
        }
    }
}

Fix cell reusing/image loading bug

//
// Created by Alexander Tkachenko on 9/9/17.
//

import UIKit

final class ImageLoadableView: UIView, ImageLoadable {
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var placeholderView: UIView!
    @IBInspectable var animated: Bool = true

    private var image: UIImage?
    private var urlInProgress: URL?
    private var dirty: Bool { return image != imageView.image }

    func load(imageURL: URL?) {
        guard let url = imageURL else {
            image = nil
            return
        }
        urlInProgress = url
        imageLoader.load(with: url, into: self) {
            [weak self] result in
            if (url == self?.urlInProgress) {
                self?.image = result.image
                self?.updateSubviews()
            }
        }
    }

    func prepareForReuse() {
        image = nil
        imageView.image = nil
        imageView.alpha = 0
    }

    private func updateSubviews() {
        guard dirty else { return }
        let newAlpha: CGFloat = image == nil ? 0 : 1
        if animated {
            imageView.image = image
            UIView.animate(withDuration: 0.3,
                           delay: 0,
                           options: [.allowUserInteraction, .beginFromCurrentState],
                           animations: {
                            self.imageView.alpha = newAlpha
            },
                           completion: nil)
        }
        else {
            imageView.alpha = newAlpha
            imageView.image = image
        }
    }
}


import XCTest

class TVHomeActionsShare:XCTestCase
{
    override func setUp()
    {
        super.setUp()
        continueAfterFailure = false
        XCUIApplication().launch()
    }
}

Create test for share to appear

import XCTest

class TVHomeActionsShare:XCTestCase
{
    override func setUp()
    {
        super.setUp()
        continueAfterFailure = false
        XCUIApplication().launch()
    }

    func testShareSheetAppears()
    {
        let app:XCUIApplication = XCUIApplication()

        XCTAssertFalse(
            app.sheets["Share"].exists,
            "sheet should be nil")

        app.buttons["VHomeActionsShare_button"].tap()

        XCTAssertTrue(
            app.sheets["Share"].exists,
            "sheet should appear")
    }
}


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

var my_global: Int = 0  // global variable

func main() {
  let q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
  dispatch_async(q) {
    my_global = 42
    sleep(100)
  }
  dispatch_async(q) {
    usleep(10000)
    my_global = 43
    exit(1)
  }
  sleep(100)
}

main()

Change Swift TSan test to use pthreads rather than GCD.

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

var my_global: Int = 0  // global variable

func main() {
  var thread1: pthread_t? = nil
  var thread2: pthread_t? = nil

  pthread_create(&thread1, nil, { _ in
    my_global = 42
    sleep(100)
    return nil
  }, nil)

  pthread_create(&thread2, nil, { _ in
    usleep(10000)
    my_global = 43
    exit(1)
  }, nil)
}

main()


import UIKit

/// Converts a generic element to `NSAttributedString`.  Should only be used if a specific converter is not found.
///
class GenericElementConverter: ElementConverter {

    let serializer: AttributedStringSerializer

    init(using serializer: AttributedStringSerializer) {
        self.serializer = serializer
    }

    // MARK: - ElementConverter

    func canConvert(element: ElementNode) -> Bool {
        return true
    }

    func convert(_ element: ElementNode, inheriting attributes: [AttributedStringKey: Any]) -> NSAttributedString {
        let content = NSMutableAttributedString()

        for child in element.children {
            let childContent = serializer.serialize(child, inheriting: attributes)
            content.append(childContent)
        }

        return content
    }
}

Fix a memory leak issue

import UIKit

/// Converts a generic element to `NSAttributedString`.  Should only be used if a specific converter is not found.
///
class GenericElementConverter: ElementConverter {

    unowned let serializer: AttributedStringSerializer

    init(using serializer: AttributedStringSerializer) {
        self.serializer = serializer
    }

    // MARK: - ElementConverter

    func canConvert(element: ElementNode) -> Bool {
        return true
    }

    func convert(_ element: ElementNode, inheriting attributes: [AttributedStringKey: Any]) -> NSAttributedString {
        let content = NSMutableAttributedString()

        for child in element.children {
            let childContent = serializer.serialize(child, inheriting: attributes)
            content.append(childContent)
        }

        return content
    }
}


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

extension Module {
	public static let modules: [String:Module] = Dictionary([
		unit,
		boolean,
		list,
		natural,
		maybe,
		either,
		pair,
		prelude,
		sigma,
		vector,
		finiteSet,
		string,
	].map { ($0.name, $0) })
}

Add propositional equality to the directory.

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

extension Module {
	public static let modules: [String:Module] = Dictionary([
		unit,
		boolean,
		list,
		natural,
		maybe,
		either,
		pair,
		prelude,
		propositionalEquality,
		sigma,
		vector,
		finiteSet,
		string,
	].map { ($0.name, $0) })
}


//
//  PushPayload.swift
//  Ello
//
//  Created by Gordon Fontenot on 5/20/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

public struct PushPayload {
    let info: [String: AnyObject]
}

public extension PushPayload {
    var applicationTarget: String {
        return info["application_target"] as? String ?? ""
    }

    var message: String {
        let aps = info["aps"] as? [String: AnyObject]
        return aps?["alert"] as? String ?? "New Notification"
    }
}

Fix parsing of push payloads

//
//  PushPayload.swift
//  Ello
//
//  Created by Gordon Fontenot on 5/20/15.
//  Copyright (c) 2015 Ello. All rights reserved.
//

public struct PushPayload {
    let info: [String: AnyObject]
}

public extension PushPayload {
    var applicationTarget: String {
        return info["application_target"] as? String ?? ""
    }

    var message: String {
        let aps = info["aps"] as? [String: AnyObject]
        let alert = aps?["alert"] as? [String: String]
        return alert?["body"] ?? "New Notification"
    }
}


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

var d = [String:String]()
_ = "\(d.map{ [$0 : $0] })" // expected-error {{contextual closure type specifies '(key: String, value: String)', but 1 was used in closure body, try adding extra parentheses around the single tuple argument}}

Update a diagnostic string in a -verify test

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

var d = [String:String]()
_ = "\(d.map{ [$0 : $0] })" // expected-error {{type of expression is ambiguous without more context}}


import Foundation
import QuartzCore

extension UINavigationBar {

    func wmf_applyGalleryTopGradientBackground() {
        if (!CGRectIsNull(bounds)){
            if (CGRectGetWidth(bounds) > 0 && CGRectGetHeight(bounds) > 0){
                setBackgroundImage(wmf_galleryTopGradientBackgroundImage(), forBarMetrics: .Default)
            }
        }
    }

    func wmf_galleryTopGradientBackgroundImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        let context = UIGraphicsGetCurrentContext()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 1.0]
        let bottom = UIColor.clearColor().CGColor
        let top = UIColor.blackColor().CGColor

        let gradient = CGGradientCreateWithColors(colorSpace, [top, bottom], locations)

        let start = CGPoint(x: 0, y: 0)
        let end = CGPoint(x: 0, y: CGRectGetHeight(bounds))

        CGContextDrawLinearGradient(context!, gradient!, start, end, [])

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage!
    }
}

Adjust top gradient stops to better match mock.

import Foundation
import QuartzCore

extension UINavigationBar {

    func wmf_applyGalleryTopGradientBackground() {
        if (!CGRectIsNull(bounds)){
            if (CGRectGetWidth(bounds) > 0 && CGRectGetHeight(bounds) > 0){
                setBackgroundImage(wmf_galleryTopGradientBackgroundImage(), forBarMetrics: .Default)
            }
        }
    }

    func wmf_galleryTopGradientBackgroundImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        let context = UIGraphicsGetCurrentContext()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 0.78, 1.0]
        let top = UIColor.blackColor().CGColor
        let middle = UIColor.blackColor().CGColor
        let bottom = UIColor.clearColor().CGColor

        let gradient = CGGradientCreateWithColors(colorSpace, [top, middle, bottom], locations)

        let start = CGPoint(x: 0, y: 0)
        let end = CGPoint(x: 0, y: CGRectGetHeight(bounds))

        CGContextDrawLinearGradient(context!, gradient!, start, end, [])

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage!
    }
}


//
//  NSScreen+Amethyst.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 5/8/16.
//  Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//

import ApplicationServices
import Foundation
import Silica

public extension NSScreen {
    public static func screenDescriptions() -> [[String: AnyObject]]? {
        let cfScreenDescriptions = CGSCopyManagedDisplaySpaces(_CGSDefaultConnection()).takeRetainedValue()
        guard let screenDescriptions = cfScreenDescriptions as NSArray as? [[String: AnyObject]] else {
            return nil
        }
        return screenDescriptions
    }

    public func screenIdentifier() -> String {
        let managedDisplay = CGSCopyBestManagedDisplayForRect(_CGSDefaultConnection(), self.frameIncludingDockAndMenu())
        return String(managedDisplay!.takeRetainedValue())
    }

    public func focusScreen() {
        let screenFrame = self.frame
        let mouseCursorPoint = NSPoint(x: screenFrame.midX, y: screenFrame.midY)
        let mouseMoveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: mouseCursorPoint, mouseButton: .left)
        mouseMoveEvent?.flags = CGEventFlags(rawValue: 0)
        mouseMoveEvent?.post(tap: .cghidEventTap)
    }
}

Stop assuming return values always exist for some private APIs

//
//  NSScreen+Amethyst.swift
//  Amethyst
//
//  Created by Ian Ynda-Hummel on 5/8/16.
//  Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//

import ApplicationServices
import Foundation
import Silica

public extension NSScreen {
    public static func screenDescriptions() -> [[String: AnyObject]]? {
        guard let cfScreenDescriptions = CGSCopyManagedDisplaySpaces(_CGSDefaultConnection())?.takeRetainedValue() else {
            return nil
        }
        guard let screenDescriptions = cfScreenDescriptions as NSArray as? [[String: AnyObject]] else {
            return nil
        }
        return screenDescriptions
    }

    public func screenIdentifier() -> String {
        let managedDisplay = CGSCopyBestManagedDisplayForRect(_CGSDefaultConnection(), self.frameIncludingDockAndMenu())
        return String(managedDisplay!.takeRetainedValue())
    }

    public func focusScreen() {
        let screenFrame = self.frame
        let mouseCursorPoint = NSPoint(x: screenFrame.midX, y: screenFrame.midY)
        let mouseMoveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: mouseCursorPoint, mouseButton: .left)
        mouseMoveEvent?.flags = CGEventFlags(rawValue: 0)
        mouseMoveEvent?.post(tap: .cghidEventTap)
    }
}


enum Velocity: Equatable {
    case Default
    case PPP
    case PP
    case P
    case MP
    case MF
    case F
    case FF
    case FFF
    case Number(Int)

    var numerical: Int {
        switch self {
        case Default:       return 72
        case PPP:           return 16
        case PP:            return 32
        case P:             return 48
        case MP:            return 64
        case MF:            return 80
        case F:             return 96
        case FF:            return 112
        case FFF:           return 127
        case let Number(v): return v
        }
    }
}

func ==(lhs: Velocity, rhs: Velocity) -> Bool {
    switch (lhs, rhs) {
    case (.Default, .Default):           return true
    case (.PPP,     .PPP):               return true
    case (.PP,      .PP):                return true
    case (.P,       .P):                 return true
    case (.MP,      .MP):                return true
    case (.MF,      .MF):                return true
    case (.F,       .F):                 return true
    case (.FF,      .FF):                return true
    case (.FFF,     .FFF):               return true
    case let (.Number (l), .Number (r)): return l == r
    default:                             return false
    }
}

Add velocities from drum hits

enum Velocity: Equatable {
    case Default
    case PPP
    case PP
    case P
    case MP
    case MF
    case F
    case FF
    case FFF
    case Soft
    case Hard
    case Number(Int)

    var numerical: Int {
        switch self {
        case Default:       return 72
        case PPP:           return 16
        case PP:            return 32
        case P:             return 48
        case MP:            return 64
        case MF:            return 80
        case F:             return 96
        case FF:            return 112
        case FFF:           return 127
        case Soft:          return 64
        case Hard:          return 127
        case let Number(v): return v
        }
    }
}

func ==(lhs: Velocity, rhs: Velocity) -> Bool {
    switch (lhs, rhs) {
    case (.Default, .Default):           return true
    case (.PPP,     .PPP):               return true
    case (.PP,      .PP):                return true
    case (.P,       .P):                 return true
    case (.MP,      .MP):                return true
    case (.MF,      .MF):                return true
    case (.F,       .F):                 return true
    case (.FF,      .FF):                return true
    case (.FFF,     .FFF):               return true
    case (.Soft,    .Soft):              return true
    case (.Hard,    .Hard):              return true
    case let (.Number (l), .Number (r)): return l == r
    default:                             return false
    }
}


import UIKit

protocol CameraAssembly: class {
    func module(initialActiveCameraType: CameraType, overridenTheme: PaparazzoUITheme?) -> (UIView, CameraModuleInput)
}

protocol CameraAssemblyFactory {
    func cameraAssembly() -> CameraAssembly
}

Add extension without new parameter

import UIKit

protocol CameraAssembly: class {
    func module(initialActiveCameraType: CameraType, overridenTheme: PaparazzoUITheme?) -> (UIView, CameraModuleInput)
}

protocol CameraAssemblyFactory {
    func cameraAssembly() -> CameraAssembly
}

extension CameraAssembly {
    func module(initialActiveCameraType: CameraType) -> (UIView, CameraModuleInput) {
        return module(initialActiveCameraType: initialActiveCameraType, overridenTheme: nil)
    }
}


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

@testable import ReSwiftRx
import XCTest

class RxTests: XCTestCase {

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

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

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

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

}

Bring test coverage to 100%

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

@testable import ReSwiftRx
import XCTest

class RxTests: XCTestCase {

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

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

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

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

}


import AudioToolbox
import Foundation
import Sockets
import Streams

public extension Socket
{
	public func createAudioStream() -> ReadableStream<AudioData>
	{
		let stream = Streams.Stream<AudioData>()
		var description: AudioStreamBasicDescription? = nil

		let parse = try! AFSUtility.CreateCustomAudioStreamParser(
			onStreamReady: { (_, asbd, cookieData) in
				description = asbd.pointee
		},
			onPackets: { (_ numBytes: UInt32, _ numPackets: UInt32, _ inputData: UnsafeRawPointer, _ packetDescriptions: UnsafeMutablePointer<AudioStreamPacketDescription>?, _ startTime: UnsafePointer<AudioTimeStamp>?) in
				stream.publish(AudioData.Create(description!, numBytes, numPackets, inputData, packetDescriptions, startTime))
		})

		DispatchQueue.global().async {
			while let data = self.read(maxBytes: 4 * 1024) {
				try! parse(data)
			}
		}

		return ReadableStream(stream)
	}
}

Stop publishing to the audio stream when the socket is disposed and when the stream is disposed.

import AudioToolbox
import Foundation
import Cancellation
import Scope
import Sockets
import Streams

public extension Socket
{
	public func createAudioStream() -> ReadableStream<AudioData>
	{
		let tokenSource = CancellationTokenSource()
		let stream = Streams.Stream<AudioData>()
		stream.addDownstreamDisposable(Scope {
			tokenSource.cancel()
		})

		var description: AudioStreamBasicDescription? = nil

		let parse = try! AFSUtility.CreateCustomAudioStreamParser(
			onStreamReady: { (_, asbd, cookieData) in
				description = asbd.pointee
		},
			onPackets: { (_ numBytes: UInt32, _ numPackets: UInt32, _ inputData: UnsafeRawPointer, _ packetDescriptions: UnsafeMutablePointer<AudioStreamPacketDescription>?, _ startTime: UnsafePointer<AudioTimeStamp>?) in
				stream.publish(AudioData.Create(description!, numBytes, numPackets, inputData, packetDescriptions, startTime))
		})

		DispatchQueue.global().async {
			while !tokenSource.isCancellationRequested && self.isValid, let data = self.read(maxBytes: 4 * 1024) {
				try! parse(data)
			}
		}

		return ReadableStream(stream)
	}
}


import Foundation
import Aztec

// MARK: - VideoAttachment
//
extension VideoAttachment {

    @objc var videoPressID: String? {
        get {
            return extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute]?.toString()
        }
        set {
            if let nonNilValue = newValue {
                extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute] = .string(nonNilValue)
            } else {
                extraAttributes.remove(named: VideoShortcodeProcessor.videoPressHTMLAttribute)
            }
        }
    }
}

Add helper method to detect if video is a WP shortcode.

import Foundation
import Aztec

// MARK: - VideoAttachment
//
extension VideoAttachment {

    @objc var videoPressID: String? {
        get {
            return extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute]?.toString()
        }
        set {
            if let nonNilValue = newValue {
                extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute] = .string(nonNilValue)
            } else {
                extraAttributes.remove(named: VideoShortcodeProcessor.videoPressHTMLAttribute)
            }
        }
    }

    @objc var isShortcode: Bool {
        get {
            return extraAttributes[VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute]?.toString() == "true"
        }
        set {
            if newValue {
                extraAttributes[VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute] = .string(String("true"))
            } else {
                extraAttributes.remove(named: VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute)
            }
        }
    }
}


//
//  Person.swift
//  FreddyTests
//
//  Created by Matthew D. Mathias on 3/21/15.
//  Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//

import Freddy

public struct Person: CustomStringConvertible {
    public enum EyeColor: String {
        case Brown = "brown"
        case Blue = "blue"
        case Green = "green"
    }

    public let name: String
    public var age: Int
    public let eyeColor: EyeColor
    public let spouse: Bool

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

extension Person.EyeColor: JSONDecodable {}
extension Person.EyeColor: JSONEncodable {}

extension Person: JSONDecodable {
    public init(json value: JSON) throws {
        name = try value.string("name")
        age = try value.int("age")
        eyeColor = try value.decode("eyeColor")
        spouse = try value.bool("spouse")
    }
}

extension Person: JSONEncodable {
    public func toJSON() -> JSON {
        return .Dictionary(["name": .String(name), "age": .Int(age), "eyeColor": .String(eyeColor.rawValue), "spouse": .Bool(spouse)])
    }
}

Use toJSON() on enum type

//
//  Person.swift
//  FreddyTests
//
//  Created by Matthew D. Mathias on 3/21/15.
//  Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//

import Freddy

public struct Person: CustomStringConvertible {
    public enum EyeColor: String {
        case Brown = "brown"
        case Blue = "blue"
        case Green = "green"
    }

    public let name: String
    public var age: Int
    public let eyeColor: EyeColor
    public let spouse: Bool

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

extension Person.EyeColor: JSONDecodable {}
extension Person.EyeColor: JSONEncodable {}

extension Person: JSONDecodable {
    public init(json value: JSON) throws {
        name = try value.string("name")
        age = try value.int("age")
        eyeColor = try value.decode("eyeColor")
        spouse = try value.bool("spouse")
    }
}

extension Person: JSONEncodable {
    public func toJSON() -> JSON {
        return .Dictionary(["name": .String(name), "age": .Int(age), "eyeColor": eyeColor.toJSON(), "spouse": .Bool(spouse)])
    }
}


//
//  RequestBuilder.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/30/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

enum RequestEndPoint: String {
    case Beer = "beer"
    case Beers = "beers"
}

extension NSURL {
    func URLByAppendingPathComponent(endPoint: RequestEndPoint) -> NSURL {
        return URLByAppendingPathComponent(endPoint.rawValue)
    }

    func URLByAppendingGETVariable<T : RawRepresentable where T.RawValue == String>(param: T, value: String, isFirstVar: Bool) -> NSURL {
        let url = isFirstVar ? "?" : "&"
        let path = url + param.rawValue + "=" + value
        return NSURL(string: self.path! + path)!
    }
}

class RequestBuilder {
    let endPoint: RequestEndPoint

    init(endPoint: RequestEndPoint) {
        self.endPoint = endPoint
    }

    func buildRequest<T : RawRepresentable where T.RawValue == String>(requestParams: [T: String]) -> NSURL {
        var beerRequest = BreweryDBBaseURL.URLByAppendingPathComponent(endPoint)

        for (index, param) in requestParams.enumerate() {
            beerRequest = beerRequest.URLByAppendingGETVariable(param.0, value: param.1, isFirstVar: index == 0 ? true : false)
        }

        return beerRequest
    }
}

Use absolute string rather than path

//
//  RequestBuilder.swift
//  BreweryDB
//
//  Created by Jake Welton on 1/30/16.
//  Copyright © 2016 Jake Welton. All rights reserved.
//

import Foundation

enum RequestEndPoint: String {
    case Beer = "beer"
    case Beers = "beers"
}

extension NSURL {
    func URLByAppendingPathComponent(endPoint: RequestEndPoint) -> NSURL {
        return URLByAppendingPathComponent(endPoint.rawValue)
    }

    func URLByAppendingGETVariable<T : RawRepresentable where T.RawValue == String>(param: T, value: String, isFirstVar: Bool) -> NSURL {
        let url = isFirstVar ? "?" : "&"
        let path = url + param.rawValue + "=" + value
        return NSURL(string: self.absoluteString + path)!
    }
}

class RequestBuilder {
    let endPoint: RequestEndPoint

    init(endPoint: RequestEndPoint) {
        self.endPoint = endPoint
    }

    func buildRequest<T : RawRepresentable where T.RawValue == String>(requestParams: [T: String]) -> NSURL {
        var beerRequest = BreweryDBBaseURL.URLByAppendingPathComponent(endPoint)

        for (index, param) in requestParams.enumerate() {
            beerRequest = beerRequest.URLByAppendingGETVariable(param.0, value: param.1, isFirstVar: index == 0 ? true : false)
        }

        return beerRequest
    }
}


//
//  UIViewController+Error.swift
//  Example
//
//  Created by ishkawa on 2016/07/29.
//  Copyright © 2016年 Shinichiro Oba. All rights reserved.
//

import UIKit
import APIKit
import JSONRPCKit

extension UIViewController {

    func showAlertWithError(error: SessionTaskError) {
        let title: String?
        let message: String?

        switch error {
        case .ConnectionError(let error as NSError):
            title = error.localizedDescription
            message = error.localizedRecoverySuggestion

        case .ResponseError(let error as JSONRPCError):
            if case .MissingBothResultAndError(let object) = error {
                let data = try! NSJSONSerialization.dataWithJSONObject(object, options: .PrettyPrinted)
                let string = String(data: data, encoding: NSUTF8StringEncoding)!
                print(string)
            }

            if case .ResponseError(_, let errorMessage, let data as String) = error {
                title = errorMessage
                message = data
            } else {
                fallthrough
            }

        default:
            title = "Unknown error"
            message = nil
        }

        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let alertAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(alertAction)
        presentViewController(alertController, animated: true, completion: nil)
    }

}

Remove debug log in example project

//
//  UIViewController+Error.swift
//  Example
//
//  Created by ishkawa on 2016/07/29.
//  Copyright © 2016年 Shinichiro Oba. All rights reserved.
//

import UIKit
import APIKit
import JSONRPCKit

extension UIViewController {

    func showAlertWithError(error: SessionTaskError) {
        let title: String?
        let message: String?

        switch error {
        case .ConnectionError(let error as NSError):
            title = error.localizedDescription
            message = error.localizedRecoverySuggestion

        case .ResponseError(let error as JSONRPCError):
            if case .ResponseError(_, let errorMessage, let data as String) = error {
                title = errorMessage
                message = data
            } else {
                fallthrough
            }

        default:
            title = "Unknown error"
            message = nil
        }

        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let alertAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(alertAction)
        presentViewController(alertController, animated: true, completion: nil)
    }

}


// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "TTGSnackbar",
    platforms: [.iOS(.v91)],
    products: [
        .library(name: "TTGSnackbar", targets: ["TTGSnackbar"])
    ],
    targets: [
        .target(name: "TTGSnackbar", path: "TTGSnackbar")
    ]
)

Fix broken ".v91" platform version

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "TTGSnackbar",
    platforms: [.iOS(.v9)],
    products: [
        .library(name: "TTGSnackbar", targets: ["TTGSnackbar"])
    ],
    targets: [
        .target(name: "TTGSnackbar", path: "TTGSnackbar")
    ]
)


// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
extension Array {
    func test() {
        return //% self.expect("frame variable -d run -- self", substrs=['[0] = 1', '[1] = 2', '[2] = 3'])
    }
}
var a = [1,2,3]

a.test()

Add another test to TestSwiftGenericExtension.py.

// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
extension Array {
    func test() {
        print("PATPAT") //% self.expect("p self", substrs=['[0] = 1', '[1] = 2', '[2] = 3'])
        return //% self.expect("frame variable -d run -- self", substrs=['[0] = 1', '[1] = 2', '[2] = 3'])
    }
}
var a = [1,2,3]

a.test()


//
//  DataControllerTests.swift
//  FlingChallengeKit
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

@testable import FlingChallengeKit
import XCTest

class DataControllerTests: XCTestCase {

  let queue = dispatch_queue_create("com.alexkolov.DataControllerTests", DISPATCH_QUEUE_CONCURRENT)

  func testDataControllerInitialization() {
    do {
      XCTAssertTrue(NSThread.isMainThread())

      let controller = try DataController()
      XCTAssertNotNil(controller)

      let mainContext = controller.managedObjectContext
      XCTAssertNotNil(mainContext)
      XCTAssertTrue(mainContext.concurrencyType == .MainQueueConcurrencyType)
    }
    catch {
      XCTFail()
    }
  }

  func testDataControllerThreadedInitialization() {
    let expectation = expectationWithDescription("Should create private managed object context")

    dispatch_async(queue) {
      XCTAssertFalse(NSThread.isMainThread())
      do {
        let anotherController = try DataController()
        let privateContext = anotherController.managedObjectContext
        XCTAssertNotNil(privateContext)
        XCTAssertTrue(privateContext.concurrencyType == .PrivateQueueConcurrencyType)
        expectation.fulfill()
      }
      catch {
        XCTFail()
      }
    }

    waitForExpectationsWithTimeout(5, handler: nil)
  }

}

Test that private MOC has main queue MOC as parent

//
//  DataControllerTests.swift
//  FlingChallengeKit
//
//  Created by Alexander Kolov on 5/8/16.
//  Copyright © 2016 Alexander Kolov. All rights reserved.
//

@testable import FlingChallengeKit
import XCTest

class DataControllerTests: XCTestCase {

  let queue = dispatch_queue_create("com.alexkolov.DataControllerTests", DISPATCH_QUEUE_CONCURRENT)

  func testDataControllerInitialization() {
    do {
      XCTAssertTrue(NSThread.isMainThread())

      let controller = try DataController()
      XCTAssertNotNil(controller)

      let mainContext = controller.managedObjectContext
      XCTAssertNotNil(mainContext)
      XCTAssertTrue(mainContext.concurrencyType == .MainQueueConcurrencyType)
    }
    catch {
      XCTFail()
    }
  }

  func testDataControllerThreadedInitialization() {
    let expectation = expectationWithDescription("Should create private managed object context")

    dispatch_async(queue) {
      XCTAssertFalse(NSThread.isMainThread())
      do {
        let anotherController = try DataController()
        let privateContext = anotherController.managedObjectContext
        XCTAssertNotNil(privateContext)
        XCTAssertTrue(privateContext.concurrencyType == .PrivateQueueConcurrencyType)
        XCTAssertTrue(privateContext.parentContext?.concurrencyType == .MainQueueConcurrencyType)
        expectation.fulfill()
      }
      catch {
        XCTFail()
      }
    }

    waitForExpectationsWithTimeout(5, handler: nil)
  }

}


import PackageDescription

let package = Package(
    name: "SteamPress",
    dependencies: [
    	.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
    	.Package(url: "https://github.com/scinfu/SwiftSoup.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/LeafMarkdown.git", majorVersion: 0),
    	.Package(url: "https://github.com/nodes-vapor/paginator", majorVersion: 0)
    ]
)

Use Broken Hands fork of Swift Soup to test changes

import PackageDescription

let package = Package(
    name: "SteamPress",
    dependencies: [
    	.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/SwiftSoup.git", majorVersion: 1),
    	.Package(url: "https://github.com/brokenhandsio/LeafMarkdown.git", majorVersion: 0),
    	.Package(url: "https://github.com/nodes-vapor/paginator", majorVersion: 0)
    ]
)


import RxSwift

public protocol DisposableCollection {
	associatedtype AddDisposableReturnType

	func addDisposable(_ disposable: Disposable) -> AddDisposableReturnType
}

extension CompositeDisposable: DisposableCollection {
	public typealias AddDisposableReturnType = DisposeKey?
}

extension DisposeBag: DisposableCollection {
	public typealias AddDisposableReturnType = Void
}

// Append Disposable
infix operator ++ {
associativity left

// Binds same as addition
precedence 140
}

/**
 Appends a disposable to another disposable collection, aka a CompositeDisposable or DisposeBag.

 In this form it's equivalent to `addDisposable` method and allows chaining of subscriptions

 - parameter composite: Disposable collection to add the disposable to.
 - parameter disposable: A disposable to be added to the collection.
 - returns: The disposable collection.
 */
public func ++<T: DisposableCollection>(composite: T, disposable: Disposable) -> T {
	composite.addDisposable(disposable)
	return composite
}

Make some warnings in unit tests go away

import RxSwift

public protocol DisposableCollection {
	associatedtype AddDisposableReturnType

	func addDisposable(_ disposable: Disposable) -> AddDisposableReturnType
}

extension CompositeDisposable: DisposableCollection {
	public typealias AddDisposableReturnType = DisposeKey?
}

extension DisposeBag: DisposableCollection {
	public typealias AddDisposableReturnType = Void
}

// Append Disposable
infix operator ++ {
associativity left

// Binds same as addition
precedence 140
}

/**
 Appends a disposable to another disposable collection, aka a CompositeDisposable or DisposeBag.

 In this form it's equivalent to `addDisposable` method and allows chaining of subscriptions

 - parameter composite: Disposable collection to add the disposable to.
 - parameter disposable: A disposable to be added to the collection.
 - returns: The disposable collection.
 */
@discardableResult
public func ++<T: DisposableCollection>(composite: T, disposable: Disposable) -> T {
	composite.addDisposable(disposable)
	return composite
}


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

final class TagTests: XCTestCase {
	func testConstructsOneTagPerLabel() {
		assert(Tag.tags([ "a", "b", "c" ]).count, ==, 3)
	}

	func testConstructsTagsInOrder() {
		let tags = Tag.tags([ "a", "b", "c" ])
		assert(tags[0], ==, Tag.Here("a", ["b", "c"]))
		assert(tags[1], ==, Tag.There("a", ["b", "c"], { Tag.Here("b", ["c"]) }))
		assert(tags[2], ==, Tag.There("a", ["b", "c"], { Tag.There("b", ["c"], { Tag.Here("c", []) }) }))
	}

	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType([ Term("Enumeration"), Term(.Type(0)) ])
		let actual = Term("Tag").out.typecheck(Expression<Term>.tag.context, against: expected)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}
}

import Assertions
@testable import Manifold
import XCTest

Remove the Swift tests of the host language definition of Tag.

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

final class TagTests: XCTestCase {
	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType([ Term("Enumeration"), Term(.Type(0)) ])
		let actual = Term("Tag").out.typecheck(Expression<Term>.tag.context, against: expected)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}
}

import Assertions
@testable import Manifold
import XCTest


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

final class TagTests: XCTestCase {
	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType(Enumeration, Term(.Type(0)))
		let actual = Tag.out.checkType(expected, environment, context)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}

	func testBranchesProducesAType() {
		let branches = Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), environment, context)
		assert(branches.left, ==, nil)
		assert(branches.right, ==, .Type(0))
	}

	func testBranchesOfEmptyEnumerationIsUnitType() {
		assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
	}
}

private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]

private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment

import Assertions
@testable import Manifold
import Prelude
import XCTest

Test the construction of the empty tag.

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

final class TagTests: XCTestCase {
	func testEmptyEnumerationYieldsEmptyTag() {
		assert(Manifold.Tag.tags([]), ==, [])
	}

	func testTagTypechecksAsFunction() {
		let expected = Expression.FunctionType(Enumeration, Term(.Type(0)))
		let actual = Tag.out.checkType(expected, environment, context)
		assert(actual.left, ==, nil)
		assert(actual.right, ==, expected)
	}

	func testBranchesProducesAType() {
		let branches = Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.UnitType))))].out.checkType(.Type(0), environment, context)
		assert(branches.left, ==, nil)
		assert(branches.right, ==, .Type(0))
	}

	func testBranchesOfEmptyEnumerationIsUnitType() {
		assert(Branches[Empty, Term(.lambda(Tag[Empty], const(Term(.BooleanType))))].out.evaluate(environment), ==, .UnitType)
	}
}

private let Enumeration = Term("Enumeration")
private let Branches = Term("Branches")
private let `nil` = Term("[]")
private let Tag = Term("Tag")
private let Empty = `nil`[Term("String")]

private let module = Expression<Term>.tag
private let context = module.context
private let environment = module.environment

import Assertions
@testable import Manifold
import Prelude
import XCTest


//
//  NSURL+Resource.swift
//  URLGrey
//
//  Created by Zachary Waldowski on 10/21/14.
//  Copyright (c) 2014 Zachary Waldowski. All rights reserved.
//

import Foundation

public extension NSURL {

    public func value<K: ResourceReadable, R: ResultType where K.ReadResult == R>(forResource resource: K) -> R {
        let key = resource.key

        var value: AnyObject?
        var fetchError: NSError?
        if !getResourceValue(&value, forKey: key, error: &fetchError) {
            return K.ReadResult(failure: error(code: URLError.ResourceRead(key), underlying: fetchError))
        }
        return resource.read(value)
    }

    public func setValue<K: ResourceWritable, V where K.InputValue == V>(value: V, forResource resource: K) -> VoidResult {
        let key = resource.key

        return flatMap(resource.write(value)) { finalValue -> VoidResult in
            var saveError: NSError?
            if !self.setResourceValue(finalValue, forKey: key, error: &saveError) {
                return failure(error(code: URLError.ResourceWrite(key), underlying: saveError))
            }
            return success()
        }
    }

}

Use failure() in rsrc read instead of initializer

//
//  NSURL+Resource.swift
//  URLGrey
//
//  Created by Zachary Waldowski on 10/21/14.
//  Copyright (c) 2014 Zachary Waldowski. All rights reserved.
//

import Foundation

public extension NSURL {

    public func value<K: ResourceReadable, R: ResultType where K.ReadResult == R>(forResource resource: K) -> R {
        let key = resource.key

        var value: AnyObject?
        var fetchError: NSError?
        if !getResourceValue(&value, forKey: key, error: &fetchError) {
            return failure(error(code: URLError.ResourceRead(key), underlying: fetchError))
        }
        return resource.read(value)
    }

    public func setValue<K: ResourceWritable, V where K.InputValue == V>(value: V, forResource resource: K) -> VoidResult {
        let key = resource.key

        return flatMap(resource.write(value)) { finalValue -> VoidResult in
            var saveError: NSError?
            if !self.setResourceValue(finalValue, forKey: key, error: &saveError) {
                return failure(error(code: URLError.ResourceWrite(key), underlying: saveError))
            }
            return success()
        }
    }

}