Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove unnecessary code of Xcode automatic conversion | //
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//
import Foundation
import Dispatch
public extension RunLoop {
public func waitForSemaphore(_ sem: DispatchSemaphore) {
repeat {
run(mode: RunLoop.Mode.default, before: Date(timeIntervalSinceNow: 0.01))
} while .success != sem.wait(timeout: DispatchTime.now())
}
}
| //
// NSRunLoop+Utils.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2016 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//
import Foundation
import Dispatch
public extension RunLoop {
public func waitForSemaphore(_ sem: DispatchSemaphore) {
repeat {
run(mode: .default, before: Date(timeIntervalSinceNow: 0.01))
} while .success != sem.wait(timeout: DispatchTime.now())
}
}
|
Use consistent variable name in documentation | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
import Firestore
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// [START default_firestore]
FirebaseApp.configure()
let defaultStore = Firestore.firestore()
// [END default_firestore]
print(defaultStore) // silence warning
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
import Firestore
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// [START default_firestore]
FirebaseApp.configure()
let db = Firestore.firestore()
// [END default_firestore]
print(db) // silence warning
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
Enable logs in test project | //
// AppDelegate.swift
// React
//
// Created by Sacha Durand Saint Omer on 29/03/2017.
// Copyright © 2017 Freshos. All rights reserved.
//
// TODO stateless component ?
// TODO ViewLayout with spacies and margins in the childrne's aray ??
import UIKit
import Komponents
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: NavigationVC()) // Using a UIViewController Component.
window?.makeKeyAndVisible()
return true
}
}
// Other ways to display components:
// // Using View Controller wrapper.
// window?.rootViewController = ComponentVC(component: TestLoop())
// // Using UIView wrapper.
// let vc = UIViewController()
// window?.rootViewController = vc
// let loginView = ComponentView(component: LoginComponent())
// loginView.frame = vc.view.frame
// vc.view.addSubview(loginView)
// // Using bare Komponents engine.
// let vc = UIViewController()
// window?.rootViewController = vc
// let engine = KomponentsEngine()
// engine.render(component: LoginComponent(), in:vc.view)
| //
// AppDelegate.swift
// React
//
// Created by Sacha Durand Saint Omer on 29/03/2017.
// Copyright © 2017 Freshos. All rights reserved.
//
// TODO stateless component ?
// TODO ViewLayout with spacies and margins in the childrne's aray ??
import UIKit
import Komponents
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: NavigationVC()) // Using a UIViewController Component.
window?.makeKeyAndVisible()
Komponents.logsEnabled = true
return true
}
}
// Other ways to display components:
// // Using View Controller wrapper.
// window?.rootViewController = ComponentVC(component: TestLoop())
// // Using UIView wrapper.
// let vc = UIViewController()
// window?.rootViewController = vc
// let loginView = ComponentView(component: LoginComponent())
// loginView.frame = vc.view.frame
// vc.view.addSubview(loginView)
// // Using bare Komponents engine.
// let vc = UIViewController()
// window?.rootViewController = vc
// let engine = KomponentsEngine()
// engine.render(component: LoginComponent(), in:vc.view)
|
Add typealiases for BlockOperation and OperationQueueDelegate | //
// Swift3Typealiases.swift
// PSOperations
//
// Created by Dev Team on 9/20/16.
// Copyright © 2016 Pluralsight. All rights reserved.
//
public typealias PSOperation = Operation
public typealias PSOperationQueue = OperationQueue
| //
// Swift3Typealiases.swift
// PSOperations
//
// Created by Dev Team on 9/20/16.
// Copyright © 2016 Pluralsight. All rights reserved.
//
public typealias PSOperation = Operation
public typealias PSOperationQueue = OperationQueue
public typealias PSOperationQueueDelegate = OperationQueueDelegate
public typealias PSBlockOperation = BlockOperation
|
Add an override for --> | // Copyright (c) 2015 Rob Rix. All rights reserved.
/// Returns a parser which maps parse trees into another type.
public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (C, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
return { input, sourcePos in
parser(input, sourcePos).map { (f(input, sourcePos.index..<$1.index, $0), $1) }
}
}
/// Returns a parser which maps parse results.
///
/// This enables e.g. adding identifiers for error handling.
public func --> <C: CollectionType, T, U> (parser: Parser<C, T>.Function, transform: Parser<C, T>.Result -> Parser<C, U>.Result) -> Parser<C, U>.Function {
return parser >>> transform
}
import Prelude
| // Copyright (c) 2015 Rob Rix. All rights reserved.
/// Returns a parser which maps parse trees into another type.
public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (C, SourcePos<C.Index>, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
return { input, inputPos in
parser(input, inputPos).map { output, outputPos in
(f(input, outputPos, inputPos.index..<outputPos.index, output), outputPos)
}
}
}
public func --> <C: CollectionType, T, U>(parser: Parser<C, T>.Function, f: (SourcePos<C.Index>, Range<C.Index>, T) -> U) -> Parser<C, U>.Function {
return parser --> { f($1, $2, $3) }
}
/// Returns a parser which maps parse results.
///
/// This enables e.g. adding identifiers for error handling.
public func --> <C: CollectionType, T, U> (parser: Parser<C, T>.Function, transform: Parser<C, T>.Result -> Parser<C, U>.Result) -> Parser<C, U>.Function {
return parser >>> transform
}
import Prelude
|
Add sign/verify and key exchange tests | import XCTest
@testable import Ed25519
class Ed25519Tests: XCTestCase {
func testSeed() throws {
let seed = try Seed()
XCTAssertNotEqual([UInt8](repeating: 0, count: 32), seed.buffer)
}
static var allTests = [
("testSeed", testSeed),
]
}
| import XCTest
@testable import Ed25519
class Ed25519Tests: XCTestCase {
func testSeed() throws {
let seed = try Seed()
XCTAssertEqual(32, seed.bytes.count)
XCTAssertNotEqual([UInt8](repeating: 0, count: 32), seed.bytes)
}
func testSignAndVerify() throws {
let seed = try Seed()
let keyPair = KeyPair(seed: seed)
let message = [UInt8]("Hello World!".utf8)
let otherMessage = [UInt8]("Bonan tagon!".utf8)
let signature = keyPair.sign(message)
var tamperedSignature = signature
tamperedSignature[3] = tamperedSignature[3] &+ 1
XCTAssertTrue(try keyPair.verify(signature: signature, message: message))
XCTAssertFalse(try keyPair.verify(signature: signature, message: otherMessage))
XCTAssertFalse(try keyPair.verify(signature: tamperedSignature, message: message))
XCTAssertFalse(try keyPair.verify(signature: signature, message: []))
XCTAssertThrowsError(try keyPair.verify(signature: [1,2,3], message: message))
}
func testKeyExchange() throws {
let keyPair = KeyPair(seed: try Seed())
let otherKeyPair = KeyPair(seed: try Seed())
XCTAssertNotEqual(keyPair.privateKey.bytes, otherKeyPair.privateKey.bytes)
XCTAssertNotEqual(keyPair.publicKey.bytes, otherKeyPair.publicKey.bytes)
let secret1 = try KeyPair.keyExchange(publicKey: keyPair.publicKey.bytes,
privateKey: otherKeyPair.privateKey.bytes)
let secret2 = try KeyPair.keyExchange(publicKey: otherKeyPair.publicKey.bytes,
privateKey: keyPair.privateKey.bytes)
XCTAssertEqual(secret1, secret2)
}
static var allTests = [
("testSeed", testSeed),
("testSignAndVerify", testSignAndVerify),
("testKeyExchange", testKeyExchange)
]
}
|
Fix test failure on iPad | import XCTest
class ScreenshotGenerator: XCTestCase {
var app: XCUIApplication!
let automationController = AutomationController()
override func setUp() {
super.setUp()
app = automationController.app
setupSnapshot(app)
enforceCorrectDeviceOrientation()
app.launch()
}
private func enforceCorrectDeviceOrientation() {
let isTablet = UIDevice.current.userInterfaceIdiom == .pad
let device = XCUIDevice.shared
if isTablet {
device.orientation = .landscapeLeft
} else {
device.orientation = .portrait
}
}
private func hideKeyboard() {
let hideKeyboardButton = app.buttons["Hide keyboard"]
if hideKeyboardButton.exists {
hideKeyboardButton.tap()
}
}
func testScreenshots() {
automationController.transitionToContent()
snapshot("01_News")
automationController.tapTab(.schedule)
app.tables.firstMatch.swipeDown()
snapshot("02_Schedule")
let searchField = app.searchFields["Search"]
searchField.tap()
searchField.typeText("comic")
app.tables["Search results"].staticTexts["ECC Room 4"].tap()
if app.tables.buttons["Add to Favourites"].exists {
app.tables.buttons["Add to Favourites"].tap()
}
snapshot("03_EventDetail")
hideKeyboard()
automationController.tapTab(.dealers)
snapshot("04_Dealers")
app.tables.staticTexts["Eurofurence Shop"].tap()
snapshot("05_DealerDetail")
automationController.tapTab(.information)
snapshot("06_Information")
}
}
| import XCTest
class ScreenshotGenerator: XCTestCase {
var app: XCUIApplication!
let automationController = AutomationController()
override func setUp() {
super.setUp()
app = automationController.app
setupSnapshot(app)
enforceCorrectDeviceOrientation()
app.launch()
}
private func enforceCorrectDeviceOrientation() {
let isTablet = UIDevice.current.userInterfaceIdiom == .pad
let device = XCUIDevice.shared
if isTablet {
device.orientation = .landscapeLeft
} else {
device.orientation = .portrait
}
}
func testScreenshots() {
automationController.transitionToContent()
snapshot("01_News")
automationController.tapTab(.schedule)
app.tables.firstMatch.swipeDown()
snapshot("02_Schedule")
app.tables.staticTexts["Artists' Lounge"].tap()
snapshot("03_EventDetail")
automationController.tapTab(.dealers)
snapshot("04_Dealers")
app.tables.staticTexts["Eurofurence Shop"].tap()
snapshot("05_DealerDetail")
automationController.tapTab(.information)
snapshot("06_Information")
}
}
|
Improve UIViewController add/remove child methods | //
// Premier+UIViewController.swift
// PremierKit
//
// Created by Ricardo Pereira on 24/08/2019.
// Copyright © 2019 Ricardo Pereira. All rights reserved.
//
import UIKit
extension UIViewController {
func add(_ child: UIViewController) {
addChild(child)
view.addSubview(child.view)
child.didMove(toParent: self)
}
func remove() {
guard parent != nil else {
return
}
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
| //
// Premier+UIViewController.swift
// PremierKit
//
// Created by Ricardo Pereira on 24/08/2019.
// Copyright © 2019 Ricardo Pereira. All rights reserved.
//
import UIKit
extension UIViewController {
public func add(asChildViewController viewController: UIViewController) {
addChild(viewController)
view.addSubview(viewController.view)
viewController.didMove(toParent: self)
}
public func removeAsChildViewController() {
guard parent != nil else {
return
}
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
|
Add internal struct Logger that will be used as a default logger | //
// AsyncType+Debug.swift
// BrightFutures
//
// Created by Oleksii on 23/09/2016.
// Copyright © 2016 Thomas Visser. All rights reserved.
//
import Result
public protocol LoggerType {
func log(message: String)
}
| //
// AsyncType+Debug.swift
// BrightFutures
//
// Created by Oleksii on 23/09/2016.
// Copyright © 2016 Thomas Visser. All rights reserved.
//
import Result
public protocol LoggerType {
func log(message: String)
}
struct Logger: LoggerType {
func log(message: String) {
print(message)
}
}
|
Use predicate instead of mather for tests | //
// Satisfy.swift
// OMM
//
// Created by Ivan Nikitin on 06/10/16.
// Copyright © 2016 Ivan Nikitin. All rights reserved.
//
import Nimble
func satisfy<T>(closure: @escaping (T) -> Void) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "satisfy closure"
guard let actualValue = try actualExpression.evaluate() else {
return false
}
return gatherFailingExpectations { closure(actualValue) }.isEmpty
}
}
| //
// Satisfy.swift
// OMM
//
// Created by Ivan Nikitin on 06/10/16.
// Copyright © 2016 Ivan Nikitin. All rights reserved.
//
import Nimble
func satisfy<T>(closure: @escaping (T) -> Void) -> Predicate<T> {
return Predicate.simple("satisfy closure") { actualExpression in
guard let actualValue = try actualExpression.evaluate() else {
return .fail
}
let failures = gatherFailingExpectations { closure(actualValue) }
return failures.isEmpty ? .matches : .fail
}
}
|
Fix problem with file path with spaces | //
// IgnoreFile.swift
// R.swift
//
// Created by Mathijs Kadijk on 01-10-16.
// Copyright © 2016 Mathijs Kadijk. All rights reserved.
//
import Foundation
class IgnoreFile {
private let patterns: [NSURL]
init() {
patterns = []
}
init(ignoreFileURL: URL) throws {
let parentDirString = ignoreFileURL.deletingLastPathComponent().path + "/"
patterns = try String(contentsOf: ignoreFileURL)
.components(separatedBy: CharacterSet.newlines)
.filter(IgnoreFile.isPattern)
.flatMap { IgnoreFile.listFilePaths(pattern: parentDirString + $0) }
.map { NSURL.init(string: $0) }
.flatMap { $0 }
}
static private func isPattern(potentialPattern: String) -> Bool {
// Check for empty line
if potentialPattern.characters.count == 0 { return false }
// Check for commented line
if potentialPattern.characters.first == "#" { return false }
return true
}
static private func listFilePaths(pattern: String) -> [String] {
if (pattern.isEmpty) { return [] }
return Glob.init(pattern: pattern).paths
}
func match(url: NSURL) -> Bool {
return patterns.any { url.path == $0.path }
}
}
| //
// IgnoreFile.swift
// R.swift
//
// Created by Mathijs Kadijk on 01-10-16.
// Copyright © 2016 Mathijs Kadijk. All rights reserved.
//
import Foundation
class IgnoreFile {
private let patterns: [NSURL]
init() {
patterns = []
}
init(ignoreFileURL: URL) throws {
let parentDirString = ignoreFileURL.deletingLastPathComponent().path + "/"
patterns = try String(contentsOf: ignoreFileURL)
.components(separatedBy: CharacterSet.newlines)
.filter(IgnoreFile.isPattern)
.flatMap { IgnoreFile.listFilePaths(pattern: parentDirString + $0) }
.map { $0.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) }
.flatMap { $0 }
.map { NSURL.init(string: $0) }
.flatMap { $0 }
}
static private func isPattern(potentialPattern: String) -> Bool {
// Check for empty line
if potentialPattern.characters.count == 0 { return false }
// Check for commented line
if potentialPattern.characters.first == "#" { return false }
return true
}
static private func listFilePaths(pattern: String) -> [String] {
if (pattern.isEmpty) { return [] }
return Glob.init(pattern: pattern).paths
}
func match(url: NSURL) -> Bool {
return patterns.any { url.path == $0.path }
}
}
|
Improve tests for private methods testing | // https://github.com/Quick/Quick
import Quick
import Nimble
import LoginKit
class LoginKitSpec: QuickSpec {
override func spec() {
describe("testing travis ci"){
it("failure") {
expect(2) == 1
}
it("success") {
expect(1) == 1
}
}
describe("LoginKitConfig"){
it("logoImage is an image"){
expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage))
}
it("authType is JWT by default"){
expect(LoginKitConfig.authType) == AuthType.JWT
}
}
describe("LoginController") {
// it("save password ticked"){
// let loginController = LoginController()
// expect(LoginService.storePassword) == false
// loginController.savePasswordTapped()
// expect(LoginService.storePassword) == true
// }
//
// it("can read") {
// expect("number") == "string"
// }
//
// it("will eventually fail") {
// expect("time").toEventually( equal("done") )
// }
//
// context("these will pass") {
//
// it("can do maths") {
// expect(23) == 23
// }
//
// it("can read") {
// expect("🐮") == "🐮"
// }
//
// it("will eventually pass") {
// var time = "passing"
//
// dispatch_async(dispatch_get_main_queue()) {
// time = "done"
// }
//
// waitUntil { done in
// NSThread.sleepForTimeInterval(0.5)
// expect(time) == "done"
//
// done()
// }
// }
// }
}
}
}
| // https://github.com/Quick/Quick
import Quick
import Nimble
@testable import LoginKit
class LoginKitSpec: QuickSpec {
override func spec() {
describe("testing travis ci"){
it("failure") {
expect(2) == 1
}
it("success") {
expect(1) == 1
}
}
describe("LoginKitConfig"){
it("logoImage is an image"){
expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage))
}
it("authType is JWT by default"){
expect(LoginKitConfig.authType) == AuthType.JWT
}
}
describe("LoginController") {
it("saves password on tap"){
let lc = LoginController()
let _ = lc.view
expect(lc.savePasswordButton.selected) == false
lc.savePasswordTapped()
expect(lc.savePasswordButton.selected) == true
}
}
}
}
|
Add tests for TabmanBar itemCountLimit | //
// TabmanViewControllerTests.swift
// Tabman
//
// Created by Merrick Sapsford on 08/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import XCTest
@testable import Tabman
import Pageboy
class TabmanViewControllerTests: XCTestCase {
var tabmanViewController: TabmanTestViewController!
//
// MARK: Environment
//
override func setUp() {
super.setUp()
self.tabmanViewController = TabmanTestViewController()
self.tabmanViewController.loadViewIfNeeded()
}
}
| //
// TabmanViewControllerTests.swift
// Tabman
//
// Created by Merrick Sapsford on 08/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import XCTest
@testable import Tabman
import Pageboy
class TabmanViewControllerTests: XCTestCase {
var tabmanViewController: TabmanTestViewController!
//
// MARK: Environment
//
override func setUp() {
super.setUp()
self.tabmanViewController = TabmanTestViewController()
self.tabmanViewController.loadViewIfNeeded()
}
//
// MARK: Tests
//
/// Test that the item count limit on a TabmanBar is correctly handled
/// with valid data.
func testItemCountLimit() {
self.tabmanViewController.bar.style = .blockTabBar
self.tabmanViewController.bar.items = [TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test")]
XCTAssertTrue(self.tabmanViewController.tabmanBar?.items?.count == 5,
"TabmanBar itemCountLimit is not evaluated correctly for valid item count.")
}
/// Test that the item count limit on a TabmanBar is correctly handled
/// with data that exceeds the limit.
func testItemCountLimitExceeded() {
self.tabmanViewController.bar.style = .blockTabBar
self.tabmanViewController.bar.items = [TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test"),
TabmanBarItem(title: "test")]
XCTAssertNil(self.tabmanViewController.tabmanBar?.items,
"TabmanBar itemCountLimit is not evaluated correctly for invalid item count.")
}
}
|
Fix deprecation warning about event.context being deprecated and always nil on 10.12 and later | /*
Copyright (c) 2001-2020, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Cocoa
class SourcesOutlineView: NSOutlineView {
override func mouseDown(with event: NSEvent) {
// Ignore all double-clicks (and triple-clicks and so on) by pretending they are single-clicks.
var modifiedEvent: NSEvent?
if event.clickCount > 1 {
modifiedEvent = NSEvent.mouseEvent(with: event.type, location: event.locationInWindow, modifierFlags: event.modifierFlags, timestamp: event.timestamp, windowNumber: event.windowNumber, context: event.context, eventNumber: event.eventNumber, clickCount: 1, pressure: event.pressure)
}
super.mouseDown(with: modifiedEvent ?? event)
}
}
| /*
Copyright (c) 2001-2020, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Cocoa
class SourcesOutlineView: NSOutlineView {
override func mouseDown(with event: NSEvent) {
// Ignore all double-clicks (and triple-clicks and so on) by pretending they are single-clicks.
var modifiedEvent: NSEvent?
if event.clickCount > 1 {
modifiedEvent = NSEvent.mouseEvent(with: event.type, location: event.locationInWindow, modifierFlags: event.modifierFlags, timestamp: event.timestamp, windowNumber: event.windowNumber, context: nil, eventNumber: event.eventNumber, clickCount: 1, pressure: event.pressure)
}
super.mouseDown(with: modifiedEvent ?? event)
}
}
|
Use AppDelegateAssemblyStub when running tests | import UIKit
extension Container {
var appDelegateAssembly: AppDelegateAssembly {
return Assembly()
}
private struct Assembly: AppDelegateAssembly {
var window: UIWindow {
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = ViewController()
return window
}
}
}
| import UIKit
extension Container {
var appDelegateAssembly: AppDelegateAssembly {
if let stubClass = NSClassFromString("SharedShoppingAppTests.AppDelegateAssemblyStub") as? NSObject.Type,
let stubInstance = stubClass.init() as? AppDelegateAssembly {
return stubInstance
}
return Assembly()
}
private struct Assembly: AppDelegateAssembly {
var window: UIWindow {
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = ViewController()
return window
}
}
}
|
Fix ToDoAction did not conform to Action | import TDRedux
public typealias Store = TDRedux.Store<State>
public protocol ToDoAction { }
public struct ToDo {
public let title: String
public init(title: String) {
self.title = title
}
}
public struct State {
public static let initial = State.init(todos: [])
public let todos: [ToDo]
public init(todos: [ToDo]) {
self.todos = todos
}
func add(title: String) -> State {
return .init(todos: todos + [.init(title: title)])
}
}
public enum ToDoActions: ToDoAction {
case add(title: String)
}
public let reducer = Reducer(initialState: State.initial) { (state, action: ToDoActions) in
switch action {
case let .add(title):
return state.add(title: title)
}
}
| import TDRedux
public typealias Store = TDRedux.Store<State>
public protocol ToDoAction: Action { }
public struct ToDo {
public let title: String
public init(title: String) {
self.title = title
}
}
public struct State {
public static let initial = State.init(todos: [])
public let todos: [ToDo]
public init(todos: [ToDo]) {
self.todos = todos
}
func add(title: String) -> State {
return .init(todos: todos + [.init(title: title)])
}
}
public enum ToDoActions: ToDoAction {
case add(title: String)
}
public let reducer = Reducer(initialState: State.initial) { (state, action: ToDoActions) in
switch action {
case let .add(title):
return state.add(title: title)
}
}
|
Replace `join` on a string with `joinWithSeparator` on a collection of strings. | //
// OpenWeatherMap.swift
// SwinjectSimpleExample
//
// Created by Yoichi Tagaya on 8/10/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
struct OpenWeatherMap {
// Replace the empty string with YOUR OWN KEY!
// The key is available for free.
// http://openweathermap.org
private static let apiKey = ""
private static let cityIds = [
6077243, 524901, 5368361, 1835848, 3128760, 4180439,
2147714, 264371, 1816670, 2643743, 3451190, 1850147
]
static let url = "http://api.openweathermap.org/data/2.5/group"
static var parameters: [String: String] {
return [
"APPID": apiKey,
"id": ",".join(cityIds.map { String($0) })
]
}
}
| //
// OpenWeatherMap.swift
// SwinjectSimpleExample
//
// Created by Yoichi Tagaya on 8/10/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
struct OpenWeatherMap {
// Replace the empty string with YOUR OWN KEY!
// The key is available for free.
// http://openweathermap.org
private static let apiKey = ""
private static let cityIds = [
6077243, 524901, 5368361, 1835848, 3128760, 4180439,
2147714, 264371, 1816670, 2643743, 3451190, 1850147
]
static let url = "http://api.openweathermap.org/data/2.5/group"
static var parameters: [String: String] {
return [
"APPID": apiKey,
"id": cityIds.map { String($0) }.joinWithSeparator(",")
]
}
}
|
Return resource bundle only when it exists | //
// DDKHelper.swift
// DJIDemoKitDemo
//
// Created by Pandara on 2017/8/31.
// Copyright © 2017年 Pandara. All rights reserved.
//
import UIKit
public class DDKHelper {
public class func showAlert(title: String?, message: String?, at viewCon: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewCon.present(viewCon, animated: true, completion: nil)
}
public class func resourceBunde() -> Bundle? {
let frameworkBundle = Bundle(for: DDKStartViewController.self)
if let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("DDKResource.bundle") {
let resourceBundle = Bundle(url: bundleURL)
return resourceBundle
}
return nil
}
}
| //
// DDKHelper.swift
// DJIDemoKitDemo
//
// Created by Pandara on 2017/8/31.
// Copyright © 2017年 Pandara. All rights reserved.
//
import UIKit
public class DDKHelper {
public class func showAlert(title: String?, message: String?, at viewCon: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewCon.present(viewCon, animated: true, completion: nil)
}
public class func resourceBunde() -> Bundle? {
let frameworkBundle = Bundle(for: DDKStartViewController.self)
if let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("DDKResource.bundle"), let resourceBundle = Bundle(url: bundleURL) {
return resourceBundle
}
return nil
}
}
|
Replace magic number `1` with `STDOUT_FILENO`. | //
// Formatting.swift
// Carthage
//
// Created by J.D. Healy on 1/29/15.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import Commandant
import Foundation
import LlamaKit
import PrettyColors
import ReactiveCocoa
extension Color.Wrap {
func autowrap(string: String) -> String {
return Formatting.color ? self.wrap(string) : string
}
}
internal struct Formatting {
static let color = Terminal.isTTY && !Terminal.isDumb
static let bulletin = Color.Wrap(foreground: .Blue, style: .Bold)
static let bullets: String = {
return bulletin.autowrap("***") + " "
}()
static let URL = [StyleParameter.Underlined] as Color.Wrap
static let projectName = [StyleParameter.Bold] as Color.Wrap
static let path = Color.Wrap(foreground: .Yellow)
static func quote(string: String, quotationMark: String = "\u{0022}" /* double quote */) -> String {
return Color.Wrap(foreground: .Green).autowrap(quotationMark + string + quotationMark)
}
}
internal struct Terminal {
static let isTTY: Bool = isatty(1) == 1
static let term: String? = getEnvironmentVariable("TERM").value()
static let isDumb: Bool = (Terminal.term?.lowercaseString as NSString?)?.isEqualToString("dumb") ?? false
}
| //
// Formatting.swift
// Carthage
//
// Created by J.D. Healy on 1/29/15.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import Commandant
import Foundation
import LlamaKit
import PrettyColors
import ReactiveCocoa
extension Color.Wrap {
func autowrap(string: String) -> String {
return Formatting.color ? self.wrap(string) : string
}
}
internal struct Formatting {
static let color = Terminal.isTTY && !Terminal.isDumb
static let bulletin = Color.Wrap(foreground: .Blue, style: .Bold)
static let bullets: String = {
return bulletin.autowrap("***") + " "
}()
static let URL = [StyleParameter.Underlined] as Color.Wrap
static let projectName = [StyleParameter.Bold] as Color.Wrap
static let path = Color.Wrap(foreground: .Yellow)
static func quote(string: String, quotationMark: String = "\u{0022}" /* double quote */) -> String {
return Color.Wrap(foreground: .Green).autowrap(quotationMark + string + quotationMark)
}
}
internal struct Terminal {
static let term: String? = getEnvironmentVariable("TERM").value()
static let isDumb: Bool = (Terminal.term?.lowercaseString as NSString?)?.isEqualToString("dumb") ?? false
static let isTTY: Bool = isatty(STDOUT_FILENO) == 1
}
|
Add constant for manga eden image url prefix | //
// ImageURL.swift
// Yomu
//
// Created by Sendy Halim on 6/10/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import Foundation
import Argo
/// A data structure that represents image url that points to Mangaeden api
/// docs: http://www.mangaeden.com/api/
struct ImageURL: CustomStringConvertible {
let endpoint: String
var description: String {
return "https://cdn.mangaeden.com/mangasimg/\(endpoint)"
}
}
extension ImageURL: Decodable {
static func decode(json: JSON) -> Decoded<ImageURL> {
switch json {
case JSON.String(let endpoint):
return pure(ImageURL(endpoint: endpoint))
default:
return .typeMismatch("String endpoint", actual: json)
}
}
}
| //
// ImageURL.swift
// Yomu
//
// Created by Sendy Halim on 6/10/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import Foundation
import Argo
/// A data structure that represents image url that points to Mangaeden api
/// docs: http://www.mangaeden.com/api/
struct ImageURL: CustomStringConvertible {
static let prefix = "https://cdn.mangaeden.com/mangasimg"
let endpoint: String
var description: String {
return "\(ImageURL.prefix)/\(endpoint)"
}
}
extension ImageURL: Decodable {
static func decode(json: JSON) -> Decoded<ImageURL> {
switch json {
case JSON.String(let endpoint):
return pure(ImageURL(endpoint: endpoint))
default:
return .typeMismatch("String endpoint", actual: json)
}
}
}
|
Clean up file manager block in Swift 2 | //
// NSFileManager+DirectoryContents.swift
// URLGrey
//
// Created by Zachary Waldowski on 10/23/14.
// Copyright © 2014-2015. Some rights reserved.
//
import Foundation
// MARK: Directory Enumeration
extension NSFileManager {
public func directory(URL url: NSURL, fetchResources: [URLResourceType] = [], options mask: NSDirectoryEnumerationOptions = [], errorHandler handler: ((NSURL, NSError) -> Bool)? = nil) -> AnySequence<NSURL> {
let keyStrings = fetchResources.map { $0.key }
let unsafeHandler = handler.map { block -> (NSURL!, NSError!) -> Bool in
{ block($0, $1) }
}
if let enumerator = enumeratorAtURL(url, includingPropertiesForKeys: keyStrings, options: mask, errorHandler: unsafeHandler) {
return AnySequence(enumerator.lazy.map(unsafeDowncast))
} else {
return AnySequence(EmptyGenerator())
}
}
}
| //
// NSFileManager+DirectoryContents.swift
// URLGrey
//
// Created by Zachary Waldowski on 10/23/14.
// Copyright © 2014-2015. Some rights reserved.
//
import Foundation
// MARK: Directory Enumeration
extension NSFileManager {
public func directory(URL url: NSURL, fetchResources: [URLResourceType] = [], options mask: NSDirectoryEnumerationOptions = [], errorHandler handler: ((NSURL, NSError) -> Bool)? = nil) -> AnySequence<NSURL> {
let keyStrings = fetchResources.map { $0.key }
if let enumerator = enumeratorAtURL(url, includingPropertiesForKeys: keyStrings, options: mask, errorHandler: handler) {
return AnySequence(enumerator.lazy.map(unsafeDowncast))
} else {
return AnySequence(EmptyGenerator())
}
}
}
|
Add split enabled to init track | //
// MercadoPagoCheckout+Tracking.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 13/12/2018.
//
import Foundation
// MARK: Tracking
extension MercadoPagoCheckout {
internal func startTracking() {
MPXTracker.sharedInstance.setPublicKey(viewModel.publicKey)
MPXTracker.sharedInstance.startNewFlow()
// Track init event
var properties: [String: Any] = [:]
if !String.isNullOrEmpty(viewModel.checkoutPreference.id) {
properties["checkout_preference_id"] = viewModel.checkoutPreference.id
} else {
properties["checkout_preference"] = viewModel.checkoutPreference.getCheckoutPrefForTracking()
}
properties["esc_enabled"] = viewModel.getAdvancedConfiguration().escEnabled
properties["express_enabled"] = viewModel.getAdvancedConfiguration().expressEnabled
MPXTracker.sharedInstance.trackEvent(path: TrackingPaths.Events.getInitPath(), properties: properties)
}
}
| //
// MercadoPagoCheckout+Tracking.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 13/12/2018.
//
import Foundation
// MARK: Tracking
extension MercadoPagoCheckout {
internal func startTracking() {
MPXTracker.sharedInstance.setPublicKey(viewModel.publicKey)
MPXTracker.sharedInstance.startNewFlow()
// Track init event
var properties: [String: Any] = [:]
if !String.isNullOrEmpty(viewModel.checkoutPreference.id) {
properties["checkout_preference_id"] = viewModel.checkoutPreference.id
} else {
properties["checkout_preference"] = viewModel.checkoutPreference.getCheckoutPrefForTracking()
}
properties["esc_enabled"] = viewModel.getAdvancedConfiguration().escEnabled
properties["express_enabled"] = viewModel.getAdvancedConfiguration().expressEnabled
viewModel.populateCheckoutStore()
properties["split_enabled"] = viewModel.paymentPlugin?.supportSplitPaymentMethodPayment(checkoutStore: PXCheckoutStore.sharedInstance)
MPXTracker.sharedInstance.trackEvent(path: TrackingPaths.Events.getInitPath(), properties: properties)
}
}
|
Fix brace (from Hound CI's comment). | //
// RoutingProtocol.swift
// SUSwiftSugar
//
// Created by Suguru Kishimoto on 2016/03/23.
//
//
import Foundation
public protocol RoutingProtocol {
associatedtype ParameterType = AnyObject
func presentViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool, completion: (() -> Void)?)
func pushViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool)
func setupWithParameter(parameter: ParameterType?)
}
public extension RoutingProtocol where Self: UIViewController{
func setupWithParam(params: ParameterType?) {
}
func presentViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool = true, completion: (() -> ())? = nil) {
viewController.setupWithParameter(parameter)
presentViewController(viewController, animated: animated, completion: completion)
}
func pushViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool = true) {
viewController.setupWithParameter(parameter)
self.navigationController?.pushViewController(viewController, animated: animated)
}
}
| //
// RoutingProtocol.swift
// SUSwiftSugar
//
// Created by Suguru Kishimoto on 2016/03/23.
//
//
import Foundation
public protocol RoutingProtocol {
associatedtype ParameterType = AnyObject
func presentViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool, completion: (() -> Void)?)
func pushViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool)
func setupWithParameter(parameter: ParameterType?)
}
public extension RoutingProtocol where Self: UIViewController {
func setupWithParam(params: ParameterType?) {
}
func presentViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool = true, completion: (() -> ())? = nil) {
viewController.setupWithParameter(parameter)
presentViewController(viewController, animated: animated, completion: completion)
}
func pushViewController<To: RoutingProtocol where To: UIViewController>
(viewController: To, parameter: To.ParameterType?, animated: Bool = true) {
viewController.setupWithParameter(parameter)
self.navigationController?.pushViewController(viewController, animated: animated)
}
}
|
Optimize solution to Binary Tree Zigzag Level Order Traversal | /**
* Question Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
* Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
*
* Note: use a boolean value to determine if needs to be added reversely
*
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*
*/
class BinaryTreeZigzagLevelOrderTraversal {
func zigzagLevelOrder(root: TreeNode?) -> [[Int]] {
var res = [[Int]](), queue = [TreeNode](), isReverse = false
if let root = root {
queue.append(root)
}
while !queue.isEmpty {
let size = queue.count
var level = [Int]()
for _ in 0..<size {
let node = queue.removeFirst()
// add val
level.insert(node.val, at: isReverse ? 0 : level.count)
// add TreeNodes in next level
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
res.append(level)
isReverse = !isReverse
}
return res
}
} | /**
* Question Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
* Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
*
* Note: use a boolean value to determine if needs to be added reversely
*
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*
*/
class BinaryTreeZigzagLevelOrderTraversal {
func zigzagLevelOrder(root: TreeNode?) -> [[Int]] {
guard let root = root else {
return [[Int]]()
}
var res = [[Int]](), isReverse = false, nodeQ = [root]
while !nodeQ.isEmpty {
let currentLevel = nodeQ.map { $0.val }
res.append(isReverse ? currentLevel.reversed() : currentLevel)
isReverse = !isReverse
nodeQ = nodeQ.flatMap { [$0.left, $0.right].compactMap { $0 } }
}
return res
}
} |
Add corner radius to sb app icons. | //
// SpringBoardAppIconViewCell.swift
// UIPlayground
//
// Created by Kip Nicol on 9/20/16.
// Copyright © 2016 Kip Nicol. All rights reserved.
//
import UIKit
class SpringBoardAppIconViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
// TODO: update this
backgroundColor = .blue
}
}
| //
// SpringBoardAppIconViewCell.swift
// UIPlayground
//
// Created by Kip Nicol on 9/20/16.
// Copyright © 2016 Kip Nicol. All rights reserved.
//
import UIKit
class SpringBoardAppIconViewCell: UICollectionViewCell {
let cornerRadius = CGFloat(12)
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
clipsToBounds = true
layer.cornerRadius = cornerRadius
// TODO: update this
backgroundColor = .blue
}
}
|
Support Xcode 7 beta 6 | //
// Helper functions to work with strings.
//
import Foundation
public struct TegString {
public static func blank(text: String) -> Bool {
let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmed.isEmpty
}
public static func trim(text: String) -> String {
return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
public static func contains(text: String, substring: String,
ignoreCase: Bool = false,
ignoreDiacritic: Bool = false) -> Bool {
var options: UInt = 0
if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil
}
//
// Joins elements of the array into a string with separator.
// Blank elements are skipped.
//
public static func joinNonBlank(array: [String], separator: String ) -> String {
let nonBlankStrings = array.filter { !self.blank($0) }
return separator.join(nonBlankStrings)
}
//
// Returns a single space if string is empty.
// It is used to set UITableView cells labels as a workaround.
//
public static func singleSpaceIfEmpty(text: String) -> String {
if text == "" {
return " "
}
return text
}
}
| //
// Helper functions to work with strings.
//
import Foundation
public struct TegString {
public static func blank(text: String) -> Bool {
let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return trimmed.isEmpty
}
public static func trim(text: String) -> String {
return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
public static func contains(text: String, substring: String,
ignoreCase: Bool = false,
ignoreDiacritic: Bool = false) -> Bool {
var options: UInt = 0
if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil
}
//
// Returns a single space if string is empty.
// It is used to set UITableView cells labels as a workaround.
//
public static func singleSpaceIfEmpty(text: String) -> String {
if text == "" {
return " "
}
return text
}
}
|
Add a test for init with name | //
// BeerTests.swift
// BreweryDB
//
// Created by Jake Welton on 1/3/16.
// Copyright © 2016 Jake Welton. All rights reserved.
//
import XCTest
class BeerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| //
// BeerTests.swift
// BreweryDB
//
// Created by Jake Welton on 1/3/16.
// Copyright © 2016 Jake Welton. All rights reserved.
//
import XCTest
@testable import BreweryDB
class BeerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBeerCanBeInitializedWithName() {
let beer: Beer? = Beer(name: "Beer name")
XCTAssertNotNil(beer)
}
}
|
Edit : w poprzednim commicie zapomnialem skompilowac projektu wiec wrzucam kolejny commit juz po kompilacji | //
// TestLogic.swift
// StudyBox_iOS
//
// Created by user on 12.03.2016.
// Copyright © 2016 BLStream. All rights reserved.
//
import Foundation
class Test {
private var deck : [Flashcard]
private var currentCard : Flashcard?
private var passedFlashcards = 0
private var index = 0
private var numberOfFlashcardsInFullDeck : Int
init(deck : [Flashcard]) {
self.deck = deck
currentFlashcard()
self.numberOfFlashcardsInFullDeck = deck.count
}
func currentFlashcard() {
var rand : Int
if(deck.count == 0) {
currentCard = nil
}
else {
rand = Int(arc4random_uniform(UInt32(deck.count)))
currentCard = deck[rand]
deck.removeAtIndex(rand)
index += 1
}
}
func correctAnswer() { //funkcja podpieta pod przycisk dobra odpowiedz
passedFlashcards += 1
currentFlashcard()
}
func IncorrectAnswer() { //funkcja podpieta pod przycisk zla odpowiedz
currentFlashcard()
}
} | //
// TestLogic.swift
// StudyBox_iOS
//
// Created by user on 12.03.2016.
// Copyright © 2016 BLStream. All rights reserved.
//
import Foundation
class Test {
private var deck : [Flashcard]
private var currentCard : Flashcard?
private var passedFlashcards = 0
private var index = 0
private var numberOfFlashcardsInFullDeck : Int
init(deck : [Flashcard]) {
self.deck = deck
self.numberOfFlashcardsInFullDeck = deck.count
currentFlashcard()
}
func currentFlashcard() {
var rand : Int
if(deck.count == 0) {
currentCard = nil
}
else {
rand = Int(arc4random_uniform(UInt32(deck.count)))
currentCard = deck[rand]
deck.removeAtIndex(rand)
index += 1
}
}
func correctAnswer() { //funkcja podpieta pod przycisk dobra odpowiedz
passedFlashcards += 1
currentFlashcard()
}
func IncorrectAnswer() { //funkcja podpieta pod przycisk zla odpowiedz
currentFlashcard()
}
} |
Change method to overload to the one that supported Any | /// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: inout Any) throws {
try property(type: type(of: instance), key: key).write(value, to: mutableStorage(instance: &instance))
}
/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: AnyObject) throws {
var copy: Any = instance
try set(value, key: key, for: ©)
}
/// Set value for key of an instance
public func set<T>(_ value: Any, key: String, for instance: inout T, instanceType: Any.Type = T.self) throws {
try property(type: instanceType, key: key).write(value, to: mutableStorage(instance: &instance, type: instanceType))
}
private func property(type: Any.Type, key: String) throws -> Property.Description {
guard let property = try properties(type).first(where: { $0.key == key }) else { throw ReflectionError.instanceHasNoKey(type: type, key: key) }
return property
}
| /// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: inout Any, instanceType: Any.Type? = nil) throws {
let type = instanceType ?? type(of: instance)
try property(type: type(of: instance), key: key).write(value, to: mutableStorage(instance: &instance, type: type))
}
/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: AnyObject) throws {
var copy: Any = instance
try set(value, key: key, for: ©)
}
/// Set value for key of an instance
public func set<T>(_ value: Any, key: String, for instance: inout T) throws {
try property(type: T.self, key: key).write(value, to: mutableStorage(instance: &instance))
}
private func property(type: Any.Type, key: String) throws -> Property.Description {
guard let property = try properties(type).first(where: { $0.key == key }) else { throw ReflectionError.instanceHasNoKey(type: type, key: key) }
return property
}
|
Add a fold overload that will work on Array. | // Copyright © 2015 Rob Rix. All rights reserved.
extension CollectionType {
public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
if !isEmpty {
let some = self[startIndex..<startIndex.advancedBy(1)]
return (first: some[some.startIndex], rest: dropFirst())
}
return nil
}
public var rest: SubSequence {
return isEmpty
? self[startIndex..<endIndex]
: dropFirst()
}
}
extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
var current = uncons
return anyGenerator {
let next = current
current = current?.rest.uncons
return next
}
}
}
extension CollectionType where SubSequence == Self {
public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
return first.map {
combine($0, dropFirst().fold(initial, combine: combine))
} ?? initial
}
}
| // Copyright © 2015 Rob Rix. All rights reserved.
extension CollectionType {
public var uncons: (first: SubSequence._Element, rest: SubSequence)? {
if !isEmpty {
let some = self[startIndex..<startIndex.advancedBy(1)]
return (first: some[some.startIndex], rest: dropFirst())
}
return nil
}
public var rest: SubSequence {
return isEmpty
? self[startIndex..<endIndex]
: dropFirst()
}
}
extension CollectionType where SubSequence: CollectionType, SubSequence.SubSequence == SubSequence {
public var conses: AnyGenerator<(first: SubSequence._Element, rest: SubSequence)> {
var current = uncons
return anyGenerator {
let next = current
current = current?.rest.uncons
return next
}
}
public func fold<Out>(initial: Out, @noescape combine: (SubSequence._Element, Out) -> Out) -> Out {
return self[indices].fold(initial, combine: combine)
}
}
extension CollectionType where SubSequence == Self {
public func fold<Out>(initial: Out, @noescape combine: (Generator.Element, Out) -> Out) -> Out {
return first.map {
combine($0, dropFirst().fold(initial, combine: combine))
} ?? initial
}
}
|
Make N, S accessible from the command line |
/*
RECUR 1 SWIFT
Simply run with: 'swift-t recur-1.swift | nl'
*/
app (void v) dummy(string parent, int stage, int id, void block)
{
"echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}
N = 4; // Data split factor
S = 3; // Maximum stage number (tested up to S=7, 21,844 dummy tasks)
(void v) runstage(int N, int S, string parent, int stage, int id, void block)
{
string this = parent+int2string(id);
v = dummy(parent, stage, id, block);
if (stage < S)
{
foreach id_child in [0:N-1]
{
runstage(N, S, this, stage+1, id_child, v);
}
}
}
int stage = 1;
foreach id in [0:N-1]
{
runstage(N, S, "", stage, id, propagate());
}
|
/*
RECUR 1 SWIFT
Simply run with: 'swift-t recur-1.swift | nl'
Or specify the N, S values:
'swift-t recur-1.swift -N=6 -S=6 | nl'
for 55,986 tasks.
*/
import sys;
app (void v) dummy(string parent, int stage, int id, void block)
{
"echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}
// Data split factor with default
N = string2int(argv("N", "4"));
// Maximum stage number with default
// (tested up to S=7, 21,844 dummy tasks)
S = string2int(argv("S", "3"));
(void v) runstage(int N, int S, string parent, int stage, int id, void block)
{
string this = parent+int2string(id);
v = dummy(parent, stage, id, block);
if (stage < S)
{
foreach id_child in [0:N-1]
{
runstage(N, S, this, stage+1, id_child, v);
}
}
}
int stage = 1;
foreach id in [0:N-1]
{
runstage(N, S, "", stage, id, propagate());
}
|
Throw error correctly (for real this time) | import Vapor
import Validation
public struct JSONValidator: Validator {
public func validate(_ input: String) throws {
do {
_ = try JSON(bytes: input.makeBytes())
} catch {
throw Validator.error("Invalid JSON.")
}
}
}
| import Vapor
import Validation
public struct JSONValidator: Validator {
public func validate(_ input: String) throws {
do {
_ = try JSON(bytes: input.makeBytes())
} catch {
throw self.error("Invalid JSON.")
}
}
}
|
Add cocoapods conditional import of Moya in ReactiveMoyaAvialability. | import Moya
import ReactiveSwift
@available(*, unavailable, renamed: "ReactiveSwiftMoyaProvider")
public class ReactiveCocoaMoyaProvider { }
extension ReactiveSwiftMoyaProvider {
@available(*, unavailable, renamed: "request(_:)")
public func request(token: Target) -> SignalProducer<Response, MoyaError> { fatalError() }
}
| #if !COCOAPODS
import Moya
#endif
import ReactiveSwift
@available(*, unavailable, renamed: "ReactiveSwiftMoyaProvider")
public class ReactiveCocoaMoyaProvider { }
extension ReactiveSwiftMoyaProvider {
@available(*, unavailable, renamed: "request(_:)")
public func request(token: Target) -> SignalProducer<Response, MoyaError> { fatalError() }
}
|
Clarify text for initiating the initial download | //
// PresentationTier.swift
// Eurofurence
//
// Created by Thomas Sherwood on 09/07/2017.
// Copyright © 2017 Eurofurence. All rights reserved.
//
import Foundation
import UIKit
struct PresentationTier {
static func assemble(window: UIWindow) -> PresentationTier {
return PresentationTier(window: window)
}
private var routers: StoryboardRouters
private var finishedTutorialProvider: UserDefaultsTutorialStateProvider
private init(window: UIWindow) {
self.routers = StoryboardRouters(window: window)
self.finishedTutorialProvider = UserDefaultsTutorialStateProvider(userDefaults: .standard)
let appContext = ApplicationContext(firstTimeLaunchProviding: finishedTutorialProvider, tutorialItems: makeTutorialItems())
BootstrappingModule.bootstrap(context: appContext, routers: routers)
}
private func makeTutorialItems() -> [TutorialPageInfo] {
let action = TutorialBlockAction { }
let beginDownloadAction = TutorialPageAction(actionDescription: "Let's Go",
action: action)
let beginDownloadItem = TutorialPageInfo(image: #imageLiteral(resourceName: "tuto01_notificationIcon"),
title: "Hello!",
description: "This is a work in progress, hit the button below to skip this for now.",
primaryAction: beginDownloadAction)
return [beginDownloadItem]
}
}
| //
// PresentationTier.swift
// Eurofurence
//
// Created by Thomas Sherwood on 09/07/2017.
// Copyright © 2017 Eurofurence. All rights reserved.
//
import Foundation
import UIKit
struct PresentationTier {
static func assemble(window: UIWindow) -> PresentationTier {
return PresentationTier(window: window)
}
private var routers: StoryboardRouters
private var finishedTutorialProvider: UserDefaultsTutorialStateProvider
private init(window: UIWindow) {
self.routers = StoryboardRouters(window: window)
self.finishedTutorialProvider = UserDefaultsTutorialStateProvider(userDefaults: .standard)
let appContext = ApplicationContext(firstTimeLaunchProviding: finishedTutorialProvider, tutorialItems: makeTutorialItems())
BootstrappingModule.bootstrap(context: appContext, routers: routers)
}
private func makeTutorialItems() -> [TutorialPageInfo] {
let action = TutorialBlockAction { }
let beginDownloadAction = TutorialPageAction(actionDescription: "Begin Download",
action: action)
let beginDownloadItem = TutorialPageInfo(image: #imageLiteral(resourceName: "tuto02_informationIcon"),
title: "Offline Usage",
description: "The Eurofurence app is intended to remain fully functional while offline. To do this, we need to download a few megabytes of data. This may take several minutes depending upon the speed of your connection.",
primaryAction: beginDownloadAction)
return [beginDownloadItem]
}
}
|
Use Comparable to sort the free variables. | // Copyright (c) 2015 Rob Rix. All rights reserved.
public func constraints(graph: Graph<Node>) -> (Term, constraints: ConstraintSet) {
let parameters = Node.parameters(graph)
let returns = Node.returns(graph)
let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
return (simplify(reduce(parameters, returnType) {
.function(Term(), $0.0)
}), [])
}
private func simplify(type: Term) -> Term {
return Substitution(
(type.freeVariables
|> (flip(sorted) <| { $0.value < $1.value })
|> reverse
|> enumerate
|> lazy)
.map {
($1, Term(integerLiteral: $0))
}).apply(type)
}
import Manifold
import Prelude
| // Copyright (c) 2015 Rob Rix. All rights reserved.
public func constraints(graph: Graph<Node>) -> (Term, constraints: ConstraintSet) {
let parameters = Node.parameters(graph)
let returns = Node.returns(graph)
let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
return (simplify(reduce(parameters, returnType) {
.function(Term(), $0.0)
}), [])
}
private func simplify(type: Term) -> Term {
return Substitution(
(type.freeVariables
|> sorted
|> reverse
|> enumerate
|> lazy)
.map {
($1, Term(integerLiteral: $0))
}).apply(type)
}
import Manifold
import Prelude
|
Add pre-defined errors from JSON-RPC spec | // ----------------------------------------------------------------------------
//
// RPCError.swift
//
// @author Denis Kolyasev <kolyasev@gmail.com>
//
// ----------------------------------------------------------------------------
public class RPCError
{
// MARK: Construction
init(code: Int, message: String, data: Any?)
{
// Init instance variables
self.code = code
self.message = message
self.data = data
}
// MARK: Properties
public let code: Int
public let message: String
public let data: Any?
}
// ----------------------------------------------------------------------------
| // ----------------------------------------------------------------------------
//
// RPCError.swift
//
// @author Denis Kolyasev <kolyasev@gmail.com>
//
// ----------------------------------------------------------------------------
public struct RPCError: Error
{
// MARK: - Construction
init(code: Int, message: String, data: Any?)
{
// Init instance variables
self.code = code
self.message = message
self.data = data
}
// MARK: - Properties
public let code: Int
public let message: String
public let data: Any?
}
// ----------------------------------------------------------------------------
extension RPCError
{
// MARK: - Constants
/// Invalid JSON was received by the server.
/// An error occurred on the server while parsing the JSON text.
public static let parseError = RPCError(code: -32700, message: "Parse error", data: nil)
/// The JSON sent is not a valid Request object.
public static let invalidRequest = RPCError(code: -32600, message: "Invalid Request", data: nil)
/// The method does not exist / is not available.
public static let methodNotFound = RPCError(code: -32601, message: "Method not found", data: nil)
/// Invalid method parameter(s).
public static let invalidParams = RPCError(code: -32602, message: "Invalid params", data: nil)
/// Internal JSON-RPC error.
public static let internalError = RPCError(code: -32603, message: "Internal error", data: nil)
}
// ----------------------------------------------------------------------------
|
Make Confiuration model properties public | import Foundation
public struct Configuration {
let token: String
let units: Unit?
let exclude: Exclude?
let extend: Extend?
let lang: String?
init (token: String,
units: Unit? = nil,
exclude: Exclude? = nil,
extend: Extend? = nil,
lang: String? = nil) {
self.token = token
self.units = units
self.exclude = exclude
self.extend = extend
self.lang = lang
}
}
enum Unit: String {
case us, si, ca, uk2, auto
}
enum Exclude: String {
case currently, minutely, hourly, daily, alerts, flags
}
enum Extend: String {
case hourly
}
| import Foundation
public struct Configuration {
public let token: String
public let units: Unit?
public let exclude: Exclude?
public let extend: Extend?
public let lang: String?
public init (token: String,
units: Unit? = nil,
exclude: Exclude? = nil,
extend: Extend? = nil,
lang: String? = nil) {
self.token = token
self.units = units
self.exclude = exclude
self.extend = extend
self.lang = lang
}
}
public enum Unit: String {
case us, si, ca, uk2, auto
}
public enum Exclude: String {
case currently, minutely, hourly, daily, alerts, flags
}
public enum Extend: String {
case hourly
}
|
Add computed property for perk type | import Foundation
extension DPerk
{
}
| import Foundation
extension DPerk
{
var type:DPerkType
{
get
{
guard
let type:DPerkType = DPerkType(
rawValue:rawType)
else
{
return DPerkType.error
}
return type
}
set(newValue)
{
rawType = newValue.rawValue
}
}
}
|
Add mission module ( Foundation ) | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
@objc(MotionViewOrderStrategy)
public enum MotionViewOrderStrategy: Int {
case auto
case sourceViewOnTop
case destinationViewOnTop
}
| /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
@objc(MotionViewOrderStrategy)
public enum MotionViewOrderStrategy: Int {
case auto
case sourceViewOnTop
case destinationViewOnTop
}
|
Add long delay when starting session | import XCTest
@testable import Phakchi
class ControlServiceClientTestCase: XCTestCase {
var controlServiceClient: ControlServiceClient!
override func setUp() {
super.setUp()
self.controlServiceClient = ControlServiceClient()
}
func testStart() {
var session: Session!
let exp = expectation(description: "session was started")
let controlServiceClient = ControlServiceClient()
controlServiceClient.start(session: "consumer name",
providerName: "provider name") { (newSession) in
session = newSession
XCTAssertEqual(session.consumerName, "consumer name")
XCTAssertEqual(session.providerName, "provider name")
XCTAssertNotNil(session)
exp.fulfill()
}
waitForExpectations(timeout: 5.0, handler: nil)
}
}
| import XCTest
@testable import Phakchi
class ControlServiceClientTestCase: XCTestCase {
var controlServiceClient: ControlServiceClient!
override func setUp() {
super.setUp()
self.controlServiceClient = ControlServiceClient()
}
func testStart() {
var session: Session!
let expectationToStart = expectation(description: "session was started")
let controlServiceClient = ControlServiceClient()
controlServiceClient.start(session: "consumer name",
providerName: "provider name") { (newSession) in
session = newSession
XCTAssertEqual(session.consumerName, "consumer name")
XCTAssertEqual(session.providerName, "provider name")
XCTAssertNotNil(session)
expectationToStart.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)
}
}
|
Fix ReactiveTask errors being output too verbosely | //
// main.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-10.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import CarthageKit
import Commandant
import Foundation
import LlamaKit
let commands = CommandRegistry()
commands.register(BootstrapCommand())
commands.register(BuildCommand())
commands.register(CheckoutCommand())
commands.register(UpdateCommand())
commands.register(VersionCommand())
let helpCommand = HelpCommand(registry: commands)
commands.register(helpCommand)
var arguments = Process.arguments
// Remove the executable name.
assert(arguments.count >= 1)
arguments.removeAtIndex(0)
let verb = arguments.first ?? helpCommand.verb
if arguments.count > 0 {
// Remove the command name.
arguments.removeAtIndex(0)
}
switch commands.runCommand(verb, arguments: arguments) {
case .Some(.Success):
exit(EXIT_SUCCESS)
case let .Some(.Failure(error)):
let errorDescription = (error.domain == CarthageErrorDomain || error.domain == CommandantErrorDomain ? error.localizedDescription : error.description)
fputs("\(errorDescription)\n", stderr)
exit(EXIT_FAILURE)
case .None:
fputs("Unrecognized command: '\(verb)'. See `carthage help`.\n", stderr)
exit(EXIT_FAILURE)
}
| //
// main.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-10.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import CarthageKit
import Commandant
import Foundation
import LlamaKit
import ReactiveTask
let commands = CommandRegistry()
commands.register(BootstrapCommand())
commands.register(BuildCommand())
commands.register(CheckoutCommand())
commands.register(UpdateCommand())
commands.register(VersionCommand())
let helpCommand = HelpCommand(registry: commands)
commands.register(helpCommand)
var arguments = Process.arguments
// Remove the executable name.
assert(arguments.count >= 1)
arguments.removeAtIndex(0)
let verb = arguments.first ?? helpCommand.verb
if arguments.count > 0 {
// Remove the command name.
arguments.removeAtIndex(0)
}
switch commands.runCommand(verb, arguments: arguments) {
case .Some(.Success):
exit(EXIT_SUCCESS)
case let .Some(.Failure(error)):
let errorDescription = (error.domain == CarthageErrorDomain || error.domain == CommandantErrorDomain || error.domain == ReactiveTaskError.domain ? error.localizedDescription : error.description)
fputs("\(errorDescription)\n", stderr)
exit(EXIT_FAILURE)
case .None:
fputs("Unrecognized command: '\(verb)'. See `carthage help`.\n", stderr)
exit(EXIT_FAILURE)
}
|
Add Swift package test target | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Metron",
products: [.library(name: "Metron", targets: ["Metron"])],
targets: [.target(name: "Metron", dependencies: [], path: "./source/Metron", exclude: ["Test"])]
)
| // swift-tools-version:4.2
// https://github.com/apple/swift-evolution/blob/master/proposals/0162-package-manager-custom-target-layouts.md
// https://swift.org/package-manager
import PackageDescription
let package = Package(
name: "Metron",
products: [
.library(name: "Metron", targets: ["Metron"])
],
targets: [
.target(name: "Metron", dependencies: [], path: "./source/Metron", exclude: ["Test"]),
.testTarget(name: "Metron-Test", dependencies: ["Metron"], path: "./source/Metron/Test")
]
)
|
Fix the path to make-old.py | // Ensure that the LLVMIR hash of the 2nd compilation in batch mode
// is consistent no matter if the first one generates code or not.
// RUN: %empty-directory(%t)
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: touch -t 201901010101 %t/*.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// RUN: cp %t/main{,-old}.o
// RUN: cp %t/other{,-old}.o
// RUN: %{python} %S/Inputs/make-old.py %t/*.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// Ensure that code generation was not performed for other.swift
// RUN: ls -t %t | %FileCheck %s
// CHECK: other.swift
// CHECK: other.o
| // Ensure that the LLVMIR hash of the 2nd compilation in batch mode
// is consistent no matter if the first one generates code or not.
// RUN: %empty-directory(%t)
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: touch -t 201901010101 %t/*.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// RUN: cp %t/main{,-old}.o
// RUN: cp %t/other{,-old}.o
// RUN: %{python} %S/../Inputs/make-old.py %t/*.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// Ensure that code generation was not performed for other.swift
// RUN: ls -t %t | %FileCheck %s
// CHECK: other.swift
// CHECK: other.o
|
Add conversion with functional operators for deserialization | //
// FirebaseModel+Extension.swift
// FirebaseCommunity
//
// Created by Victor Alisson on 15/08/17.
//
import Foundation
import FirebaseCommunity
public extension FirebaseModel {
typealias JSON = [String: Any]
internal static var classPath: DatabaseReference {
return reference.child(Self.className)
}
static var reference: DatabaseReference {
return Database.database().reference()
}
internal static var className: String {
return String(describing: self)
}
internal static var autoId: String {
return Self.reference.childByAutoId().key
}
func toJSONObject() -> JSON? {
return toJSON()
}
}
| //
// FirebaseModel+Extension.swift
// FirebaseCommunity
//
// Created by Victor Alisson on 15/08/17.
//
import Foundation
import FirebaseCommunity
public extension FirebaseModel {
typealias JSON = [String: Any]
internal static var classPath: DatabaseReference {
return reference.child(Self.className)
}
static var reference: DatabaseReference {
return Database.database().reference()
}
internal static var className: String {
return String(describing: self)
}
internal static var autoId: String {
return Self.reference.childByAutoId().key
}
func toJSONObject() -> JSON? {
return toJSON()
}
internal static func getFirebaseModels(_ snapshot: DataSnapshot) -> [Self]? {
let dataSnapshot = snapshot.children.allObjects as? [DataSnapshot]
let keys = dataSnapshot?.map({$0.key})
let arraySelf = dataSnapshot?.flatMap({Self.deserialize(from: $0.value as? NSDictionary)})
if let firebaseModels = arraySelf {
for firebaseModel in firebaseModels {keys?.forEach({firebaseModel.key = $0})}
}
return arraySelf
}
}
|
Add a test for circular protocol inheritance through a typealias | // RUN: %target-typecheck-verify-swift
// With a bit of effort, we could make this work -- but for now, let's just
// not crash.
protocol P {
var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'; do you want to add a stub?}}
}
struct S : P { // expected-error {{type 'S' does not conform to protocol 'P'}}
static var x = 0 // expected-note {{candidate operates on a type, not an instance as required}}
var x = S.x // expected-note {{candidate references itself}}
}
| // RUN: %target-typecheck-verify-swift
// With a bit of effort, we could make this work -- but for now, let's just
// not crash.
protocol P {
var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'; do you want to add a stub?}}
}
struct S : P { // expected-error {{type 'S' does not conform to protocol 'P'}}
static var x = 0 // expected-note {{candidate operates on a type, not an instance as required}}
var x = S.x // expected-note {{candidate references itself}}
}
// FIXME: Lousy diagnostics on this case.
protocol SR9224_Foo: SR9224_Foobar {} // expected-error 2 {{protocol 'SR9224_Foo' refines itself}}
protocol SR9224_Bar: SR9224_Foobar {} // expected-error {{protocol 'SR9224_Bar' refines itself}} expected-note {{protocol 'SR9224_Bar' declared here}}
typealias SR9224_Foobar = SR9224_Foo & SR9224_Bar |
Allow perf test-case for rdar://74035425 to run only on macOS | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan
struct Value {
let debugDescription: String
}
func test(values: [[Value]]) -> String {
"[" + "" + values.map({ "[" + $0.map({ $0.debugDescription }).joined(separator: ", ") + "]" }).joined(separator: ", ") + "]"
}
| // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan
// REQUIRES: OS=macosx
struct Value {
let debugDescription: String
}
func test(values: [[Value]]) -> String {
"[" + "" + values.map({ "[" + $0.map({ $0.debugDescription }).joined(separator: ", ") + "]" }).joined(separator: ", ") + "]"
}
|
Update application didiFinishLaunching method with Swift 3 syntax | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
| ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
|
Make popPush public and generic. | //
// PopPushAlgorithm.swift
// TinyRedux
//
// Created by Daniel Tartaglia on 3/18/17.
// Copyright © 2017 Daniel Tartaglia. All rights reserved.
//
import Foundation
func popPush(current: [String], target: [String], pop: (String) -> Void, push: (String) -> Void) {
var count = current.count
if let indexOfChange = Array(zip(current, target)).index(where: { $0 != $1 }) {
while count > indexOfChange {
count -= 1
pop(current[count])
}
}
while count > target.count {
count -= 1
pop(current[count])
}
while count < target.count {
push(target[count])
count += 1
}
}
| //
// PopPushAlgorithm.swift
// TinyRedux
//
// Created by Daniel Tartaglia on 3/18/17.
// Copyright © 2017 Daniel Tartaglia. All rights reserved.
//
import Foundation
public
func popPush<T>(current: [T], target: [T], pop: (T) -> Void, push: (T) -> Void) where T: Equatable {
var count = current.count
if let indexOfChange = Array(zip(current, target)).index(where: { $0 != $1 }) {
while count > indexOfChange {
count -= 1
pop(current[count])
}
}
while count > target.count {
count -= 1
pop(current[count])
}
while count < target.count {
push(target[count])
count += 1
}
}
|
Add check for post data | import Vapor
import HTTP
import Foundation
final class PostController: ResourceRepresentable {
func index(request: Request) throws -> ResponseRepresentable {
// get all the post objects from the database
return try Post.all().makeNode().converted(to: JSON.self)
}
func create(request: Request) throws -> ResponseRepresentable {
var post = try request.post()
post.id = UUID().uuidString.makeNode()
try post.save()
return post
}
func show(request: Request, post: Post) throws -> ResponseRepresentable {
return post
}
func delete(request: Request, post: Post) throws -> ResponseRepresentable {
try post.delete()
return JSON([:])
}
func update(request: Request, post: Post) throws -> ResponseRepresentable {
let new = try request.post()
var post = post
post.content = new.content
try post.save()
return post
}
func makeResource() -> Resource<Post> {
return Resource(
index: index,
store: create,
show: show,
modify: update,
destroy: delete
)
}
}
extension Request {
func post() throws -> Post {
guard let json = json else { throw Abort.badRequest }
return try Post(node: json)
}
}
| import Vapor
import HTTP
import Foundation
final class PostController: ResourceRepresentable {
func index(request: Request) throws -> ResponseRepresentable {
// get all the post objects from the database
return try Post.all().makeNode().converted(to: JSON.self)
}
func create(request: Request) throws -> ResponseRepresentable {
var post = try request.post()
post.id = UUID().uuidString.makeNode()
try post.save()
return post
}
func show(request: Request, post: Post) throws -> ResponseRepresentable {
return post
}
func delete(request: Request, post: Post) throws -> ResponseRepresentable {
try post.delete()
return JSON([:])
}
func update(request: Request, post: Post) throws -> ResponseRepresentable {
let new = try request.post()
var post = post
post.content = new.content
try post.save()
return post
}
func makeResource() -> Resource<Post> {
return Resource(
index: index,
store: create,
show: show,
modify: update,
destroy: delete
)
}
}
extension Request {
func post() throws -> Post {
guard let json = json,
let _ = json["title"]?.string,
let _ = json["content"]?.string,
let _ = json["author"]?.string else { throw Abort.badRequest }
return try Post(node: json)
}
}
|
Update Table of Content for doc playground | /*:
# FormationLayout
----

## How To Use
- Open **Documentation/Doc.xcworkspace**.
- Build the **FormationLayout-iOS** scheme (⌘+B).
- Open **Doc** playground in the **Project navigator**.
- Click "Show Result" button at the most right side of each `demo` line.

## Table of Content
- [FormationLayout](FormationLayout)
- [Anchors](Anchors)
- [Helpers](Helpers)
- [Pin](Pin)
- [Group](Group)
- [Condition](Condition)
----
[Next](@next)
*/
| /*:
# FormationLayout
----

## How To Use
- Open **Documentation/Doc.xcworkspace**.
- Build the **FormationLayout-iOS** scheme (⌘+B).
- Open **Doc** playground in the **Project navigator**.
- Click "Show Result" button at the most right side of each `demo` line.

## Table of Content
- [FormationLayout](FormationLayout)
- [Anchors](Anchors)
- [Helpers](Helpers)
- [Pin](Pin)
- [Abreast](Abreast)
- [Group](Group)
- [Condition](Condition)
- [Priority](Priority)
----
[Next](@next)
*/
|
Remove public param method, replace with paramAtIndex method. | public enum Method: String {
case CONNECT
case DELETE
case GET
case HEAD
case OPTIONS
case PATCH
case POST
case PUT
case TRACE
}
public struct Request {
let method: Method
let path: Path
let headers: [(String, String)]
let body: String? // FIXME: Data instead?
init(method: Method, path: Path, headers: [(String, String)] = [], body: String? = nil) {
self.method = method
self.path = path
self.headers = headers
self.body = body
}
// init(method: Method, path: String, headers: [(String, String)] = [], body: String? = nil) {
// self.init(method: method, path: Path(stringLiteral: path), headers: headers, body: body)
// }
}
public struct MatchedRequest {
public let request: Request
public let route: Route
public func param<T: PathType>(key: String) -> T? {
let wildcard = ":" + key
guard let wildcardIndex = route.path.indexOfWildcard(wildcard) else { return nil }
let value = request.path.components[wildcardIndex]
return T.fromString(value)
}
}
| public enum Method: String {
case CONNECT
case DELETE
case GET
case HEAD
case OPTIONS
case PATCH
case POST
case PUT
case TRACE
}
public struct Request {
let method: Method
let path: Path
let headers: [(String, String)]
let body: String? // FIXME: Data instead?
init(method: Method, path: Path, headers: [(String, String)] = [], body: String? = nil) {
self.method = method
self.path = path
self.headers = headers
self.body = body
}
// init(method: Method, path: String, headers: [(String, String)] = [], body: String? = nil) {
// self.init(method: method, path: Path(stringLiteral: path), headers: headers, body: body)
// }
}
public struct MatchedRequest {
public let request: Request
public let route: Route
internal func paramAtIndex<T: PathType>(index: Int) -> T {
let wildcardKey = route.path.wildcards[index]
return param(wildcardKey: wildcardKey)
}
private func param<T: PathType>(wildcardKey wildcardKey: String) -> T {
guard let wildcardIndex = route.path.indexOfWildcard(wildcardKey) else {
preconditionFailure("No wildcard with key \(wildcardKey)")
}
let value = request.path.components[wildcardIndex]
return T.fromString(value)!
}
}
|
Allow to pass objects around with slice model | //
// PieSliceModel.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
public class PieSliceModel: CustomDebugStringConvertible {
public let value: Double
public let color: UIColor
public init(value: Double, color: UIColor) {
self.value = value
self.color = color
}
public var debugDescription: String {
return "{value: \(value)}"
}
}
| //
// PieSliceModel.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
public class PieSliceModel: CustomDebugStringConvertible {
public let value: Double
public let color: UIColor
public let obj: Any? /// optional object to pass around e.g. to the layer's text generators
public init(value: Double, color: UIColor, obj: Any? = nil) {
self.value = value
self.color = color
self.obj = obj
}
public var debugDescription: String {
return "{value: \(value), obj: \(String(describing: obj))}"
}
}
|
Add a test of unapplied functions. | // Copyright (c) 2015 Rob Rix. All rights reserved.
import Tesseract
import XCTest
final class EnvironmentTests: XCTestCase {
func testNodeRepresentingConstantEvaluatesToConstant() {
let a = Identifier()
let graph = Graph(nodes: [ a: Node.Symbolic(Prelude["true"]!.0) ])
let evaluated = evaluate(graph, a)
assertEqual(assertNotNil(assertRight(evaluated)?.constant()), true)
}
}
| // Copyright (c) 2015 Rob Rix. All rights reserved.
import Tesseract
import XCTest
final class EnvironmentTests: XCTestCase {
func testNodeRepresentingConstantEvaluatesToConstant() {
let a = Identifier()
let graph = Graph(nodes: [ a: Node.Symbolic(Prelude["true"]!.0) ])
let evaluated = evaluate(graph, a)
assertEqual(assertNotNil(assertRight(evaluated)?.constant()), true)
}
func testNodeRepresentingFunctionWithNoInputsEvaluatesToFunction() {
let a = Identifier()
let graph = Graph(nodes: [ a: Node.Symbolic(Prelude["identity"]!.0) ])
let evaluated = evaluate(graph, a)
assertEqual(assertNotNil(assertRight(evaluated)?.function()).map { $0(1) }, 1)
}
}
|
Document support for Swift 3 and 4 | // swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "Regex"
)
| // swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "Regex",
swiftLanguageVersions: [3, 4]
)
|
Reset database before each test | import HTTP
import Vapor
import XCTest
@testable import App
class PostRequestTests: TestCase {
let droplet = try! Droplet.testable()
func testCreate() throws {
let testContent = "test content"
let requestBody = try Body(JSON(node: ["content": testContent]))
let request = Request(method: .post,
uri: "/posts",
headers: ["Content-Type": "application/json"],
body: requestBody)
try droplet.testResponse(to: request)
.assertStatus(is: .ok)
.assertJSON("id", passes: { json in json.int != nil })
.assertJSON("content", equals: testContent)
}
func testList() throws {
try Post(content: "List test 1").save()
try Post(content: "List test 2").save()
let response = try droplet.testResponse(to: .get, at: "/posts")
XCTAssertEqual(response.status, .ok)
guard let json = response.json else {
XCTFail("Error getting JSON from response \(response)")
return
}
guard let recordArray = json.array else {
XCTFail("expected response json to be an array")
return
}
XCTAssertEqual(recordArray.count, 2)
XCTAssertEqual(recordArray.first?.object?["content"]?.string, "List test 1")
}
}
| import HTTP
import Vapor
import XCTest
@testable import App
class PostRequestTests: TestCase {
let droplet = try! Droplet.testable()
override func setUp() {
super.setUp()
try! Post.all().forEach { try $0.delete() }
}
func testCreate() throws {
let testContent = "test content"
let requestBody = try Body(JSON(node: ["content": testContent]))
let request = Request(method: .post,
uri: "/posts",
headers: ["Content-Type": "application/json"],
body: requestBody)
try droplet.testResponse(to: request)
.assertStatus(is: .ok)
.assertJSON("id", passes: { json in json.int != nil })
.assertJSON("content", equals: testContent)
}
func testList() throws {
try Post(content: "List test 1").save()
try Post(content: "List test 2").save()
let response = try droplet.testResponse(to: .get, at: "/posts")
XCTAssertEqual(response.status, .ok)
guard let json = response.json else {
XCTFail("Error getting JSON from response \(response)")
return
}
guard let recordArray = json.array else {
XCTFail("expected response json to be an array")
return
}
XCTAssertEqual(recordArray.count, 2)
XCTAssertEqual(recordArray.first?.object?["content"]?.string, "List test 1")
}
}
|
Test the elaboration of checked function types. | // Copyright © 2015 Rob Rix. All rights reserved.
final class ElaborationTests: XCTestCase {
func testInfersTheTypeOfType() {
let term: Term = .Type
assert(try? term.elaborateType(nil, [:], [:]), ==, .Unroll(.Type(1), .Identity(.Type(0))))
}
}
import Assertions
import Manifold
import XCTest
| // Copyright © 2015 Rob Rix. All rights reserved.
final class ElaborationTests: XCTestCase {
func testInfersTheTypeOfType() {
let term: Term = .Type
assert(try? term.elaborateType(nil, [:], [:]), ==, .Unroll(.Type(1), .Identity(.Type(0))))
}
func testChecksLambdasAgainstFunctionTypes() {
assert(try? Term.Lambda(.Local(0), .Type, 0).elaborateType(.Type --> .Type, [:], [:]), ==, .Unroll(.Type --> .Type, .Identity(.Lambda(.Unroll(.Type, .Identity(.Type(0))), .Unroll(.Type, .Abstraction(.Local(0), .Unroll(.Type, .Variable(.Local(0)))))))))
}
}
import Assertions
import Manifold
import XCTest
|
Add more CCGRect manipulation functions | import CoreGraphics
/// Swift extensions to CGRect
public extension CGRect {
/// The rectangle stripped of any origin information, marking its bounds
var bounds: CGRect {
var bounds = self
bounds.origin = CGPoint()
return bounds
}
/// Convenience initializer to create a CGRect with only a CGPoint
init(origin: CGPoint) {
self.origin = origin
self.size = CGSize()
}
/// Convenience initializer to create a CGRect with only a CGSize
init(size: CGSize) {
self.origin = CGPoint()
self.size = size
}
/// Create a new rect by changing this rect's origin property
func rectWithOrigin(origin: CGPoint) -> CGRect {
var rect = self
rect.origin = origin
return rect
}
/// Create a new rect by changing this rect's size property
func rectWithSize(size: CGSize) -> CGRect {
var rect = self
rect.size = size
return rect
}
}
| import CoreGraphics
/// Swift extensions to CGRect
public extension CGRect {
/// The rectangle stripped of any origin information, marking its bounds
var bounds: CGRect {
var bounds = self
bounds.origin = CGPoint()
return bounds
}
/// Convenience initializer to create a CGRect with only a CGPoint
init(origin: CGPoint) {
self.origin = origin
self.size = CGSize()
}
/// Convenience initializer to create a CGRect with only a CGSize
init(size: CGSize) {
self.origin = CGPoint()
self.size = size
}
/// Create a new rect by changing this rect's origin property
func rectWithOrigin(origin: CGPoint) -> CGRect {
var rect = self
rect.origin = origin
return rect
}
/// Create a new rect by changing this rect's size property
func rectWithSize(size: CGSize) -> CGRect {
var rect = self
rect.size = size
return rect
}
/// Create a new rect by changing this rect's width
func rectWithWidth(width: CGFloat) -> CGRect {
var rect = self
rect.size.width = width
return rect
}
/// Create a new rect by changing this rect's height
func rectWithHeight(height: CGFloat) -> CGRect {
var rect = self
rect.size.height = height
return rect
}
/// Create a new rect by resizing this rect
func resizedRectByX(widthChange: CGFloat, y heightChange: CGFloat) -> CGRect {
var rect = self
rect.size.width += widthChange
rect.size.height += heightChange
return rect
}
}
|
Remove code to make starter project | import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: # Pollster
//: __Challenge:__ Complete the following class to simulate a polling mechanism using `dispatch_after()`
class Pollster {
let callback: (String) -> ()
private var active: Bool = false
private let isoloationQueue = dispatch_queue_create("com.raywenderlich.pollster.isolation", DISPATCH_QUEUE_SERIAL)
init(callback: (String) -> ()) {
self.callback = callback
}
func start() {
print("Start polling")
active = true
dispatch_async(isoloationQueue) {
self.makeRequest()
}
}
func stop() {
active = false
print("Stop polling")
}
private func makeRequest() {
if active {
callback("\(NSDate())")
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1))
dispatch_after(dispatchTime, isoloationQueue) {
self.makeRequest()
}
}
}
}
//: The following will test the completed class
let pollster = Pollster(callback: { print($0) })
pollster.start()
delay(5) {
pollster.stop()
delay(2) {
print("Finished")
XCPlaygroundPage.currentPage.finishExecution()
}
}
| import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: # Pollster
//: __Challenge:__ Complete the following class to simulate a polling mechanism using `dispatch_after()`
class Pollster {
let callback: (String) -> ()
init(callback: (String) -> ()) {
self.callback = callback
}
func start() {
print("Start polling")
}
func stop() {
print("Stop polling")
}
private func makeRequest() {
callback("\(NSDate())")
}
}
//: The following will test the completed class
let pollster = Pollster(callback: { print($0) })
pollster.start()
delay(5) {
pollster.stop()
delay(2) {
print("Finished")
XCPlaygroundPage.currentPage.finishExecution()
}
}
|
Adjust socket buffer size to MTU and set deadline to forever | import UDP
public class OSCServer: MessageDispatcher {
public typealias Message = OSCMessage
let socket: UDPSocket
let dispatcher = OSCMessageDispatcher
public init(port: Int) throws {
socket = try UDPSocket(ip: IP(port: port))
}
// override
public func register(pattern: String, _ listener: @escaping (OSCMessage) -> Void) {
dispatcher.register(pattern: pattern, listener)
}
// override
public func unregister(pattern: String) {
dispatcher.unregister(pattern: pattern)
}
// override
public func dispatch(message: OSCMessage) {
dispatcher.dispatch(message: message)
}
public func listen() {
let deadline = 5.seconds.fromNow()
while true {
do {
let (buffer, _) = try socket.read(upTo: 4096, deadline: deadline)
let msg = OSCMessage(data: buffer.bytes )
/// might crash during dispatch if message is garbled
dispatcher.dispatch(message: msg)
} catch {
// DISPLAY SOME ERROR
print("Failed to read message \(error)")
break
}
}
}
}
| import UDP
public class OSCServer: MessageDispatcher {
public typealias Message = OSCMessage
let socket: UDPSocket
let dispatcher = OSCMessageDispatcher
public init(port: Int) throws {
socket = try UDPSocket(ip: IP(port: port))
}
// override
public func register(pattern: String, _ listener: @escaping (OSCMessage) -> Void) {
dispatcher.register(pattern: pattern, listener)
}
// override
public func unregister(pattern: String) {
dispatcher.unregister(pattern: pattern)
}
// override
public func dispatch(message: OSCMessage) {
dispatcher.dispatch(message: message)
}
public func listen() {
while true {
do {
let (buffer, _) = try socket.read(upTo: 1536, deadline: .never)
let msg = OSCMessage(data: buffer.bytes )
/// might crash during dispatch if message is garbled
dispatcher.dispatch(message: msg)
} catch {
print("Failed to read message \(error)")
break
}
}
}
}
|
Add store property to app delegate | //
// AppDelegate.swift
// HomeControl
//
// Created by Julian Grosshauser on 06/11/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = .whiteColor()
return window
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window?.rootViewController = UINavigationController(rootViewController: SetupController())
window?.makeKeyAndVisible()
return true
}
}
| //
// AppDelegate.swift
// HomeControl
//
// Created by Julian Grosshauser on 06/11/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//MARK: Properties
var window: UIWindow? = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = .whiteColor()
return window
}()
private let store = Store()
//MARK: UIApplicationDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window?.rootViewController = UINavigationController(rootViewController: SetupController())
window?.makeKeyAndVisible()
return true
}
}
|
Edit comments to make them clearer. | //
// Networking.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/22/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import ReactiveCocoa
public protocol Networking {
/// Gets a `SignalProducer` emitting a JSON root element ( an array or dictionary).
func requestJSON(url: String, parameters: [String : AnyObject]?) -> SignalProducer<AnyObject, NetworkError>
/// Gets a `SignalProducer` emitting an `UIImage`.
func requestImage(url: String) -> SignalProducer<UIImage, NetworkError>
}
| //
// Networking.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/22/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import ReactiveCocoa
public protocol Networking {
/// Returns a `SignalProducer` emitting a JSON root element ( an array or dictionary).
func requestJSON(url: String, parameters: [String : AnyObject]?) -> SignalProducer<AnyObject, NetworkError>
/// Returns a `SignalProducer` emitting an `UIImage`.
func requestImage(url: String) -> SignalProducer<UIImage, NetworkError>
}
|
Add constant terms of a given value. | // Copyright (c) 2014 Rob Rix. All rights reserved.
enum Term {
case Parameter(String, Type)
case Return(String, Type)
}
| // Copyright (c) 2014 Rob Rix. All rights reserved.
enum Term {
case Parameter(String, Type)
case Return(String, Type)
case Constant(Value)
}
enum Value {
case Boolean(Swift.Bool)
case Integer(Swift.Int)
case String(Swift.String)
}
|
Remove the assumption set return. | // Copyright (c) 2015 Rob Rix. All rights reserved.
public func constraints(graph: Graph<Node>) -> (Term, assumptions: AssumptionSet, constraints: ConstraintSet) {
let parameters = Node.parameters(graph)
let returns = Node.returns(graph)
let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
return (reduce(parameters, returnType) {
.function(Term(), $0.0)
}, [:], [])
}
import Manifold
| // Copyright (c) 2015 Rob Rix. All rights reserved.
public func constraints(graph: Graph<Node>) -> (Term, constraints: ConstraintSet) {
let parameters = Node.parameters(graph)
let returns = Node.returns(graph)
let returnType: Term = reduce(returns, nil) { $0.0.map { .product(Term(), $0) } ?? Term() } ?? .Unit
return (reduce(parameters, returnType) {
.function(Term(), $0.0)
}, [])
}
import Manifold
|
Add a Task convenience for unit tests | //
// Fixtures.swift
// DeferredTests
//
// Created by Zachary Waldowski on 6/10/15.
// Copyright © 2014-2016 Big Nerd Ranch. Licensed under MIT.
//
import XCTest
@testable import Deferred
#if SWIFT_PACKAGE
import Result
#endif
let TestTimeout: NSTimeInterval = 15
enum Error: ErrorType {
case First
case Second
case Third
}
extension ResultType {
var value: Value? {
return withValues(ifSuccess: { $0 }, ifFailure: { _ in nil })
}
var error: ErrorType? {
return withValues(ifSuccess: { _ in nil }, ifFailure: { $0 })
}
}
| //
// Fixtures.swift
// DeferredTests
//
// Created by Zachary Waldowski on 6/10/15.
// Copyright © 2014-2016 Big Nerd Ranch. Licensed under MIT.
//
import XCTest
@testable import Deferred
#if SWIFT_PACKAGE
import Result
#endif
let TestTimeout: NSTimeInterval = 15
enum Error: ErrorType {
case First
case Second
case Third
}
extension XCTestCase {
func waitForTaskToComplete<T>(task: Task<T>) -> TaskResult<T>! {
let expectation = expectationWithDescription("task completed")
var result: TaskResult<T>?
task.uponMainQueue { [weak expectation] in
result = $0
expectation?.fulfill()
}
waitForExpectationsWithTimeout(TestTimeout, handler: nil)
return result
}
}
extension ResultType {
var value: Value? {
return withValues(ifSuccess: { $0 }, ifFailure: { _ in nil })
}
var error: ErrorType? {
return withValues(ifSuccess: { _ in nil }, ifFailure: { $0 })
}
}
|
Remove non-ascii dash character from a comment. | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Wrapper for a contiguous array of T. UnsafeArray is both a
/// Collection—which is multi-pass if you use indices or call
/// generate() on it—and a Generator, which can only be assumed to be
/// single-pass. It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {
var startIndex: Int {
return 0
}
var endIndex: Int {
return _end - _position
}
subscript(i: Int) -> T {
assert(i >= 0)
assert(i < endIndex)
return (_position + i).get()
}
init(start: UnsafePointer<T>, length: Int) {
_position = start
_end = start + length
}
mutating func next() -> T? {
if _position == _end {
return .None
}
return .Some((_position++).get())
}
func generate() -> UnsafeArray {
return self
}
var _position, _end: UnsafePointer<T>
}
| //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Wrapper for a contiguous array of T. UnsafeArray is both a
/// Collection-which is multi-pass if you use indices or call
/// generate() on it-and a Generator, which can only be assumed to be
/// single-pass. It's not clear how well this combination will work
/// out, or whether all Collections should also be Streams; consider
/// this an experiment.
struct UnsafeArray<T> : Collection, Generator {
var startIndex: Int {
return 0
}
var endIndex: Int {
return _end - _position
}
subscript(i: Int) -> T {
assert(i >= 0)
assert(i < endIndex)
return (_position + i).get()
}
init(start: UnsafePointer<T>, length: Int) {
_position = start
_end = start + length
}
mutating func next() -> T? {
if _position == _end {
return .None
}
return .Some((_position++).get())
}
func generate() -> UnsafeArray {
return self
}
var _position, _end: UnsafePointer<T>
}
|
Update transport to extend message transfer. | //
// Transport.swift
// Transport
//
// Created by Paul Young on 26/08/2014.
// Copyright (c) 2014 CocoaFlow. All rights reserved.
//
import JSONLib
public protocol Transport {
/**
Send a message from the runtime.
:param: channel
:param: topic
:param: payload
*/
func send(channel: String, _ topic: String, _ payload: JSON) -> Void
}
| //
// Transport.swift
// Transport
//
// Created by Paul Young on 26/08/2014.
// Copyright (c) 2014 CocoaFlow. All rights reserved.
//
import MessageTransfer
public protocol Transport: MessageSenderWorkaround {
init(_ messageReceiver: MessageReceiverWorkaround)
}
|
Mark package as macos only | // swift-tools-version:5.0
// Managed by ice
import PackageDescription
let package = Package(
name: "Shout",
products: [
.library(name: "Shout", targets: ["Shout"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/BlueSocket", from: "1.0.46"),
],
targets: [
.systemLibrary(name: "CSSH", pkgConfig: "libssh2"),
.target(name: "Shout", dependencies: ["CSSH", "Socket"]),
.testTarget(name: "ShoutTests", dependencies: ["Shout"]),
]
)
| // swift-tools-version:5.0
// Managed by ice
import PackageDescription
let package = Package(
name: "Shout",
platforms: [
.macOS(.v10_10)
],
products: [
.library(name: "Shout", targets: ["Shout"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/BlueSocket", from: "1.0.46"),
],
targets: [
.systemLibrary(name: "CSSH", pkgConfig: "libssh2"),
.target(name: "Shout", dependencies: ["CSSH", "Socket"]),
.testTarget(name: "ShoutTests", dependencies: ["Shout"]),
]
)
|
Update SIL optimizer tests for Optional: Equatable conformance. | // RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -module-name=test -emit-sil -o - -verify | %FileCheck %s
// CHECK-LABEL: sil {{.*}} @{{.*}}generic_func
// CHECK: switch_enum_addr
// CHECK: return
func generic_func<T>(x: [T]?) -> Bool {
return x == nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_rhs_nil(x: [Int]?) -> Bool {
return x == nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_lhs_nil(x: [Int]?) -> Bool {
return nil == x
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_non_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_rhs_non_nil(x: [Int]?) -> Bool {
return x != nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_non_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_lhs_non_nil(x: [Int]?) -> Bool {
return nil != x
}
| // RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -module-name=test -emit-sil -o - -verify | %FileCheck %s
struct X { }
// CHECK-LABEL: sil {{.*}} @{{.*}}generic_func
// CHECK: switch_enum_addr
// CHECK: return
func generic_func<T>(x: [T]?) -> Bool {
return x == nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_rhs_nil(x: [X]?) -> Bool {
return x == nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_lhs_nil(x: [X]?) -> Bool {
return nil == x
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_non_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_rhs_non_nil(x: [X]?) -> Bool {
return x != nil
}
// CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_non_nil
// CHECK: switch_enum_addr
// CHECK: return
func array_func_lhs_non_nil(x: [X]?) -> Bool {
return nil != x
}
|
Add font name to decorationPreference | //
// DecorationPreference.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 1/16/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
open class DecorationPreference : NSObject{
var baseColor: UIColor = UIColor.purple
var textColor: UIColor = UIColor.black
var fontName: String?
public func setBaseColor(color: UIColor){
baseColor = color
}
public func enableDarkFont(){
textColor = UIColor.black
}
public func enableLightFont(){
textColor = UIColor.white
}
public func setFontName(fontName: String){
}
public func getBaseColor() -> UIColor {
return baseColor
}
public func getTextColor() -> UIColor {
return textColor
}
}
| //
// DecorationPreference.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 1/16/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
open class DecorationPreference : NSObject{
var baseColor: UIColor = UIColor.purple
var textColor: UIColor = UIColor.black
var fontName: String = ".SFUIDisplay-Regular"
public func setBaseColor(color: UIColor){
baseColor = color
}
public func enableDarkFont(){
textColor = UIColor.black
}
public func enableLightFont(){
textColor = UIColor.white
}
public func setFontName(fontName: String){
self.fontName = fontName
}
public func getBaseColor() -> UIColor {
return baseColor
}
public func getTextColor() -> UIColor {
return textColor
}
public func getFontName() -> String {
return fontName
}
}
|
Add fmap operator for List<T> and | //
// Functor.swift
// tibasic
//
// Created by Michael Welch on 7/22/15.
// Copyright © 2015 Michael Welch. All rights reserved.
//
import Foundation
func fmap<ParserA:ParserType, A, B where ParserA.TokenType==A>(f:A->B, _ t:ParserA) -> Parser<B> {
return t.bind { success(f($0)) }
}
// Like Haskell fmap, <$>
public func <§><ParserA:ParserType, A, B where ParserA.TokenType==A>(lhs:A->B, rhs:ParserA) -> Parser<B> {
return fmap(lhs, rhs)
}
public func <§><A,B>(lhs:A->B, rhs:A?) -> B? {
return rhs.map(lhs)
}
// Tuple Functor on rhs
public func <§><A,B,C>(lhs:A->B, rhs:(A,C)) -> (B,C) {
return (lhs(rhs.0), rhs.1)
} | //
// Functor.swift
// tibasic
//
// Created by Michael Welch on 7/22/15.
// Copyright © 2015 Michael Welch. All rights reserved.
//
import Foundation
func fmap<ParserA:ParserType, A, B where ParserA.TokenType==A>(f:A->B, _ t:ParserA) -> Parser<B> {
return t.bind { success(f($0)) }
}
// Like Haskell fmap, <$>
public func <§><ParserA:ParserType, A, B where ParserA.TokenType==A>(lhs:A->B, rhs:ParserA) -> Parser<B> {
return fmap(lhs, rhs)
}
public func <§><A,B>(lhs:A->B, rhs:A?) -> B? {
return rhs.map(lhs)
}
public func <§><A,B>(lhs:A->B, rhs:[A]) -> [B] {
return rhs.map(lhs)
}
// Tuple Functor on rhs
public func <§><A,B,C>(lhs:A->B, rhs:(A,C)) -> (B,C) {
return (lhs(rhs.0), rhs.1)
}
public func <§><A,B>(lhs:A->B, rhs:List<A>) -> List<B> {
return (rhs.map(lhs))
}
extension List {
public func map<B>(f:T->B) -> List<B> {
return self.reduce(List<B>.Nil, combine: {List<B>.Cons(h: f($1), t: $0)})
}
} |
Change delete and deleteAll type to Void | // MARK: - Delete
public extension <%= model.name %> {
var delete: Bool {
get {
let deleteSQL = "DELETE FROM \(<%= model.name %>.tableName) \(itself)"
executeSQL(deleteSQL)
return true
}
}
static var deleteAll: Bool { get { return <%= model.relation_name %>().deleteAll } }
}
public extension <%= model.relation_name %> {
var delete: Bool { get { return deleteAll } }
var deleteAll: Bool {
get {
self.result.forEach { $0.delete }
return true
}
}
}
| // MARK: - Delete
public extension <%= model.name %> {
var delete: Void {
get {
let deleteSQL = "DELETE FROM \(<%= model.name %>.tableName) \(itself)"
executeSQL(deleteSQL)
}
}
static var deleteAll: Void { get { return <%= model.relation_name %>().deleteAll } }
}
public extension <%= model.relation_name %> {
var delete: Void { get { return deleteAll } }
var deleteAll: Void {
get {
self.result.forEach { $0.delete }
}
}
}
|
Remove unnecessary let for switch-case | //
// VersionCommand.swift
// SwiftCov
//
// Created by JP Simard on 2015-05-20.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Commandant
import Result
import SwiftCovFramework
struct VersionCommand: CommandType {
typealias ClientError = SwiftCovError
let verb = "version"
let function = "Display the current version of SwiftCov"
func run(mode: CommandMode) -> Result<(), CommandantError<SwiftCovError>> {
switch mode {
case let .Arguments:
let version = NSBundle(identifier: SwiftCovFrameworkBundleIdentifier)?.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
println(version!)
default:
break
}
return .success(())
}
}
| //
// VersionCommand.swift
// SwiftCov
//
// Created by JP Simard on 2015-05-20.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Commandant
import Result
import SwiftCovFramework
struct VersionCommand: CommandType {
typealias ClientError = SwiftCovError
let verb = "version"
let function = "Display the current version of SwiftCov"
func run(mode: CommandMode) -> Result<(), CommandantError<SwiftCovError>> {
switch mode {
case .Arguments:
let version = NSBundle(identifier: SwiftCovFrameworkBundleIdentifier)?.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
println(version!)
default:
break
}
return .success(())
}
}
|
Add support to indicate the bundle in which the Storyboard should be located | //
// Storyboard.swift
// BothamUI
//
// Created by Davide Mendolia on 03/12/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
public struct BothamStoryboard {
private let name: String
public init(name: String) {
self.name = name
}
private func storyboard(name: String) -> UIStoryboard {
return UIStoryboard(name: name, bundle: NSBundle.mainBundle())
}
public func initialViewController<T>() -> T {
let uiStoryboard = storyboard(name)
return uiStoryboard.instantiateInitialViewController() as! T
}
public func instantiateViewController<T>(viewControllerIdentifier: String) -> T {
let uiStoryboard = storyboard(name)
return uiStoryboard.instantiateViewControllerWithIdentifier(viewControllerIdentifier) as! T
}
public func instantiateViewController<T>() -> T {
return instantiateViewController(String(T.self))
}
} | //
// Storyboard.swift
// BothamUI
//
// Created by Davide Mendolia on 03/12/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
public struct BothamStoryboard {
private let name: String
private let bundle: NSBundle
public init(name: String, bundle: NSBundle = NSBundle.mainBundle()) {
self.name = name
self.bundle = bundle
}
private func storyboard(name: String, bundle: NSBundle) -> UIStoryboard {
return UIStoryboard(name: name, bundle: bundle)
}
public func initialViewController<T>() -> T {
let uiStoryboard = storyboard(name, bundle: bundle)
return uiStoryboard.instantiateInitialViewController() as! T
}
public func instantiateViewController<T>(viewControllerIdentifier: String) -> T {
let uiStoryboard = storyboard(name, bundle: bundle)
return uiStoryboard.instantiateViewControllerWithIdentifier(viewControllerIdentifier) as! T
}
public func instantiateViewController<T>() -> T {
return instantiateViewController(String(T.self))
}
} |
Add library path management in Application Manager | //
// ApplicationManager.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 13/02/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
final class ApplicationManager: BaseManager {
var UUID: String {
if let uuid = preferences.stringForKey("uuid") {
return uuid
}
let uuid = NSUUID().UUIDString
preferences.setObject(uuid, forKey: "uuid")
return uuid
}
var isInDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
var isInProduction: Bool {
return !isInDebug
}
var bundleIdentifier: String {
return NSBundle.mainBundle().bundleIdentifier ?? ""
}
var disablesIdleTimer: Bool {
get {
return UIApplication.sharedApplication().idleTimerDisabled
}
set {
UIApplication.sharedApplication().idleTimerDisabled = newValue
}
}
func handleFirstLaunch() {
// if app hasn't been launched before
if !preferences.boolForKey("already_launched") {
preferences.setBool(true, forKey: "already_launched")
// delete all pairing keychain items
PairingKeychainItem.destroyAll()
}
}
} | //
// ApplicationManager.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 13/02/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
final class ApplicationManager: BaseManager {
//lazy private var logger = { return Logger.sharedInstance("ApplicationManager") }()
var UUID: String {
if let uuid = preferences.stringForKey("uuid") {
return uuid
}
let uuid = NSUUID().UUIDString
preferences.setObject(uuid, forKey: "uuid")
return uuid
}
var isInDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
var isInProduction: Bool {
return !isInDebug
}
var bundleIdentifier: String {
return NSBundle.mainBundle().bundleIdentifier ?? ""
}
var disablesIdleTimer: Bool {
get {
return UIApplication.sharedApplication().idleTimerDisabled
}
set {
UIApplication.sharedApplication().idleTimerDisabled = newValue
}
}
var libraryDirectoryPath: String {
return NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String
}
// MARK: Utilities
func handleFirstLaunch() {
// if app hasn't been launched before
if !preferences.boolForKey("already_launched") {
preferences.setBool(true, forKey: "already_launched")
// delete all pairing keychain items
PairingKeychainItem.destroyAll()
}
}
func printLibraryPathIfNeeded() {
if self.isInDebug {
Logger.sharedInstance(self.className()).info(libraryDirectoryPath)
}
}
} |
Add label to username associated value | //
// ApiUrls.swift
// GithubClient
//
// Created by Eduardo Arenas on 8/5/17.
// Copyright © 2017 GameChanger. All rights reserved.
//
import Foundation
enum ApiUrl {
private static let baseURL = "https://api.github.com/"
case user(String)
case users
var fullPath: String {
switch self {
case .user(let username): return ApiUrl.fullPath(from: ["users", username])
case .users: return ApiUrl.fullPath(from: ["users"])
}
}
static func fullPath(from components: [CustomStringConvertible]) -> String {
let endpointPath = components.map({ $0.description }).joined(separator: "/")
return baseURL.appending(endpointPath)
}
}
| //
// ApiUrls.swift
// GithubClient
//
// Created by Eduardo Arenas on 8/5/17.
// Copyright © 2017 GameChanger. All rights reserved.
//
import Foundation
enum ApiUrl {
private static let baseURL = "https://api.github.com/"
// Users
case user(username: String)
case users
var fullPath: String {
switch self {
case .user(let username): return ApiUrl.fullPath(from: ["users", username])
case .users: return ApiUrl.fullPath(from: ["users"])
}
}
static func fullPath(from components: [CustomStringConvertible]) -> String {
let endpointPath = components.map({ $0.description }).joined(separator: "/")
return baseURL.appending(endpointPath)
}
}
|
Update dependencies for Vapor 2 | import PackageDescription
let package = Package(
name: "JWTKeychain",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
.Package(url: "https://github.com/vapor/mysql-provider.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
.Package(url: "https://github.com/vapor/jwt-provider.git", Version(1,0,0, prereleaseIdentifiers: ["beta"])),
.Package(url: "https://github.com/vapor/bcrypt.git", Version(1,0,0, prereleaseIdentifiers: ["beta"])),
.Package(url: "https://github.com/nodes-vapor/sugar.git", Version(2,0,0, prereleaseIdentifiers: ["beta"])),
.Package(url: "https://github.com/nodes-vapor/flash.git", Version(1,0,0, prereleaseIdentifiers: ["beta"]))
]
)
| import PackageDescription
let package = Package(
name: "JWTKeychain",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2),
.Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2),
// TODO: update url once PR is accepted
.Package(url: "https://github.com/siemensikkema/jwt-provider.git", majorVersion: 1),
.Package(url: "https://github.com/vapor/bcrypt.git", majorVersion: 1),
.Package(url: "https://github.com/nodes-vapor/sugar.git", majorVersion: 2),
.Package(url: "https://github.com/nodes-vapor/flash.git", majorVersion: 1)
]
)
|
Fix whitespaces for a closure | // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-sil -module-name coverage_member_closure %s | FileCheck %s
class C {
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_member_closure.C.__allocating_init
init() {
if (false) { // CHECK: [[@LINE]]:16 -> [[@LINE+2]]:6 : 1
// ...
}
}
// Closures in members show up at the end of the constructor's map.
// CHECK-NOT: sil_coverage_map
// CHECK: [[@LINE+1]]:55 -> [[@LINE+1]]:77 : 2
var completionHandler: (String, [String]) -> Void = {(foo, bar) in return}
}
| // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-sil -module-name coverage_member_closure %s | FileCheck %s
class C {
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_member_closure.C.__allocating_init
init() {
if (false) { // CHECK: [[@LINE]]:16 -> [[@LINE+2]]:6 : 1
// ...
}
}
// Closures in members show up at the end of the constructor's map.
// CHECK-NOT: sil_coverage_map
// CHECK: [[@LINE+1]]:55 -> [[@LINE+1]]:79 : 2
var completionHandler: (String, [String]) -> Void = { (foo, bar) in return }
}
|
Make test-case for rdar://problem/20859567 slightly more complicated | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
struct Stringly {
init(string: String) {}
init(format: String, _ args: Any...) {}
init(stringly: Stringly) {}
}
[Int](0..<1).map {
print(Stringly(format: "%d: ", $0 * 2) + ["a", "b", "c", "d"][$0 * 2] + ",")
// expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}}
}
| // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
struct Stringly {
init(string: String) {}
init(format: String, _ args: Any...) {}
init(stringly: Stringly) {}
}
[Int](0..<1).map {
// expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}}
print(Stringly(format: "%d: ", $0 * 2 * 42) + ["a", "b", "c", "d", "e", "f", "g"][$0 * 2] + ",")
}
|
Set log level to min | import UIKit
import Firebase
@UIApplicationMain
class AppDelegate:UIResponder, UIApplicationDelegate
{
var window:UIWindow?
func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey:Any]?) -> Bool
{
FirebaseApp.configure()
let window:UIWindow = UIWindow(frame:UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
let parent:ControllerParent = ControllerParent()
window.rootViewController = parent
return true
}
}
| import UIKit
import Firebase
@UIApplicationMain
class AppDelegate:UIResponder, UIApplicationDelegate
{
var window:UIWindow?
func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey:Any]?) -> Bool
{
FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.min)
FirebaseApp.configure()
let window:UIWindow = UIWindow(frame:UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
let parent:ControllerParent = ControllerParent()
window.rootViewController = parent
return true
}
}
|
Make sure Route tests succeed | //
// TestRoute.swift
// SweetRouter
//
// Created by Oleksii on 17/03/2017.
// Copyright © 2017 ViolentOctopus. All rights reserved.
//
import XCTest
import SweetRouter
class TestRoute: XCTestCase {
func testUrlRouteEquatable() {
XCTAssertEqual(URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")), URL.Route(path: ["myPath"], query: ("user", "some"), ("date", "12.04.02")))
XCTAssertNotEqual(URL.Route(path: ["myPath"]), URL.Route(path: ["myPath"], query: ("user", nil)))
}
}
| //
// TestRoute.swift
// SweetRouter
//
// Created by Oleksii on 17/03/2017.
// Copyright © 2017 ViolentOctopus. All rights reserved.
//
import XCTest
import SweetRouter
class TestRoute: XCTestCase {
func testUrlRouteEquatable() {
XCTAssertEqual(URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")), URL.Route(path: ["myPath"], query: ("user", nil), ("date", "12.04.02")))
XCTAssertNotEqual(URL.Route(path: ["myPath"]), URL.Route(path: ["myPath"], query: ("user", nil)))
}
}
|
Fix patients view controller to actually display patients in the list. | //
// BPETrackUsersViewController.swift
// BPApp
//
// Created by Chris Blackstone on 4/24/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import UIKit
class BPETrackUsersViewControler: UITableViewController {
@IBAction func back() {
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Users", for: indexPath)
let titleLabel = cell.viewWithTag(10) as! UILabel
titleLabel.text = "Chris Blackstone"
return cell
}
}
| //
// BPETrackUsersViewController.swift
// BPApp
//
// Created by Chris Blackstone on 4/24/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import UIKit
class BPETrackUsersViewControler: UITableViewController {
@IBAction func back() {
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Config.patients.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Users", for: indexPath)
let titleLabel = cell.viewWithTag(10) as! UILabel
titleLabel.text = "\(Config.patients[indexPath.row].lastName), \(Config.patients[indexPath.row].firstName)"
return cell
}
}
|
Add initializer to NSRect by center point and size | //
// NSRect+PointHelpers.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 04/12/15.
// Copyright © 2015 Felipe Espinoza Dev. All rights reserved.
//
import Cocoa
extension NSRect {
init(p1: NSPoint, p2: NSPoint) {
origin = NSMakePoint(min(p1.x, p2.x), min(p1.y, p2.y))
size = NSSize(width: abs(p2.x - p1.x), height: abs(p2.y - p1.y))
}
var bottomLeftPoint: NSPoint { return origin }
var bottomRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y) }
var topRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y + size.height) }
var topLeftPoint: NSPoint { return NSMakePoint(origin.x, origin.y + size.height) }
var center: NSPoint { return NSMakePoint(origin.x + size.width / 2, origin.y + size.height / 2) }
var maxX: CGFloat { return origin.x + size.width }
var maxY: CGFloat { return origin.x + size.width }
} | //
// NSRect+PointHelpers.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 04/12/15.
// Copyright © 2015 Felipe Espinoza Dev. All rights reserved.
//
import Cocoa
extension NSRect {
init(p1: NSPoint, p2: NSPoint) {
origin = NSMakePoint(min(p1.x, p2.x), min(p1.y, p2.y))
size = NSSize(width: abs(p2.x - p1.x), height: abs(p2.y - p1.y))
}
init(center: NSPoint, size: NSSize) {
origin = NSMakePoint(center.x - size.width / 2, center.y - size.height / 2)
self.size = size
}
var bottomLeftPoint: NSPoint { return origin }
var bottomRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y) }
var topRightPoint: NSPoint { return NSMakePoint(origin.x + size.width, origin.y + size.height) }
var topLeftPoint: NSPoint { return NSMakePoint(origin.x, origin.y + size.height) }
var center: NSPoint { return NSMakePoint(origin.x + size.width / 2, origin.y + size.height / 2) }
var maxX: CGFloat { return origin.x + size.width }
var maxY: CGFloat { return origin.x + size.width }
} |
Change how to update the FirebaseModel | //
// Updatable+Extension.swift
// FirebaseCommunity
//
// Created by Victor Alisson on 16/08/17.
//
import Foundation
public extension Updatable where Self: FirebaseModel {
func update(completion: @escaping (_ error: Error?) -> Void) {
Self.path.updateChildValues(self.toJSON()) { (error, reference) in
completion(error)
}
}
}
| //
// Updatable+Extension.swift
// FirebaseCommunity
//
// Created by Victor Alisson on 16/08/17.
//
import Foundation
public extension Updatable where Self: FirebaseModel {
func update(completion: @escaping (_ error: Error?) -> Void) {
guard let key = self.key else {
return
}
Self.classPath.child(key).updateChildValues(toJSON()) { (error, reference) in
completion(error)
}
}
}
|
Remove unused change action in StackRoute for now | //
// StackViewController.swift
// Beeline
//
// Created by Karl Bowden on 5/01/2016.
// Copyright © 2016 Featherweight Labs. All rights reserved.
//
import UIKit
public class StackViewController: UINavigationController {
public enum TransitionAction {
case Pop(Segment)
case Push(Segment)
case Change(Segment)
}
public var currentStack: [Segment] = []
public func setStack(newStack: [Segment]) {
let transitionStack = ZippedStack(currentStack, newStack)
let stackActions = transitionActions(transitionStack)
performActions(stackActions)
currentStack = newStack
}
public func transitionActions(stack: ZippedStack<Segment>) -> [TransitionAction] {
let fromActions: [TransitionAction] = stack.from.reverse().map { .Pop($0) }
let toActions: [TransitionAction] = stack.to.map { .Push($0) }
return fromActions + toActions
}
public func performActions(actionStack: [TransitionAction]) {
for action in actionStack {
switch action {
case .Push(let segment):
pushViewController(segment.create(), animated: true)
case .Pop:
popViewControllerAnimated(true)
case .Change:
fatalError("No change event yet")
}
}
}
}
| //
// StackViewController.swift
// Beeline
//
// Created by Karl Bowden on 5/01/2016.
// Copyright © 2016 Featherweight Labs. All rights reserved.
//
import UIKit
public class StackViewController: UINavigationController {
public enum TransitionAction {
case Pop(Segment)
case Push(Segment)
}
public var currentStack: [Segment] = []
public func setStack(newStack: [Segment]) {
let transitionStack = ZippedStack(currentStack, newStack)
let stackActions = transitionActions(transitionStack)
performActions(stackActions)
currentStack = newStack
}
public func transitionActions(stack: ZippedStack<Segment>) -> [TransitionAction] {
let fromActions: [TransitionAction] = stack.from.reverse().map { .Pop($0) }
let toActions: [TransitionAction] = stack.to.map { .Push($0) }
return fromActions + toActions
}
public func performActions(actionStack: [TransitionAction]) {
for action in actionStack {
switch action {
case .Push(let segment):
pushViewController(segment.create(), animated: true)
case .Pop:
popViewControllerAnimated(true)
}
}
}
}
|
Make sendPost button the default | //
// AdianTests.swift
// AdianTests
//
// Created by Jeremy on 2015-12-02.
// Copyright © 2015 Jeremy W. Sherman. All rights reserved.
//
import XCTest
@testable import Adian
class ComposePostViewControllerTests: XCTestCase {
var composePostViewController: ComposePostViewController!
override func setUp() {
super.setUp()
composePostViewController = ComposePostViewController.instantiate()
}
override func tearDown() {
super.tearDown()
}
func testKnowsItsStoryboardID() {
// passes if we don't explode when as!'ing the ComposePostViewController in setUp()
}
func testHasASendButton() {
havingLoadedItsView()
XCTAssertNotNil(composePostViewController.sendButton, "nil sendButton")
}
func havingLoadedItsView() {
_ = composePostViewController.view
}
}
| //
// AdianTests.swift
// AdianTests
//
// Created by Jeremy on 2015-12-02.
// Copyright © 2015 Jeremy W. Sherman. All rights reserved.
//
import XCTest
@testable import Adian
class ComposePostViewControllerTests: XCTestCase {
var composePostViewController: ComposePostViewController!
override func setUp() {
super.setUp()
composePostViewController = ComposePostViewController.instantiate()
}
override func tearDown() {
super.tearDown()
}
func testKnowsItsStoryboardID() {
// passes if we don't explode when as!'ing the ComposePostViewController in setUp()
}
func testHasASendButton() {
havingLoadedItsView()
XCTAssertNotNil(composePostViewController.sendButton, "nil sendButton")
}
func testSendButtonIsDefaultButton() {
havingLoadedItsView()
XCTAssertEqual(composePostViewController.sendButton.keyEquivalent, "\r")
}
func havingLoadedItsView() {
_ = composePostViewController.view
}
}
|
Fix build problem on linux | // Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
extension DataWithPointer {
func getZipStringField(_ length: Int, _ useUtf8: Bool) -> String? {
guard length > 0
else { return "" }
let bytes = self.bytes(count: length)
let bytesAreUtf8 = ZipString.needsUtf8(bytes)
if !useUtf8 && ZipString.cp437Available && !bytesAreUtf8 {
return String(data: Data(bytes: bytes), encoding: String.Encoding(rawValue:
CFStringConvertEncodingToNSStringEncoding(ZipString.cp437Encoding)))
} else {
return String(data: Data(bytes: bytes), encoding: .utf8)
}
}
}
| // Copyright (c) 2017 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
#if os(Linux)
import CoreFoundation
#endif
extension DataWithPointer {
func getZipStringField(_ length: Int, _ useUtf8: Bool) -> String? {
guard length > 0
else { return "" }
let bytes = self.bytes(count: length)
let bytesAreUtf8 = ZipString.needsUtf8(bytes)
if !useUtf8 && ZipString.cp437Available && !bytesAreUtf8 {
return String(data: Data(bytes: bytes), encoding: String.Encoding(rawValue:
CFStringConvertEncodingToNSStringEncoding(ZipString.cp437Encoding)))
} else {
return String(data: Data(bytes: bytes), encoding: .utf8)
}
}
}
|
Update comments for stack with getMin(). | //
// Stack.swift
// Stack GetMin()
//
// Created by Vyacheslav Khorkov on 16/08/2017.
// Copyright © 2017 Vyacheslav Khorkov. All rights reserved.
//
import Foundation
public struct Stack<T> {
public var isEmpty: Bool { return array.isEmpty }
public var count: Int { return array.count }
public var top: T? { return array.last }
public var min: T? { return minimums.last }
public mutating func push(_ value: T) {
array.append(value)
minimums.append(Swift.min(value, min ?? value))
}
public mutating func pop() -> T? {
minimums.popLast()
return array.popLast()
}
// MARK: - Private
private var array = [T]()
private var minimums = [T]()
}
| //
// Stack.swift
// Stack based on two arrays.
//
// Created by Vyacheslav Khorkov on 16/08/2017.
// Copyright © 2017 Vyacheslav Khorkov. All rights reserved.
//
import Foundation
// Stack based on two arrays.
public struct Stack<Element: Comparable> {
// Returns true if stack is empty.
// Complexity: O(1)
public var isEmpty: Bool { return a.isEmpty }
// Returns the count of elements.
// Complexity: O(1)
public var count: Int { return a.count }
// Returns the top element of stack.
// Complexity: O(1)
public var top: Element? { return a.last }
// Returns the minimum element.
// CompComplexity: O(1)
public var min: Element? { return mins.last }
// Appends a new element to the top.
// Complexity: O(1)
public mutating func push(_ element: Element) {
a.append(element)
mins.append(Swift.min(element, min ?? element))
}
// Removes and returns the top element.
// Complexity: O(1)
public mutating func pop() -> Element? {
mins.popLast()
return a.popLast()
}
// This stack based on array.
// Memory: O(n)
private var a: [Element] = []
// Additional array for minimums.
// Memory: O(n)
private var mins: [Element] = []
}
|
Fix assets not found (nil) when used as pod | // Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
import Foundation
import UIKit
public extension UIImage {
public enum SnapTagsViewAssets : String {
case RedCloseButton = "RedCloseButton"
case RoundedButton = "RoundedButton"
case RoundedButton_WhiteWithGreyBorder = "RoundedButton_WhiteWithGreyBorder"
case RoundedButtonFilled = "RoundedButtonFilled"
case YellowCloseButton = "YellowCloseButton"
public var image: UIImage {
return UIImage(asset: self)
}
}
convenience init!(asset: SnapTagsViewAssets) {
self.init(named: asset.rawValue)
}
}
| // Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
import Foundation
import UIKit
private class classInSameBundleAsAssets: NSObject {}
public extension UIImage {
public enum SnapTagsViewAssets : String {
case RedCloseButton = "RedCloseButton"
case RoundedButton = "RoundedButton"
case RoundedButton_WhiteWithGreyBorder = "RoundedButton_WhiteWithGreyBorder"
case RoundedButtonFilled = "RoundedButtonFilled"
case YellowCloseButton = "YellowCloseButton"
public var image: UIImage {
return UIImage(asset: self)
}
}
convenience init!(asset: SnapTagsViewAssets) {
let bundle = NSBundle(forClass: classInSameBundleAsAssets.self)
self.init(named: asset.rawValue, inBundle: bundle, compatibleWithTraitCollection: nil)
}
}
|
Add a test with a mock HTTP response | //
// vidal_api_swiftTests.swift
// vidal-api.swiftTests
//
// Created by Jean-Christophe GAY on 31/01/2015.
// Copyright (c) 2015 Vidal. All rights reserved.
//
import Foundation
import XCTest
import VidalApi
class HelloVidalTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
XCTAssertEqual(hello(), "Hello Vidal")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| //
// vidal_api_swiftTests.swift
// vidal-api.swiftTests
//
// Created by Jean-Christophe GAY on 31/01/2015.
// Copyright (c) 2015 Vidal. All rights reserved.
//
import Foundation
import XCTest
import VidalApi
class HelloVidalTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
OHHTTPStubs.removeAllStubs()
}
func testExample() {
XCTAssertEqual(hello(), "Hello Vidal")
}
func testHttp() {
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest!) -> Bool in
return true
}, withStubResponse:( { (request: NSURLRequest!) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(
data:"Hello Vidal".dataUsingEncoding(NSUTF8StringEncoding),
statusCode: 200,
headers: ["Content-Type" : "text/json"])
}))
let expect = expectationWithDescription("test using http mock")
var result:String?
let url = NSURL(string: "http://whatever.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
result = NSString(data: data, encoding: NSUTF8StringEncoding)
expect.fulfill()
}
task.resume()
waitForExpectationsWithTimeout(10, handler: { (error: NSError!) -> Void in
XCTAssertEqual(result!, "Hello Vidal")
})
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
|
Add methods required for cartoons mode. | //
// Residue.swift
// IMVS
//
// Created by Allistair Crossley on 13/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
/**
* Amino Acid Residue
*
* A protein chain will have somewhere in the range of 50 to 2000 amino acid residues.
* You have to use this term because strictly speaking a peptide chain isn't made up of amino acids.
* When the amino acids combine together, a water molecule is lost. The peptide chain is made up
* from what is left after the water is lost - in other words, is made up of amino acid residues.
* http://www.chemguide.co.uk/organicprops/aminoacids/proteinstruct.html
* C and N terminus
*/
class Residue {
var name: String = ""
var atoms: [Atom] = []
convenience init() {
self.init(name: "NONE")
}
init(name: String) {
self.name = name
}
func addAtom(atom: Atom) {
atoms.append(atom)
}
}
| //
// Residue.swift
// IMVS
//
// Created by Allistair Crossley on 13/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
/**
* Amino Acid Residue
*
* A protein chain will have somewhere in the range of 50 to 2000 amino acid residues.
* You have to use this term because strictly speaking a peptide chain isn't made up of amino acids.
* When the amino acids combine together, a water molecule is lost. The peptide chain is made up
* from what is left after the water is lost - in other words, is made up of amino acid residues.
* http://www.chemguide.co.uk/organicprops/aminoacids/proteinstruct.html
* C and N terminus
*/
class Residue {
var name: String = ""
var atoms: [Atom] = []
convenience init() {
self.init(name: "NONE")
}
init(name: String) {
self.name = name
}
func addAtom(atom: Atom) {
atoms.append(atom)
}
func getAlphaCarbon() -> Atom? {
for atom in atoms {
if atom.element == "C" && atom.remoteness == "A" {
return atom
}
}
return nil
}
/** TODO - Might not be 100% right grabbing the first O - check */
func getCarbonylOxygen() -> Atom? {
for atom in atoms {
if atom.element == "O" {
return atom
}
}
return nil
}
}
|
Add jsonArray property on Array with JSONRepresentable elements | //
// JSONArray.swift
// SwiftyJSONModel
//
// Created by Oleksii on 21/09/2016.
// Copyright © 2016 Oleksii Dykan. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct JSONArray<T> where T: JSONInitializable & JSONRepresentable {
public let array: [T]
public init(_ array: [T]) {
self.array = array
}
}
extension JSONArray: JSONInitializable {
public init(json: JSON) throws {
guard json.type == .array else {
throw JSONModelError.invalidJSON
}
array = try json.arrayValue().map({ try T(json: $0) })
}
}
extension JSONArray: JSONRepresentable {
public var jsonValue: JSON {
return JSON(array.map({ $0.jsonValue }))
}
}
| //
// JSONArray.swift
// SwiftyJSONModel
//
// Created by Oleksii on 21/09/2016.
// Copyright © 2016 Oleksii Dykan. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct JSONArray<T> where T: JSONInitializable & JSONRepresentable {
public let array: [T]
public init(_ array: [T]) {
self.array = array
}
}
extension JSONArray: JSONInitializable {
public init(json: JSON) throws {
guard json.type == .array else {
throw JSONModelError.invalidJSON
}
array = try json.arrayValue().map({ try T(json: $0) })
}
}
extension JSONArray: JSONRepresentable {
public var jsonValue: JSON {
return JSON(array.map({ $0.jsonValue }))
}
}
extension Array where Element: JSONInitializable & JSONRepresentable {
var jsonArray: JSONArray<Element> {
return JSONArray<Element>(self)
}
}
|
Update dependencies (S4 0.8, URI 0.8) | import PackageDescription
let package = Package(
name: "HTTPParser",
dependencies: [
.Package(url: "https://github.com/Zewo/CHTTPParser.git", majorVersion: 0, minor: 5),
.Package(url: "https://github.com/Zewo/URI.git", majorVersion: 0, minor: 7),
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 6),
]
)
| import PackageDescription
let package = Package(
name: "HTTPParser",
dependencies: [
.Package(url: "https://github.com/Zewo/CHTTPParser.git", majorVersion: 0, minor: 5),
.Package(url: "https://github.com/Zewo/URI.git", majorVersion: 0, minor: 8),
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 8),
]
)
|
Use a currency formatter to display the gift's price | //
// GiftCell.swift
// Babies
//
// Created by phi161 on 27/05/16.
// Copyright © 2016 Stanhope Road. All rights reserved.
//
import UIKit
class GiftCell: UITableViewCell {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var currencyLabel: UILabel!
func updateInterface(gift: Gift) {
let textPrompt = NSLocalizedString("TAP_TO_EDIT_GIFT", comment: "Prompt text when the gift details is nil or empty")
titleLabel.text = (gift.details ?? "").isEmpty ? textPrompt : gift.details!
if let date = gift.date {
dateLabel.text = NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)
} else {
dateLabel.text = "n/a"
}
currencyLabel.text = gift.price?.stringValue
}
}
| //
// GiftCell.swift
// Babies
//
// Created by phi161 on 27/05/16.
// Copyright © 2016 Stanhope Road. All rights reserved.
//
import UIKit
class GiftCell: UITableViewCell {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var currencyLabel: UILabel!
func updateInterface(gift: Gift) {
// Details
let textPrompt = NSLocalizedString("TAP_TO_EDIT_GIFT", comment: "Prompt text when the gift details is nil or empty")
titleLabel.text = (gift.details ?? "").isEmpty ? textPrompt : gift.details!
// Date
if let date = gift.date {
dateLabel.text = NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)
} else {
dateLabel.text = "n/a"
}
// Price
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale.currentLocale()
currencyLabel.text = formatter.stringFromNumber(gift.price!)
}
}
|
Remove minor version from generic branch | import PackageDescription
let package = Package(
name: "GIO",
dependencies: [
.Package(url: "https://github.com/rhx/SwiftGObject.git", majorVersion: 2, minor: 46)
]
)
| import PackageDescription
let package = Package(
name: "GIO",
dependencies: [
.Package(url: "https://github.com/rhx/SwiftGObject.git", majorVersion: 2)
]
)
|
Add warning not to add anything to the identifier-at-eof test | // RUN: %incr-transfer-tree --expected-incremental-syntax-tree %S/Outputs/extend-identifier-at-eof.json %s
func foo() {}
_ = x<<<|||x>>> | // RUN: %incr-transfer-tree --expected-incremental-syntax-tree %S/Outputs/extend-identifier-at-eof.json %s
func foo() {}
// ATTENTION: This file is testing the EOF token.
// DO NOT PUT ANYTHING AFTER THE CHANGE, NOT EVEN A NEWLINE
_ = x<<<|||x>>> |
Fix request's multipart data getter | extension Request {
/**
Multipart encoded request data sent using
the `multipart/form-data...` header.
Used by web browsers to send files.
*/
public var multipart: [String: Multipart]? {
if let existing = storage["multipart"] as? [String: Multipart]? {
return existing
} else if let type = headers["Content-Type"] where type.contains("multipart/form-data") {
guard case let .data(body) = body else { return nil }
guard let boundary = try? Multipart.parseBoundary(contentType: type) else { return nil }
let multipart = Multipart.parse(Data(body), boundary: boundary)
storage["multipart"] = multipart
return multipart
} else {
return nil
}
}
}
| extension Request {
/**
Multipart encoded request data sent using
the `multipart/form-data...` header.
Used by web browsers to send files.
*/
public var multipart: [String: Multipart]? {
if let existing = storage["multipart"] as? [String: Multipart] {
return existing
} else if let type = headers["Content-Type"] where type.contains("multipart/form-data") {
guard case let .data(body) = body else { return nil }
guard let boundary = try? Multipart.parseBoundary(contentType: type) else { return nil }
let multipart = Multipart.parse(Data(body), boundary: boundary)
storage["multipart"] = multipart
return multipart
} else {
return nil
}
}
}
|
Add parent to user item | import Foundation
class MFirebaseDUserItem:MFirebaseDProtocol
{
let identifier:String?
required init?(snapshot:Any?, identifier:String?)
{
self.identifier = identifier
}
}
| import Foundation
class MFirebaseDUserItem:MFirebaseDProtocol
{
let identifier:String?
var parent:MFirebaseDProtocol?
{
get
{
let userList:MFirebaseDUser? = MFirebaseDUser(
snapshot:nil,
identifier:nil)
return userList
}
}
required init?(snapshot:Any?, identifier:String?)
{
self.identifier = identifier
}
}
|
Use constants for time conversions | import Darwin.POSIX
import Dispatch
import struct Foundation.TimeInterval
func sleep(for timeInterval: TimeInterval) {
let microSeconds: useconds_t = .init(timeInterval * 1_000_000)
usleep(microSeconds)
}
extension DispatchGroup {
func wait(for timeInterval: TimeInterval) -> DispatchTimeoutResult {
let dispatchTime = DispatchTime.now() + (timeInterval * 1_000_000_000)
return wait(timeout: dispatchTime)
}
}
| import Darwin.POSIX
import Dispatch
import struct Foundation.TimeInterval
func sleep(for timeInterval: TimeInterval) {
let microSeconds: useconds_t = .init(timeInterval * Double(USEC_PER_SEC))
usleep(microSeconds)
}
extension DispatchGroup {
func wait(for timeInterval: TimeInterval) -> DispatchTimeoutResult {
let dispatchTime = DispatchTime.now() + (timeInterval * Double(NSEC_PER_SEC))
return wait(timeout: dispatchTime)
}
}
|
Disable new SwiftToCxxToSwift Interop test | // RUN: %empty-directory(%t)
// RUN: split-file %s %t
// RUN: touch %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod.h -I %t -enable-experimental-cxx-interop
// RUN: %FileCheck %s < %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod2.h -I %t -enable-experimental-cxx-interop
// RUN: %check-interop-cxx-header-in-clang(%t/swiftMod2.h -Wno-error)
//--- header.h
#include "swiftMod.h"
//--- module.modulemap
module SwiftToCxxTest {
header "header.h"
requires cplusplus
}
//--- swiftMod.swift
import SwiftToCxxTest
@_expose(Cxx)
public func testFunction() -> String {
let arr = Swift.Array<Int>()
let rng = Swift.SystemRandomNumberGenerator()
return ""
}
// CHECK: namespace Swift __attribute__((swift_private)) {
// CHECK: namespace SwiftMod __attribute__((swift_private)) {
// CHECK-NOT: namespace Swift {
| // RUN: %empty-directory(%t)
// RUN: split-file %s %t
// RUN: touch %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod.h -I %t -enable-experimental-cxx-interop
// RUN: %FileCheck %s < %t/swiftMod.h
// RUN: %target-swift-frontend -typecheck %t/swiftMod.swift -typecheck -module-name SwiftMod -emit-clang-header-path %t/swiftMod2.h -I %t -enable-experimental-cxx-interop
// RUN: %check-interop-cxx-header-in-clang(%t/swiftMod2.h -Wno-error)
// XFAIL: OS=linux-android, OS=linux-androideabi
//--- header.h
#include "swiftMod.h"
//--- module.modulemap
module SwiftToCxxTest {
header "header.h"
requires cplusplus
}
//--- swiftMod.swift
import SwiftToCxxTest
@_expose(Cxx)
public func testFunction() -> String {
let arr = Swift.Array<Int>()
let rng = Swift.SystemRandomNumberGenerator()
return ""
}
// CHECK: namespace Swift __attribute__((swift_private)) {
// CHECK: namespace SwiftMod __attribute__((swift_private)) {
// CHECK-NOT: namespace Swift {
|
Load user avatar file and display it as a circle. | //
// FriendUserCell.swift
// RoadTripPlanner
//
// Created by Diana Fisher on 10/23/17.
// Copyright © 2017 RoadTripPlanner. All rights reserved.
//
import UIKit
import Parse
class FriendUserCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var addRemoveButton: UIButton!
var avatarFile: PFFile?
var user: PFUser! {
didSet {
usernameLabel.text = user.username
avatarFile = user.avatarFile
}
}
override func awakeFromNib() {
super.awakeFromNib()
guard let avatarFile = self.avatarFile else { return }
Utils.fileToImage(file: avatarFile) { (image) in
self.avatarImageView.image = image
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func addRemoveButtonPressed(_ sender: Any) {
}
}
| //
// FriendUserCell.swift
// RoadTripPlanner
//
// Created by Diana Fisher on 10/23/17.
// Copyright © 2017 RoadTripPlanner. All rights reserved.
//
import UIKit
import Parse
class FriendUserCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var addRemoveButton: UIButton!
var user: PFUser! {
didSet {
usernameLabel.text = user.username
guard let avatarFile = user.avatarFile else { return }
Utils.fileToImage(file: avatarFile) { (image) in
self.avatarImageView.image = image
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
avatarImageView.layer.cornerRadius = avatarImageView.frame.size.height / 2
avatarImageView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func addRemoveButtonPressed(_ sender: Any) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.