repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
premilj/MyGV | MyGVUITests/MyGVUITests.swift | 1 | 1237 | //
// MyGVUITests.swift
// MyGVUITests
//
// Created by Saltmarch Server on 6/3/16.
// Copyright © 2016 Saltmarch. All rights reserved.
//
import XCTest
class MyGVUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| apache-2.0 |
maxim-pervushin/Overlap | Overlap/App/Editors/IntervalEditor.swift | 1 | 1806 | //
// Created by Maxim Pervushin on 29/04/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import Foundation
class IntervalEditor {
var timeZone: NSTimeZone? = nil {
didSet {
updated?()
}
}
var start: Double? = nil {
didSet {
updated?()
}
}
var end: Double? = nil {
didSet {
updated?()
}
}
var updated: (Void -> Void)? = nil {
didSet {
updated?()
}
}
var interval: Interval? {
set {
if let newValue = newValue {
originalTimeZone = newValue.timeZone
timeZone = newValue.timeZone
originalStart = newValue.start
start = newValue.start
originalEnd = newValue.end
end = newValue.end
} else {
originalTimeZone = nil
timeZone = nil
originalStart = nil
start = nil
originalEnd = nil
end = nil
}
}
get {
if let timeZone = timeZone, start = start, end = end {
return Interval(timeZone: timeZone, start: start, end: end)
} else {
return nil
}
}
}
private var originalTimeZone: NSTimeZone? = nil {
didSet {
updated?()
}
}
private var originalStart: Double? = nil {
didSet {
updated?()
}
}
private var originalEnd: Double? = nil {
didSet {
updated?()
}
}
var hasChanges: Bool {
return originalTimeZone != timeZone || originalStart != start || originalEnd != end
}
}
| mit |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Backend/Processing/IMGLYStickerFilter.swift | 1 | 4146 | //
// IMGLYStickerFilter.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 24/03/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
#if os(iOS)
import UIKit
import CoreImage
#elseif os(OSX)
import AppKit
import QuartzCore
#endif
import CoreGraphics
public class IMGLYStickerFilter: CIFilter {
/// A CIImage object that serves as input for the filter.
public var inputImage: CIImage?
/// The sticker that should be rendered.
#if os(iOS)
public var sticker: UIImage?
#elseif os(OSX)
public var sticker: NSImage?
#endif
/// The transform to apply to the sticker
public var transform = CGAffineTransformIdentity
/// The relative center of the sticker within the image.
public var center = CGPoint()
/// The relative size of the sticker within the image.
public var size = CGSize()
override init() {
super.init()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Returns a CIImage object that encapsulates the operations configured in the filter. (read-only)
public override var outputImage: CIImage! {
if inputImage == nil {
return CIImage.emptyImage()
}
if sticker == nil {
return inputImage
}
var stickerImage = createStickerImage()
var stickerCIImage = CIImage(CGImage: stickerImage.CGImage)
var filter = CIFilter(name: "CISourceOverCompositing")
filter.setValue(inputImage, forKey: kCIInputBackgroundImageKey)
filter.setValue(stickerCIImage, forKey: kCIInputImageKey)
return filter.outputImage
}
#if os(iOS)
private func createStickerImage() -> UIImage {
let rect = inputImage!.extent()
let imageSize = rect.size
UIGraphicsBeginImageContext(imageSize)
UIColor(white: 1.0, alpha: 0.0).setFill()
UIRectFill(CGRect(origin: CGPoint(), size: imageSize))
let context = UIGraphicsGetCurrentContext()
drawStickerInContext(context, withImageOfSize: imageSize)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
#elseif os(OSX)
private func createStickerImage() -> NSImage {
let rect = inputImage!.extent()
let imageSize = rect.size
let image = NSImage(size: imageSize)
image.lockFocus()
NSColor(white: 1, alpha: 0).setFill()
NSRectFill(CGRect(origin: CGPoint(), size: imageSize))
let context = NSGraphicsContext.currentContext()!.CGContext
drawStickerInContext(context, withImageOfSize: imageSize)
image.unlockFocus()
return image
}
#endif
private func drawStickerInContext(context: CGContextRef, withImageOfSize imageSize: CGSize) {
CGContextSaveGState(context)
let center = CGPoint(x: self.center.x * imageSize.width, y: self.center.y * imageSize.height)
let size = CGSize(width: self.size.width * imageSize.width, height: self.size.height * imageSize.height)
let imageRect = CGRect(origin: center, size: size)
// Move center to origin
CGContextTranslateCTM(context, imageRect.origin.x, imageRect.origin.y)
// Apply the transform
CGContextConcatCTM(context, self.transform)
// Move the origin back by half
CGContextTranslateCTM(context, imageRect.size.width * -0.5, imageRect.size.height * -0.5)
sticker?.drawInRect(CGRect(origin: CGPoint(), size: size))
CGContextRestoreGState(context)
}
}
extension IMGLYStickerFilter: NSCopying {
public override func copyWithZone(zone: NSZone) -> AnyObject {
let copy = super.copyWithZone(zone) as! IMGLYStickerFilter
copy.inputImage = inputImage?.copyWithZone(zone) as? CIImage
copy.sticker = sticker
copy.center = center
copy.size = size
copy.transform = transform
return copy
}
}
| apache-2.0 |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Backend/Processing/Response Filters/IMGLYLithoFilter.swift | 1 | 560 | //
// IMGLYLithoFilter.swift
// imglyKit
//
// Created by Carsten Przyluczky on 24/02/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import Foundation
public class IMGLYLithoFilter: IMGLYResponseFilter {
init() {
super.init(responseName: "Litho")
self.imgly_displayName = "Litho"
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override var filterType:IMGLYFilterType {
get {
return IMGLYFilterType.Litho
}
}
} | apache-2.0 |
devxoul/SwiftyImage | Tests/SwiftyImageTests/SwiftyImageTests.swift | 1 | 1300 | //
// SwiftyImageTests.swift
// SwiftyImageTests
//
// Created by 전수열 on 7/14/15.
// Copyright (c) 2015 Suyeol Jeon. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import XCTest
@testable import SwiftyImage
class SwiftyImageTests: XCTestCase {
func testCache() {
XCTAssertEqual(
UIImage.size(width: 10, height: 20).color(.blue).corner(radius: 5).border(width: 12).border(color: .red).image,
UIImage.size(width: 10, height: 20).color(.blue).corner(radius: 5).border(width: 12).border(color: .red).image
)
XCTAssertEqual(
UIImage.resizable().color(.blue).corner(radius: 5).border(width: 12).border(color: .red).image,
UIImage.resizable().color(.blue).corner(radius: 5).border(width: 12).border(color: .red).image
)
XCTAssertNotEqual(
UIImage.resizable().color(.blue).corner(radius: 5).border(width: 12).border(color: .red).image,
UIImage.resizable().color(.red).corner(radius: 5).border(width: 12).border(color: .blue).image
)
}
func testCacheLock() {
for _ in 0..<100 {
DispatchQueue.global().async {
_ = UIImage.resizable().border(width: 1).corner(radius: 15).image
}
}
let expectation = XCTestExpectation()
XCTWaiter().wait(for: [expectation], timeout: 1)
}
}
#endif
| mit |
codestergit/swift | test/IRGen/objc_generic_protocol_conformance.swift | 3 | 857 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -primary-file %s -import-objc-header %S/Inputs/objc_generic_protocol_conformance.h | %FileCheck --check-prefix=SIL %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -primary-file %s -import-objc-header %S/Inputs/objc_generic_protocol_conformance.h | %FileCheck --check-prefix=IR %s
// REQUIRES: objc_interop
protocol P {
func foo()
}
extension Foo: P {}
// SIL-LABEL: sil private [transparent] [thunk] @_T0So3FooCyxG33objc_generic_protocol_conformance1PADs9AnyObjectRzlAdEP3fooyyFTW {{.*}} @pseudogeneric
// IR-LABEL: define internal swiftcc void @_T0So3FooCyxG33objc_generic_protocol_conformance1PADs9AnyObjectRzlAdEP3fooyyFTW(%TSo3FooC** noalias nocapture swiftself dereferenceable({{4|8}}), %swift.type*{{( %Self)?}}, i8**{{( %SelfWitnessTable)?}})
| apache-2.0 |
jgrantr/GRNetworkKit | Example/Pods/PromiseKit/Sources/Configuration.swift | 1 | 559 | import Dispatch
public struct PMKConfiguration {
/// the default queues that promises handlers dispatch to
public var Q: (map: DispatchQueue?, return: DispatchQueue?) = (map: DispatchQueue.main, return: DispatchQueue.main)
public var catchPolicy = CatchPolicy.allErrorsExceptCancellation
}
//TODO disallow modification of this after first promise instantiation
//TODO this should be per module too, eg. frameworks you use that provide promises
// should be confident about the queues their code runs on
public var conf = PMKConfiguration()
| mit |
alltheflow/copypasta | CopyPasta/PasteViewModel.swift | 1 | 1056 | //
// PasteViewModel.swift
// CopyPasta
//
// Created by Agnes Vasarhelyi on 23/11/15.
// Copyright © 2015 Agnes Vasarhelyi. All rights reserved.
//
import Foundation
import VinceRP
class PasteViewModel {
let pasteboardService = PasteboardService()
init() {
timer(1.0) {
self.pasteboardService.pollPasteboardItems()
}
}
func pasteboardItems() -> observable {
return pasteboardService.pasteboardItems
}
func items() -> [PasteboardItem] {
return pasteboardItems()*
}
func countHidden() -> Hub<Bool> {
return pasteboardItems().map { $0.count == 0 }
}
func itemCountString() -> Hub<String> {
return pasteboardItems()
.dispatchOnMainQueue()
.map { "\($0.count) items" }
}
func selectItemAtIndex(index: Int) {
let item = self.items()[index]
pasteboardService.addItemToPasteboard(item)
}
func itemAtIndex(index: Int) -> PasteboardItem {
return self.items()[index]
}
}
| mit |
apple/swift | test/IDE/complete_vararg.swift | 13 | 5144 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 | %FileCheck %s -check-prefix=TOP_LEVEL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OBJ_DOT_1 | %FileCheck %s -check-prefix=OBJ_DOT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FREE_FUNC_1 | %FileCheck %s -check-prefix=FREE_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FREE_FUNC_2 | %FileCheck %s -check-prefix=FREE_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=INIT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_1 | %FileCheck %s -check-prefix=METHOD_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_2 | %FileCheck %s -check-prefix=METHOD_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=SUBSCRIPT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_FREE_FUNC_1 | %FileCheck %s -check-prefix=GENERIC_FREE_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INTERESTING_TYPE_1 | %FileCheck %s -check-prefix=INTERESTING_TYPE_1
func freeFunc1(x x: Int...) { }
func freeFunc2(x x: Int, y y: Int...) { }
class C {
init(x: Int...) { }
func method1(x: Int...) { }
func method2(x: Int, y: Int...) { }
func method4(`do` : Int...) {}
func method5(_ `class` : Int...) {}
func method6(`class` `protocol`: Int...) {}
func method7(`inout` value: Int...) {}
subscript(i: Int...) -> Int { return 0 }
}
func genericFreeFunc1<T>(t t: T...) { }
func interestingType1(x x: (Int, (Int, String))...) { }
func testTopLevel() {
#^TOP_LEVEL_1^#
}
// TOP_LEVEL_1: Begin completions
// TOP_LEVEL_1-DAG: Decl[FreeFunction]/CurrModule: freeFunc1({#x: Int...#})[#Void#]{{; name=.+$}}
// TOP_LEVEL_1-DAG: Decl[FreeFunction]/CurrModule: freeFunc2({#x: Int#}, {#y: Int...#})[#Void#]{{; name=.+$}}
// TOP_LEVEL_1-DAG: Decl[FreeFunction]/CurrModule: genericFreeFunc1({#t: T...#})[#Void#]{{; name=.+$}}
// TOP_LEVEL_1-DAG: Decl[FreeFunction]/CurrModule: interestingType1({#x: (Int, (Int, String))...#})[#Void#]{{; name=.+$}}
// TOP_LEVEL_1: End completions
var obj = C()
func testObjDot1() {
obj.#^OBJ_DOT_1^#
}
// OBJ_DOT_1: Begin completions
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method1({#x: Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method2({#x: Int#}, {#y: Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method4({#do: Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method5({#(class): Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method6({#class: Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: method7({#`inout`: Int...#})[#Void#]{{; name=.+$}}
// OBJ_DOT_1: End completions
func testFreeFunc() {
freeFunc1(#^FREE_FUNC_1^#
freeFunc2(#^FREE_FUNC_2^#
}
// FREE_FUNC_1: Begin completions, 1 items
// FREE_FUNC_1: Decl[FreeFunction]/CurrModule/Flair[ArgLabels]: ['(']{#x: Int...#}[')'][#Void#]{{; name=.+$}}
// FREE_FUNC_1: End completions
// FREE_FUNC_2: Begin completions, 1 items
// FREE_FUNC_2: Decl[FreeFunction]/CurrModule/Flair[ArgLabels]: ['(']{#x: Int#}, {#y: Int...#}[')'][#Void#]{{; name=.+$}}
// FREE_FUNC_2: End completions
func testInit() {
let c =C(#^INIT_1^#
}
// INIT_1: Begin completions, 1 items
// INIT_1: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ['(']{#x: Int...#}[')'][#C#]{{; name=.+$}}
// INIT_1: End completions
func testMethod() {
obj.method1(#^METHOD_1^#
obj.method2(#^METHOD_2^#
}
// METHOD_1: Begin completions, 1 items
// METHOD_1: Decl[InstanceMethod]/CurrNominal/Flair[ArgLabels]: ['(']{#x: Int...#}[')'][#Void#]{{; name=.+$}}
// METHOD_1: End completions
// METHOD_2: Begin completions, 1 items
// METHOD_2: Decl[InstanceMethod]/CurrNominal/Flair[ArgLabels]: ['(']{#x: Int#}, {#y: Int...#}[')'][#Void#]{{; name=.+$}}
// METHOD_2: End completions
func testSubscript() {
obj#^SUBSCRIPT_1^#
}
// SUBSCRIPT_1: Begin completions
// SUBSCRIPT_1: Decl[Subscript]/CurrNominal: [{#(i): Int...#}][#Int#]{{; name=.+$}}
// SUBSCRIPT_1: End completions
func testGenericFreeFunc() {
genericFreeFunc1(#^GENERIC_FREE_FUNC_1^#
}
// GENERIC_FREE_FUNC_1: Begin completions, 1 items
// GENERIC_FREE_FUNC_1: Decl[FreeFunction]/CurrModule/Flair[ArgLabels]: ['(']{#t: T...#}[')'][#Void#]{{; name=.+$}}
// GENERIC_FREE_FUNC_1: End completions
func testInterestingType() {
interestingType1(#^INTERESTING_TYPE_1^#
}
// INTERESTING_TYPE_1: Begin completions, 1 items
// INTERESTING_TYPE_1: Decl[FreeFunction]/CurrModule/Flair[ArgLabels]: ['(']{#x: (Int, (Int, String))...#}[')'][#Void#]{{; name=.+$}}
// INTERESTING_TYPE_1: End completions
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27406-swift-protocoltype-canonicalizeprotocols.swift | 1 | 496 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var f{class a{struct S<T where g:C{class A{class a{class a{var I=""enum B{class a{class a{let f={
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/09933-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 11 | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let d {
protocol A {
func e(d: A in
protocol A {
class B : d<b> {
class d<b
let b = e
| mit |
acastano/tabs-scrolling-controller | Tabs/Tabs/Controllers/Tabs/Tab1/Tab1CollectionViewCell.swift | 1 | 519 |
import UIKit
class Tab1CollectionViewCell: UICollectionViewCell {
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupHierarchy()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupHierarchy() {
contentView.addSubview(titleLabel)
}
private func setupConstraints() {
titleLabel.pinToSuperviewEdges()
}
}
| apache-2.0 |
shahabc/ProjectNexus | Mobile Buy SDK Sample Apps/Advanced App - ObjC/Mobile Buy SDK Advanced Sample/ProductCollectionViewController.swift | 1 | 4364 | //
// ProductCollectionViewController.swift
// Mobile Buy SDK Advanced Sample
//
// Created by Victor Hong on 15/12/2016.
// Copyright © 2016 Shopify. All rights reserved.
//
import UIKit
import SDWebImage
class ProductCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collection: BUYCollection?
//var collections: [BUYCollection] = []
var products: [BUYProduct] = []
var collectionOperation : Operation?
//var cart: BUYCart?
let singleton = Singleton.sharedInstance
@IBOutlet weak var productCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = collection?.title
self.getCollectionWithSortOrder(collectionSort:.collectionDefault)
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = productCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? ProductCollectionViewCell
let product = self.products[indexPath.row]
//cell?.backgroundColor = .randomColor()
if let image = product.images[0] as? BUYImageLink {
if let imageurl = image.sourceURL {
cell?.productCollectionImageView.sd_setImage(with: imageurl, placeholderImage: UIImage(named: "placeholder.png"))
}
}
cell?.productCollectionLabel.text = product.title
cell?.productCollectionLabel.sizeToFit()
if let productPrice = product.minimumPrice {
cell?.priceCollectionLabel.text = "$\(productPrice)"
cell?.priceCollectionLabel.sizeToFit()
}
return cell!
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let product = products[indexPath.row]
let productViewController = setThemeVC()
productViewController.load(with: product) { success, error in
if (error == nil) {
self.navigationController?.pushViewController(productViewController, animated: true)
}
}
}
func setThemeVC() -> ProductViewController {
let theme = Theme()
theme.style = ThemeStyle(rawValue: 0)!
theme.tintColor = UIColor(red: 0.47999998927116394, green: 0.70999997854232788, blue: 0.36000001430511475, alpha: 1)
theme.showsProductImageBackground = true
let productViewController = ProductViewController(client: singleton.client, cart: singleton.cart)
productViewController?.merchantId = ""
return productViewController!
}
func getCollectionWithSortOrder(collectionSort: BUYCollectionSort){
self.collectionOperation?.cancel()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.collectionOperation = (singleton.client.getProductsPage(1, inCollection: self.collection?.identifier, withTags: nil, sortOrder: collectionSort, completion: {
products, page, reachedEnd, error in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if (error == nil && (products != nil)) {
self.products = products!
self.productCollectionView.reloadData()
} else {
print("Error fetching products: \(error)")
}
}))
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
beingadrian/OutfitRecommenderApp-Starter | OutfitRecommender/OutfitRecommender/AppDelegate.swift | 1 | 2156 | //
// AppDelegate.swift
// OutfitRecommender
//
// Created by Adrian Wisaksana on 5/27/16.
// Copyright © 2016 MakeSchool. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
ccrama/Slide-iOS | Slide for Reddit/SettingsHistory.swift | 1 | 8582 | //
// SettingsHistory.swift
// Slide for Reddit
//
// Created by Carlos Crane on 7/17/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import UIKit
class SettingsHistory: BubbleSettingTableViewController {
var saveHistoryCell: UITableViewCell = InsetCell()
var saveHistory = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var saveNSFWHistoryCell: UITableViewCell = InsetCell()
var saveNSFWHistory = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var hideSeenCell: UITableViewCell = InsetCell()
var hideSeen = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var readOnScrollCell: UITableViewCell = InsetCell()
var readOnScroll = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var dotCell: UITableViewCell = InsetCell()
var dot = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var exportCollectionsCell: UITableViewCell = InsetCell()
var clearHistory: UITableViewCell = InsetCell()
var clearSubs: UITableViewCell = InsetCell()
@objc func switchIsChanged(_ changed: UISwitch) {
if changed == saveHistory {
SettingValues.saveHistory = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_saveHistory)
} else if changed == saveNSFWHistory {
SettingValues.saveNSFWHistory = !changed.isOn
UserDefaults.standard.set(!changed.isOn, forKey: SettingValues.pref_saveNSFWHistory)
} else if changed == hideSeen {
SettingValues.hideSeen = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_hideSeen)
} else if changed == dot {
SettingValues.newIndicator = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_newIndicator)
} else if changed == readOnScroll {
SettingValues.markReadOnScroll = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_markReadOnScroll)
}
UserDefaults.standard.synchronize()
doDisables()
tableView.reloadData()
}
public func createCell(_ cell: UITableViewCell, _ switchV: UISwitch? = nil, isOn: Bool, text: String) {
cell.textLabel?.text = text
cell.textLabel?.textColor = ColorUtil.theme.fontColor
cell.backgroundColor = ColorUtil.theme.foregroundColor
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
if let s = switchV {
s.isOn = isOn
s.addTarget(self, action: #selector(SettingsLayout.switchIsChanged(_:)), for: UIControl.Event.valueChanged)
cell.accessoryView = s
}
cell.selectionStyle = UITableViewCell.SelectionStyle.none
}
override func loadView() {
super.loadView()
self.view.backgroundColor = ColorUtil.theme.backgroundColor
// set the title
self.title = "History"
self.headers = ["Settings", "Clear history", "Export data"]
createCell(saveHistoryCell, saveHistory, isOn: SettingValues.saveHistory, text: "Save submission and subreddit history")
createCell(saveNSFWHistoryCell, saveNSFWHistory, isOn: !SettingValues.saveNSFWHistory, text: "Hide NSFW submission and subreddit history")
createCell(readOnScrollCell, readOnScroll, isOn: SettingValues.markReadOnScroll, text: "Mark submissions as read when scrolled off screen")
createCell(dotCell, dot, isOn: SettingValues.newIndicator, text: "New submissions indicator")
createCell(exportCollectionsCell, nil, isOn: false, text: "Export your Slide collections as .csv")
exportCollectionsCell.accessoryType = .disclosureIndicator
dotCell.detailTextLabel?.numberOfLines = 0
dotCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
dotCell.detailTextLabel?.text = "Enabling this will disable the 'grayed out' effect of read submissions"
createCell(hideSeenCell, hideSeen, isOn: SettingValues.hideSeen, text: "Hide read posts automatically")
hideSeenCell.detailTextLabel?.numberOfLines = 0
hideSeenCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
hideSeenCell.detailTextLabel?.text = "Enabling this may lead to no posts loading in a subreddit"
clearHistory.textLabel?.text = "Clear submission history"
clearHistory.backgroundColor = ColorUtil.theme.foregroundColor
clearHistory.textLabel?.textColor = ColorUtil.theme.fontColor
clearHistory.selectionStyle = UITableViewCell.SelectionStyle.none
clearHistory.accessoryType = .disclosureIndicator
clearSubs.textLabel?.text = "Clear subreddit history"
clearSubs.backgroundColor = ColorUtil.theme.foregroundColor
clearSubs.textLabel?.textColor = ColorUtil.theme.fontColor
clearSubs.selectionStyle = UITableViewCell.SelectionStyle.none
clearSubs.accessoryType = .disclosureIndicator
doDisables()
self.tableView.tableFooterView = UIView()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
if indexPath.row == 0 {
History.clearHistory()
BannerUtil.makeBanner(text: "Submission history cleared!", color: GMColor.green500Color(), seconds: 5, context: self)
} else {
Subscriptions.clearSubHistory()
BannerUtil.makeBanner(text: "Subreddit history cleared!", color: GMColor.green500Color(), seconds: 5, context: self)
}
}
if indexPath.section == 2 {
exportCollectionsCSV(from: Collections.collectionIDs)
}
tableView.deselectRow(at: indexPath, animated: true)
}
func doDisables() {
if SettingValues.saveHistory {
saveNSFWHistory.isEnabled = true
readOnScroll.isEnabled = true
} else {
saveNSFWHistory.isEnabled = false
readOnScroll.isEnabled = false
}
}
func exportCollectionsCSV(from: NSDictionary) {
var csvString = "\("Collection Name"),\("Reddit permalink")\n\n"
for key in from.allKeys {
csvString += "\(from[key] ?? "") , https://redd.it/\((key as! String).replacingOccurrences(of: "t3_", with: ""))\n"
}
let fileManager = FileManager.default
do {
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileURL = path.appendingPathComponent("Slide-Collections\(Date().dateString().replacingOccurrences(of: " ", with: "-").replacingOccurrences(of: ",", with: "-")).csv")
try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
var filesToShare = [Any]()
filesToShare.append(fileURL)
let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
} catch {
print("error creating file")
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return self.saveHistoryCell
case 1: return self.saveNSFWHistoryCell
case 2: return self.readOnScrollCell
case 3: return self.dotCell
case 4: return self.hideSeenCell
default: fatalError("Unknown row in section 0")
}
case 1:
switch indexPath.row {
case 0: return self.clearHistory
case 1: return self.clearSubs
default: fatalError("Unknown row in section 0")
}
case 2:
return exportCollectionsCell
default: fatalError("Unknown section")
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 5 // section 0 has 2 rows
case 1: return 2
case 2: return 1
default: fatalError("Unknown number of sections")
}
}
}
| apache-2.0 |
masters3d/xswift | exercises/gigasecond/Sources/GigasecondExample.swift | 1 | 2778 | import Foundation
private extension tm {
var year: Int32 { return tm_year + 1900 }
var month: Int32 { return tm_mon + 1 }
var day: Int32 { return tm_mday }
var time:(hour: Int32, mins: Int32, secs: Int32) {
return (hour: tm_hour, mins: tm_min, secs:tm_sec)
}
init(year: Int32, month: Int32, day: Int32, hour: Int32 = 0, mins: Int32 = 0, secs: Int32 = 0) {
self.init()
self.tm_year = year - 1900
self.tm_mon = month - 1
self.tm_mday = day
self.tm_hour = hour
self.tm_min = mins
self.tm_sec = secs
}
mutating func dateByAddingSeconds(_ seconds: Int) -> tm {
var d1 = timegm(&self) + seconds
return gmtime(&d1).pointee
}
private func addLeadingZero(_ input: Int32) -> String {
var addZero = false
(0...9).forEach {
if $0 == Int(input) {
addZero = true
}
}
if addZero {
return "0\(input)"
} else { return String(input) }
}
var description: String {
let date = [year, month, day, time.hour, time.mins, time.secs].map { addLeadingZero($0) }
return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5]
}
}
func == (lhs: Gigasecond, rhs: Gigasecond) -> Bool {
return lhs.description == rhs.description
}
func == (lhs: String, rhs: Gigasecond) -> Bool {
return lhs == rhs.description
}
struct Gigasecond: Equatable, CustomStringConvertible {
private var startDate: tm!
private var gigasecondDate: tm!
init?(from: String) {
if let result = parse(from) {
var start = result
self.startDate = start
self.gigasecondDate = start.dateByAddingSeconds(1_000_000_000)
} else {
return nil
}
}
private func parse(_ input: String) -> tm? {
let dateTime = input.characters.split(separator: "T").map { String($0) }
if dateTime.count > 1 {
let date = dateTime[0].characters.split(separator: "-").map { String($0) }
let time = dateTime[1].characters.split(separator: ":").map { String($0) }
if date.count == 3 && time.count == date.count {
let year = Int32(date[0]) ?? 0
let month = Int32(date[1]) ?? 0
let day = Int32(date[2]) ?? 0
let hour = Int32(time[0]) ?? 0
let minute = Int32(time[1]) ?? 0
let second = Int32(time[2]) ?? 0
return tm(year: year, month: month, day: day, hour: hour, mins: minute, secs: second)
}
}
return nil
}
var description: String {
return gigasecondDate.description
}
}
| mit |
tardieu/swift | validation-test/compiler_crashers_fixed/00344-substituteinputsugarargumenttype.swift | 65 | 521 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func f<T, f: Int = {
struct S {
func b<T -> T]()(b(t: I) -> S<f : a {
}
enum S<I : A"")
func g: NSManagedObject {
}
}
S()?
| apache-2.0 |
orlandoamorim/FamilyKey | FamilyKey/DataManager.swift | 1 | 610 | //
// DataManager.swift
// FamilyKey
//
// Created by Orlando Amorim on 02/06/17.
// Copyright © 2017 Orlando Amorim. All rights reserved.
//
import Foundation
let sumaryUrl = ""
public class DataManager {
public class func getDataFromFile(_ named:String) -> Data? {
guard let filePath = Bundle.main.path(forResource: named, ofType:"json") else {
return nil
}
do {
let data = try Data(contentsOf: URL(fileURLWithPath:filePath), options: .uncached)
return data
} catch {
return nil
}
}
}
| mit |
antonio081014/LeetCode-CodeBase | Swift/different-ways-to-add-parentheses.swift | 1 | 3121 | class Solution {
/// - Complexity:
/// - Time: O(2 ^ n), n = number of operator in expression. Since, at each operator, we could split the expr there or not.
/// - Space: O(m), m = possible result for current expression.
func diffWaysToCompute(_ expression: String) -> [Int] {
if let num = Int(expression) {
return [num]
}
var result = [Int]()
for index in expression.indices {
if "+-*".contains(expression[index]) {
let left = diffWaysToCompute(String(expression[..<index]))
let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex]))
if expression[index] == Character("+") {
for l in left {
for r in right {
result.append(l + r)
}
}
} else if expression[index] == Character("-") {
for l in left {
for r in right {
result.append(l - r)
}
}
} else if expression[index] == Character("*") {
for l in left {
for r in right {
result.append(l * r)
}
}
}
}
}
// print(expression, result)
return result
}
}
class Solution {
/// Recursive solution with memorization.
private var memo: [String : [Int]]!
func diffWaysToCompute(_ expression: String) -> [Int] {
memo = [String : [Int]]()
return helper(expression)
}
private func helper(_ expression: String) -> [Int] {
if let ret = self.memo[expression] { return ret }
if let num = Int(expression) {
return [num]
}
var result = [Int]()
for index in expression.indices {
if "+-*".contains(expression[index]) {
let left = diffWaysToCompute(String(expression[..<index]))
let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex]))
if expression[index] == Character("+") {
for l in left {
for r in right {
result.append(l + r)
}
}
} else if expression[index] == Character("-") {
for l in left {
for r in right {
result.append(l - r)
}
}
} else if expression[index] == Character("*") {
for l in left {
for r in right {
result.append(l * r)
}
}
}
}
}
self.memo[expression] = result
return result
}
}
| mit |
cpimhoff/AntlerKit | Framework/AntlerKit/Utilities/Enums.swift | 1 | 454 | //
// Enums.swift
// AntlerKit
//
// Created by Charlie Imhoff on 4/28/17.
// Copyright © 2017 Charlie Imhoff. All rights reserved.
//
import Foundation
public enum Direction {
case up, down, left, right
public var vector : Vector {
switch self {
case .up:
return Vector(dx: 0, dy: 1)
case .down:
return Vector(dx: 0, dy: -1)
case .left:
return Vector(dx: -1, dy: 0)
case .right:
return Vector(dx: 1, dy: 0)
}
}
}
| mit |
jzucker2/SwiftyKit | Example/SwiftyKit/AppDelegate.swift | 1 | 2762 | //
// AppDelegate.swift
// SwiftyKit
//
// Created by jzucker2 on 07/27/2017.
// Copyright (c) 2017 jzucker2. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let bounds = UIScreen.main.bounds
let window = UIWindow(frame: bounds)
self.window = window
let tabBarController = UITabBarController()
let plainNavController = UINavigationController(rootViewController: PlainViewController())
let errorNavController = UINavigationController(rootViewController: ErrorViewController())
errorNavController.title = "Errors"
tabBarController.viewControllers = [plainNavController, errorNavController]
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
xusader/firefox-ios | Storage/SQL/SQLiteReadingList.swift | 2 | 2285 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
/**
* The SQLite-backed implementation of the ReadingList protocol.
*/
public class SQLiteReadingList: ReadingList {
let db: BrowserDB
let table = ReadingListTable<ReadingListItem>()
required public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(table)
}
public func clear(complete: (success: Bool) -> Void) {
var err: NSError? = nil
db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
if err != nil {
self.debug("Clear failed: \(err!.localizedDescription)")
complete(success: false)
} else {
complete(success: true)
}
}
}
public func get(complete: (data: Cursor) -> Void) {
var err: NSError? = nil
let res = db.query(&err) { (conn: SQLiteDBConnection, inout err: NSError?) -> Cursor in
return self.table.query(conn, options: nil)
}
dispatch_async(dispatch_get_main_queue()) {
complete(data: res)
}
}
public func add(#item: ReadingListItem, complete: (success: Bool) -> Void) {
var err: NSError? = nil
let inserted = db.insert(&err) { (conn, inout err: NSError?) -> Int in
return self.table.insert(conn, item: item, err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
if err != nil {
self.debug("Add failed: \(err!.localizedDescription)")
}
complete(success: err == nil)
}
}
public func shareItem(item: ShareItem) {
add(item: ReadingListItem(url: item.url, title: item.title)) { (success) -> Void in
// Nothing we can do here when items are added from an extension.
}
}
private let debug_enabled = false
private func debug(msg: String) {
if debug_enabled {
println("SQLiteReadingList: " + msg)
}
}
}
| mpl-2.0 |
willlarche/material-components-ios | components/Buttons/examples/ButtonsDynamicTypeViewController.swift | 2 | 3166 | /*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialButtons
class ButtonsDynamicTypeViewController: UIViewController {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Buttons", "Buttons (DynamicType)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.9, alpha:1.0)
let titleColor = UIColor.white
let backgroundColor = UIColor(white: 0.1, alpha: 1.0)
let flatButtonStatic = MDCRaisedButton()
flatButtonStatic.setTitleColor(titleColor, for: .normal)
flatButtonStatic.setBackgroundColor(backgroundColor, for: .normal)
flatButtonStatic.setTitle("Static", for: UIControlState())
flatButtonStatic.sizeToFit()
flatButtonStatic.translatesAutoresizingMaskIntoConstraints = false
flatButtonStatic.addTarget(self, action: #selector(tap), for: .touchUpInside)
view.addSubview(flatButtonStatic)
let flatButtonDynamic = MDCRaisedButton()
flatButtonDynamic.setTitleColor(titleColor, for: .normal)
flatButtonDynamic.setBackgroundColor(backgroundColor, for: .normal)
flatButtonDynamic.setTitle("Dynamic", for: UIControlState())
flatButtonDynamic.sizeToFit()
flatButtonDynamic.translatesAutoresizingMaskIntoConstraints = false
flatButtonDynamic.addTarget(self, action: #selector(tap), for: .touchUpInside)
flatButtonDynamic.mdc_adjustsFontForContentSizeCategory = true
view.addSubview(flatButtonDynamic)
let views = [
"flatStatic": flatButtonStatic,
"flatDynamic": flatButtonDynamic
]
centerView(view: flatButtonDynamic, onView: self.view)
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:[flatStatic]-40-[flatDynamic]",
options: .alignAllCenterX,
metrics: nil,
views: views))
}
// MARK: Private
func centerView(view: UIView, onView: UIView) {
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerX,
relatedBy: .equal,
toItem: onView,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0))
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerY,
relatedBy: .equal,
toItem: onView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
}
@objc func tap(_ sender: Any) {
print("\(type(of: sender)) was tapped.")
}
}
| apache-2.0 |
kvvzr/Twinkrun-iOS | Twinkrun/Models/TWRPlayer.swift | 2 | 4778 |
//
// TWRPlayer.swift
// Twinkrun
//
// Created by Kawazure on 2014/10/09.
// Copyright (c) 2014年 Twinkrun. All rights reserved.
//
import Foundation
import CoreBluetooth
class TWRPlayer: NSObject, NSCoding {
let identifier: NSUUID?
var playWith: Bool, countedScore: Bool
var name: NSString
var colorSeed: UInt32, RSSI: Int?
var score: Int?
var roles: [TWRRole]?
var option: TWRGameOption?
let version = "2.0"
init(playerName: NSString, identifier: NSUUID?, colorSeed: UInt32) {
self.name = playerName
self.identifier = identifier
self.colorSeed = colorSeed % 1024
self.option = TWROption.sharedInstance.gameOption
playWith = true
countedScore = false
super.init()
createRoleList()
}
init(advertisementDataLocalName: String, identifier: NSUUID) {
var data: [String] = advertisementDataLocalName.componentsSeparatedByString(",")
self.name = data[0]
self.colorSeed = UInt32(Int(data[1])!)
self.identifier = identifier
self.option = TWROption.sharedInstance.gameOption
playWith = true
countedScore = true
super.init()
}
required init(coder aDecoder: NSCoder) {
playWith = true
countedScore = false
if let _ = aDecoder.decodeObjectForKey("version") as? String {
self.name = aDecoder.decodeObjectForKey("name") as! NSString
self.identifier = aDecoder.decodeObjectForKey("identifier") as? NSUUID
self.colorSeed = UInt32(aDecoder.decodeIntegerForKey("colorSeed"))
self.score = aDecoder.decodeIntegerForKey("score")
super.init()
} else {
self.name = aDecoder.decodeObjectForKey("playerName") as! NSString
self.identifier = nil
self.colorSeed = UInt32((aDecoder.decodeObjectForKey("colorListSeed") as! NSNumber).integerValue)
super.init()
}
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(identifier, forKey: "identifier")
aCoder.encodeInteger(Int(colorSeed), forKey: "colorSeed")
if let score = score {
aCoder.encodeInteger(score, forKey: "score")
}
aCoder.encodeObject(version, forKey: "version")
}
func createRoleList() {
roles = []
for role in option!.roles {
for _ in 0 ..< role.count {
roles!.append(role)
}
}
roles!.shuffle(colorSeed)
}
func advertisementData(UUID: CBUUID) -> [String: AnyObject] {
return [
CBAdvertisementDataServiceUUIDsKey: [UUID],
CBAdvertisementDataLocalNameKey: (splitString(name, bytes: 12) as String) + "," + String(colorSeed)
]
}
func previousRole(second: UInt) -> TWRRole? {
let sec = second % option!.gameTime()
var progress: UInt = 0
for i in 0 ..< roles!.count {
let nextLimit = progress + roles![i].time
if nextLimit > sec {
return i == 0 ? roles!.last! : roles![i - 1]
}
progress = nextLimit
}
return nil
}
func currentRole(second: UInt) -> TWRRole {
let sec = second % option!.gameTime()
var progress: UInt = 0
var current: TWRRole?
for i in 0 ..< roles!.count {
let nextLimit = progress + roles![i].time
if nextLimit > sec {
current = roles![i]
break
}
progress = nextLimit
}
return current!
}
func nextRole(second: UInt) -> TWRRole? {
var progress: UInt = 0
for i in 0 ..< roles!.count - 1 {
let nextLimit = progress + roles![i].time
if nextLimit > second {
return roles![i + 1]
}
progress = nextLimit
}
return nil
}
private func splitString(input: NSString, bytes length: Int) -> NSString {
let data = input.dataUsingEncoding(NSUTF8StringEncoding)
for i in (0...min(length, data!.length)).reverse() {
if let result:NSString = NSString(data: data!.subdataWithRange(NSRange(location: 0, length: i)), encoding: NSUTF8StringEncoding) {
if result.length > 0 {
return result
}
}
}
return ""
}
}
func ==(this: TWRPlayer, that: TWRPlayer) -> Bool {
return this.identifier == that.identifier
} | mit |
HaloWang/FangYuan | FangYuan/OnlyForDemo/DemoSpecific.swift | 1 | 1787 |
import Foundation
/// This class is used to provide FangYuan.Ruler's logic
///
/// - Warning: Only available in demo codes
open class EnableConstraintHolder {
public enum Section {
case left
case right
case width
case top
case bottom
case height
}
fileprivate static let holderView = UIView()
open static var validSections = [Section]()
open class func validAt(_ section:Section) -> Bool {
for _section in validSections {
if section == _section {
return true
}
}
return false
}
open class func pushConstraintAt(_ section: EnableConstraintHolder.Section) {
var sections = [Section]()
let rx = holderView.rulerX
let ry = holderView.rulerY
switch section {
case .bottom:
ry.c = 0
case .height:
ry.b = 0
case .top:
ry.a = 0
case .left:
rx.a = 0
case .width:
rx.b = 0
case .right:
rx.c = 0
}
if rx.a != nil {
sections.append(.left)
}
if rx.b != nil {
sections.append(.width)
}
if rx.c != nil {
sections.append(.right)
}
if ry.a != nil {
sections.append(.top)
}
if ry.b != nil {
sections.append(.height)
}
if ry.c != nil {
sections.append(.bottom)
}
validSections = sections
}
open class func randomSections() {
}
open class func clearSections() {
}
}
| mit |
gregstula/LifeGenSwift | oop-gol/LifeGenSwiftTests/LifeGenSwiftTests.swift | 3 | 924 | //
// LifeGenSwiftTests.swift
// LifeGenSwiftTests
//
// Created by Gregory D. Stula on 9/8/15.
// Copyright (c) 2015 Gregory D. Stula. All rights reserved.
//
import UIKit
import XCTest
class LifeGenSwiftTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
nguyenantinhbk77/practice-swift | CoreGraphics/QuartzFun/QuartzFun/ViewController.swift | 2 | 1961 | //
// ViewController.swift
// QuartzFun
//
// Created by Domenico on 01/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var colorControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeColor(sender: UISegmentedControl) {
let drawingColorSelection =
DrawingColor(rawValue: UInt(sender.selectedSegmentIndex))
if let drawingColor = drawingColorSelection {
let funView = view as! QuartzFunView;
switch drawingColor {
case .Red:
funView.currentColor = UIColor.redColor()
funView.useRandomColor = false
case .Blue:
funView.currentColor = UIColor.blueColor()
funView.useRandomColor = false
case .Yellow:
funView.currentColor = UIColor.yellowColor()
funView.useRandomColor = false
case .Green:
funView.currentColor = UIColor.greenColor()
funView.useRandomColor = false
case .Random:
funView.useRandomColor = true
default:
break;
}
}
}
@IBAction func changeShape(sender: UISegmentedControl) {
let shapeSelection = Shape(rawValue: UInt(sender.selectedSegmentIndex))
if let shape = shapeSelection {
let funView = view as! QuartzFunView;
funView.shape = shape;
colorControl.hidden = shape == Shape.Image
}
}
}
| mit |
alblue/swift | test/Inputs/conditional_conformance_subclass.swift | 1 | 12240 | public func takes_p1<T: P1>(_: T.Type) {}
public protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
public protocol P2 {}
public protocol P3 {}
public struct IsP2: P2 {}
public class Base<A> {}
extension Base: P1 where A: P2 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Base.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF"(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Base.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public class SubclassGeneric<T>: Base<T> {}
public class SubclassConcrete: Base<IsP2> {}
public class SubclassGenericConcrete: SubclassGeneric<IsP2> {}
public func subclassgeneric_generic<T: P2>(_: T.Type) {
takes_p1(SubclassGeneric<T>.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCMa"(i64 0, %swift.type* %T)
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func subclassgeneric_concrete() {
takes_p1(SubclassGeneric<IsP2>.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass24subclassgeneric_concreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0)
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0)
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
public func subclassconcrete() {
takes_p1(SubclassConcrete.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass16subclassconcreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
public func subclassgenericconcrete() {
takes_p1(SubclassGenericConcrete.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgenericconcreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
// witness tabel instantiation function for Base : P1
// CHECK-LABEL: define internal void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWI"(i8**, %swift.type* %"Base<A>", i8**)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8***
// CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0
// CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8
// CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8***
// CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8
// CHECK-NEXT: ret void
// CHECK-NEXT: }
| apache-2.0 |
Samiabo/Weibo | Weibo/Weibo/Classes/Home/LSPresentationController.swift | 1 | 1080 | //
// LSPresentationController.swift
// Weibo
//
// Created by han xuelong on 2016/12/31.
// Copyright © 2016年 han xuelong. All rights reserved.
//
import UIKit
class LSPresentationController: UIPresentationController {
lazy var coverView: UIView = UIView()
var presentedFrame: CGRect = .zero
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
presentedView?.frame = presentedFrame
setupCoverView()
}
}
// MARK: - UI
extension LSPresentationController {
func setupCoverView() {
containerView?.insertSubview(coverView, at: 0)
coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.2)
coverView.frame = containerView!.bounds
let tap = UITapGestureRecognizer(target: self, action:#selector(LSPresentationController.coverViewClick))
coverView.addGestureRecognizer(tap)
}
}
// MARK: - 事件监听
extension LSPresentationController {
func coverViewClick() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| mit |
dreamsxin/swift | validation-test/stdlib/Collection/MinimalMutableRangeReplaceableBidirectionalCollection.swift | 2 | 4866 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %S/../../../utils/gyb %s -o %t/main.swift
// RUN: %S/../../../utils/line-directive %t/main.swift -- %target-build-swift %t/main.swift -o %t/MinimalMutableRangeReplaceableBidirectionalCollection.swift.a.out
// RUN: %S/../../../utils/line-directive %t/main.swift -- %target-run %t/MinimalMutableRangeReplaceableBidirectionalCollection.swift.a.out
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var CollectionTests = TestSuite("Collection")
// Test collections using value types as elements.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addRangeReplaceableBidirectionalCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
CollectionTests.addMutableBidirectionalCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
}
// Test collections using a reference type as element.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addRangeReplaceableBidirectionalCollectionTests(
makeCollection: { (elements: [LifetimeTracked]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: { (element: OpaqueValue<Int>) in
LifetimeTracked(element.value, identity: element.identity)
},
extractValue: { (element: LifetimeTracked) in
OpaqueValue(element.value, identity: element.identity)
},
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
CollectionTests.addMutableBidirectionalCollectionTests(
makeCollection: { (elements: [LifetimeTracked]) in
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValue: { (element: OpaqueValue<Int>) in
LifetimeTracked(element.value, identity: element.identity)
},
extractValue: { (element: LifetimeTracked) in
OpaqueValue(element.value, identity: element.identity)
},
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableBidirectionalCollection(elements: elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
}
runAllTests()
| apache-2.0 |
mozilla-mobile/firefox-ios | Tests/ClientTests/Helpers/RatingPromptManagerTests.swift | 2 | 11218 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import XCTest
import StoreKit
import Shared
import Storage
@testable import Client
class RatingPromptManagerTests: XCTestCase {
var urlOpenerSpy: URLOpenerSpy!
var promptManager: RatingPromptManager!
var mockProfile: MockProfile!
var createdGuids: [String] = []
var sentry: CrashingMockSentryClient!
override func setUp() {
super.setUp()
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
urlOpenerSpy = URLOpenerSpy()
}
override func tearDown() {
super.tearDown()
createdGuids = []
promptManager?.reset()
promptManager = nil
mockProfile?.shutdown()
mockProfile = nil
sentry = nil
urlOpenerSpy = nil
}
func testShouldShowPrompt_requiredAreFalse_returnsFalse() {
setupEnvironment(numberOfSession: 0,
hasCumulativeDaysOfUse: false)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_requiredTrueWithoutOptional_returnsFalse() {
setupEnvironment()
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_withRequiredRequirementsAndOneOptional_returnsTrue() {
setupEnvironment(isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 1)
}
func testShouldShowPrompt_lessThanSession5_returnsFalse() {
setupEnvironment(numberOfSession: 4,
hasCumulativeDaysOfUse: true,
isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_cumulativeDaysOfUseFalse_returnsFalse() {
setupEnvironment(numberOfSession: 5,
hasCumulativeDaysOfUse: false,
isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_sentryHasCrashedInLastSession_returnsFalse() {
setupEnvironment(isBrowserDefault: true)
sentry?.enableCrashOnLastLaunch = true
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_isBrowserDefaultTrue_returnsTrue() {
setupEnvironment(isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 1)
}
func testShouldShowPrompt_hasTPStrict_returnsTrue() {
setupEnvironment()
mockProfile.prefs.setString(BlockingStrength.strict.rawValue, forKey: ContentBlockingConfig.Prefs.StrengthKey)
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 1)
}
// MARK: Bookmarks
func testShouldShowPrompt_hasNotMinimumMobileBookmarksCount_returnsFalse() {
setupEnvironment()
createBookmarks(bookmarkCount: 2, withRoot: BookmarkRoots.MobileFolderGUID)
updateData(expectedRatingPromptOpenCount: 0)
}
func testShouldShowPrompt_hasMinimumMobileBookmarksCount_returnsTrue() {
setupEnvironment()
createBookmarks(bookmarkCount: 5, withRoot: BookmarkRoots.MobileFolderGUID)
updateData(expectedRatingPromptOpenCount: 1)
}
func testShouldShowPrompt_hasOtherBookmarksCount_returnsFalse() {
setupEnvironment()
createBookmarks(bookmarkCount: 5, withRoot: BookmarkRoots.ToolbarFolderGUID)
updateData(expectedRatingPromptOpenCount: 0)
}
func testShouldShowPrompt_has5FoldersInMobileBookmarks_returnsFalse() {
setupEnvironment()
createFolders(folderCount: 5, withRoot: BookmarkRoots.MobileFolderGUID)
updateData(expectedRatingPromptOpenCount: 0)
}
func testShouldShowPrompt_has5SeparatorsInMobileBookmarks_returnsFalse() {
setupEnvironment()
createSeparators(separatorCount: 5, withRoot: BookmarkRoots.MobileFolderGUID)
updateData(expectedRatingPromptOpenCount: 0)
}
func testShouldShowPrompt_hasRequestedTwoWeeksAgo_returnsTrue() {
setupEnvironment(isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded(at: Date().lastTwoWeek)
XCTAssertEqual(ratingPromptOpenCount, 1)
}
// MARK: Number of times asked
func testShouldShowPrompt_hasRequestedInTheLastTwoWeeks_returnsFalse() {
setupEnvironment()
promptManager.showRatingPromptIfNeeded(at: Date().lastTwoWeek)
XCTAssertEqual(ratingPromptOpenCount, 0)
}
func testShouldShowPrompt_requestCountTwiceCountIsAtOne() {
setupEnvironment(isBrowserDefault: true)
promptManager.showRatingPromptIfNeeded()
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(ratingPromptOpenCount, 1)
}
// MARK: App Store
func testGoToAppStoreReview() {
RatingPromptManager.goToAppStoreReview(with: urlOpenerSpy)
XCTAssertEqual(urlOpenerSpy.openURLCount, 1)
XCTAssertEqual(urlOpenerSpy.capturedURL?.absoluteString, "https://itunes.apple.com/app/id\(AppInfo.appStoreId)?action=write-review")
}
}
// MARK: - Places helpers
private extension RatingPromptManagerTests {
func createFolders(folderCount: Int, withRoot root: String, file: StaticString = #filePath, line: UInt = #line) {
(1...folderCount).forEach { index in
mockProfile.places.createFolder(parentGUID: root, title: "Folder \(index)", position: nil).uponQueue(.main) { guid in
guard let guid = guid.successValue else {
XCTFail("CreateFolder method did not return GUID", file: file, line: line)
return
}
self.createdGuids.append(guid)
}
}
// Make sure the folders we create are deleted at the end of the test
addTeardownBlock { [weak self] in
self?.createdGuids.forEach { guid in
_ = self?.mockProfile.places.deleteBookmarkNode(guid: guid)
}
}
}
func createSeparators(separatorCount: Int, withRoot root: String, file: StaticString = #filePath, line: UInt = #line) {
(1...separatorCount).forEach { index in
mockProfile.places.createSeparator(parentGUID: root, position: nil).uponQueue(.main) { guid in
guard let guid = guid.successValue else {
XCTFail("CreateFolder method did not return GUID", file: file, line: line)
return
}
self.createdGuids.append(guid)
}
}
// Make sure the separators we create are deleted at the end of the test
addTeardownBlock { [weak self] in
self?.createdGuids.forEach { guid in
_ = self?.mockProfile.places.deleteBookmarkNode(guid: guid)
}
}
}
func createBookmarks(bookmarkCount: Int, withRoot root: String) {
(1...bookmarkCount).forEach { index in
let bookmark = ShareItem(url: "http://www.example.com/\(index)", title: "Example \(index)", favicon: nil)
_ = mockProfile.places.createBookmark(parentGUID: root,
url: bookmark.url,
title: bookmark.title,
position: nil).value
}
// Make sure the bookmarks we create are deleted at the end of the test
addTeardownBlock { [weak self] in
self?.deleteBookmarks(bookmarkCount: bookmarkCount)
}
}
func deleteBookmarks(bookmarkCount: Int) {
(1...bookmarkCount).forEach { index in
_ = mockProfile.places.deleteBookmarksWithURL(url: "http://www.example.com/\(index)")
}
}
func updateData(expectedRatingPromptOpenCount: Int, file: StaticString = #filePath, line: UInt = #line) {
let expectation = self.expectation(description: "Rating prompt manager data is loaded")
promptManager.updateData(dataLoadingCompletion: { [weak self] in
guard let promptManager = self?.promptManager else {
XCTFail("Should have reference to promptManager", file: file, line: line)
return
}
promptManager.showRatingPromptIfNeeded()
XCTAssertEqual(self?.ratingPromptOpenCount, expectedRatingPromptOpenCount, file: file, line: line)
expectation.fulfill()
})
waitForExpectations(timeout: 5, handler: nil)
}
}
// MARK: - Setup helpers
private extension RatingPromptManagerTests {
func setupEnvironment(numberOfSession: Int32 = 5,
hasCumulativeDaysOfUse: Bool = true,
isBrowserDefault: Bool = false,
functionName: String = #function) {
mockProfile = MockProfile(databasePrefix: functionName)
mockProfile.reopen()
mockProfile.prefs.setInt(numberOfSession, forKey: PrefsKeys.SessionCount)
setupPromptManager(hasCumulativeDaysOfUse: hasCumulativeDaysOfUse)
RatingPromptManager.isBrowserDefault = isBrowserDefault
}
func setupPromptManager(hasCumulativeDaysOfUse: Bool) {
let mockCounter = CumulativeDaysOfUseCounterMock(hasCumulativeDaysOfUse)
sentry = CrashingMockSentryClient()
promptManager = RatingPromptManager(profile: mockProfile,
daysOfUseCounter: mockCounter,
sentry: sentry)
}
func createSite(number: Int) -> Site {
let site = Site(url: "http://s\(number)ite\(number).com/foo", title: "A \(number)")
site.id = number
site.guid = "abc\(number)def"
return site
}
var ratingPromptOpenCount: Int {
UserDefaults.standard.object(forKey: RatingPromptManager.UserDefaultsKey.keyRatingPromptRequestCount.rawValue) as? Int ?? 0
}
}
// MARK: - CumulativeDaysOfUseCounterMock
class CumulativeDaysOfUseCounterMock: CumulativeDaysOfUseCounter {
private let hasMockRequiredDaysOfUse: Bool
init(_ hasRequiredCumulativeDaysOfUse: Bool) {
self.hasMockRequiredDaysOfUse = hasRequiredCumulativeDaysOfUse
}
override var hasRequiredCumulativeDaysOfUse: Bool {
return hasMockRequiredDaysOfUse
}
}
// MARK: - CrashingMockSentryClient
class CrashingMockSentryClient: SentryProtocol {
var enableCrashOnLastLaunch = false
var crashedLastLaunch: Bool {
return enableCrashOnLastLaunch
}
}
// MARK: - URLOpenerSpy
class URLOpenerSpy: URLOpenerProtocol {
var capturedURL: URL?
var openURLCount = 0
func open(_ url: URL) {
capturedURL = url
openURLCount += 1
}
}
| mpl-2.0 |
meanjoe45/JKBCrypt | examples/JKBCrypt/JKBCryptTests/JKBCryptTests.swift | 1 | 901 | //
// JKBCryptTests.swift
// JKBCryptTests
//
// Created by Joe Kramer on 6/19/15.
// Copyright (c) 2015 Joe Kramer. All rights reserved.
//
import UIKit
import XCTest
class JKBCryptTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
AlexRamey/mbird-iOS | iOS Client/DevotionsController/DevotionScheduler.swift | 1 | 2874 | //
// DevotionScheduler.swift
// iOS Client
//
// Created by Alex Ramey on 5/17/18.
// Copyright © 2018 Mockingbird. All rights reserved.
//
import Foundation
import UserNotifications
enum NotificationPermission {
case allowed, denied, error
}
protocol DevotionScheduler {
func cancelNotifications()
func promptForNotifications(withDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int, completion: @escaping (NotificationPermission) -> Void)
}
class Scheduler: DevotionScheduler {
let center = UNUserNotificationCenter.current()
func cancelNotifications() {
self.center.removeAllPendingNotificationRequests()
}
func promptForNotifications(withDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int, completion: @escaping (NotificationPermission) -> Void) {
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if granted {
self.scheduleNotifications(withCenter: self.center, forDevotions: devotions, atHour: hour, minute: minute)
completion(.allowed)
} else if error != nil {
completion(.error)
} else {
completion(.denied)
}
}
}
private func scheduleNotifications(withCenter center: UNUserNotificationCenter, forDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int) {
let startDate = Date().toMMddString()
let sortedDevotions = devotions.sorted {$0.date < $1.date}
guard let startIndex = (sortedDevotions.index { $0.dateAsMMdd == startDate }) else {
return
}
var index = startIndex
var outstandingNotifications: Int = 0
while outstandingNotifications < MBConstants.DEVOTION_NOTIFICATION_WINDOW_SIZE {
outstandingNotifications += 1
let devotion = sortedDevotions[index]
let notificationId = "daily-devotion-\(devotion.dateAsMMdd)"
if let dateComponents = devotion.dateComponentsForNotification(hour: hour, minute: minute) {
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let content = DevotionNotificationContent(devotion: devotion)
let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
center.add(request)
}
index = (index + 1) % sortedDevotions.count
}
}
}
extension Date {
static let ddMMFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd"
return formatter
}()
func toMMddString() -> String {
return Date.ddMMFormatter.string(from: self)
}
}
| mit |
BuildGamesWithUs/TurnKitFramework | TurnKit/TurnKitiOSTests/Config.swift | 1 | 325 | //
// Config.swift
// TurnKit
//
// Created by Shawn Campbell on 7/27/15.
// Copyright © 2015 TeamAwesomeMcPants. All rights reserved.
//
import Foundation
/*
* Config object to store options for the
* turn based game.
*
*
*/
class Config: NSObject {
var Sync : Bool = false
var NumberOfPlayers : Int = 0
} | mit |
KrishMunot/swift | test/DebugInfo/dynamic_layout.swift | 6 | 525 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
func markUsed<T>(_ t: T) {}
class Class <T> {
var x: T
init(_x : T) {x = _x}
// Verify that the mangling of the decl context of the type U is correct.
// CHECK: !DICompositeType({{.*}}name: "{{[^"]*}}_TtQq_FC14dynamic_layout5Class3foo{{[^"]*}}"
func foo <U> (_ y : U) -> (T,U) {
var tuple = (x,y)
return tuple
}
}
func main() {
var v = Class<Int64>(_x: 1)
var tuple = v.foo("hi")
markUsed(tuple.0)
markUsed(tuple.1)
}
main()
| apache-2.0 |
JuanjoArreola/Apic | Sources/Route.swift | 1 | 1513 | import Foundation
public enum Route {
case get(String)
case post(String)
case put(String)
case delete(String)
case head(String)
case patch(String)
func getURL() throws -> URL {
switch self {
case .get(let string): return try url(from: string)
case .post(let string): return try url(from: string)
case .put(let string): return try url(from: string)
case .delete(let string): return try url(from: string)
case .head(let string): return try url(from: string)
case .patch(let string): return try url(from: string)
}
}
var httpMethod: String {
switch self {
case .get: return "GET"
case .post: return "POST"
case .put: return "PUT"
case .delete: return "DELETE"
case .head: return "HEAD"
case .patch: return "PATCH"
}
}
var preferredParameterEncoding: ParameterEncoding {
switch self {
case .get: return .url
case .post: return .json
case .put: return .json
case .delete: return .url
case .head: return .url
case .patch: return .json
}
}
private func url(from string: String) throws -> URL {
if let url = URL(string: string) {
return url
}
throw RepositoryError.invalidURL(url: string)
}
}
public enum RepositoryError: Error {
case invalidURL(url: String)
case encodingError
case networkConnection
}
| mit |
tangbing/swift_budejie | swift_budejie/classes/Other/Define.swift | 1 | 491 |
//
// myView.swift
// swift_budejie
//
// Created by mac on 2017/7/13.
// Copyright © 2017年 macTb. All rights reserved.
//
import UIKit
public let ScreenW: CGFloat = UIScreen.main.bounds.size.width
public let ScreenH: CGFloat = UIScreen.main.bounds.size.height
public let RgbGlobalBg: UIColor = UIColor.init(red: 223/225.0, green: 223/225.0, blue: 223/225.0, alpha: 1.0)
public let RgbTagBg: UIColor = UIColor.init(red: 223/225.0, green: 223/225.0, blue: 223/225.0, alpha: 1.0)
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/28182-anonymous-namespace-favorcalloverloads.swift | 5 | 212 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case found by https://github.com/jtbandes (Jacob Bandes-Storch)
// <rdar://23719809>
func~=switch 0{case 0
| apache-2.0 |
victoraliss0n/FireRecord | FireRecord/Source/Extensions/Database/Limitable+FirebaseModel.swift | 2 | 697 | //
// Limitable+FirebaseModel.swift
// FireRecord
//
// Created by Victor Alisson on 28/09/17.
//
import Foundation
public extension Limitable where Self: FirebaseModel {
static func `where`(value: Any) -> Self.Type {
Self.fireRecordQuery = Self.fireRecordQuery?.queryEqual(toValue: value)
return self
}
public static func start(atValue value: Any) -> Self.Type {
Self.fireRecordQuery = Self.fireRecordQuery?.queryStarting(atValue: value)
return self
}
public static func end(atValue value: Any) -> Self.Type {
Self.fireRecordQuery = Self.fireRecordQuery?.queryEnding(atValue: value)
return self
}
}
| mit |
xwu/swift | stdlib/public/Concurrency/AsyncPrefixSequence.swift | 1 | 3777 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Returns an asynchronous sequence, up to the specified maximum length,
/// containing the initial elements of the base asynchronous sequence.
///
/// Use `prefix(_:)` to reduce the number of elements produced by the
/// asynchronous sequence.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `prefix(_:)` method causes the modified
/// sequence to pass through the first six values, then end.
///
/// for await number in Counter(howHigh: 10).prefix(6) {
/// print("\(number) ")
/// }
/// // prints "1 2 3 4 5 6"
///
/// If the count passed to `prefix(_:)` exceeds the number of elements in the
/// base sequence, the result contains all of the elements in the sequence.
///
/// - Parameter count: The maximum number of elements to return. The value of
/// `count` must be greater than or equal to zero.
/// - Returns: An asynchronous sequence starting at the beginning of the
/// base sequence with at most `count` elements.
@inlinable
public __consuming func prefix(
_ count: Int
) -> AsyncPrefixSequence<Self> {
precondition(count >= 0,
"Can't prefix a negative number of elements from an async sequence")
return AsyncPrefixSequence(self, count: count)
}
}
/// An asynchronous sequence, up to a specified maximum length,
/// containing the initial elements of a base asynchronous sequence.
@available(SwiftStdlib 5.5, *)
public struct AsyncPrefixSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let count: Int
@usableFromInline
init(_ base: Base, count: Int) {
self.base = base
self.count = count
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncPrefixSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The prefix sequence produces whatever type of element its base iterator
/// produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the prefix sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var remaining: Int
@usableFromInline
init(_ baseIterator: Base.AsyncIterator, count: Int) {
self.baseIterator = baseIterator
self.remaining = count
}
/// Produces the next element in the prefix sequence.
///
/// Until reaching the number of elements to include, this iterator calls
/// `next()` on its base iterator and passes through the result. After
/// reaching the maximum number of elements, subsequent calls to `next()`
/// return `nil`.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
if remaining != 0 {
remaining &-= 1
return try await baseIterator.next()
} else {
return nil
}
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), count: count)
}
}
| apache-2.0 |
MichleMin/ElegantSlideMenuView | iOSDemo/iOSDemo/ShareholdeCenterNoCell.swift | 1 | 267 | //
// ShareholdeCenterNoCell.swift
// KWallet
//
// Created by Min on 2017/3/21.
// Copyright © 2017年 cdu.com. All rights reserved.
//
import UIKit
class ShareholdeCenterNoCell: UICollectionViewCell {
override func awakeFromNib() {
}
}
| mit |
SandeepTharu/CustomView | CustomView/AppDelegate.swift | 1 | 2156 | //
// AppDelegate.swift
// CustomView
//
// Created by Anit Shrestha Manadhar on 1/27/16.
// Copyright © 2016 Technotroop. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
mikekavouras/Glowb-iOS | Glowb/Wizard/Models/DeviceCommunicationManager.swift | 1 | 4907 | //
// ParticleSetupCommunicationManager.swift
// ParticleConnect
//
// Created by Mike Kavouras on 8/28/16.
// Copyright © 2016 Mike Kavouras. All rights reserved.
//
import Foundation
enum DeviceType: String {
case core = "Core"
case photon = "Photon"
case electron = "Electron"
}
class DeviceCommunicationManager {
static let ConnectionEndpointAddress = "192.168.0.1"
static let ConnectionEndpointPortString = "5609"
static let ConnectionEndpointPort = 5609;
var connection: DeviceConnection?
var connectionCommand: (() -> Void)?
var completionCommand: ((ResultType<JSON, ConnectionError>) -> Void)?
// MARK: Public API
func sendCommand<T: ParticleCommunicable>(_ type: T.Type, completion: @escaping (ResultType<T.ResponseType, ConnectionError>) -> Void) {
runCommand(onConnection: { connection in
connection.writeString(T.command)
}, onCompletion: { result in
switch result {
case .success(let json):
if let stuff = T.parse(json) {
completion(.success(stuff))
}
case .failure(let error):
completion(.failure(error))
}
})
}
func configureAP(network: Network, completion: @escaping (ResultType<JSON, ConnectionError>) -> Void) {
runCommand(onConnection: { connection in
guard let json = network.asJSON,
let data = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted),
let jsonString = String(data: data, encoding: String.Encoding.utf8) else
{
completion(.failure(ConnectionError.couldNotConnect))
return
}
let command = String(format: "configure-ap\n%ld\n\n%@", jsonString.count, jsonString)
connection.writeString(command)
}, onCompletion: completion)
}
func connectAP(completion: @escaping (ResultType<JSON, ConnectionError>) -> Void) {
runCommand(onConnection: { connection in
let request: JSON = ["idx":0]
guard let json = try? JSONSerialization.data(withJSONObject: request, options: .prettyPrinted),
let jsonString = String(data: json, encoding: String.Encoding.utf8) else
{
completion(.failure(ConnectionError.couldNotConnect))
return
}
let command = String(format: "connect-ap\n%ld\n\n%@", jsonString.count, jsonString)
connection.writeString(command)
}, onCompletion: completion)
}
// MARK: Run commands
private func runCommand(onConnection: @escaping (DeviceConnection) -> Void,
onCompletion: @escaping (ResultType<JSON, ConnectionError>) -> Void) {
guard DeviceCommunicationManager.canSendCommandCall() else { return }
completionCommand = onCompletion
openConnection { connection in
onConnection(connection)
}
}
private func openConnection(withCommand command: @escaping (DeviceConnection) -> Void) {
let ipAddress = DeviceCommunicationManager.ConnectionEndpointAddress
let port = DeviceCommunicationManager.ConnectionEndpointPort
connection = DeviceConnection(withIPAddress: ipAddress, port: port)
connection!.delegate = self;
connectionCommand = { [unowned self] in
command(self.connection!)
}
}
// MARK: Wifi connection
class func canSendCommandCall() -> Bool {
// TODO: refer to original source
if !Wifi.isDeviceConnected(.photon) {
return false
}
return true
}
}
// MARK: - Connection delegate
extension DeviceCommunicationManager: DeviceConnectionDelegate {
func deviceConnection(connection: DeviceConnection, didReceiveData data: String) {
do {
guard let json = try JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: .allowFragments) as? JSON else {
completionCommand?(.failure(ConnectionError.jsonParseError))
return
}
completionCommand?(.success(json))
}
catch {
completionCommand?(.failure(ConnectionError.jsonParseError))
}
}
func deviceConnection(connection: DeviceConnection, didUpdateState state: DeviceConnectionState) {
switch state {
case .opened:
connectionCommand?()
case .openTimeout:
completionCommand?(.failure(ConnectionError.timeout))
case .error:
completionCommand?(.failure(ConnectionError.couldNotConnect))
default: break
}
}
}
| mit |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/CountryPicker/CountryPickerModel.swift | 2 | 1603 | //
// CountryPickerModel.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 03/11/2016.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class CountryPickerModel: BaseModel {
override func willStartModelLoading(callback: @escaping Callback) {
callback(true, nil, nil, nil)
}
override func didFinishModelLoading(data: Any?, error: ErrorEntity?) {
// ...
}
}
| mit |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Extensions/Date+Common.swift | 2 | 7351 | //
// Date+Common.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 26/10/2016.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
let kLocaleEnglish = "en_GB"
let kLocaleGerman = "de_DE"
let kDateFormatForParsingDates = "yyyy-M-d'T'H:mm:ssZ"
// This formatter is used for displaying dates relative to user's location and device setttings
var _dateFormatterForViewingDates: DateFormatter? = nil
// This formatter will be used for parsing dates only
var _dateFormatterForParsingDates: DateFormatter? = nil
let dateConfigInit = {
if (_dateFormatterForParsingDates == nil) {
_dateFormatterForParsingDates = DateFormatter()
// All the dates received from the backend are expected to be UTC/GMT
// Therefore manually setting time zone to 0
_dateFormatterForParsingDates?.timeZone = TimeZone.init(secondsFromGMT:0)
// Need to set this workaround. Otherwise parsing date from string (dateFromString) will return nil if user has turned off 24-Hour time in Time and Date settings.
// Solution used from: http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature
_dateFormatterForParsingDates?.locale = Locale.init(identifier:"en_US_POSIX")
}
if (_dateFormatterForViewingDates == nil) {
_dateFormatterForViewingDates = DateFormatter()
// This will set formatter to relative time zone to user's zone
_dateFormatterForViewingDates?.timeZone = TimeZone.current
}
}
// On how to use init for static class methods
// http://stackoverflow.com/a/24137213/597292
extension Date {
static func setLocale(language: String) {
var newLocale: String?
if (language.isEqual(ConstLangKeys.langEnglish)) {
newLocale = kLocaleEnglish
} else if (language.isEqual(ConstLangKeys.langGerman)) {
newLocale = kLocaleGerman
} else {
newLocale = kLocaleEnglish
}
_dateFormatterForViewingDates?.locale = Locale.init(identifier:newLocale!)
}
// MARK: Retrieving from date
func stringFromDate(format: String) -> String? {
var dateString: String?
synchronized(obj: _dateFormatterForViewingDates!) {
_dateFormatterForViewingDates!.timeZone = TimeZone.current
_dateFormatterForViewingDates!.dateFormat = format;
dateString = _dateFormatterForViewingDates!.string(from: self)
}
return dateString
}
func stringFromDate() -> String? {
var dateString: String?
synchronized(obj: _dateFormatterForViewingDates!) {
_dateFormatterForViewingDates!.dateStyle = DateFormatter.Style.short
_dateFormatterForViewingDates!.timeZone = TimeZone.current
dateString = _dateFormatterForViewingDates!.string(from: self)
_dateFormatterForViewingDates!.dateStyle = DateFormatter.Style.none
}
return dateString
}
func shortStringFromDate() -> String? {
var dateString: String?
synchronized(obj: _dateFormatterForViewingDates!) {
dateString = self.stringFromDate(format:"EEE d MMM")
}
return dateString
}
/*- (NSString *)dateShortStringFromDate:(NSDate *)date;
- (NSString *)timeFromDate;
- (NSString *)localTimeFromDate;
- (NSString *)stringWithoutDayFromDate:(NSDate *)date;
- (NSString *)year:(NSDate *)date;
- (NSString *)month:(NSDate *)date;
- (NSString *)monthFullName:(NSDate *)date;
- (NSString *)day:(NSDate *)date;
- (NSString *)previousMonth:(NSDate *)date;
- (NSString *)nextMonth:(NSDate *)date;
- (NSString *)weekDayShortName:(NSDate *)date;
- (NSString *)weekDayLongName:(NSDate *)date;
- (NSString *)gmtDateTimeString:(NSDate *)date;
- (NSString *)localDate;
- (NSString *)localTime;
- (NSString *)currentTimeZone;
- (NSInteger)timeZoneOffsetFromUTC;
+ (NSInteger)daysWithinEraFromDate:(NSDate *)startDate toDate:(NSDate *)endDate
+ (NSInteger)hoursBetweenDate:(NSDate *)startDate andDate:(NSDate *)endDate;
+ (NSInteger)minutesBetweenDate:(NSDate *)startDate andDate:(NSDate *)endDate;
+ (NSInteger)secondsBetweenDate:(NSDate *)startDate andDate:(NSDate *)endDate;
- (NSInteger)monthTotalDays:(NSDate *)date;
- (NSInteger)previousMonthTotalDays:(NSDate *)date;
- (NSInteger)weekDay:(NSDate *)date;
// MARK: Creating new date
+ (NSDate *)dateFromString:(NSString *)dateString;
+ (NSDate *)dateFromString:(NSString *)dateString format:(NSString *)formatString;
- (NSDate *)dateFromYear:(NSString *)year month:(NSString *)month day:(NSString *)day;
- (NSDate *)dateFromYear:(NSString *)year month:(NSString *)month day:(NSString *)day hour:(NSString *)hour minute:(NSString *)minute;
- (NSDate *)dateFromIntegersYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute;
- (NSDate *)dateWithMidnightTimeFromDate:(NSDate *)date;
- (NSDate *)monthFirstDayDate:(NSDate *)date;
- (NSDate *)monthLastDayDate:(NSDate *)date;
- (NSDate *)dateFromDate:(NSDate *)date byAddingNumberOfDays:(NSInteger)dayNum;
- (NSDate *)dateWithoutTime:(NSDate *)date;
+ (BOOL)date:(NSDate *)date1 isLaterThanOrEqualTo:(NSDate *)date2;
+ (BOOL)date:(NSDate *)date1 isEarlierThanOrEqualTo:(NSDate*)date2;
+ (BOOL)date:(NSDate *)date1 isLaterThan:(NSDate*)date2;
+ (BOOL)date:(NSDate *)date1 isEarlierThan:(NSDate*)date2;
+ (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2;
+ (BOOL)isSameMonthWithDate1:(NSDate*)date1 date2:(NSDate*)date2;
- (void)calculateSiblingMonthsForDate:(NSDate *)date siblingLength:(NSInteger)months earlierDate:(NSDate **)earlierDate laterDate:(NSDate **)laterDate;*/
}
| mit |
ScoutHarris/WordPress-iOS | WordPress/Classes/Extensions/String+RegEx.swift | 1 | 2882 | import Foundation
// MARK: - String: RegularExpression Helpers
//
extension String {
/// Find all matches of the specified regex.
///
/// - Parameters:
/// - regex: the regex to use.
/// - options: the regex options.
///
/// - Returns: the requested matches.
///
func matches(regex: String, options: NSRegularExpression.Options = []) -> [NSTextCheckingResult] {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: characters.count)
return regex.matches(in: self, options: [], range: fullRange)
}
/// Replaces all matches of a given RegEx, with a template String.
///
/// - Parameters:
/// - regex: the regex to use.
/// - template: the template string to use for the replacement.
/// - options: the regex options.
///
/// - Returns: a new string after replacing all matches with the specified template.
///
func replacingMatches(of regex: String, with template: String, options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: characters.count)
return regex.stringByReplacingMatches(in: self,
options: [],
range: fullRange,
withTemplate: template)
}
/// Replaces all matches of a given RegEx using a provided block.
///
/// - Parameters:
/// - regex: the regex to use for pattern matching.
/// - options: the regex options.
/// - block: the block that will be used for the replacement logic.
///
/// - Returns: the new string.
///
func replacingMatches(of regex: String, options: NSRegularExpression.Options = [], using block: (String, [String]) -> String) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: characters.count)
let matches = regex.matches(in: self, options: [], range: fullRange)
var newString = self
for match in matches.reversed() {
let matchRange = range(from: match.range)
let matchString = substring(with: matchRange)
var submatchStrings = [String]()
for submatchIndex in 0 ..< match.numberOfRanges {
let submatchRange = self.range(from: match.rangeAt(submatchIndex))
let submatchString = self.substring(with: submatchRange)
submatchStrings.append(submatchString)
}
newString.replaceSubrange(matchRange, with: block(matchString, submatchStrings))
}
return newString
}
}
| gpl-2.0 |
darrarski/SharedShopping-iOS | SharedShoppingApp/UI/Alert/ViewControllers/AlertViewControllerFactory.swift | 1 | 1405 | import UIKit
protocol AlertViewControllerCreating {
func createAlertViewController(viewModel: AlertViewModel) -> UIViewController
}
class AlertViewControllerFactory: AlertViewControllerCreating {
typealias ActionFactory = (String, UIAlertActionStyle, @escaping (UIAlertAction) -> Void) -> UIAlertAction
init(actionFactory: @escaping ActionFactory) {
self.actionFactory = actionFactory
}
// MARK: AlertViewControllerCreating
func createAlertViewController(viewModel: AlertViewModel) -> UIViewController {
let viewController = UIAlertController(title: viewModel.title,
message: viewModel.message,
preferredStyle: .alert)
viewModel.actions.forEach { actionViewModel in
let action = actionFactory(actionViewModel.title, alertActionStyle(for: actionViewModel.style), { _ in
actionViewModel.handler()
})
viewController.addAction(action)
}
return viewController
}
// MARK: Private
private let actionFactory: ActionFactory
private func alertActionStyle(for style: AlertActionViewModel.Style) -> UIAlertActionStyle {
switch style {
case .confirm: return .default
case .cancel: return .cancel
case .destruct: return .destructive
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/10903-no-stacktrace.swift | 11 | 259 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum b {
struct D {
class a {
{
}
func a {
case
{
protocol P {
let start = {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14653-swift-sourcemanager-getmessage.swift | 11 | 225 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
{
var b {
{
{
[ {
extension Array {
class
case ,
| mit |
Cristian-A/tigress.cli | Tigress/Terminal/ConsoleIO.swift | 1 | 2035 | // + -------------------------------------- +
// | ConsoleIO.swift |
// | |
// | Class ConsoleIO |
// | |
// | Created by Cristian A. |
// | Copyright © cr. All rights reserved. |
// + -------------------------------------- +
import Foundation
class ConsoleIO {
/// Options available to the user.
enum OptionType: String {
// TODO: Add File Option
case text = "t"
// case file = "f"
case help = "h"
case unknown
init(value: String) {
switch value {
case "t", "text": self = .text
// case "f", "file": self = .file
case "h", "help": self = .help
default: self = .unknown
}
}
}
/// Initializes the IO
/// information module.
init() {
let argc = CommandLine.argc
let args = CommandLine.arguments
if args.count < 2 {
printUsage()
return
}
let argument = args[1]
let (option, value) = getOption(argument.substring(from: argument.characters.index(argument.startIndex, offsetBy: 1)))
switch option {
case .text:
if argc != 3 {
if argc > 3 {
print("Syntax Error: Too many arguments for option \(option.rawValue).")
} else {
print("Syntax Error: Too few arguments for option \(option.rawValue).")
}
print("Type 'tigress -h' to open the help page.")
} else {
let text = args[2]
let stripe = Tigress.stripeHash(of: text)
let paw = Tigress.pawHash(of: text)
print("")
print("Hash (Stripe): \(stripe)")
print("Paw Shorthand: \(paw)")
print("")
}
// case .file: break
case .help:
printUsage()
case .unknown:
print("Syntax Error: Unknown option '\(value)'")
printUsage()
}
}
/// Prints the usage.
func printUsage() {
print("")
print("Usage: tigress [-t text]")
print("")
}
/// Gets the selected option.
func getOption(_ option: String) -> (option: OptionType, value: String) {
return (OptionType(value: option), option)
}
}
| mit |
CosmicMind/Algorithm | Tests/SortedMultiSetTests.swift | 1 | 8421 | /*
* 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 XCTest
@testable import Algorithm
class SortedMultiSetTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testInt() {
var s = SortedMultiSet<Int>()
XCTAssert(0 == s.count, "Test failed, got \(s.count).")
for _ in 0..<1000 {
s.insert(1)
s.insert(2)
s.insert(3)
}
XCTAssert(3000 == s.count, "Test failed.\(s)")
XCTAssert(1 == s[0], "Test failed.")
XCTAssert(2 == s[1000], "Test failed.")
XCTAssert(3 == s[2000], "Test failed.")
for _ in 0..<500 {
s.remove(1)
s.remove(3)
}
XCTAssert(1000 == s.count, "Test failed.")
s.remove(2)
s.remove(2)
s.insert(10)
XCTAssert(1 == s.count, "Test failed.")
s.remove(10)
XCTAssert(0 == s.count, "Test failed.")
s.insert(1)
s.insert(2)
s.insert(3)
s.remove(1, 2)
XCTAssert(1 == s.count, "Test failed.")
s.removeAll()
XCTAssert(0 == s.count, "Test failed.")
}
func testRemove() {
var s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9)
s1.remove(1, 2, 3, 5)
XCTAssert(5 == s1.count, "Test failed.")
}
func testIntersect() {
let s1 = SortedMultiSet<Int>(elements: 1, 1, 2, 3, 4, 5, 5)
let s2 = SortedMultiSet<Int>(elements: 1, 1, 2, 5, 6, 7, 8, 9, 10)
let s3 = SortedMultiSet<Int>(elements: 1, 1, 2, 5, 5, 10, 11, 12, 13, 14, 15)
XCTAssert(SortedMultiSet<Int>(elements: 1, 1, 2, 5) == s1.intersection(s2), "Test failed. \(s1.intersection(s2))")
XCTAssert(SortedMultiSet<Int>(elements: 1, 1, 2, 5, 5) == s1.intersection(s3), "Test failed. \(s1.intersection(s3))")
}
func testIntersectInPlace() {
var s1 = SortedMultiSet<Int>(elements: 1, 1, 2, 3, 4, 5)
var s2 = SortedMultiSet<Int>(elements: 1, 1, 2, 5, 6, 7, 8, 9, 10)
s1.formIntersection(s2)
XCTAssert(SortedMultiSet<Int>(elements: 1, 1, 2, 5) == s1, "Test failed. \(s1)")
s1.insert(3, 4, 5, 5, 5)
s2.insert(5)
s1.formIntersection(s2)
XCTAssert(SortedMultiSet<Int>(elements: 1, 1, 2, 5, 5) == s1, "Test failed. \(s1)")
}
func testIsDisjointWith() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3)
let s2 = SortedMultiSet<Int>(elements: 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 5, 6, 7)
XCTAssertFalse(s1.isDisjoint(with: s2), "Test failed.")
XCTAssert(s1.isDisjoint(with: s3), "Test failed.")
XCTAssertFalse(s2.isDisjoint(with: s3), "Test failed.")
}
func testSubtract() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 3, 3, 4, 5)
let s2 = SortedMultiSet<Int>(elements: 4, 5, -1)
let s3 = SortedMultiSet<Int>(elements: 3, 5, 0, -7)
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 3, 3) == s1.subtracting(s2), "Test failed. \(s1.subtracting(s2))")
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 3, 4) == s1.subtracting(s3), "Test failed. \(s1.subtracting(s3))")
}
func testSubtractInPlace() {
var s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 3, 3, 4, 5)
let s2 = SortedMultiSet<Int>(elements: 4, 5, -1)
let s3 = SortedMultiSet<Int>(elements: 3, 5, 0, -7)
s1.subtract(s2)
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 3, 3) == s1, "Test failed. \(s1)")
s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 3, 3, 4, 5)
s1.subtract(s3)
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 3, 4) == s1, "Test failed. \(s1)")
}
func testUnion() {
let s1 = SortedMultiSet<Int>(elements: 0, 0, 1, 2, 3, 4, 7, 7, 5)
let s2 = SortedMultiSet<Int>(elements: 5, -1, 6, 8, 7, 9, 9)
XCTAssert(SortedMultiSet<Int>(elements: -1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9) == s1.union(s2), "Test failed. \(s1.union(s2))")
}
func testUnionInPlace() {
var s1 = SortedMultiSet<Int>(elements: 0, 0, 1, 2, 3, 4, 7, 7, 5)
let s2 = SortedMultiSet<Int>(elements: 5, -1, 0, 6, 8, 7, 9, 9)
s1.formUnion(s2)
XCTAssert(SortedMultiSet<Int>(elements: -1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9) == s1, "Test failed. \(s1)")
}
func testIsSubsetOf() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 2, 3)
let s2 = SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 2, 2, 3, 4, 5)
XCTAssert(s1 <= s1, "Test failed. \(s1.intersection(s2))")
XCTAssert(s1 <= s2, "Test failed.")
XCTAssertFalse(s1 <= s3, "Test failed.")
}
func testIsSupersetOf() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7)
let s2 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 5, 6, 7, 8)
XCTAssert(s1 >= s1, "Test failed.")
XCTAssert(s1 >= s2, "Test failed.")
XCTAssertFalse(s1 >= s3, "Test failed.")
}
func testIsStrictSubsetOf() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3)
let s2 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 2, 3, 4, 5)
XCTAssert(s1 < s2, "Test failed.")
XCTAssertFalse(s1 < s3, "Test failed.")
}
func testIsStrictSupersetOf() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7)
let s2 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 5, 6, 7, 8)
XCTAssert(s1 > s2, "Test failed.")
XCTAssertFalse(s1 > s3, "Test failed.")
}
func testContains() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7)
XCTAssert(s1.contains(1, 2, 3), "Test failed.")
XCTAssertFalse(s1.contains(1, 2, 3, 10), "Test failed.")
}
func testExclusiveOr() {
let s1 = SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 5, 6, 7)
let s2 = SortedMultiSet<Int>(elements: 1, 2, 3, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 5, 6, 7, 8)
XCTAssert(SortedMultiSet<Int>(elements: 6, 7) == s1.symmetricDifference(s2), "Test failed. \(s1.symmetricDifference(s2))")
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 8) == s1.symmetricDifference(s3), "Test failed. \(s1.symmetricDifference(s3))")
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 3, 4, 6, 7, 8) == s2.symmetricDifference(s3), "Test failed.")
}
func testExclusiveOrInPlace() {
var s1 = SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 5, 6, 7)
var s2 = SortedMultiSet<Int>(elements: 1, 2, 3, 4, 5)
let s3 = SortedMultiSet<Int>(elements: 5, 6, 7, 8)
s1.formSymmetricDifference(s2)
XCTAssert(SortedMultiSet<Int>(elements: 6, 7) == s1, "Test failed.")
s1 = SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 5, 6, 7)
s1.formSymmetricDifference(s3)
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 2, 3, 4, 8) == s1, "Test failed. \(s1)")
s2.formSymmetricDifference(s3)
XCTAssert(SortedMultiSet<Int>(elements: 1, 2, 3, 4, 6, 7, 8) == s2, "Test failed. \(s2)")
}
func testIndexOf() {
var s1 = SortedMultiSet<Int>()
s1.insert(1, 2, 3, 4, 5, 5, 6, 7)
XCTAssert(0 == s1.index(of: 1), "Test failed.")
XCTAssert(6 == s1.index(of: 6), "Test failed.")
XCTAssert(-1 == s1.index(of: 100), "Test failed.")
}
func testPerformance() {
self.measure() {}
}
}
| mit |
cezarywojcik/Operations | Sources/Core/Shared/AdvancedOperation.swift | 1 | 31635 | //
// AdvancedOperation.swift
// YapDB
//
// Created by Daniel Thorpe on 25/06/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
// swiftlint:disable file_length
import Foundation
// swiftlint:disable type_body_length
/**
Abstract base AdvancedOperation class which subclasses `NSOperation`.
Operation builds on `NSOperation` in a few simple ways.
1. For an instance to become `.Ready`, all of its attached
`OperationCondition`s must be satisfied.
2. It is possible to attach `OperationObserver`s to an instance,
to be notified of lifecycle events in the operation.
*/
open class AdvancedOperation: Operation, OperationDebuggable {
fileprivate enum State: Int, Comparable {
// The initial state
case initialized
// Ready to begin evaluating conditions
case pending
// It is executing
case executing
// Execution has completed, but not yet notified queue
case finishing
// The operation has finished.
case finished
func canTransitionToState(_ other: State, whenCancelled cancelled: Bool) -> Bool {
switch (self, other) {
case (.initialized, .pending),
(.pending, .executing),
(.executing, .finishing),
(.finishing, .finished):
return true
case (.pending, .finishing) where cancelled:
// When an operation is cancelled it can go from pending direct to finishing.
return true
default:
return false
}
}
}
/**
Type to express the intent of the user in regards to executing an Operation instance
- see: https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html#//apple_ref/doc/uid/TP40015243-CH39
*/
@objc public enum UserIntent: Int {
case none = 0, sideEffect, initiated
internal var qos: QualityOfService {
switch self {
case .initiated, .sideEffect:
return .userInitiated
default:
return .default
}
}
}
/// - returns: a unique String which can be used to identify the operation instance
public let identifier = UUID().uuidString
fileprivate let stateLock = NSRecursiveLock()
fileprivate var _log = Protector<LoggerType>(Logger())
fileprivate var _state = State.initialized
fileprivate var _internalErrors = [Error]()
fileprivate var _isTransitioningToExecuting = false
fileprivate var _isHandlingFinish = false
fileprivate var _isHandlingCancel = false
fileprivate var _observers = Protector([OperationObserverType]())
fileprivate let disableAutomaticFinishing: Bool
internal fileprivate(set) var directDependencies = Set<Operation>()
internal fileprivate(set) var conditions = Set<Condition>()
internal var indirectDependencies: Set<Operation> {
return Set(conditions.flatMap { $0.directDependencies })
}
// Internal operation properties which are used to manage the scheduling of dependencies
internal fileprivate(set) var evaluateConditionsOperation: GroupOperation? = .none
fileprivate var _cancelled = false // should always be set by .cancel()
/// Access the internal errors collected by the Operation
open var errors: [Error] {
return stateLock.withCriticalScope { _internalErrors }
}
/**
Expresses the user intent in regards to the execution of this Operation.
Setting this property will set the appropriate quality of service parameter
on the Operation.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
*/
open var userIntent: UserIntent = .none {
didSet {
setQualityOfServiceFromUserIntent(userIntent)
}
}
/**
Modifies the quality of service of the underlying operation.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
- returns: a Bool indicating whether or not the quality of service is .UserInitiated
*/
@available(*, unavailable, message: "This property has been deprecated in favor of userIntent.")
open var userInitiated: Bool {
get {
return qualityOfService == .userInitiated
}
set {
precondition(state < .executing, "Cannot modify userInitiated after execution has begun.")
qualityOfService = newValue ? .userInitiated : .default
}
}
/**
# Access the logger for this Operation
The `log` property can be used as the interface to access the logger.
e.g. to output a message with `LogSeverity.Info` from inside
the `Operation`, do this:
```swift
log.info("This is my message")
```
To adjust the instance severity of the LoggerType for the
`Operation`, access it via this property too:
```swift
log.severity = .Verbose
```
The logger is a very simple type, and all it does beyond
manage the enabled status and severity is send the String to
a block on a dedicated serial queue. Therefore to provide custom
logging, set the `logger` property:
```swift
log.logger = { message in sendMessageToAnalytics(message) }
```
By default, the Logger's logger block is the same as the global
LogManager. Therefore to use a custom logger for all Operations:
```swift
LogManager.logger = { message in sendMessageToAnalytics(message) }
```
*/
open var log: LoggerType {
get {
let operationName = self.operationName
return _log.read { _LoggerOperationContext(parentLogger: $0, operationName: operationName) }
}
set {
_log.write { (ward: inout LoggerType) in
ward = newValue
}
}
}
// MARK: - Initialization
public override init() {
self.disableAutomaticFinishing = false
super.init()
}
// MARK: - Disable Automatic Finishing
/**
Ability to override Operation's built-in finishing behavior, if a
subclass requires full control over when finish() is called.
Used for GroupOperation to implement proper .Finished state-handling
(only finishing after all child operations have finished).
The default behavior of Operation is to automatically call finish()
when:
(a) it's cancelled, whether that occurs:
- prior to the Operation starting
(in which case, Operation will skip calling execute())
- on another thread at the same time that the operation is
executing
(b) when willExecuteObservers log errors
To ensure that an Operation subclass does not finish until the
subclass calls finish():
call `super.init(disableAutomaticFinishing: true)` in the init.
IMPORTANT: If disableAutomaticFinishing == TRUE, the subclass is
responsible for calling finish() in *ALL* cases, including when the
operation is cancelled.
You can react to cancellation using WillCancelObserver/DidCancelObserver
and/or checking periodically during execute with something like:
```swift
guard !cancelled else {
// do any necessary clean-up
finish() // always call finish if automatic finishing is disabled
return
}
```
*/
public init(disableAutomaticFinishing: Bool) {
self.disableAutomaticFinishing = disableAutomaticFinishing
super.init()
}
// MARK: - Add Condition
/**
Add a condition to the to the operation, can only be done prior to the operation starting.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
- parameter condition: type conforming to protocol `OperationCondition`.
*/
@available(iOS, deprecated: 8, message: "Refactor OperationCondition types as Condition subclasses.")
@available(OSX, deprecated: 10.10, message: "Refactor OperationCondition types as Condition subclasses.")
open func addCondition(_ condition: OperationCondition) {
assert(state < .executing, "Cannot modify conditions after operation has begun executing, current state: \(state).")
let operation = WrappedOperationCondition(condition)
if let dependency = condition.dependencyForOperation(self) {
operation.addDependency(dependency)
}
conditions.insert(operation)
}
open func addCondition(_ condition: Condition) {
assert(state < .executing, "Cannot modify conditions after operation has begun executing, current state: \(state).")
conditions.insert(condition)
}
// MARK: - Add Observer
/**
Add an observer to the to the operation, can only be done
prior to the operation starting.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
- parameter observer: type conforming to protocol `OperationObserverType`.
*/
open func addObserver(_ observer: OperationObserverType) {
observers.append(observer)
observer.didAttachToOperation(self)
}
// MARK: - Execution
/**
Subclasses should override this method to perform their specialized task.
They must call a finish methods in order to complete.
*/
open func execute() {
print("\(type(of: self)) must override `execute()`.", terminator: "")
finish()
}
/**
Subclasses may override `finished(_:)` if they wish to react to the operation
finishing with errors.
- parameter errors: an array of `ErrorType`.
*/
@available(*, unavailable, renamed: "operationDidFinish")
open func finished(_ errors: [Error]) {
operationDidFinish(errors)
}
/**
Subclasses may override `operationWillFinish(_:)` if they wish to
react to the operation finishing with errors.
- parameter errors: an array of `ErrorType`.
*/
open func operationWillFinish(_ errors: [Error]) { /* No op */ }
/**
Subclasses may override `operationDidFinish(_:)` if they wish to
react to the operation finishing with errors.
- parameter errors: an array of `ErrorType`.
*/
open func operationDidFinish(_ errors: [Error]) { /* no op */ }
// MARK: - Cancellation
/**
Cancel the operation with an error.
- parameter error: an optional `ErrorType`.
*/
open func cancelWithError(_ error: Error? = .none) {
cancelWithErrors(error.map { [$0] } ?? [])
}
/**
Cancel the operation with multiple errors.
- parameter errors: an `[ErrorType]` defaults to empty array.
*/
open func cancelWithErrors(_ errors: [Error] = []) {
stateLock.withCriticalScope {
if !errors.isEmpty {
log.warning("Did cancel with errors: \(errors).")
}
_internalErrors += errors
}
cancel()
}
/**
Subclasses may override `operationWillCancel(_:)` if they wish to
react to the operation finishing with errors.
- parameter errors: an array of `ErrorType`.
*/
open func operationWillCancel(_ errors: [Error]) { /* No op */ }
/**
Subclasses may override `operationDidCancel(_:)` if they wish to
react to the operation finishing with errors.
- parameter errors: an array of `ErrorType`.
*/
open func operationDidCancel() { /* No op */ }
public final override func cancel() {
let willCancel = stateLock.withCriticalScope { () -> Bool in
// Do not cancel if already finished or finishing, or cancelled
guard state <= .executing && !_cancelled else { return false }
// Only a single call to cancel should continue
guard !_isHandlingCancel else { return false }
_isHandlingCancel = true
return true
}
guard willCancel else { return }
operationWillCancel(errors)
willChangeValue(forKey: Operation.KeyPath.Cancelled.rawValue)
willCancelObservers.forEach { $0.willCancelOperation(self, errors: self.errors) }
stateLock.withCriticalScope {
_cancelled = true
}
operationDidCancel()
didCancelObservers.forEach { $0.didCancelOperation(self) }
log.verbose("Did cancel.")
didChangeValue(forKey: Operation.KeyPath.Cancelled.rawValue)
// Call super.cancel() to trigger .isReady state change on cancel
// as well as isReady KVO notification.
super.cancel()
let willFinish = stateLock.withCriticalScope { () -> Bool in
let willFinish = isExecuting && !disableAutomaticFinishing && !_isHandlingFinish
if willFinish {
_isHandlingFinish = true
}
return willFinish
}
if willFinish {
_finish([], fromCancel: true)
}
}
/**
This method is used for debugging the current state of an `Operation`.
- returns: An `OperationDebugData` object containing debug data for the current `Operation`.
*/
open func debugData() -> OperationDebugData {
return OperationDebugData(
description: "Operation: \(self)",
properties: [
"cancelled": String(isCancelled),
"state": String(describing: state),
"errorCount": String(errors.count),
"QOS": String(describing: qualityOfService)
],
conditions: conditions.map { String(describing: $0) },
dependencies: dependencies.map { ($0 as? OperationDebuggable)?.debugData() ?? $0.debugDataNSOperation() })
}
internal func removeDirectDependency(_ directDependency: Operation) {
precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
directDependencies.remove(directDependency)
super.removeDependency(directDependency)
}
}
// swiftlint:enable type_body_length
// MARK: - State
public extension AdvancedOperation {
fileprivate var state: State {
get {
return stateLock.withCriticalScope { _state }
}
set (newState) {
stateLock.withCriticalScope {
assert(_state.canTransitionToState(newState, whenCancelled: isCancelled), "Attempting to perform illegal cyclic state transition, \(_state) -> \(newState) for operation: \(identity).")
log.verbose("\(_state) -> \(newState)")
_state = newState
}
}
}
/// Boolean indicator for whether the Operation is currently executing or not
final override var isExecuting: Bool {
return state == .executing
}
/// Boolean indicator for whether the Operation has finished or not
final override var isFinished: Bool {
return state == .finished
}
/// Boolean indicator for whether the Operation has cancelled or not
final override var isCancelled: Bool {
return stateLock.withCriticalScope { _cancelled }
}
/// Boolean flag to indicate that the Operation failed due to errors.
var failed: Bool {
return errors.count > 0
}
internal func willEnqueue() {
state = .pending
}
}
// MARK: - Dependencies
public extension AdvancedOperation {
internal func evaluateConditions() -> GroupOperation {
func createEvaluateConditionsOperation() -> GroupOperation {
// Set the operation on each condition
conditions.forEach { $0.operation = self }
let evaluator = GroupOperation(operations: Array(conditions))
evaluator.name = "Condition Evaluator for: \(operationName)"
super.addDependency(evaluator)
return evaluator
}
assert(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
let evaluator = createEvaluateConditionsOperation()
// Add an observer to the evaluator to see if any of the conditions failed.
evaluator.addObserver(WillFinishObserver { [unowned self] operation, errors in
if errors.count > 0 {
// If conditions fail, we should cancel the operation
self.cancelWithErrors(errors)
}
})
directDependencies.forEach {
evaluator.addDependency($0)
}
return evaluator
}
internal func addDependencyOnPreviousMutuallyExclusiveOperation(_ operation: AdvancedOperation) {
precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
super.addDependency(operation)
}
internal func addDirectDependency(_ directDependency: Operation) {
precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
directDependencies.insert(directDependency)
super.addDependency(directDependency)
}
/// Public override to get the dependencies
final override var dependencies: [Operation] {
return Array(directDependencies.union(indirectDependencies))
}
/**
Add another `NSOperation` as a dependency. It is a programmatic error to call
this method after the receiver has already started executing. Therefore, best
practice is to add dependencies before adding them to operation queues.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
- parameter operation: a `NSOperation` instance.
*/
final override func addDependency(_ operation: Operation) {
precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
addDirectDependency(operation)
}
/**
Remove another `NSOperation` as a dependency. It is a programmatic error to call
this method after the receiver has already started executing. Therefore, best
practice is to manage dependencies before adding them to operation
queues.
- requires: self must not have started yet. i.e. either hasn't been added
to a queue, or is waiting on dependencies.
- parameter operation: a `NSOperation` instance.
*/
final override func removeDependency(_ operation: Operation) {
precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).")
removeDirectDependency(operation)
}
}
// MARK: - Observers
public extension AdvancedOperation {
fileprivate(set) var observers: [OperationObserverType] {
get {
return _observers.read { $0 }
}
set {
_observers.write { (ward: inout [OperationObserverType]) in
ward = newValue
}
}
}
internal var willExecuteObservers: [OperationWillExecuteObserver] {
return observers.compactMap { $0 as? OperationWillExecuteObserver }
}
internal var willCancelObservers: [OperationWillCancelObserver] {
return observers.compactMap { $0 as? OperationWillCancelObserver }
}
internal var didCancelObservers: [OperationDidCancelObserver] {
return observers.compactMap { $0 as? OperationDidCancelObserver }
}
internal var didProduceOperationObservers: [OperationDidProduceOperationObserver] {
return observers.compactMap { $0 as? OperationDidProduceOperationObserver }
}
internal var willFinishObservers: [OperationWillFinishObserver] {
return observers.compactMap { $0 as? OperationWillFinishObserver }
}
internal var didFinishObservers: [OperationDidFinishObserver] {
return observers.compactMap { $0 as? OperationDidFinishObserver }
}
}
// MARK: - Execution
public extension AdvancedOperation {
/// Starts the operation, correctly managing the cancelled state. Cannot be over-ridden
final override func start() {
// Don't call super.start
guard !isCancelled || disableAutomaticFinishing else {
finish()
return
}
main()
}
/// Triggers execution of the operation's task, correctly managing errors and the cancelled state. Cannot be over-ridden
final override func main() {
// Inform observers that the operation will execute
willExecuteObservers.forEach { $0.willExecuteOperation(self) }
let nextState = stateLock.withCriticalScope { () -> (AdvancedOperation.State?) in
assert(!isExecuting, "Operation is attempting to execute, but is already executing.")
guard !_isTransitioningToExecuting else {
assertionFailure("Operation is attempting to execute twice, concurrently.")
return nil
}
// Check to see if the operation has now been finished
// by an observer (or anything else)
guard state <= .pending else { return nil }
// Check to see if the operation has now been cancelled
// by an observer
guard (_internalErrors.isEmpty && !isCancelled) || disableAutomaticFinishing else {
_isHandlingFinish = true
return AdvancedOperation.State.finishing
}
// Transition to the .isExecuting state, and explicitly send the required KVO change notifications
_isTransitioningToExecuting = true
return AdvancedOperation.State.executing
}
guard nextState != .finishing else {
_finish([], fromCancel: true)
return
}
guard nextState == .executing else { return }
willChangeValue(forKey: Operation.KeyPath.Executing.rawValue)
let nextState2 = stateLock.withCriticalScope { () -> (AdvancedOperation.State?) in
// Re-check state, since it could have changed on another thread (ex. via finish)
guard state <= .pending else { return nil }
state = .executing
_isTransitioningToExecuting = false
if isCancelled && !disableAutomaticFinishing && !_isHandlingFinish {
// Operation was cancelled, automatic finishing is enabled,
// but cancel is not (yet/ever?) handling the finish.
// Because cancel could have already passed the check for executing,
// handle calling finish here.
_isHandlingFinish = true
return .finishing
}
return .executing
}
// Always send the closing didChangeValueForKey
didChangeValue(forKey: Operation.KeyPath.Executing.rawValue)
guard nextState2 != .finishing else {
_finish([], fromCancel: true)
return
}
guard nextState2 == .executing else { return }
log.verbose("Will Execute")
execute()
}
/**
Produce another operation on the same queue that this instance is on.
- parameter operation: a `NSOperation` instance.
*/
final func produceOperation(_ operation: Operation) {
precondition(state > .initialized, "Cannot produce operation while not being scheduled on a queue.")
log.verbose("Did produce \(operation.operationName)")
didProduceOperationObservers.forEach { $0.operation(self, didProduceOperation: operation) }
}
}
// MARK: - Finishing
public extension AdvancedOperation {
/**
Finish method which must be called eventually after an operation has
begun executing, unless it is cancelled.
- parameter errors: an array of `ErrorType`, which defaults to empty.
*/
final func finish(_ receivedErrors: [Error] = []) {
_finish(receivedErrors, fromCancel: false)
}
fileprivate final func _finish(_ receivedErrors: [Error], fromCancel: Bool = false) {
let willFinish = stateLock.withCriticalScope { () -> Bool in
// Do not finish if already finished or finishing
guard state <= .finishing else { return false }
// Only a single call to _finish should continue
// (.cancel() sets _isHandlingFinish and fromCancel=true, if appropriate.)
guard !_isHandlingFinish || fromCancel else { return false }
_isHandlingFinish = true
return true
}
guard willFinish else { return }
// NOTE:
// - The stateLock should only be held when necessary, and should not
// be held when notifying observers (whether via KVO or Operation's
// observers) or deadlock can result.
let changedExecutingState = isExecuting
if changedExecutingState {
willChangeValue(forKey: Operation.KeyPath.Executing.rawValue)
}
stateLock.withCriticalScope {
state = .finishing
}
if changedExecutingState {
didChangeValue(forKey: Operation.KeyPath.Executing.rawValue)
}
let errors = stateLock.withCriticalScope { () -> [Error] in
_internalErrors.append(contentsOf: receivedErrors)
return _internalErrors
}
if errors.isEmpty {
log.verbose("Will finish with no errors.")
}
else {
log.warning("Will finish with \(errors.count) errors.")
}
operationWillFinish(errors)
willChangeValue(forKey: Operation.KeyPath.Finished.rawValue)
willFinishObservers.forEach { $0.willFinishOperation(self, errors: errors) }
stateLock.withCriticalScope {
state = .finished
}
operationDidFinish(errors)
didFinishObservers.forEach { $0.didFinishOperation(self, errors: errors) }
let message = !errors.isEmpty ? "errors: \(errors)" : "no errors"
log.verbose("Did finish with \(message)")
didChangeValue(forKey: Operation.KeyPath.Finished.rawValue)
}
/// Convenience method to simplify finishing when there is only one error.
@objc(aDifferentFinishWithANameThatDoesntConflictWithSomethingInObjectiveC:)
final func finish(_ receivedError: Error?) {
finish(receivedError.map { [$0]} ?? [])
}
/**
Public override which deliberately crashes your app, as usage is considered an antipattern
To promote best practices, where waiting is never the correct thing to do,
we will crash the app if this is called. Instead use discrete operations and
dependencies, or groups, or semaphores or even NSLocking.
*/
final override func waitUntilFinished() {
fatalError("Waiting on operations is an anti-pattern. Remove this ONLY if you're absolutely sure there is No Other Way™. Post a question in https://github.com/danthorpe/Operations if you are unsure.")
}
}
private func < (lhs: AdvancedOperation.State, rhs: AdvancedOperation.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func == (lhs: AdvancedOperation.State, rhs: AdvancedOperation.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/**
A common error type for Operations. Primarily used to indicate error when
an Operation's conditions fail.
*/
public enum OperationError: Error, Equatable {
/// Indicates that a condition of the Operation failed.
case conditionFailed
/// Indicates that the operation timed out.
case operationTimedOut(TimeInterval)
/// Indicates that a parent operation was cancelled (with errors).
case parentOperationCancelledWithErrors([Error])
}
/// OperationError is Equatable.
public func == (lhs: OperationError, rhs: OperationError) -> Bool {
switch (lhs, rhs) {
case (.conditionFailed, .conditionFailed):
return true
case let (.operationTimedOut(aTimeout), .operationTimedOut(bTimeout)):
return aTimeout == bTimeout
case let (.parentOperationCancelledWithErrors(aErrors), .parentOperationCancelledWithErrors(bErrors)):
// Not possible to do a real equality check here.
return aErrors.count == bErrors.count
default:
return false
}
}
extension Operation {
/**
Chain completion blocks.
- parameter block: a Void -> Void block
*/
public func addCompletionBlock(_ block: @escaping () -> Void) {
if let existing = completionBlock {
completionBlock = {
existing()
block()
}
}
else {
completionBlock = block
}
}
/**
Add multiple depdendencies to the operation. Will add each
dependency in turn.
- parameter dependencies: and array of `NSOperation` instances.
*/
public func addDependencies<S>(_ dependencies: S) where S: Sequence, S.Iterator.Element: Operation {
precondition(!isExecuting && !isFinished, "Cannot modify the dependencies after the operation has started executing.")
dependencies.forEach(addDependency)
}
/**
Remove multiple depdendencies from the operation. Will remove each
dependency in turn.
- parameter dependencies: and array of `NSOperation` instances.
*/
public func removeDependencies<S>(_ dependencies: S) where S: Sequence, S.Iterator.Element: Operation {
precondition(!isExecuting && !isFinished, "Cannot modify the dependencies after the operation has started executing.")
dependencies.forEach(removeDependency)
}
/// Removes all the depdendencies from the operation.
public func removeDependencies() {
removeDependencies(dependencies)
}
internal func setQualityOfServiceFromUserIntent(_ userIntent: AdvancedOperation.UserIntent) {
qualityOfService = userIntent.qos
}
}
private extension Operation {
enum KeyPath: String {
case Cancelled = "isCancelled"
case Executing = "isExecuting"
case Finished = "isFinished"
}
}
extension NSLock {
func withCriticalScope<T>(_ block: () -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
extension NSRecursiveLock {
func withCriticalScope<T>(_ block: () -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
extension Array where Element: Operation {
internal var splitNSOperationsAndOperations: ([Operation], [AdvancedOperation]) {
return reduce(([], [])) { result, element in
var (ns, op) = result
if let operation = element as? AdvancedOperation {
op.append(operation)
}
else {
ns.append(element)
}
return (ns, op)
}
}
internal var userIntent: AdvancedOperation.UserIntent {
get {
let (_, ops) = splitNSOperationsAndOperations
return ops.map { $0.userIntent }.max { $0.rawValue < $1.rawValue } ?? .none
}
}
internal func forEachOperation(body: (AdvancedOperation) throws -> Void) rethrows {
try forEach {
if let operation = $0 as? AdvancedOperation {
try body(operation)
}
}
}
}
// swiftlint:enable file_length
| mit |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/Omar-Villegas/Ejercicios-Libro/Ejercicio79-5.swift | 1 | 744 | /*
Created by Omar Villegas on 09/02/17.
Copyright © 2017 Omar Villegas. All rights reserved.
Materia: Patrones de Diseño
Alumno: Villegas Castillo Omar
No. de control: 13211106
Ejercicios del PDF "Problemas para Resolver por Computadora 1993"
PROBLEMA 79 CAPÍTULO 5
Encontrar el promedio de 1000 números tomados al azar
*/
import Foundation
var suma = Double(0)
var numero = 0
//CICLO PARA SUMAR LOS NUMEROS ALEATORIOS
for i in 1...1000
{
var numeror = Double(arc4random() & 100 + 1) //GENERAR NÚMEROS RANDOM
suma = numeror + suma //SUMA DE LOS NÚMEROS
}
var promedio = Double(0)
//DIVISIÓN PARA EL PROMEDIO
promedio = (suma / 1000)
//IMPRIMIR RESULTADO
print("El promedio de 100 números es : \(promedio)")
| gpl-3.0 |
rice-apps/wellbeing-app | app/Pods/Socket.IO-Client-Swift/Source/SocketEngineWebsocket.swift | 2 | 3254 | //
// SocketEngineWebsocket.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/15/16.
//
// 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
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
/// Sends an engine.io message through the WebSocket transport.
///
/// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
///
/// - parameter message: The message to send.
/// - parameter withType: The type of message to send.
/// - parameter withData: The data associated with this message.
func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data])
}
// WebSocket methods
extension SocketEngineWebsocket {
func probeWebSocket() {
if ws?.isConnected ?? false {
sendWebSocketMessage("probe", withType: .ping, withData: [])
}
}
/// Sends an engine.io message through the WebSocket transport.
///
/// You shouldn't call this directly, instead call the `write` method on `SocketEngine`.
///
/// - parameter message: The message to send.
/// - parameter withType: The type of message to send.
/// - parameter withData: The data associated with this message.
public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.write(string: "\(type.rawValue)\(str)")
for data in datas {
if case let .left(bin) = createBinaryDataForSend(using: data) {
ws?.write(data: bin)
}
}
}
// MARK: Starscream delegate methods
/// Delegate method for when a message is received.
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
/// Delegate method for when binary is received.
public func websocketDidReceiveData(socket: WebSocket, data: Data) {
parseEngineData(data)
}
}
| mit |
Anders123fr/GrowingTextViewHandler | GrowingTextViewHandler/FormViewController.swift | 1 | 1136 | //
// FormViewController.swift
// GrowingTextViewHandler
//
// Created by Susmita Horrow on 08/08/16.
// Copyright © 2016 hsusmita.com. All rights reserved.
//
import UIKit
class FormViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
}
}
extension FormViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FormTableViewCellIdentifier") as? FormTableViewCell
cell?.delegate = self
return cell!
}
}
extension FormViewController: FormTableViewCellDelegate {
func formTableViewCell(_ formTableViewCell: FormTableViewCell, shouldChangeHeight height: CGFloat) {
tableView.beginUpdates()
tableView.endUpdates()
}
}
| mit |
klein-thibault/StarcraftWatch | StarcraftWatch/Models/Video.swift | 1 | 1171 | //
// Video.swift
// StarcraftWatch
//
// Created by Thibault Klein on 9/14/15.
// Copyright © 2015 Prolific Interactive. All rights reserved.
//
import Foundation
import UIKit
struct Video {
let id: String
var URL: NSURL?
let name: String
let thumbnailURL: NSURL
let largeThumbnailURL: NSURL
let description: String
init(id: String, name: String, description: String, thumbnail: NSURL, largeThumbnailURL: NSURL) {
self.id = id
self.name = name
self.description = description
self.thumbnailURL = thumbnail
self.largeThumbnailURL = largeThumbnailURL
}
func videoFormattedDescription() -> String {
return self.name + "\n" + self.description
}
mutating func videoFormattedURL() -> NSURL? {
if self.URL == nil {
let urlStr = "https://www.youtube.com/watch?v=\(self.id)"
self.URL = (NSURL(string: urlStr))
}
let videosDict = HCYoutubeParser.h264videosWithYoutubeURL(self.URL)
if let video720URL = videosDict["hd720"] as? String {
return NSURL(string: video720URL)!
}
return nil
}
}
| mit |
blkbrds/intern09_final_project_tung_bien | MyApp/Define/Color.swift | 1 | 891 | //
// Color.swift
// MyApp
//
// Created by DaoNV on 6/19/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
/**
This file defines all colors which are used in this application.
Please navigate by the control as prefix.
*/
import UIKit
extension App {
struct Color {
static let navigationBar = UIColor.black
static let navigationBarTextColor = UIColor.white
static let tableHeaderView = UIColor.gray
static let tableFooterView = UIColor.red
static let tableCellTextLabel = UIColor.yellow
static let greenTheme = UIColor.RGB(0, 192, 110)
static let grayBackground = UIColor.RGB(230, 230, 230)
static func button(state: UIControlState) -> UIColor {
switch state {
case UIControlState.normal: return .blue
default: return .gray
}
}
}
}
| mit |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/PaymentDateTableViewCell.swift | 1 | 863 | //
// PaymentDateTableViewCell.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 13/3/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import UIKit
public class PaymentDateTableViewCell: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDate: UILabel!
override public init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func awakeFromNib() {
super.awakeFromNib()
self.lblTitle.text = "Fecha".localized
}
override public func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
jum/CocoaLumberjack | Integration/watchOSSwiftIntegration Extension/ExtensionDelegate.swift | 2 | 3446 | // Software License Agreement (BSD License)
//
// Copyright (c) 2010-2019, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
| bsd-3-clause |
CPRTeam/CCIP-iOS | Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift | 3 | 7247 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public final class Rabbit: BlockCipher {
public enum Error: Swift.Error {
case invalidKeyOrInitializationVector
}
/// Size of IV in bytes
public static let ivSize = 64 / 8
/// Size of key in bytes
public static let keySize = 128 / 8
/// Size of block in bytes
public static let blockSize = 128 / 8
public var keySize: Int {
self.key.count
}
/// Key
private let key: Key
/// IV (optional)
private let iv: Array<UInt8>?
/// State variables
private var x = Array<UInt32>(repeating: 0, count: 8)
/// Counter variables
private var c = Array<UInt32>(repeating: 0, count: 8)
/// Counter carry
private var p7: UInt32 = 0
/// 'a' constants
private var a: Array<UInt32> = [
0x4d34d34d,
0xd34d34d3,
0x34d34d34,
0x4d34d34d,
0xd34d34d3,
0x34d34d34,
0x4d34d34d,
0xd34d34d3
]
// MARK: - Initializers
public convenience init(key: Array<UInt8>) throws {
try self.init(key: key, iv: nil)
}
public init(key: Array<UInt8>, iv: Array<UInt8>?) throws {
self.key = Key(bytes: key)
self.iv = iv
guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else {
throw Error.invalidKeyOrInitializationVector
}
}
// MARK: -
fileprivate func setup() {
self.p7 = 0
// Key divided into 8 subkeys
let k = Array<UInt32>(unsafeUninitializedCapacity: 8) { buf, count in
for j in 0..<8 {
buf[j] = UInt32(self.key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(self.key[Rabbit.blockSize - (2 * j + 2)]) << 8)
}
count = 8
}
// Initialize state and counter variables from subkeys
for j in 0..<8 {
if j % 2 == 0 {
self.x[j] = (k[(j + 1) % 8] << 16) | k[j]
self.c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8]
} else {
self.x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8]
self.c[j] = (k[j] << 16) | k[(j + 1) % 8]
}
}
// Iterate system four times
self.nextState()
self.nextState()
self.nextState()
self.nextState()
// Reinitialize counter variables
for j in 0..<8 {
self.c[j] = self.c[j] ^ self.x[(j + 4) % 8]
}
if let iv = iv {
self.setupIV(iv)
}
}
private func setupIV(_ iv: Array<UInt8>) {
// 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits
// 0 1 2 3 4 5 6 7 IV bytes in array
let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]])
let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]])
let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]])
let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]])
// Modify the counter state as function of the IV
c[0] = self.c[0] ^ iv0
self.c[1] = self.c[1] ^ iv1
self.c[2] = self.c[2] ^ iv2
self.c[3] = self.c[3] ^ iv3
self.c[4] = self.c[4] ^ iv0
self.c[5] = self.c[5] ^ iv1
self.c[6] = self.c[6] ^ iv2
self.c[7] = self.c[7] ^ iv3
// Iterate system four times
self.nextState()
self.nextState()
self.nextState()
self.nextState()
}
private func nextState() {
// Before an iteration the counters are incremented
var carry = self.p7
for j in 0..<8 {
let prev = self.c[j]
self.c[j] = prev &+ self.a[j] &+ carry
carry = prev > self.c[j] ? 1 : 0 // detect overflow
}
self.p7 = carry // save last carry bit
// Iteration of the system
self.x = Array<UInt32>(unsafeUninitializedCapacity: 8) { newX, count in
newX[0] = self.g(0) &+ rotateLeft(self.g(7), by: 16) &+ rotateLeft(self.g(6), by: 16)
newX[1] = self.g(1) &+ rotateLeft(self.g(0), by: 8) &+ self.g(7)
newX[2] = self.g(2) &+ rotateLeft(self.g(1), by: 16) &+ rotateLeft(self.g(0), by: 16)
newX[3] = self.g(3) &+ rotateLeft(self.g(2), by: 8) &+ self.g(1)
newX[4] = self.g(4) &+ rotateLeft(self.g(3), by: 16) &+ rotateLeft(self.g(2), by: 16)
newX[5] = self.g(5) &+ rotateLeft(self.g(4), by: 8) &+ self.g(3)
newX[6] = self.g(6) &+ rotateLeft(self.g(5), by: 16) &+ rotateLeft(self.g(4), by: 16)
newX[7] = self.g(7) &+ rotateLeft(self.g(6), by: 8) &+ self.g(5)
count = 8
}
}
private func g(_ j: Int) -> UInt32 {
let sum = self.x[j] &+ self.c[j]
let square = UInt64(sum) * UInt64(sum)
return UInt32(truncatingIfNeeded: square ^ (square >> 32))
}
fileprivate func nextOutput() -> Array<UInt8> {
self.nextState()
var output16 = Array<UInt16>(repeating: 0, count: Rabbit.blockSize / 2)
output16[7] = UInt16(truncatingIfNeeded: self.x[0]) ^ UInt16(truncatingIfNeeded: self.x[5] >> 16)
output16[6] = UInt16(truncatingIfNeeded: self.x[0] >> 16) ^ UInt16(truncatingIfNeeded: self.x[3])
output16[5] = UInt16(truncatingIfNeeded: self.x[2]) ^ UInt16(truncatingIfNeeded: self.x[7] >> 16)
output16[4] = UInt16(truncatingIfNeeded: self.x[2] >> 16) ^ UInt16(truncatingIfNeeded: self.x[5])
output16[3] = UInt16(truncatingIfNeeded: self.x[4]) ^ UInt16(truncatingIfNeeded: self.x[1] >> 16)
output16[2] = UInt16(truncatingIfNeeded: self.x[4] >> 16) ^ UInt16(truncatingIfNeeded: self.x[7])
output16[1] = UInt16(truncatingIfNeeded: self.x[6]) ^ UInt16(truncatingIfNeeded: self.x[3] >> 16)
output16[0] = UInt16(truncatingIfNeeded: self.x[6] >> 16) ^ UInt16(truncatingIfNeeded: self.x[1])
var output8 = Array<UInt8>(repeating: 0, count: Rabbit.blockSize)
for j in 0..<output16.count {
output8[j * 2] = UInt8(truncatingIfNeeded: output16[j] >> 8)
output8[j * 2 + 1] = UInt8(truncatingIfNeeded: output16[j])
}
return output8
}
}
// MARK: Cipher
extension Rabbit: Cipher {
public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
self.setup()
return Array<UInt8>(unsafeUninitializedCapacity: bytes.count) { result, count in
var output = self.nextOutput()
var byteIdx = 0
var outputIdx = 0
while byteIdx < bytes.count {
if outputIdx == Rabbit.blockSize {
output = self.nextOutput()
outputIdx = 0
}
result[byteIdx] = bytes[byteIdx] ^ output[outputIdx]
byteIdx += 1
outputIdx += 1
}
count = bytes.count
}
}
public func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
try self.encrypt(bytes)
}
}
| gpl-3.0 |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API ClientTests/Tests/Tasks/ScoreTaskCall.swift | 1 | 1962 | //
// ScoreTaskCall.swift
// Habitica API ClientTests
//
// Created by Phillip Thelen on 12.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Quick
import Nimble
import ReactiveSwift
import Habitica_Models
@testable import Habitica_API_Client
class ScoreTaskCallSpec: QuickSpec {
var stubHolder: StubHolderProtocol?
var task: TaskProtocol?
override func spec() {
HabiticaServerConfig.current = HabiticaServerConfig.stub
describe("Score task test") {
beforeEach {
self.task = APITask()
self.stubHolder = StubHolder(stubData: self.dataFor(fileName: "taskResponse", fileExtension: "json"))
}
context("Success") {
it("Should score task up") {
// swiftlint:disable:next force_unwrapping
let call = ScoreTaskCall(task: self.task!, direction: .up, stubHolder: self.stubHolder)
waitUntil(timeout: 0.5) { done in
call.objectSignal.observeValues({ (tasks) in
expect(tasks).toNot(beNil())
done()
})
call.fire()
}
}
}
context("Success") {
it("Should score task down") {
// swiftlint:disable:next force_unwrapping
let call = ScoreTaskCall(task: self.task!, direction: .down, stubHolder: self.stubHolder)
waitUntil(timeout: 0.5) { done in
call.objectSignal.observeValues({ (response) in
expect(response).toNot(beNil())
done()
})
call.fire()
}
}
}
}
}
}
| gpl-3.0 |
goblinr/omim | iphone/Maps/Classes/Components/RatingSummaryView/RatingSummaryViewSettings.swift | 8 | 1332 | import UIKit
struct RatingSummaryViewSettings {
enum Default {
static let backgroundOpacity: CGFloat = 0.16
static let colors: [MWMRatingSummaryViewValueType: UIColor] = [
.noValue: UIColor.lightGray,
.horrible: UIColor.red,
.bad: UIColor.orange,
.normal: UIColor.yellow,
.good: UIColor.green,
.excellent: UIColor.blue,
]
static let images: [MWMRatingSummaryViewValueType: UIImage] = [:]
static let textFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote)
static let textSize = textFont.pointSize
static let value = "2.2"
static let topOffset: CGFloat = 8
static let bottomOffset: CGFloat = 8
static let leadingImageOffset: CGFloat = 12
static let margin: CGFloat = 8
static let trailingTextOffset: CGFloat = 8
static let noValueText = "—"
}
init() {}
var backgroundOpacity = Default.backgroundOpacity
var colors = Default.colors
var images = Default.images
var textFont = Default.textFont
var textSize = Default.textSize
var value = Default.value
var topOffset = Default.topOffset
var bottomOffset = Default.bottomOffset
var leadingImageOffset = Default.leadingImageOffset
var margin = Default.margin
var trailingTextOffset = Default.trailingTextOffset
var noValueText = Default.noValueText
}
| apache-2.0 |
kirayamato1989/KYPhotoBrowser | KYPhotoBrowser/KYPhotoSource.swift | 1 | 524 | //
// KYPhotoSource.swift
// KYPhotoBrowser
//
// Created by 郭帅 on 2016/11/8.
// Copyright © 2016年 郭帅. All rights reserved.
//
import UIKit
public protocol KYPhotoSource {
var url: URL? {get}
var image: UIImage? {get}
var placeholder: UIImage? {get}
var des: String? {get}
func loadIfNeed(progress: ((_ source: KYPhotoSource, _ current: Int64, _ total: Int64) -> ())?, complete: ((_ source: KYPhotoSource, _ image: UIImage?, _ error: Error?) -> ())?)
func releaseImage()
}
| mit |
ingresse/ios-sdk | IngresseSDKTests/Model/TransferTicketTests.swift | 1 | 821 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class TransferTicketTests: XCTestCase {
func testDecode() {
// Given
var json = [String: Any]()
json["id"] = 1
json["guestTypeId"] = 2
json["ticketTypeId"] = 3
json["description"] = "description"
json["name"] = "name"
json["type"] = "type"
// When
let obj = JSONDecoder().decodeDict(of: TransferTicket.self, from: json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.id, 1)
XCTAssertEqual(obj?.guestTypeId, 2)
XCTAssertEqual(obj?.ticketTypeId, 3)
XCTAssertEqual(obj?.desc, "description")
XCTAssertEqual(obj?.name, "name")
XCTAssertEqual(obj?.type, "type")
}
}
| mit |
Ybrin/ExponentialBackOff | Example/Tests/Tests.swift | 1 | 2384 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ExponentialBackOff
import Async
class TableOfContentsSpec: QuickSpec {
var exponentialBackOff: ExponentialBackOffInstance!
var timeOut: TimeInterval!
override func spec() {
beforeEach {
let builder = ExponentialBackOffInstance.Builder()
builder.maxElapsedTimeMillis = 1500
builder.maxIntervalMillis = 500
self.exponentialBackOff = ExponentialBackOffInstance(builder: builder)
self.timeOut = (TimeInterval(builder.maxIntervalMillis) + TimeInterval(builder.maxIntervalMillis)) * 2
}
describe("Testing the exponential backoff algorithm") {
it("Should finish with the state failed") {
waitUntil(timeout: self.timeOut, action: { (done) in
ExponentialBackOff.sharedInstance.runGeneralBackOff(self.exponentialBackOff, codeToRun: { (last, elapsed, completion) in
var number: Int = 0
for i in 1 ... 100 {
number = number + i
}
if number != 5051 {
_ = completion(false)
} else {
_ = completion(true)
}
}, completion: { state in
if state == .failed {
print("Failed!?")
done()
}
})
})
}
it("Should finish with the state succeeded") {
waitUntil(timeout: self.timeOut, action: { (done) in
ExponentialBackOff.sharedInstance.runGeneralBackOff(self.exponentialBackOff, codeToRun: { (last, elapsed, completion) in
var number: Int = 0
for i in 1 ... 100 {
number = number + i
}
if number != 5050 {
_ = completion(false)
} else {
_ = completion(true)
}
}, completion: { state in
if state == .succeeded {
done()
}
})
})
}
}
}
}
| mit |
caicai0/ios_demo | load/Carthage/Checkouts/SwiftSoup/Tests/SwiftSoupTests/TextUtil.swift | 1 | 1115 | //
// TextUtil.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 03/11/16.
// Copyright © 2016 Nabil Chatbi. All rights reserved.
//
import Foundation
@testable import SwiftSoup
class TextUtil {
public static func stripNewlines(_ text: String) -> String {
let regex = try! NCRegularExpression(pattern: "\\n\\s*", options: .caseInsensitive)
var str = text
str = regex.stringByReplacingMatches(in: str, options: [], range: NSRange(0..<str.characters.count), withTemplate: "")
return str
}
}
//extension String{
// func replaceAll(of pattern:String,with replacement:String,options: NSRegularExpression.Options = []) -> String{
// do{
// let regex = try NSRegularExpression(pattern: pattern, options: [])
// let range = NSRange(0..<self.utf16.count)
// return regex.stringByReplacingMatches(in: self, options: [],
// range: range, withTemplate: replacement)
// }catch{
// NSLog("replaceAll error: \(error)")
// return self
// }
// }
//
// func trim() -> String {
// return trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
// }
//}
| mit |
slavapestov/swift | validation-test/compiler_crashers_fixed/27161-swift-typechecker-typecheckpattern.swift | 4 | 269 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c<T where g:a{class T{var f=b=(a{}func b<let a
| apache-2.0 |
slavapestov/swift | stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableCollectionType.swift | 1 | 40514 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
internal enum RangeSelection {
case EmptyRange
case LeftEdge
case RightEdge
case Middle
case LeftHalf
case RightHalf
internal func rangeOf<
C : CollectionType
>(collection: C) -> Range<C.Index> {
switch self {
case .EmptyRange: return collection.endIndex..<collection.endIndex
case .LeftEdge: return collection.startIndex..<collection.startIndex
case .RightEdge: return collection.endIndex..<collection.endIndex
case .Middle:
let start = collection.startIndex.advancedBy(collection.count / 4)
let end = collection.startIndex.advancedBy(3 * collection.count / 4)
return start...end
case .LeftHalf:
let start = collection.startIndex
let end = start.advancedBy(collection.count / 2)
return start..<end
case .RightHalf:
let start = collection.startIndex.advancedBy(collection.count / 2)
let end = collection.endIndex
return start..<end
}
}
}
internal enum IndexSelection {
case Start
case Middle
case End
case Last
internal func indexIn<C : CollectionType>(collection: C) -> C.Index {
switch self {
case .Start: return collection.startIndex
case .Middle: return collection.startIndex.advancedBy(collection.count / 2)
case .End: return collection.endIndex
case .Last: return collection.startIndex.advancedBy(collection.count - 1)
}
}
}
internal struct ReplaceRangeTest {
let collection: [OpaqueValue<Int>]
let newElements: [OpaqueValue<Int>]
let rangeSelection: RangeSelection
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], newElements: [Int],
rangeSelection: RangeSelection, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.newElements = newElements.map(OpaqueValue.init)
self.rangeSelection = rangeSelection
self.expected = expected
self.loc = SourceLoc(file, line, comment: "replaceRange() test data")
}
}
internal struct AppendTest {
let collection: [OpaqueValue<Int>]
let newElement: OpaqueValue<Int>
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], newElement: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.newElement = OpaqueValue(newElement)
self.expected = expected
self.loc = SourceLoc(file, line, comment: "append() test data")
}
}
internal struct AppendContentsOfTest {
let collection: [OpaqueValue<Int>]
let newElements: [OpaqueValue<Int>]
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], newElements: [Int], expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.newElements = newElements.map(OpaqueValue.init)
self.expected = expected
self.loc = SourceLoc(file, line, comment: "append() test data")
}
}
internal struct InsertTest {
let collection: [OpaqueValue<Int>]
let newElement: OpaqueValue<Int>
let indexSelection: IndexSelection
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], newElement: Int, indexSelection: IndexSelection,
expected: [Int], file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.newElement = OpaqueValue(newElement)
self.indexSelection = indexSelection
self.expected = expected
self.loc = SourceLoc(file, line, comment: "insert() test data")
}
}
internal struct InsertContentsOfTest {
let collection: [OpaqueValue<Int>]
let newElements: [OpaqueValue<Int>]
let indexSelection: IndexSelection
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], newElements: [Int], indexSelection: IndexSelection,
expected: [Int], file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.newElements = newElements.map(OpaqueValue.init)
self.indexSelection = indexSelection
self.expected = expected
self.loc = SourceLoc(file, line, comment: "insertContentsOf() test data")
}
}
internal struct RemoveAtIndexTest {
let collection: [OpaqueValue<Int>]
let indexSelection: IndexSelection
let expectedRemovedElement: Int
let expectedCollection: [Int]
let loc: SourceLoc
internal init(
collection: [Int], indexSelection: IndexSelection,
expectedRemovedElement: Int, expectedCollection: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.indexSelection = indexSelection
self.expectedRemovedElement = expectedRemovedElement
self.expectedCollection = expectedCollection
self.loc = SourceLoc(file, line, comment: "removeAtIndex() test data")
}
}
internal struct RemoveLastNTest {
let collection: [OpaqueValue<Int>]
let numberToRemove: Int
let expectedCollection: [Int]
let loc: SourceLoc
internal init(
collection: [Int], numberToRemove: Int, expectedCollection: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.numberToRemove = numberToRemove
self.expectedCollection = expectedCollection
self.loc = SourceLoc(file, line, comment: "removeLast(n: Int) test data")
}
}
internal struct RemoveRangeTest {
let collection: [OpaqueValue<Int>]
let rangeSelection: RangeSelection
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], rangeSelection: RangeSelection, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.rangeSelection = rangeSelection
self.expected = expected
self.loc = SourceLoc(file, line, comment: "removeRange() test data")
}
}
internal struct RemoveAllTest {
let collection: [OpaqueValue<Int>]
let expected: [Int]
let loc: SourceLoc
internal init(
collection: [Int], expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.expected = expected
self.loc = SourceLoc(file, line, comment: "removeAll() test data")
}
}
internal struct ReserveCapacityTest {
let collection: [OpaqueValue<Int>]
let requestedCapacity: Int
let loc: SourceLoc
internal init(
collection: [Int], requestedCapacity: Int,
file: String = #file, line: UInt = #line
) {
self.collection = collection.map(OpaqueValue.init)
self.requestedCapacity = requestedCapacity
self.loc = SourceLoc(file, line, comment: "removeAll() test data")
}
}
internal struct OperatorPlusTest {
let lhs: [OpaqueValue<Int>]
let rhs: [OpaqueValue<Int>]
let expected: [Int]
let loc: SourceLoc
internal init(
lhs: [Int], rhs: [Int], expected: [Int],
file: String = #file, line: UInt = #line
) {
self.lhs = lhs.map(OpaqueValue.init)
self.rhs = rhs.map(OpaqueValue.init)
self.expected = expected
self.loc = SourceLoc(file, line, comment: "`func +` test data")
}
}
let removeLastTests: [RemoveLastNTest] = [
RemoveLastNTest(
collection: [1010],
numberToRemove: 0,
expectedCollection: [1010]
),
RemoveLastNTest(
collection: [1010],
numberToRemove: 1,
expectedCollection: []
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 0,
expectedCollection: [1010, 2020, 3030, 4040, 5050]
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 1,
expectedCollection: [1010, 2020, 3030, 4040]
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 2,
expectedCollection: [1010, 2020, 3030]
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 3,
expectedCollection: [1010, 2020]
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 4,
expectedCollection: [1010]
),
RemoveLastNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 5,
expectedCollection: []
),
]
let appendContentsOfTests: [AppendContentsOfTest] = [
AppendContentsOfTest(
collection: [],
newElements: [],
expected: []),
AppendContentsOfTest(
collection: [1010],
newElements: [],
expected: [1010]),
AppendContentsOfTest(
collection: [1010, 2020, 3030, 4040],
newElements: [],
expected: [1010, 2020, 3030, 4040]),
AppendContentsOfTest(
collection: [],
newElements: [1010],
expected: [1010]),
AppendContentsOfTest(
collection: [1010],
newElements: [2020],
expected: [1010, 2020]),
AppendContentsOfTest(
collection: [1010],
newElements: [2020, 3030, 4040],
expected: [1010, 2020, 3030, 4040]),
AppendContentsOfTest(
collection: [1010, 2020, 3030, 4040],
newElements: [5050, 6060, 7070, 8080],
expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]),
]
extension TestSuite {
/// Adds a set of tests for `RangeReplaceableCollectionType`.
///
/// - parameter makeCollection: a factory function that creates a collection
/// instance with provided elements.
///
/// This facility can be used to test collection instances that can't be
/// constructed using APIs in the protocol (for example, `Array`s that wrap
/// `NSArray`s).
public func addForwardRangeReplaceableCollectionTests<
Collection : RangeReplaceableCollectionType,
CollectionWithEquatableElement : RangeReplaceableCollectionType
where
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addForwardCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// init()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).init()/semantics") {
let c = Collection()
expectEqualSequence([], c.map { extractValue($0).value })
}
//===----------------------------------------------------------------------===//
// init(SequenceType)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).init(SequenceType)/semantics") {
for test in appendContentsOfTests {
let c = Collection(test.newElements.map(wrapValue))
expectEqualSequence(
test.newElements.map { $0.value },
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// replaceRange()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).replaceRange()/semantics") {
let tests: [ReplaceRangeTest] = [
ReplaceRangeTest(
collection: [],
newElements: [],
rangeSelection: .EmptyRange,
expected: []),
ReplaceRangeTest(
collection: [],
newElements: [1010, 2020, 3030],
rangeSelection: .EmptyRange,
expected: [1010, 2020, 3030]),
ReplaceRangeTest(
collection: [4040],
newElements: [1010, 2020, 3030],
rangeSelection: .LeftEdge,
expected: [1010, 2020, 3030, 4040]),
ReplaceRangeTest(
collection: [1010],
newElements: [2020, 3030, 4040],
rangeSelection: .RightEdge,
expected: [1010, 2020, 3030, 4040]),
ReplaceRangeTest(
collection: [1010, 2020, 3030],
newElements: [4040],
rangeSelection: .RightEdge,
expected: [1010, 2020, 3030, 4040]),
ReplaceRangeTest(
collection: [1010, 2020, 3030, 4040, 5050],
newElements: [9090],
rangeSelection: .Middle,
expected: [1010, 9090, 5050]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let rangeToReplace = test.rangeSelection.rangeOf(c)
let newElements =
MinimalForwardCollection(elements: test.newElements.map(wrapValue))
c.replaceRange(rangeToReplace, with: newElements)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// append()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).append()/semantics") {
let tests: [AppendTest] = [
AppendTest(
collection: [],
newElement: 1010,
expected: [1010]),
AppendTest(
collection: [1010],
newElement: 2020,
expected: [1010, 2020]),
AppendTest(
collection: [1010, 2020, 3030, 4040, 5050, 6060, 7070],
newElement: 8080,
expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let newElement = wrapValue(test.newElement)
c.append(newElement)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// appendContentsOf()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).appendContentsOf()/semantics") {
for test in appendContentsOfTests {
var c = makeWrappedCollection(test.collection)
let newElements =
MinimalForwardCollection(elements: test.newElements.map(wrapValue))
c.appendContentsOf(newElements)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// insert()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).insert()/semantics") {
let tests: [InsertTest] = [
InsertTest(
collection: [],
newElement: 1010,
indexSelection: IndexSelection.Start,
expected: [1010]),
InsertTest(
collection: [2020],
newElement: 1010,
indexSelection: .Start,
expected: [1010, 2020]),
InsertTest(
collection: [1010],
newElement: 2020,
indexSelection: .End,
expected: [1010, 2020]),
InsertTest(
collection: [2020, 3030, 4040, 5050],
newElement: 1010,
indexSelection: .Start,
expected: [1010, 2020, 3030, 4040, 5050]),
InsertTest(
collection: [1010, 2020, 3030, 4040],
newElement: 5050,
indexSelection: .End,
expected: [1010, 2020, 3030, 4040, 5050]),
InsertTest(
collection: [1010, 2020, 4040, 5050],
newElement: 3030,
indexSelection: .Middle,
expected: [1010, 2020, 3030, 4040, 5050]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let newElement = wrapValue(test.newElement)
c.insert(newElement, atIndex: test.indexSelection.indexIn(c))
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// insertContentsOf()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).insertContentsOf()/semantics") {
let tests: [InsertContentsOfTest] = [
InsertContentsOfTest(
collection: [],
newElements: [],
indexSelection: IndexSelection.Start,
expected: []),
InsertContentsOfTest(
collection: [],
newElements: [1010],
indexSelection: .Start,
expected: [1010]),
InsertContentsOfTest(
collection: [],
newElements: [1010, 2020, 3030, 4040],
indexSelection: .Start,
expected: [1010, 2020, 3030, 4040]),
InsertContentsOfTest(
collection: [2020],
newElements: [1010],
indexSelection: .Start,
expected: [1010, 2020]),
InsertContentsOfTest(
collection: [1010],
newElements: [2020],
indexSelection: .End,
expected: [1010, 2020]),
InsertContentsOfTest(
collection: [4040],
newElements: [1010, 2020, 3030],
indexSelection: .Start,
expected: [1010, 2020, 3030, 4040]),
InsertContentsOfTest(
collection: [1010],
newElements: [2020, 3030, 4040],
indexSelection: .End,
expected: [1010, 2020, 3030, 4040]),
InsertContentsOfTest(
collection: [1010, 2020, 4040, 5050],
newElements: [3030],
indexSelection: .Middle,
expected: [1010, 2020, 3030, 4040, 5050]),
InsertContentsOfTest(
collection: [4040, 5050, 6060],
newElements: [1010, 2020, 3030],
indexSelection: .Start,
expected: [1010, 2020, 3030, 4040, 5050, 6060]),
InsertContentsOfTest(
collection: [1010, 2020, 3030],
newElements: [4040, 5050, 6060],
indexSelection: .End,
expected: [1010, 2020, 3030, 4040, 5050, 6060]),
InsertContentsOfTest(
collection: [1010, 2020, 3030, 7070, 8080, 9090],
newElements: [4040, 5050, 6060],
indexSelection: .Middle,
expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let newElements =
MinimalForwardCollection(elements: test.newElements.map(wrapValue))
c.insertContentsOf(newElements, at: test.indexSelection.indexIn(c))
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// removeAtIndex()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeAtIndex()/semantics") {
let tests: [RemoveAtIndexTest] = [
RemoveAtIndexTest(
collection: [1010],
indexSelection: .Start,
expectedRemovedElement: 1010,
expectedCollection: []),
RemoveAtIndexTest(
collection: [1010, 2020, 3030],
indexSelection: .Start,
expectedRemovedElement: 1010,
expectedCollection: [2020, 3030]),
RemoveAtIndexTest(
collection: [1010, 2020, 3030],
indexSelection: .Middle,
expectedRemovedElement: 2020,
expectedCollection: [1010, 3030]),
RemoveAtIndexTest(
collection: [1010, 2020, 3030],
indexSelection: .Last,
expectedRemovedElement: 3030,
expectedCollection: [1010, 2020]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let removedElement = c.removeAtIndex(test.indexSelection.indexIn(c))
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqual(
test.expectedRemovedElement,
extractValue(removedElement).value,
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// removeFirst()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst()/semantics") {
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
var c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let removedElement = c.removeFirst()
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the collection",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeFirst()/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
_ = c.removeFirst() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeFirst(n: Int)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") {
for test in removeFirstTests {
var c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
c.removeFirst(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the collection",
stackTrace: SourceLocStack().with(test.loc)
)
}
}
self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
c.removeFirst(1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") {
var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init))
expectCrashLater()
c.removeFirst(-1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") {
var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init))
expectCrashLater()
c.removeFirst(5) // Should trap.
}
//===----------------------------------------------------------------------===//
// removeRange()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeRange()/semantics") {
let tests: [RemoveRangeTest] = [
RemoveRangeTest(
collection: [],
rangeSelection: .EmptyRange,
expected: []),
RemoveRangeTest(
collection: [1010],
rangeSelection: .Middle,
expected: []),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040],
rangeSelection: .LeftHalf,
expected: [3030, 4040]),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040],
rangeSelection: .RightHalf,
expected: [1010, 2020]),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040, 5050],
rangeSelection: .Middle,
expected: [1010, 5050]),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040, 5050, 6060],
rangeSelection: .LeftHalf,
expected: [4040, 5050, 6060]),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040, 5050, 6060],
rangeSelection: .RightHalf,
expected: [1010, 2020, 3030]),
RemoveRangeTest(
collection: [1010, 2020, 3030, 4040, 5050, 6060],
rangeSelection: .Middle,
expected: [1010, 6060]),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
let rangeToRemove = test.rangeSelection.rangeOf(c)
c.removeRange(rangeToRemove)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// removeAll()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeAll()/semantics") {
let tests: [RemoveAllTest] = [
RemoveAllTest(
collection: [],
expected: []),
RemoveAllTest(
collection: [1010],
expected: []),
RemoveAllTest(
collection: [1010, 2020, 3030, 4040, 5050],
expected: []),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
c.removeAll()
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
for test in tests {
var c = makeWrappedCollection(test.collection)
c.removeAll(keepCapacity: false)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
for test in tests {
var c = makeWrappedCollection(test.collection)
c.removeAll(keepCapacity: true)
expectEqualSequence(
test.expected,
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// reserveCapacity()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).reserveCapacity()/semantics") {
let tests: [ReserveCapacityTest] = [
ReserveCapacityTest(
collection: [],
requestedCapacity: 0),
ReserveCapacityTest(
collection: [],
requestedCapacity: 3),
ReserveCapacityTest(
collection: [],
requestedCapacity: 100),
ReserveCapacityTest(
collection: [ 1010 ],
requestedCapacity: 0),
ReserveCapacityTest(
collection: [ 1010 ],
requestedCapacity: 3),
ReserveCapacityTest(
collection: [ 1010 ],
requestedCapacity: 100),
ReserveCapacityTest(
collection: [ 1010, 2020, 3030 ],
requestedCapacity: 0),
ReserveCapacityTest(
collection: [ 1010, 2020, 3030 ],
requestedCapacity: 3),
ReserveCapacityTest(
collection: [ 1010, 2020, 3030 ],
requestedCapacity: 100),
]
for test in tests {
var c = makeWrappedCollection(test.collection)
c.reserveCapacity(numericCast(test.requestedCapacity))
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// + operator
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).OperatorPlus") {
let tests: [OperatorPlusTest] = [
OperatorPlusTest(
lhs: [],
rhs: [],
expected: []),
OperatorPlusTest(
lhs: [],
rhs: [ 1010 ],
expected: [ 1010 ]),
OperatorPlusTest(
lhs: [ 1010 ],
rhs: [],
expected: [ 1010 ]),
OperatorPlusTest(
lhs: [ 1010 ],
rhs: [ 2020 ],
expected: [ 1010, 2020 ]),
OperatorPlusTest(
lhs: [ 1010, 2020, 3030 ],
rhs: [],
expected: [ 1010, 2020, 3030 ]),
OperatorPlusTest(
lhs: [],
rhs: [ 1010, 2020, 3030 ],
expected: [ 1010, 2020, 3030 ]),
OperatorPlusTest(
lhs: [ 1010 ],
rhs: [ 2020, 3030, 4040 ],
expected: [ 1010, 2020, 3030, 4040 ]),
OperatorPlusTest(
lhs: [ 1010, 2020, 3030 ],
rhs: [ 4040 ],
expected: [ 1010, 2020, 3030, 4040 ]),
OperatorPlusTest(
lhs: [ 1010, 2020, 3030, 4040 ],
rhs: [ 5050, 6060, 7070 ],
expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]),
OperatorPlusTest(
lhs: [ 1010, 2020, 3030 ],
rhs: [ 4040, 5050, 6060, 7070 ],
expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]),
]
// RangeReplaceableCollectionType + SequenceType
for test in tests {
let lhs = makeWrappedCollection(test.lhs)
let rhs = MinimalSequence(elements: test.rhs.map(wrapValue))
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.lhs.map { $0.value },
lhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
// SequenceType + RangeReplaceableCollectionType
for test in tests {
let lhs = MinimalSequence(elements: test.lhs.map(wrapValue))
let rhs = makeWrappedCollection(test.rhs)
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.rhs.map { $0.value },
rhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
// RangeReplaceableCollectionType + CollectionType
for test in tests {
let lhs = makeWrappedCollection(test.lhs)
let rhs = MinimalForwardCollection(elements: test.rhs.map(wrapValue))
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.lhs.map { $0.value },
lhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.rhs.map { $0.value },
rhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
// RangeReplaceableCollectionType + same RangeReplaceableCollectionType
for test in tests {
let lhs = makeWrappedCollection(test.lhs)
let rhs = makeWrappedCollection(test.rhs)
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.lhs.map { $0.value },
lhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.rhs.map { $0.value },
rhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
// RangeReplaceableCollectionType + MinimalForwardRangeReplaceableCollection
for test in tests {
let lhs = makeWrappedCollection(test.lhs)
let rhs = MinimalForwardRangeReplaceableCollection(
elements: test.rhs.map(wrapValue))
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.lhs.map { $0.value },
lhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.rhs.map { $0.value },
rhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
// MinimalForwardRangeReplaceableCollection + RangeReplaceableCollectionType
for test in tests {
let lhs = MinimalForwardRangeReplaceableCollection(
elements: test.lhs.map(wrapValue))
let rhs = makeWrappedCollection(test.rhs)
let result = lhs + rhs
expectEqualSequence(
test.expected,
result.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.lhs.map { $0.value },
lhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.rhs.map { $0.value },
rhs.map { extractValue($0).value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
} // addForwardRangeReplaceableCollectionTests
public func addBidirectionalRangeReplaceableCollectionTests<
Collection : RangeReplaceableCollectionType,
CollectionWithEquatableElement : RangeReplaceableCollectionType
where
Collection.Index : BidirectionalIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : BidirectionalIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : BidirectionalIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addForwardRangeReplaceableCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
addBidirectionalCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// removeLast()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/semantics") {
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
var c = makeWrappedCollection(test.collection)
let removedElement = c.removeLast()
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value,
stackTrace: SourceLocStack().with(test.loc))
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the collection",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/empty/semantics") {
var c = makeWrappedCollection([])
expectCrashLater()
c.removeLast() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeLast(n: Int)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/semantics") {
for test in removeLastTests {
var c = makeWrappedCollection(test.collection)
c.removeLast(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the collection",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/empty/semantics") {
var c = makeWrappedCollection([])
expectCrashLater()
c.removeLast(1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeNegative/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeLast(-1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeTooMany/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeLast(3) // Should trap.
}
//===----------------------------------------------------------------------===//
} // addBidirectionalRangeReplaceableCollectionTests
public func addRandomAccessRangeReplaceableCollectionTests<
Collection : RangeReplaceableCollectionType,
CollectionWithEquatableElement : RangeReplaceableCollectionType
where
Collection.Index : RandomAccessIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : RandomAccessIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : RandomAccessIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addBidirectionalRangeReplaceableCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
addRandomAccessCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
testNamePrefix += String(Collection.Type)
// No extra checks for collections with random access traversal so far.
} // addRandomAccessRangeReplaceableCollectionTests
}
| apache-2.0 |
heyogrady/SpaceEvaders | SpaceEvaders/OptionsMenu.swift | 1 | 701 | import SpriteKit
class OptionsMenu {
init(menu: SKNode, size: CGSize) {
let options = ["sound", "music", "follow", "indicators"]
var pos: CGFloat = 51
for option in options {
addOption(menu, size: size, option: option, pos: pos)
pos -= 5
}
}
func addOption(menu: SKNode, size: CGSize, option: String, pos: CGFloat) {
let height = size.height
var isOn = Options.option.get(option) ? "on" : "off"
let sprite = Sprite(named: "\(option)\(isOn)", x: size.width * pos / 60, y: 4 * height / 5, size: CGSizeMake(height / 12, height / 12))
sprite.name = "option_\(option)"
sprite.addTo(menu)
}
}
| mit |
breadwallet/breadwallet-ios | breadwallet/src/Platform/BRHTTPIndexMiddleware.swift | 1 | 1094 | //
// BRHTTPIndexMiddleware.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/19/16.
// Copyright (c) 2016-2019 Breadwinner AG. All rights reserved.
//
import Foundation
// BRHTTPIndexMiddleware returns index.html to any GET requests - regardless of the URL being requestd
class BRHTTPIndexMiddleware: BRHTTPFileMiddleware {
override func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) {
if request.method == "GET" {
let newRequest = BRHTTPRequestImpl(fromRequest: request)
newRequest.path = request.path.rtrim(["/"]) + "/index.html"
super.handle(newRequest) { resp in
if resp.response == nil {
let newRequest = BRHTTPRequestImpl(fromRequest: request)
newRequest.path = "/index.html"
super.handle(newRequest, next: next)
} else {
next(resp)
}
}
} else {
next(BRHTTPMiddlewareResponse(request: request, response: nil))
}
}
}
| mit |
vector-im/vector-ios | Riot/Modules/Room/TimelineDecorations/Threads/Summary/ThreadSummaryView.swift | 1 | 6055 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Reusable
@objc
protocol ThreadSummaryViewDelegate: AnyObject {
func threadSummaryViewTapped(_ summaryView: ThreadSummaryView)
}
/// A view to display a summary for an `MXThread` generated by the `MXThreadingService`.
@objcMembers
class ThreadSummaryView: UIView {
private enum Constants {
static let viewDefaultWidth: CGFloat = 320
static let cornerRadius: CGFloat = 8
static let lastMessageFont: UIFont = .systemFont(ofSize: 13)
}
@IBOutlet private weak var iconView: UIImageView!
@IBOutlet private weak var numberOfRepliesLabel: UILabel!
@IBOutlet private weak var lastMessageAvatarView: UserAvatarView!
@IBOutlet private weak var lastMessageContentLabel: UILabel!
private var theme: Theme = ThemeService.shared().theme
private(set) var thread: MXThreadProtocol?
private weak var session: MXSession?
private lazy var tapGestureRecognizer: UITapGestureRecognizer = {
return UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
}()
weak var delegate: ThreadSummaryViewDelegate?
// MARK: - Setup
init(withThread thread: MXThreadProtocol, session: MXSession) {
self.thread = thread
self.session = session
super.init(frame: CGRect(origin: .zero,
size: CGSize(width: Constants.viewDefaultWidth,
height: PlainRoomCellLayoutConstants.threadSummaryViewHeight)))
loadNibContent()
update(theme: ThemeService.shared().theme)
configure()
translatesAutoresizingMaskIntoConstraints = false
}
static func contentViewHeight(forThread thread: MXThreadProtocol?, fitting maxWidth: CGFloat) -> CGFloat {
return PlainRoomCellLayoutConstants.threadSummaryViewHeight
}
required init?(coder: NSCoder) {
super.init(coder: coder)
loadNibContent()
}
@nonobjc func configure(withModel model: ThreadSummaryModel) {
numberOfRepliesLabel.text = String(model.numberOfReplies)
if let avatar = model.lastMessageSenderAvatar {
lastMessageAvatarView.fill(with: avatar)
} else {
lastMessageAvatarView.avatarImageView.image = nil
}
if let lastMessage = model.lastMessageText {
let mutable = NSMutableAttributedString(attributedString: lastMessage)
mutable.setAttributes([
.font: Constants.lastMessageFont
], range: NSRange(location: 0, length: mutable.length))
lastMessageContentLabel.attributedText = mutable
} else {
lastMessageContentLabel.attributedText = nil
}
}
private func configure() {
clipsToBounds = true
layer.cornerRadius = Constants.cornerRadius
addGestureRecognizer(tapGestureRecognizer)
guard let thread = thread,
let lastMessage = thread.lastMessage,
let session = session,
let eventFormatter = session.roomSummaryUpdateDelegate as? MXKEventFormatter,
let room = session.room(withRoomId: lastMessage.roomId) else {
lastMessageAvatarView.avatarImageView.image = nil
lastMessageContentLabel.text = nil
return
}
let lastMessageSender = session.user(withUserId: lastMessage.sender)
let fallbackImage = AvatarFallbackImage.matrixItem(lastMessage.sender,
lastMessageSender?.displayname)
let avatarViewData = AvatarViewData(matrixItemId: lastMessage.sender,
displayName: lastMessageSender?.displayname,
avatarUrl: lastMessageSender?.avatarUrl,
mediaManager: session.mediaManager,
fallbackImage: fallbackImage)
room.state { [weak self] roomState in
guard let self = self else { return }
let formatterError = UnsafeMutablePointer<MXKEventFormatterError>.allocate(capacity: 1)
let lastMessageText = eventFormatter.attributedString(from: lastMessage.replyStrippedVersion,
with: roomState,
error: formatterError)
let model = ThreadSummaryModel(numberOfReplies: thread.numberOfReplies,
lastMessageSenderAvatar: avatarViewData,
lastMessageText: lastMessageText)
self.configure(withModel: model)
}
}
// MARK: - Action
@objc
private func tapped(_ sender: UITapGestureRecognizer) {
guard thread != nil else { return }
delegate?.threadSummaryViewTapped(self)
}
}
extension ThreadSummaryView: NibOwnerLoadable {}
extension ThreadSummaryView: Themable {
func update(theme: Theme) {
self.theme = theme
backgroundColor = theme.colors.system
iconView.tintColor = theme.colors.secondaryContent
numberOfRepliesLabel.textColor = theme.colors.secondaryContent
lastMessageContentLabel.textColor = theme.colors.secondaryContent
}
}
| apache-2.0 |
glimpseio/GlimpseXML | GlimpseXMLTests/GlimpseXMLTests.swift | 1 | 22690 | //
// GlimpseXMLTests.swift
// GlimpseXMLTests
//
// Created by Marc Prud'hommeaux on 10/13/14.
// Copyright (c) 2014 glimpse.io. All rights reserved.
//
import GlimpseXML
import XCTest
/// Temporary (hopefully) shims for XCTAssert methods that can accept throwables
extension XCTestCase {
/// Same as XCTAssertEqual, but handles throwable autoclosures
func XCTAssertEqualX<T: Equatable>(@autoclosure v1: () throws -> T, @autoclosure _ v2: () throws -> T, file: StaticString = #file, line: UInt = #line) {
do {
let x1 = try v1()
let x2 = try v2()
if x1 != x2 {
XCTFail("Not equal", file: file, line: line)
}
} catch {
XCTFail(String(error), file: file, line: line)
}
}
}
class GlimpseXMLTests: XCTestCase {
func testXMLParsing() throws {
let xml = "<?xml version=\"1.0\" encoding=\"gbk\"?>\n<res><body><msgtype>12</msgtype><langflag>zh_CN</langflag><engineid>1</engineid><tokensn>1000000001</tokensn><dynamicpass>111111</dynamicpass><emptyfield/></body></res>\n"
do {
let value = try Document.parseString(xml)
XCTAssertEqual(xml, value.serialize(indent: false, encoding: nil) ?? "")
XCTAssertNotEqual(xml, value.serialize(indent: true, encoding: nil) ?? "")
}
}
func testHTMLParsing() throws {
let html = "<html><head><title>Some HTML!</title><body><p>Some paragraph<br>Another Line</body></html>" // malformed
do {
let value = try Document.parseString(html, html: true)
XCTAssertEqual("<?xml version=\"1.0\" standalone=\"yes\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><head><title>Some HTML!</title></head><body><p>Some paragraph<br/>Another Line</p></body></html>\n", value.serialize(indent: false, encoding: nil) ?? "")
}
}
func testXMLParseDemo() throws {
// iTunes Library Location <http://support.apple.com/en-us/HT201610>
let music = ("~/Music/iTunes/iTunes Music Library.xml" as NSString).stringByExpandingTildeInPath
if !NSFileManager.defaultManager().fileExistsAtPath(music) { return }
do {
let doc = try GlimpseXML.Document.parseFile(music)
let rootNodeName: String? = doc.rootElement.name
print("Library Type: \(rootNodeName)")
let trackCount = try doc.xpath("/plist/dict/key[text()='Tracks']/following-sibling::dict/key").first?.text
print("Track Count: \(trackCount)")
let dq = try doc.xpath("//key[text()='Artist']/following-sibling::string[text()='Bob Dylan']").count
print("Dylan Quotient: \(dq)")
}
}
func testXMLWriteDemo() {
let node = Node(name: "library", attributes: [("url", "glimpse.io")], children: [
Node(name: "inventory", children: [
Node(name: "book", attributes: [("checkout", "true")], children: [
Node(name: "title", text: "I am a Bunny" ),
Node(name: "author", text: "Richard Scarry"),
]),
Node(name: "book", attributes: [("checkout", "false")], children: [
Node(name: "title", text: "You were a Bunny" ),
Node(name: "author", text: "Scarry Richard"),
]),
]),
])
let compact: String = node.serialize()
//print(compact)
XCTAssertFalse(compact.isEmpty)
let formatted: String = node.serialize(indent: true)
//print(formatted)
XCTAssertFalse(formatted.isEmpty)
let doc = Document(root: node)
let encoded: String = doc.serialize(indent: true, encoding: "ISO-8859-1")
//print(encoded)
XCTAssertFalse(encoded.isEmpty)
}
func testXMLParseErrors() {
do {
let _ = try Document.parseString("<xmlXXX>foo</xml>")
XCTFail("Should have thrown exception")
} catch {
if let error = error as? CustomDebugStringConvertible {
XCTAssertEqual(error.debugDescription, "Parser Fatal [1:21]: Opening and ending tag mismatch: xmlXXX line 1 and xml\n")
} else {
XCTFail("Error was not CustomDebugStringConvertible")
}
}
}
func testNamespaces() {
let ns = Namespace(href: "http://www.exmaple.com", prefix: "ex")
XCTAssertEqual("<nd/>", Node(name: "nd").serialize())
XCTAssertEqual("<nd>hello</nd>", Node(name: "nd", text: "hello").serialize())
XCTAssertEqual("<ex:nd>hello</ex:nd>", Node(name: "nd", namespace: ns, text: "hello").serialize())
XCTAssertEqual("<ex:nd><child>goodbye</child></ex:nd>", Node(name: "nd", namespace: ns, text: "will be clobbered", children: [Node(name: "child", text: "goodbye")]).serialize())
let node = Node(name: "foo")
node.text = "bar"
XCTAssertEqual("<foo>bar</foo>", node.serialize())
node.name = "stuff"
node.text = "x >= y & a < b"
node["attr1"] = "val1"
XCTAssertEqual("val1", node["attr1"] ?? "")
node["attr1"] = nil
XCTAssertNil(node["attr1"])
node["attr1"] = "val2"
XCTAssertEqual("val2", node["attr1"] ?? "")
node.updateAttribute("attrname", value: "attrvalue", namespace: ns)
XCTAssertEqual("<stuff attr1=\"val2\" ex:attrname=\"attrvalue\">x >= y & a < b</stuff>", node.serialize())
node.children = [ Node(name: "child1"), Node(name: "child2", text: "Child Contents") ]
XCTAssertEqual("<stuff attr1=\"val2\" ex:attrname=\"attrvalue\"><child1/><child2>Child Contents</child2></stuff>", node.serialize())
let doc = Document(root: node)
XCTAssertEqualX(1, try doc.xpath("/stuff/child1").count ?? -1)
XCTAssertNotNil(ns)
}
func testXMLTree() throws {
XCTAssertEqual(Node(name: "parent", text: "Text Content").serialize(), Node(name: "parent", children: [ Node(text: "Text Content") ]).serialize())
var fname, lname: Node?
let rootNode = Node(name: "company", attributes: [("name", "impathic")], children: [
Node(name: "employees", children: [
Node(name: "employee", attributes: [("active", "true")], children: [
fname <- Node(name: "firstName", text: "Marc" ),
lname <- Node(name: "lastName", text: "Prud'hommeaux"),
]),
Node(name: "employee", children: [
Node(name: "firstName", children: [ Node(text: "Emily") ]),
Node(name: "lastName", text: "Tucker"),
]),
]),
])
XCTAssertEqual("<company name=\"impathic\"><employees><employee active=\"true\"><firstName>Marc</firstName><lastName>Prud'hommeaux</lastName></employee><employee><firstName>Emily</firstName><lastName>Tucker</lastName></employee></employees></company>", rootNode.serialize())
XCTAssertEqual(1, fname?.children.count ?? -1)
XCTAssertEqual(1, lname?.children.count ?? -1)
// XCTAssertEqualX(1, try rootNode.xpath("//company").count)
// XCTAssertEqualX(1, try rootNode.xpath("../company").count)
// XCTAssertEqualX(2, try rootNode.xpath("./employees/employee").count)
XCTAssertEqual("employee", fname?.parent?.name ?? "<null>")
XCTAssertEqual("true", fname?.parent?["active"] ?? "<null>")
fname?.name = "fname"
fname?.text = "Markus"
fname?.parent?["active"] = nil
fname?.parent?.next?.children.first?.name = "fname"
XCTAssertTrue(fname == fname?.parent?.children.first, "tree traversal of nodes should equate")
XCTAssertFalse(fname === fname?.parent?.children.first, "tree traversal of nodes are not identical")
XCTAssertEqual("<company name=\"impathic\"><employees><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee><employee><fname>Emily</fname><lastName>Tucker</lastName></employee></employees></company>", rootNode.serialize())
// assign the node to a new Document
XCTAssertNil(rootNode.document)
let doc = Document(root: rootNode)
XCTAssertNotNil(rootNode.document)
if let nodeDoc = rootNode.document {
XCTAssertEqual(doc, nodeDoc)
XCTAssertFalse(doc === nodeDoc, "nodes should not have been identical")
XCTAssertEqual(doc.rootElement, rootNode)
XCTAssertFalse(doc.rootElement === rootNode, "nodes should not have been identical")
}
XCTAssertEqual("<?xml version=\"1.0\" encoding=\"utf8\"?>\n<company name=\"impathic\"><employees><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee><employee><fname>Emily</fname><lastName>Tucker</lastName></employee></employees></company>\n", doc.serialize())
// swap order of employees
fname?.parent?.next?.next = fname?.parent
XCTAssertEqual("<?xml version=\"1.0\" encoding=\"utf8\"?>\n<company name=\"impathic\"><employees><employee><fname>Emily</fname><lastName>Tucker</lastName></employee><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee></employees></company>\n", doc.serialize())
// swap back
fname?.parent?.prev?.prev = fname?.parent
XCTAssertEqual("<?xml version=\"1.0\" encoding=\"utf8\"?>\n<company name=\"impathic\"><employees><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee><employee><fname>Emily</fname><lastName>Tucker</lastName></employee></employees></company>\n", doc.serialize())
do {
let parse3 = try Document.parseString(doc.serialize())
XCTAssertEqual(parse3.serialize(indent: true), doc.serialize(indent: true))
XCTAssertEqualX(1, try doc.xpath("//company").count)
XCTAssertEqualX(1, try doc.xpath("//company[@name = 'impathic']").count)
XCTAssertEqualX(1, try doc.xpath("//employees").count)
XCTAssertEqualX(2, try doc.xpath("//employee").count)
XCTAssertEqualX(2, try doc.xpath("/company/employees/employee").count)
XCTAssertEqualX(1, try doc.xpath("/company/employees/employee/fname[text() != 'Emily']").count)
XCTAssertEqualX(1, try doc.xpath("/company/employees/employee/fname[text() = 'Emily']").count)
XCTAssertEqualX(1, try doc.xpath("/company/employees/employee/fname[text() = 'Markus']").count)
XCTAssertEqualX(2, try fname?.parent?.xpath("../employee").count ?? -1)
XCTAssertEqualX(2, try fname?.parent?.xpath("../..//employee").count ?? -1)
XCTAssertEqualX(1, try fname?.parent?.xpath("./fname[text() = 'Markus']").count ?? -1)
// XCTAssertEqual("XPath Error [0:0]: ", doc.xpath("+").error?.debugDescription ?? "NOERROR")
try doc.xpath("/company/employees/employee/fname[text() = 'Emily']").first?.text = "Emilius"
XCTAssertEqualX(0, try doc.xpath("/company/employees/employee/fname[text() = 'Emily']").count)
XCTAssertEqual("<?xml version=\"1.0\" encoding=\"utf8\"?>\n<company name=\"impathic\"><employees><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee><employee><fname>Emilius</fname><lastName>Tucker</lastName></employee></employees></company>\n", doc.serialize())
try doc.xpath("/company").first? += Node(name: "descriptionText", children: [
Node(text: "This is a super awesome company! It is > than the others & it is cool too!!")
])
try doc.xpath("/company").first? += Node(name: "descriptionData", children: [
Node(cdata: "This is a super awesome company! It is > than the others & it is cool too!!"),
])
XCTAssertEqual("<?xml version=\"1.0\" encoding=\"utf8\"?>\n<company name=\"impathic\"><employees><employee><fname>Markus</fname><lastName>Prud'hommeaux</lastName></employee><employee><fname>Emilius</fname><lastName>Tucker</lastName></employee></employees><descriptionText>This is a super awesome company! It is > than the others & it is cool too!!</descriptionText><descriptionData><![CDATA[This is a super awesome company! It is > than the others & it is cool too!!]]></descriptionData></company>\n", doc.serialize())
}
}
func testUnicodeEncoding() {
// from http://www.lookout.net/2011/06/special-unicode-characters-for-error.html
/// The Byte Order Mark U+FEFF is a special character defining the byte order and endianess of text data.
let uBOM = "\u{FEFF}"
/// The Right to Left Override U+202E defines special meaning to re-order the
/// display of text for right-to-left reading.
let uRLO = "\u{202E}"
/// Mongolian Vowel Separator U+180E is invisible and has the whitespace property.
let uMVS = "\u{180E}"
/// Word Joiner U+2060 is an invisible zero-width character.
let uWordJoiner = "\u{2060}"
/// A reserved code point U+FEFE
let uReservedCodePoint = "\u{FEFE}"
/// The code point U+FFFF is guaranteed to not be a Unicode character at all
let _ = "\u{FFFF}" // uNotACharacter
/// An unassigned code point U+0FED
let uUnassigned = "\u{0FED}"
/// An illegal low half-surrogate U+DEAD
// let uDEAD = "\u{DEAD}"
/// An illegal high half-surrogate U+DAAD
// let uDAAD = "\u{DAAD}"
/// A Private Use Area code point U+F8FF which Apple happens to use for its logo.
let uPrivate = "\u{F8FF}"
/// U+FF0F FULLWIDTH SOLIDUS should normalize to / in a hostname
let uFullwidthSolidus = "\u{FF0F}"
/// Code point with a numerical mapping and value U+1D7D6 MATHEMATICAL BOLD DIGIT EIGHT
// let uBoldEight = char.ConvertFromUtf32(0x1D7D6);
/// IDNA2003/2008 Deviant - U+00DF normalizes to "ss" during IDNA2003's mapping phase,
/// different from its IDNA2008 mapping.
/// See http://www.unicode.org/reports/tr46/
let uIdnaSs = "\u{00DF}"
/// U+FDFD expands by 11x (UTF-8) and 18x (UTF-16) under NFKC/NFKC
let uFDFA = "\u{FDFA}"
/// U+0390 expands by 3x (UTF-8) under NFD
let u0390 = "\u{0390}"
/// U+1F82 expands by 4x (UTF-16) under NFD
let u1F82 = "\u{1F82}"
/// U+FB2C expands by 3x (UTF-16) under NFC
let uFB2C = "\u{FB2C}"
/// U+1D160 expands by 3x (UTF-8) under NFC
// let u1D160 = char.ConvertFromUtf32(0x1D160);
let chars = [
"ABC",
"👀 💝 🐱",
uBOM,
uRLO, // cool: <emojis></emojis>
uMVS,
uWordJoiner,
uReservedCodePoint,
// uNotACharacter, // "Parser Fatal [2:9]: PCDATA invalid Char value 65535"
uUnassigned,
uPrivate,
uFullwidthSolidus,
uIdnaSs,
uFDFA,
u0390,
u1F82,
uFB2C,
]
let allChars = chars.reduce("", combine: +) // concatination of all of the above
for chars in chars + [allChars] {
let doc = Document(root: Node(name: "blah", text: chars))
// "latin1" error: "encoding error : output conversion failed due to conv error, bytes 0x00 0x3F 0x78 0x6D I/O error : encoder error"
let data = doc.serialize(encoding: "utf8")
XCTAssertTrue((data as NSString).containsString(chars))
// println("data: [\(data.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))] \(data)")
do {
let parsed = try Document.parseString(data)
XCTAssertEqualX(1, try parsed.xpath("//blah[text() = '\(chars)']").count ?? -1)
} catch {
XCTFail(String(error))
}
}
}
func enumerateLibXMLTests(f: String->Void) {
let dir = "/opt/src/libxml"
if let enumerator = NSFileManager.defaultManager().enumeratorAtPath(dir) {
let files: NSArray = enumerator.allObjects.map({ "\(dir)/\($0)" }).filter({ $0.hasSuffix(".xml") })
// concurrent enumeration will verify that multi-threaded access works
files.enumerateObjectsWithOptions(.Concurrent, usingBlock: { (file, index, keepGoing) -> Void in
f("\(file)")
})
} else {
// XCTFail("no libxml test files found") // it's fine; we don't need to have them
}
}
func XXXtestLoadTestsProfiling() {
measureBlock { self.testLoadLibxmlTests() }
}
/// Tests all the xml test files from libxml
func testLoadLibxmlTests() {
let expectFailures = [
"libxml/os400/iconv/bldcsndfa/ccsid_mibenum.xml",
"libxml/result/namespaces/err_10.xml",
"libxml/result/errors/attr1.xml",
"libxml/result/namespaces/err_11.xml",
"libxml/result/SVG/bike-errors.xml",
"libxml/result/valid/t8a.xml",
"libxml/result/xmlid/id_err1.xml",
"libxml/result/xmlid/id_err2.xml",
"libxml/result/xmlid/id_tst1.xml",
"libxml/result/errors/attr2.xml",
"libxml/result/xmlid/id_tst2.xml",
"libxml/result/xmlid/id_tst3.xml",
"libxml/result/xmlid/id_tst4.xml",
"libxml/result/valid/index.xml",
"libxml/doc/examples/tst.xml",
"libxml/test/errors/attr1.xml",
"libxml/test/errors/name.xml",
"libxml/test/errors/attr2.xml",
"libxml/test/errors/attr4.xml",
"libxml/test/errors/name2.xml",
"libxml/test/errors/cdata.xml",
"libxml/test/errors/charref1.xml",
"libxml/test/errors/comment1.xml",
"libxml/test/recurse/lol5.xml",
"libxml/test/errors/content1.xml",
"libxml/test/japancrlf.xml",
"libxml/test/namespaces/err_10.xml",
"libxml/test/namespaces/err_11.xml",
"libxml/result/valid/t8.xml",
"libxml/test/recurse/lol1.xml",
"libxml/test/recurse/lol2.xml",
"libxml/result/errors/attr4.xml",
"libxml/test/recurse/lol4.xml",
"libxml/test/valid/t8.xml",
"libxml/test/valid/t8a.xml",
"libxml/result/errors/cdata.xml",
"libxml/result/errors/charref1.xml",
"libxml/result/errors/comment1.xml",
"libxml/doc/tutorial/includestory.xml",
"libxml/result/errors/content1.xml",
"libxml/result/errors/name.xml",
"libxml/result/errors/name2.xml",
"libxml/test/recurse/lol6.xml",
"libxml/os400/iconv/bldcsndfa/ccsid_mibenum.xml",
"libxml/result/errors/attr1.xml",
"libxml/result/namespaces/err_10.xml",
"libxml/result/namespaces/err_11.xml",
"libxml/result/SVG/bike-errors.xml",
"libxml/result/errors/attr2.xml",
"libxml/doc/examples/tst.xml",
"libxml/result/valid/t8a.xml",
"libxml/result/xmlid/id_err1.xml",
"libxml/result/xmlid/id_err2.xml",
"libxml/result/xmlid/id_tst1.xml",
"libxml/result/xmlid/id_tst2.xml",
"libxml/result/xmlid/id_tst3.xml",
"libxml/result/xmlid/id_tst4.xml",
"libxml/result/valid/index.xml",
"libxml/test/errors/name.xml",
"libxml/test/errors/name2.xml",
"libxml/test/errors/attr1.xml",
"libxml/test/errors/attr2.xml",
"libxml/test/errors/attr4.xml",
"libxml/test/errors/cdata.xml",
"libxml/test/errors/charref1.xml",
"libxml/test/errors/comment1.xml",
"libxml/test/errors/content1.xml",
"libxml/test/japancrlf.xml",
"libxml/test/namespaces/err_10.xml",
"libxml/test/namespaces/err_11.xml",
"libxml/test/recurse/lol5.xml",
"libxml/result/valid/t8.xml",
"libxml/test/recurse/lol1.xml",
"libxml/test/recurse/lol2.xml",
"libxml/test/recurse/lol4.xml",
"libxml/test/valid/t8.xml",
"libxml/test/valid/t8a.xml",
"libxml/doc/tutorial/includestory.xml",
"libxml/result/errors/attr4.xml",
"libxml/result/errors/cdata.xml",
"libxml/result/errors/charref1.xml",
"libxml/result/errors/comment1.xml",
"libxml/result/errors/content1.xml",
"libxml/result/errors/name.xml",
"libxml/result/errors/name2.xml",
"libxml/test/recurse/lol6.xml",
]
enumerateLibXMLTests { file in
do {
let doc = try Document.parseFile(file)
let nodes = try doc.xpath("//*")
// println("parsed \(file) nodes: \(nodes?.count ?? -1) error: \(doc.error)")
XCTAssert(nodes.count > 0)
} catch {
for path in expectFailures {
if file.hasSuffix(path) { return }
}
XCTFail("XML file should not have failed: \(file)")
}
}
}
// func testNSLoadTestsProfiling() {
// measureBlock { self.testNSLoadLibxmlTests() }
// }
//
// func testNSLoadLibxmlTests() {
// // some files crash NSXMLParser!
// let skip = ["xmltutorial.xml", "badcomment.xml", "defattr2.xml", "example-8.xml", "xmlbase-c14n11spec-102.xml", "xmlbase-c14n11spec2-102.xml"]
//
// enumerateLibXMLTests { file in
// if contains(skip, file.lastPathComponent) {
// return
// }
// var error: NSError?
// println("parsing: \(file)")
// let doc = NSXMLDocument(contentsOfURL: NSURL(fileURLWithPath: file)!, options: 0, error: &error)
// let nodes = doc?.nodesForXPath("//*", error: &error)
// if let nodes = nodes {
// XCTAssert(nodes.count > 0)
// }
// }
// }
}
/// assign the given field to the given variable, just like "=" except that the assignation is returned by the function: “Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value”
private func <- <T>(inout assignee: T?, assignation: T) -> T {
assignee = assignation
return assignation
}
infix operator <- { assignment }
| mit |
jjochen/photostickers | MessagesExtension/Scenes/Messages App/MessagesAppViewController.swift | 1 | 3051 | //
// MessagesAppViewController.swift
// MessageExtension
//
// Created by Jochen on 28.03.19.
// Copyright © 2019 Jochen Pfeiffer. All rights reserved.
//
import Messages
import Reusable
import RxCocoa
import RxDataSources
import RxFlow
import RxSwift
import UIKit
/* TODO:
* check https://github.com/sergdort/CleanArchitectureRxSwift
* show toolbar with edit/done button only in expanded mode
* only in edit mode: edit, sort, delete sticker
*/
class MessagesAppViewController: MSMessagesAppViewController, StoryboardBased {
private lazy var application: Application = {
Application()
}()
private let disposeBag = DisposeBag()
private let coordinator = FlowCoordinator()
private let requestPresentationStyle = PublishSubject<MSMessagesAppPresentationStyle>()
override func viewDidLoad() {
super.viewDidLoad()
RxImagePickerDelegateProxy.register { RxImagePickerDelegateProxy(imagePicker: $0) }
view.tintColor = StyleKit.appColor
setupFlow()
}
private func setupFlow() {
coordinator.rx.willNavigate.subscribe(onNext: { flow, step in
print("will navigate to flow=\(flow) and step=\(step)")
}).disposed(by: disposeBag)
coordinator.rx.didNavigate.subscribe(onNext: { flow, step in
print("did navigate to flow=\(flow) and step=\(step)")
}).disposed(by: disposeBag)
requestPresentationStyle.asDriver(onErrorDriveWith: Driver.empty())
.drive(rx.requestPresentationStyle)
.disposed(by: disposeBag)
let appFlow = StickerBrowserFlow(withServices: application.appServices,
requestPresentationStyle: requestPresentationStyle,
currentPresentationStyle: rx.willTransitionToPresentationStyle.asDriver())
let appStepper = OneStepper(withSingleStep: PhotoStickerStep.stickerBrowserIsRequired)
Flows.whenReady(flow1: appFlow) { [unowned self] root in
self.embed(viewController: root)
}
coordinator.coordinate(flow: appFlow, with: appStepper)
}
}
extension MessagesAppViewController {
private func embed(viewController: UIViewController) {
for child in children {
child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()
}
addChild(viewController)
viewController.view.frame = view.bounds
viewController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(viewController.view)
NSLayoutConstraint.activate([
viewController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
viewController.view.rightAnchor.constraint(equalTo: view.rightAnchor),
viewController.view.topAnchor.constraint(equalTo: view.topAnchor),
viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
viewController.didMove(toParent: self)
}
}
| mit |
shuoli84/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaPage.swift | 3 | 844 | //
// WikipediaPage.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
struct WikipediaPage {
let title: String
let text: String
init(title: String, text: String) {
self.title = title
self.text = text
}
// tedious parsing part
static func parseJSON(json: NSDictionary) -> RxResult<WikipediaPage> {
let title = json.valueForKey("parse")?.valueForKey("title") as? String
let text = json.valueForKey("parse")?.valueForKey("text")?.valueForKey("*") as? String
if title == nil || text == nil {
return failure(apiError("Error parsing page content"))
}
return success(WikipediaPage(title: title!, text: text!))
}
} | mit |
erichoracek/Carthage | Source/CarthageKit/ProducerQueue.swift | 2 | 1749 | //
// ProducerQueue.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2015-05-23.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import ReactiveCocoa
/// Serializes the execution of SignalProducers, like flatten(.Concat), but
/// without all needing to be enqueued in the same context.
///
/// This allows you to manually enqueue producers from any code that has access
/// to the queue object, instead of being required to funnel all producers
/// through a single producer-of-producers.
internal final class ProducerQueue {
private let queue: dispatch_queue_t
/// Initializes a queue with the given debug name.
init(name: String) {
queue = dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}
/// Creates a SignalProducer that will enqueue the given producer when
/// started, wait until the queue is empty to begin work, and block other
/// work while executing.
func enqueue<T, Error>(producer: SignalProducer<T, Error>) -> SignalProducer<T, Error> {
return SignalProducer { observer, disposable in
dispatch_async(self.queue) {
if disposable.disposed {
return
}
// Prevent further operations from starting until we're
// done.
dispatch_suspend(self.queue)
producer.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observe(Signal.Observer { event in
observer.put(event)
if event.isTerminating {
dispatch_resume(self.queue)
}
})
}
}
}
}
}
/// Shorthand for enqueuing the given producer upon the given queue.
internal func startOnQueue<T, Error>(queue: ProducerQueue) -> SignalProducer<T, Error> -> SignalProducer<T, Error> {
return { producer in queue.enqueue(producer) }
}
| mit |
sztoth/PodcastChapters | PodcastChaptersTests/Tests/Controllers/ViewModels/ChaptersViewModelTests.swift | 1 | 599 | //
// ChaptersViewModelTests.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 03. 21..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import XCTest
@testable import PodcastChapters
class ChaptersViewModelTests: XCTestCase {
var chaptersViewModel: ChaptersViewModel!
var podcastMonitor: PodcastMonitorMock!
override func setUp() {
super.setUp()
podcastMonitor = PodcastMonitorMock()
chaptersViewModel = ChaptersViewModel(podcastMonitor: podcastMonitor)
}
func test_ObservablesGivingProperValues() {
}
}
| mit |
wwq0327/iOS9Example | Enum.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift | 1 | 780 | //: [Previous](@previous)
import Foundation
/**
- param
- returns: String
*/
enum NumberParser: Int {
// 将数字转换成汉字
case One = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero
var singleNumberToChinese: String {
switch self {
case .One:
return "一"
case .Two:
return "二"
case .Three:
return "三"
case .Four:
return "四"
case .Five:
return "五"
case .Six:
return "六"
case .Seven:
return "七"
case .Eight:
return "八"
case .Nine:
return "九"
case .Zero:
return "零"
}
}
}
NumberParser(rawValue: 2)
| apache-2.0 |
ospr/UIPlayground | UIPlaygroundUI/SpringBoardAppCollectionViewController.swift | 1 | 5257 | //
// SpringBoardAppCollectionViewController.swift
// UIPlayground
//
// Created by Kip Nicol on 9/20/16.
// Copyright © 2016 Kip Nicol. All rights reserved.
//
import UIKit
protocol SpringBoardAppCollectionViewControllerDelegate: class {
func springBoardAppCollectionViewController(_ viewController: SpringBoardAppCollectionViewController, didSelectAppInfo appInfo: SpringBoardAppInfo, selectedAppIconButton: UIButton)
func springBoardAppCollectionViewControllerDidUpdateEditMode(_ viewController: SpringBoardAppCollectionViewController)
}
private let reuseIdentifier = "Cell"
struct SpringBoardAppInfo {
let appName: String
let image: UIImage
}
class SpringBoardAppCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let appCollectionLayout: SpringBoardAppCollectionLayout
let appInfoItems: [SpringBoardAppInfo]
var editModeEnabled: Bool = false {
didSet {
if editModeEnabled != oldValue {
// Reload cells to start/stop animations
collectionView!.reloadData()
}
}
}
weak var delegate: SpringBoardAppCollectionViewControllerDelegate?
fileprivate var appInfoByAppIconButtons = [UIButton : SpringBoardAppInfo]()
init(appInfoItems: [SpringBoardAppInfo], appCollectionLayout: SpringBoardAppCollectionLayout) {
self.appCollectionLayout = appCollectionLayout
self.appInfoItems = appInfoItems
let viewLayout = UICollectionViewFlowLayout()
viewLayout.minimumInteritemSpacing = appCollectionLayout.minimumInteritemSpacing
viewLayout.minimumLineSpacing = appCollectionLayout.minimumLineSpacing
viewLayout.itemSize = appCollectionLayout.itemSize
viewLayout.sectionInset = appCollectionLayout.sectionInset
super.init(collectionViewLayout: viewLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.backgroundColor = .clear
collectionView!.register(SpringBoardAppIconViewCell.self, forCellWithReuseIdentifier: "AppIconCell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// The cells stop animating sometimes when the view disappears
// (eg spring board page view transitions)
for cell in collectionView!.visibleCells {
if let cell = cell as? SpringBoardAppIconViewCell {
updateCellAnimations(cell)
}
}
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return appInfoItems.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let appInfo = appInfoItems[indexPath.row]
let appIconCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AppIconCell", for: indexPath) as! SpringBoardAppIconViewCell
appIconCell.delegate = self
appIconCell.appNameLabel.text = appInfo.appName
appIconCell.appIconImage = appInfo.image
appIconCell.appIconLength = appCollectionLayout.iconLength
appIconCell.appIconButtonView.removeTarget(nil, action: nil, for: .allEvents)
appIconCell.appIconButtonView.addTarget(self, action: #selector(appIconButtonWasTapped), for: .touchUpInside)
appInfoByAppIconButtons[appIconCell.appIconButtonView] = appInfo
updateCellAnimations(appIconCell)
return appIconCell
}
// MARK: - Working with Animations
func updateCellAnimations(_ cell: SpringBoardAppIconViewCell) {
let jitterAnimationKey = "Jitter"
if editModeEnabled {
if cell.layer.animation(forKey: jitterAnimationKey) == nil {
let jitterAnimation = CAAnimation.jitterAnimation()
// Add a offset to the animation time to cause the cells
// to jitter at different offsets
jitterAnimation.timeOffset = CACurrentMediaTime() + drand48()
cell.layer.add(jitterAnimation, forKey: jitterAnimationKey)
}
}
else {
cell.layer.removeAnimation(forKey: jitterAnimationKey)
}
cell.appIconButtonView.isUserInteractionEnabled = !editModeEnabled
}
// MARK: - Handling touch events
func appIconButtonWasTapped(sender: UIButton) {
let appInfo = appInfoByAppIconButtons[sender]!
delegate?.springBoardAppCollectionViewController(self, didSelectAppInfo: appInfo, selectedAppIconButton: sender)
}
}
extension SpringBoardAppCollectionViewController: SpringBoardAppIconViewCellDelegate {
func springBoardAppIconViewCell(didLongPress springBoardAppIconViewCell: SpringBoardAppIconViewCell) {
delegate?.springBoardAppCollectionViewControllerDidUpdateEditMode(self)
}
}
| mit |
GeoffSpielman/SimonSays | simon_says_iOS_app/SimonSaysUITests/SimonSaysUITests.swift | 1 | 1250 | //
// SimonSaysUITests.swift
// SimonSaysUITests
//
// Created by Will Clark on 2016-06-25.
// Copyright © 2016 WillClark. All rights reserved.
//
import XCTest
class SimonSaysUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
adambard/tapstream-sdk | examples/iOS/SwiftExample/SwiftExample/ViewController.swift | 2 | 248 | import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
rock-n-code/Kashmir | Kashmir/Shared/Features/Data Source/Protocols/DataSource.swift | 1 | 6835 | //
// DataSource.swift
// Kashmir
//
// Created by Javier Cicchelli on 09/11/2016.
// Copyright © 2016 Rock & Code. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/**
This protocol defines the minimal requirements a compliant data source instance should implement in order to provide data to a view controller.
*/
public protocol DataSource: class {
/// Generic placeholder for the data type instances to use as the source from where the data for the data source is generated.
associatedtype SourceData
/// Generic placeholder for the section type instances, which must implement the `Sectionable` protocol.
associatedtype Section: Sectionable
/// Generic placeholder for the item type instances, which must implement the `Itemable` protocol.
associatedtype Item: Itemable
// MARK: Properties
/// The dictionary that persist in memory both section and item type instances obtained from the `source`.
var data: [Section: [Item]] { get set }
/// The source of data for the `data` dictionary.
var sourceData: SourceData? { get set }
var numberOfSections: Int { get }
// MARK: Initializers
/**
Default initializer.
- returns: A pristine data source with an empty `data` dictionary.
*/
init()
init(data: SourceData)
// MARK: Functions
func update(data updatedData: SourceData)
/**
Loads the data from the source into the data dictionary.
- important: This function is, in fact, a helper function and as such is executed inside the `init(data: )` and the `update(data: )` functions and it **must not** be called outside that scope at all.
- remarks: While implementing this function, the developer has to create the `Section` and the `Items` instances as he/she needs based on his/her data requirements.
*/
func load()
func numberOfItems(at sectionIndex: Int) throws -> Int
func items(at sectionIndex: Int) throws -> [Item]
func items(at indexPaths: [IndexPath]) throws -> [Item]
func section(at sectionIndex: Int) throws -> Section
func item(at indexPath: IndexPath) throws -> Item
}
// MARK: -
public extension DataSource {
// MARK: Properties
/// The number of sections on the dictionary.
var numberOfSections: Int {
return data.keys.count
}
// MARK: Initializers
/**
Recommended initializer.
- important: This initializer **must** be used in order to populate the `data` dictionary.
- parameter data: An source data instance which is mapped from a JSON response.
- returns: A data source with a dictionary filled with sections and theirs respective items.
*/
init(data: SourceData) {
self.init()
self.data = [:]
self.sourceData = data
load()
}
// MARK: Functions
/**
Updates the data of the data source.
- important: This function **must** be used in order to update the `data` dictionary.
- parameter data: An source data instance which is mapped from a JSON response.
*/
func update(data updatedData: SourceData) {
self.data = [:]
sourceData = updatedData
load()
}
/**
Gets the number of items within a section given its index position.
- parameter at: The index position of a `Section` instance.
- throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function.
- returns: The number of items within the given section.
*/
func numberOfItems(at sectionIndex: Int) throws -> Int {
guard numberOfSections > 0 else {
return 0
}
let section = try self.section(at: sectionIndex)
let items = data[section]!
return items.count
}
/**
Creates an array of items within a section given its index position.
- parameter at: The index position of a `Section` instance.
- throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function.
- returns: An array of items within the given section.
*/
func items(at sectionIndex: Int) throws -> [Item] {
guard try numberOfItems(at: sectionIndex) > 0 else {
throw DataSourceError.itemsEmpty
}
let section = try self.section(at: sectionIndex)
return data[section]!
}
/**
Creates an array of items with given array of indexPaths.
- parameter at: An array of indexPaths.
- throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function.
- returns: An array of items within the given array of indexPaths.
*/
func items(at indexPaths: [IndexPath]) throws -> [Item] {
var items = [Item]()
for indexPath in indexPaths {
guard try numberOfItems(at: indexPath.section) > 0 else {
throw DataSourceError.itemsEmpty
}
let item = try self.item(at: indexPath)
items.append(item)
}
return items
}
/**
Gets a section instance given its index position.
- parameter at: The index position of a `Section` instance
- throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function.
- returns: A `Section` instance based on the given index position.
*/
func section(at sectionIndex: Int) throws -> Section {
guard numberOfSections > 0 else {
throw DataSourceError.sectionsEmpty
}
guard sectionIndex <= numberOfSections - 1 else {
throw DataSourceError.sectionIndexOutOfBounds
}
return data.keys.filter({ $0.index == sectionIndex }).first!
}
/**
Gets an item instance given an index path.
- parameter at: An index path indicating a both a position in the section and its respective items array.
- throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function.
- returns: An `Item` instance based on the given index path.
*/
func item(at indexPath: IndexPath) throws -> Item {
guard try numberOfItems(at: indexPath.section) > 0 else {
throw DataSourceError.itemsEmpty
}
let section = try self.section(at: indexPath.section)
let items = data[section]!
guard indexPath.item <= items.count - 1 else {
throw DataSourceError.itemIndexOutOfBounds
}
return items[indexPath.item]
}
}
| mit |
evanfrawley/Tipulator | Tipulator/ViewController.swift | 1 | 537 | //
// ViewController.swift
// Tipulator
//
// Created by Evan J. Frawley on 12/14/15.
// Copyright (c) 2015 Evan J. Frawley. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
Diego5529/tcc-swift3 | tcc-swift3/src/model/objects/EventType+CoreDataProperties.swift | 1 | 548 | //
// EventType+CoreDataProperties.swift
//
//
// Created by Diego Oliveira on 30/05/17.
//
//
import Foundation
import CoreData
extension EventType {
@nonobjc public class func fetchRequest() -> NSFetchRequest<EventType> {
return NSFetchRequest<EventType>(entityName: "EventType")
}
@NSManaged public var id: NSNumber?
@NSManaged public var long_description: String?
@NSManaged public var short_description: String?
@NSManaged public var title: String?
@NSManaged public var has_many_events: Event?
}
| mit |
leyap/VPNOn | VPNOn/LTVPNTableViewController+Geo.swift | 1 | 781 | //
// LTVPNTableViewController+Geo.swift
// VPNOn
//
// Created by Lex on 3/3/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import VPNOnKit
extension LTVPNTableViewController
{
func geoDidUpdate(notification: NSNotification) {
if let vpn = notification.object as VPN? {
VPNManager.sharedManager.geoInfoOfHost(vpn.server) {
geoInfo in
vpn.countryCode = geoInfo.countryCode
vpn.isp = geoInfo.isp
vpn.latitude = geoInfo.latitude
vpn.longitude = geoInfo.longitude
vpn.managedObjectContext!.save(nil)
self.tableView.reloadData()
}
}
}
}
| mit |
piglikeYoung/iOS8-day-by-day | 29-safari-action/MarqueeMaker/MarqueeMaker/ViewController.swift | 22 | 788 | //
// Copyright 2014 Scott Logic
//
// 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
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| apache-2.0 |
marcw/volte-ios | VolteCore/TimelineContentProvider.swift | 1 | 560 | //
// TimelineContentProvider.swift
// Volte
//
// Created by Romain Pouclet on 2016-11-02.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Foundation
import ReactiveSwift
import Result
import CoreData
public class TimelineContentProvider {
private let storageController: StorageController
public var messages: SignalProducer<[Message], NoError> {
return storageController.messages.producer
}
public init(storageController: StorageController) {
self.storageController = storageController
}
}
| agpl-3.0 |
griff/metaz | Plugins/TheMovieDbNG/src/TVSearch.swift | 1 | 8841 | //
// Search.swift
// TheMovieDbNG
//
// Created by Brian Olsen on 22/02/2020.
//
import Foundation
import MetaZKit
@objc public class TVSearch : Search {
let tvShow : String
let season : Int?
let episode : Int?
// MARK: -
public init(show: String,
delegate: SearchProviderDelegate,
season: Int? = nil,
episode: Int? = nil)
{
self.tvShow = show
self.season = season
self.episode = episode
super.init(delegate: delegate)
}
// MARK: -
func fetch(series: String) throws -> [Int64] {
guard let name = series.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
else { throw SearchError.PercentEncoding(series) }
let url_s = "\(Plugin.BasePath)/search/tv?api_key=\(Plugin.API_KEY)&query=\(name)"
guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) }
guard let response = try request(url, type: PagedResultsJSON<IdNameJSON>.self)
else { throw SearchError.URLSession(url) }
return response.results.map { $0.id }
}
func fetch(seriesInfo id: Int64) throws -> TVShowDetailsJSON {
let url_s = "\(Plugin.BasePath)/tv/\(id)?api_key=\(Plugin.API_KEY)&append_to_response=content_ratings,credits,images"
guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) }
guard let response = try request(url, type: TVShowDetailsJSON.self)
else { throw SearchError.URLSession(url) }
return response
}
func fetch(series id: Int64, season: Int) throws -> SeasonDetailsJSON {
let url_s = "\(Plugin.BasePath)/tv/\(id)/season/\(season)?api_key=\(Plugin.API_KEY)&append_to_response=credits,images"
guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) }
guard let response = try request(url, type: SeasonDetailsJSON.self)
else { throw SearchError.URLSession(url) }
return response
}
func fetch(series id: Int64, season: Int, episode: Int) throws -> EpisodeJSON {
let url_s = "\(Plugin.BasePath)/tv/\(id)/season/\(season)/episode/\(episode)?api_key=\(Plugin.API_KEY)&append_to_response=credits,images"
guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) }
guard let response = try request(url, type: EpisodeJSON.self)
else { throw SearchError.URLSession(url) }
return response
}
// MARK: -
func merge(episodes: [EpisodeJSON],
with values: [String: Any],
posters: [RemoteData],
seasonBanners: [RemoteData]) -> [[String: Any]]
{
return episodes.map {(episode) in
var result = values
result[MZTVEpisodeTagIdent] = episode.episode_number
result.setNormalized(value: episode.name, forKey: MZTitleTagIdent)
//result[MZIMDBTagIdent] = episode.imdbId
result.setNormalized(value: episode.overview, forKey: MZShortDescriptionTagIdent)
result.setNormalized(value: episode.overview, forKey: MZLongDescriptionTagIdent)
let director = episode.crew.filter { $0.department == "Directing" }.map{ $0.name }.join()
result.setNormalized(value: director, forKey: MZDirectorTagIdent)
let screenwriter = episode.crew.filter { $0.department == "Writing" }.map{ $0.name }.join()
result.setNormalized(value: screenwriter, forKey: MZScreenwriterTagIdent)
let producers = episode.crew.filter { $0.department == "Production" }.map{ $0.name }.join()
result.setNormalized(value: producers, forKey: MZProducerTagIdent)
result.setNormalized(value: episode.production_code, forKey: MZTVEpisodeIDTagIdent)
if let actual = episode.air_date {
var firstAired : Date?
let f = DateFormatter()
f.dateFormat = "yyyy-MM-dd"
firstAired = f.date(from: actual)
if let date = firstAired {
result[MZDateTagIdent] = date
} else {
NSLog("Unable to parse release date '%@'", actual);
}
}
var images : [RemoteData] = seasonBanners
images.append(contentsOf: posters)
if !images.isEmpty {
result[MZPictureTagIdent] = images
}
return result
}
}
// MARK: -
override public func do_search() throws {
let series = try fetch(series: tvShow)
for id in series {
do {
var values = [String: Any]()
let info = try fetch(seriesInfo: id)
if info.name.normalize().isEmpty {
print("TheMovieDB TV Show has \(id) no name")
continue
}
values[MZVideoTypeTagIdent] = NSNumber(value: MZTVShowVideoType.rawValue)
values[Plugin.TMDbTVIdTagIdent] = info.id
values[MZTVShowTagIdent] = info.name
values[MZArtistTagIdent] = info.name
//values[MZIMDBTagIdent] = info.imdbId
let networks = info.networks.map { $0.name }.join()
values.setNormalized(value: networks, forKey: MZTVNetworkTagIdent)
values.setNormalized(value: info.overview, forKey: MZShortDescriptionTagIdent)
values.setNormalized(value: info.overview, forKey: MZLongDescriptionTagIdent)
let genres = info.genres.map { $0.name }.join()
values.setNormalized(value: genres, forKey: MZGenreTagIdent)
let ratingTag = MZTag.lookup(withIdentifier: MZRatingTagIdent)!
if let content_ratings = info.content_ratings {
for rating in content_ratings.results {
let ratingNr : NSNumber? = ratingTag.object(from: rating.rating) as? NSNumber? ?? nil
if let rating = ratingNr {
if rating.intValue != MZNoRating.rawValue {
values[MZRatingTagIdent] = ratingNr
break
}
}
}
}
if let credits = info.credits {
let actors = credits.cast.map { $0.name }.join()
values.setNormalized(value: actors, forKey: MZActorsTagIdent)
}
var posters : [RemoteData] = []
if let images = info.images {
posters = try images.posters.map { try Plugin.remote(image: $0, sort: "B") }
}
var seasons : [Int] = []
if let season = self.season {
seasons = [season]
} else {
seasons = info.seasons.map { $0.season_number }
}
for season in seasons {
let seasonInfo = try fetch(series: id, season: season)
var seasonBanners : [RemoteData] = []
if let banners = seasonInfo.images {
seasonBanners = try banners.posters.map { try Plugin.remote(image: $0) }
}
values[MZTVSeasonTagIdent] = season
if let credits = seasonInfo.credits {
let directors = credits.crew.filter { $0.department == "Directing" }.map{ $0.name }.join()
values.setNormalized(value: directors, forKey: MZDirectorTagIdent)
let screenwriters = credits.crew.filter { $0.department == "Writing" }.map{ $0.name }.join()
values.setNormalized(value: screenwriters, forKey: MZScreenwriterTagIdent)
let producers = credits.crew.filter { $0.department == "Production" }.map{ $0.name }.join()
values.setNormalized(value: producers, forKey: MZProducerTagIdent)
}
var episodes = seasonInfo.episodes
if let episode = self.episode {
episodes = episodes.filter { $0.episode_number == episode }
}
let results = merge(episodes: episodes,
with: values,
posters: posters,
seasonBanners: seasonBanners)
self.delegate.reportSearch(results: results)
}
} catch SearchError.Canceled {
throw SearchError.Canceled
} catch {
self.delegate.reportSearch(error: error)
}
}
}
}
| mit |
dduan/swift | validation-test/compiler_crashers_fixed/27123-swift-valuedecl-getoverloadsignature.swift | 11 | 466 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
let a{var f={class B<T where g:a{struct d{class g{func b{let a{func g{e=b
| apache-2.0 |
PGSSoft/AutoMate | AutoMate/Launch Option/LaunchOptionProtocol.swift | 1 | 1181 | //
// Options.swift
// AutoMate
//
// Created by Joanna Bednarz on 19/05/16.
// Copyright © 2016 PGS Software. All rights reserved.
//
// MARK: - LaunchOption protocol
/**
Any type that implements this protocol can be used to configure application
with TestLauncher. Type conforming to this protocol should override default implementation
of *launchArguments* or *launchEnvironments*. Choice depends on which type of configuration
option it represents.
For more info about launch arguments and environment variables check:
[here](https://developer.apple.com/library/ios/recipes/xcode_help-scheme_editor/Articles/SchemeRun.html)
*/
public protocol LaunchOption {
/// Launch arguments provided by this option.
var launchArguments: [String]? { get }
/// Launch environment variables provided by this option.
var launchEnvironments: [String: String]? { get }
/// Unique value to use when comparing with other launch options.
var uniqueIdentifier: String { get }
}
public extension LaunchOption {
/// Unique value to use when comparing with other launch options.
var uniqueIdentifier: String {
return "\(type(of: self))"
}
}
| mit |
github/Nimble | Nimble/Wrappers/ObjCMatcher.swift | 77 | 3344 | import Foundation
struct ObjCMatcherWrapper : Matcher {
let matcher: NMBMatcher
let to: String
let toNot: String
func matches(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = to
let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location)
return pass
}
func doesNotMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = toNot
let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location)
return !pass
}
}
// Equivalent to Expectation, but simplified for ObjC objects only
public class NMBExpectation : NSObject {
let _actualBlock: () -> NSObject!
var _negative: Bool
let _file: String
let _line: UInt
var _timeout: NSTimeInterval = 1.0
public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
public var withTimeout: (NSTimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.to(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not")
)
})
}
public var toNot: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toNot(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not")
)
})
}
public var notTo: (matcher: NMBMatcher) -> Void { return toNot }
public var toEventually: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventually(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"),
timeout: self._timeout
)
})
}
public var toEventuallyNot: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"),
timeout: self._timeout
)
})
}
}
@objc public class NMBObjCMatcher : NMBMatcher {
let _matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool
init(matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool) {
self._matcher = matcher
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return _matcher(
actualExpression: ({ actualBlock() as NSObject? }),
failureMessage: failureMessage,
location: location)
}
}
| apache-2.0 |
BanyaKrylov/Learn-Swift | 5.1/HW1.playground/Contents.swift | 1 | 280 | import UIKit
var str = "Homework 1"
var numInt: Int8
var numUint: UInt8
numInt = Int8.min
numUint = UInt8.max
print(numUint, numInt)
var num1 = 2
var num2: Int = 100
var numBuffer:Int
numBuffer = num1
num1 = num2
num2 = numBuffer
print("num1 = \(num1) and num2 = \(num2)")
| apache-2.0 |
cwRichardKim/RKCardView | RKCard/RKCard/RKCardView.swift | 6 | 242 | //
// RKCardView.swift
// RKCard
//
// Created by Richard Kim on 11/18/14.
// Copyright (c) 2014 Richard Kim. All rights reserved.
//
import Foundation
import UIKit
class RKCardView: UIView {
var profileImageView:UIImageView?
} | mit |
zvonler/PasswordElephant | external/github.com/CryptoSwift/Sources/CryptoSwift/CMAC.swift | 2 | 3775 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public final class CMAC: Authenticator {
public enum Error: Swift.Error {
case wrongKeyLength
}
private let key: SecureBytes
private static let BlockSize: Int = 16
private static let Zero: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
private static let Rb: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87]
public init(key: Array<UInt8>) throws {
if key.count != 16 {
throw Error.wrongKeyLength
}
self.key = SecureBytes(bytes: key)
}
// MARK: Authenticator
public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
let aes = try AES(key: Array(key), blockMode: CBC(iv: CMAC.Zero), padding: .noPadding)
let l = try aes.encrypt(CMAC.Zero)
var subKey1 = leftShiftOneBit(l)
if (l[0] & 0x80) != 0 {
subKey1 = xor(CMAC.Rb, subKey1)
}
var subKey2 = leftShiftOneBit(subKey1)
if (subKey1[0] & 0x80) != 0 {
subKey2 = xor(CMAC.Rb, subKey2)
}
let lastBlockComplete: Bool
let blockCount = (bytes.count + CMAC.BlockSize - 1) / CMAC.BlockSize
if blockCount == 0 {
lastBlockComplete = false
} else {
lastBlockComplete = bytes.count % CMAC.BlockSize == 0
}
var paddedBytes = bytes
if !lastBlockComplete {
bitPadding(to: &paddedBytes, blockSize: CMAC.BlockSize)
}
var blocks = Array(paddedBytes.batched(by: CMAC.BlockSize))
var lastBlock = blocks.popLast()!
if lastBlockComplete {
lastBlock = xor(lastBlock, subKey1)
} else {
lastBlock = xor(lastBlock, subKey2)
}
var x = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize)
var y = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize)
for block in blocks {
y = xor(block, x)
x = try aes.encrypt(y)
}
y = xor(lastBlock, x)
return try aes.encrypt(y)
}
// MARK: Helper methods
/**
Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array
- parameters:
- bytes: byte array
- returns: bit shifted bit string split again in array of bytes
*/
private func leftShiftOneBit(_ bytes: Array<UInt8>) -> Array<UInt8> {
var shifted = Array<UInt8>(repeating: 0x00, count: bytes.count)
let last = bytes.count - 1
for index in 0..<last {
shifted[index] = bytes[index] << 1
if (bytes[index + 1] & 0x80) != 0 {
shifted[index] += 0x01
}
}
shifted[last] = bytes[last] << 1
return shifted
}
}
| gpl-3.0 |
MukeshKumarS/Swift | test/IRGen/closure.swift | 2 | 3152 | // RUN: %target-swift-frontend -primary-file %s -emit-ir | FileCheck %s
// REQUIRES: CPU=x86_64
// -- partial_apply context metadata
// CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* [[DESTROY:@objectdestroy.1]], i8** null, %swift.type { i64 64 }, i32 16 }
func a(i i: Int) -> (Int) -> Int {
return { x in i }
}
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @[[CLOSURE1:_TFF7closure1aFT1iSi_FSiSiU_FSiSi]](i64, i64)
protocol Ordinable {
func ord() -> Int
}
func b<T : Ordinable>(seq seq: T) -> (Int) -> Int {
return { i in i + seq.ord() }
}
// -- partial_apply stub
// CHECK: define internal i64 @_TPA_[[CLOSURE1]](i64, %swift.refcounted*) {{.*}} {
// CHECK: }
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @[[CLOSURE2:_TFF7closure1buRxS_9OrdinablerFT3seqx_FSiSiU_FSiSi]](i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} {
// -- partial_apply stub
// CHECK: define internal i64 @_TPA_[[CLOSURE2]](i64, %swift.refcounted*) {{.*}} {
// CHECK: entry:
// CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>*
// CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1
// CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]]
// CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8
// CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1
// CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]]
// CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8
// CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2
// CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8
// CHECK: call void @swift_retain(%swift.refcounted* [[BOX]])
// CHECK: call void @swift_release(%swift.refcounted* %1)
// CHECK: [[RES:%.*]] = tail call i64 @[[CLOSURE2]](i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]])
// CHECK: ret i64 [[RES]]
// CHECK: }
// -- <rdar://problem/14443343> Boxing of tuples with generic elements
// CHECK: define hidden { i8*, %swift.refcounted* } @_TF7closure14captures_tupleu0_rFT1xTxq___FT_Txq__(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U)
func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null)
// CHECK-NOT: @swift_getTupleTypeMetadata2
// CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]])
// CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1
// CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>*
return {x}
}
| apache-2.0 |
tejen/codepath-instagram | Instagram/Instagram/CommentCell.swift | 1 | 2648 | //
// CommentCell.swift
// Instagram
//
// Created by Tejen Hasmukh Patel on 3/12/16.
// Copyright © 2016 Tejen. All rights reserved.
//
import UIKit
import Parse
class CommentCell: UITableViewCell {
weak var commentsTableController: CommentsTableViewController?;
@IBOutlet weak var profilePicView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
var loadingProfile = false;
var comment: PFObject? {
didSet {
let user = comment!["user"] as? User;
profilePicView.setImageWithURL(user!.profilePicURL!);
usernameLabel.text = user!.username;
contentLabel.text = comment!["content"] as? String;
ageLabel.text = Post.timeSince(comment!.createdAt!);
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("openProfile"));
usernameLabel.userInteractionEnabled = true;
usernameLabel.addGestureRecognizer(tapGestureRecognizer);
let tapGestureRecognizer2 = UITapGestureRecognizer(target:self, action:Selector("openProfile"));
profilePicView.userInteractionEnabled = true;
profilePicView.addGestureRecognizer(tapGestureRecognizer2);
profilePicView.clipsToBounds = true;
profilePicView.layer.cornerRadius = 15;
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func openProfile() {
if(loadingProfile) {
return;
}
loadingProfile = true;
delay(1.0) { () -> () in
self.loadingProfile = false;
}
UIView.animateWithDuration(0.05) { () -> Void in
self.usernameLabel.alpha = 0.25;
self.profilePicView.alpha = 0.25;
}
delay(0.2) { () -> () in
UIView.animateWithDuration(0.2) { () -> Void in
self.usernameLabel.alpha = 1;
self.profilePicView.alpha = 1;
}
let vc = storyboard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController;
vc.user = User.getUserByUsername(self.usernameLabel.text!);
self.commentsTableController?.navigationController?.pushViewController(vc, animated: true);
}
}
}
| apache-2.0 |
IsaoTakahashi/iOS-KaraokeSearch | KaraokeSearchTests/KaraokeSearchTests.swift | 1 | 922 | //
// KaraokeSearchTests.swift
// KaraokeSearchTests
//
// Created by 高橋 勲 on 2015/05/09.
// Copyright (c) 2015年 高橋 勲. All rights reserved.
//
import UIKit
import XCTest
class KaraokeSearchTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ilyahal/VKMusic | VkPlaylist/Album.swift | 1 | 1427 | //
// Album.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// 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.
//
/// Альбом
class Album {
/// Идентификатор
let id: Int
/// Название
let title: String
init(id: Int, title: String) {
self.id = id
self.title = title
}
} | mit |
loudnate/Loop | Loop/Managers/StatusChartsManager.swift | 1 | 3479 | //
// StatusChartsManager.swift
// Loop
//
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import Foundation
import LoopKit
import LoopUI
import SwiftCharts
class StatusChartsManager: ChartsManager {
enum ChartIndex: Int, CaseIterable {
case glucose
case iob
case dose
case cob
}
let glucose: PredictedGlucoseChart
let iob: IOBChart
let dose: DoseChart
let cob: COBChart
init(colors: ChartColorPalette, settings: ChartSettings, traitCollection: UITraitCollection) {
let glucose = PredictedGlucoseChart()
let iob = IOBChart()
let dose = DoseChart()
let cob = COBChart()
self.glucose = glucose
self.iob = iob
self.dose = dose
self.cob = cob
super.init(colors: colors, settings: settings, charts: ChartIndex.allCases.map({ (index) -> ChartProviding in
switch index {
case .glucose:
return glucose
case .iob:
return iob
case .dose:
return dose
case .cob:
return cob
}
}), traitCollection: traitCollection)
}
}
extension StatusChartsManager {
func setGlucoseValues(_ glucoseValues: [GlucoseValue]) {
glucose.setGlucoseValues(glucoseValues)
invalidateChart(atIndex: ChartIndex.glucose.rawValue)
}
func setPredictedGlucoseValues(_ glucoseValues: [GlucoseValue]) {
glucose.setPredictedGlucoseValues(glucoseValues)
invalidateChart(atIndex: ChartIndex.glucose.rawValue)
}
func setAlternatePredictedGlucoseValues(_ glucoseValues: [GlucoseValue]) {
glucose.setAlternatePredictedGlucoseValues(glucoseValues)
invalidateChart(atIndex: ChartIndex.glucose.rawValue)
}
func glucoseChart(withFrame frame: CGRect) -> Chart? {
return chart(atIndex: ChartIndex.glucose.rawValue, frame: frame)
}
var targetGlucoseSchedule: GlucoseRangeSchedule? {
get {
return glucose.targetGlucoseSchedule
}
set {
glucose.targetGlucoseSchedule = newValue
invalidateChart(atIndex: ChartIndex.glucose.rawValue)
}
}
var scheduleOverride: TemporaryScheduleOverride? {
get {
return glucose.scheduleOverride
}
set {
glucose.scheduleOverride = newValue
invalidateChart(atIndex: ChartIndex.glucose.rawValue)
}
}
}
extension StatusChartsManager {
func setIOBValues(_ iobValues: [InsulinValue]) {
iob.setIOBValues(iobValues)
invalidateChart(atIndex: ChartIndex.iob.rawValue)
}
func iobChart(withFrame frame: CGRect) -> Chart? {
return chart(atIndex: ChartIndex.iob.rawValue, frame: frame)
}
}
extension StatusChartsManager {
func setDoseEntries(_ doseEntries: [DoseEntry]) {
dose.doseEntries = doseEntries
invalidateChart(atIndex: ChartIndex.dose.rawValue)
}
func doseChart(withFrame frame: CGRect) -> Chart? {
return chart(atIndex: ChartIndex.dose.rawValue, frame: frame)
}
}
extension StatusChartsManager {
func setCOBValues(_ cobValues: [CarbValue]) {
cob.setCOBValues(cobValues)
invalidateChart(atIndex: ChartIndex.cob.rawValue)
}
func cobChart(withFrame frame: CGRect) -> Chart? {
return chart(atIndex: ChartIndex.cob.rawValue, frame: frame)
}
}
| apache-2.0 |
benlangmuir/swift | test/SILOptimizer/assemblyvision_remark/basic_yaml.swift | 7 | 5509 | // RUN: %target-swiftc_driver -O -Rpass-missed=sil-assembly-vision-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xfrontend -enable-copy-propagation -emit-sil %s -o /dev/null -Xfrontend -verify -Xfrontend -enable-lexical-borrow-scopes=false
// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -wmo -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xfrontend -enable-copy-propagation -emit-sil -save-optimization-record=yaml -save-optimization-record-path %t/note.yaml -Xfrontend -enable-lexical-borrow-scopes=false %s -o /dev/null && %FileCheck --input-file=%t/note.yaml %s
// REQUIRES: optimized_stdlib,swift_stdlib_no_asserts
// This file is testing out the basic YAML functionality to make sure that it
// works without burdening basic_yaml.swift with having to update all
// of the yaml test cases everytime new code is added.
public class Klass {}
// CHECK: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 7 ]], Column: 21 }
// CHECK-NEXT: Function: main
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'heap allocated ref of type '''
// CHECK-NEXT: - ValueType: Klass
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: ...
public var global = Klass() // expected-remark {{heap allocated ref of type 'Klass'}}
// CHECK: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 42 ]], Column: 12 }
// CHECK-NEXT: Function: 'getGlobal()'
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'begin exclusive access to value of type '''
// CHECK-NEXT: - ValueType: Klass
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: - InferredValue: 'of ''global'''
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE - 14 ]], Column: 12 }
// CHECK-NEXT: ...
//
// CHECK: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 27 ]], Column: 12 }
// CHECK-NEXT: Function: 'getGlobal()'
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'end exclusive access to value of type '''
// CHECK-NEXT: - ValueType: Klass
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: - InferredValue: 'of ''global'''
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE - 29 ]], Column: 12 }
// CHECK-NEXT: ...
//
// CHECK: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 12]], Column: 5 }
// CHECK-NEXT: Function: 'getGlobal()'
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'retain of type '''
// CHECK-NEXT: - ValueType: Klass
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: - InferredValue: 'of ''global'''
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE - 44 ]], Column: 12 }
// CHECK-NEXT: ...
@inline(never)
public func getGlobal() -> Klass {
return global // expected-remark @:5 {{retain of type 'Klass'}}
// expected-note @-49:12 {{of 'global'}}
// expected-remark @-2 {{begin exclusive access to value of type 'Klass'}}
// expected-note @-51:12 {{of 'global'}}
// NOTE: We really want the end access at :18, not :12. TODO Fix this!
// expected-remark @-5 {{end exclusive access to value of type 'Klass'}}
// expected-note @-54:12 {{of 'global'}}
}
// CHECK: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 23]], Column: 11 }
// CHECK-NEXT: Function: 'useGlobal()'
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'heap allocated ref of type '''
// CHECK-NEXT: - ValueType:
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: ...
// CHECK-NEXT: --- !Missed
// CHECK-NEXT: Pass: sil-assembly-vision-remark-gen
// CHECK-NEXT: Name: sil.memory
// CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift',
// CHECK-NEXT: Line: [[# @LINE + 12]], Column: 12 }
// CHECK-NEXT: Function: 'useGlobal()'
// CHECK-NEXT: Args:
// CHECK-NEXT: - String: 'release of type '''
// CHECK-NEXT: - ValueType:
// CHECK-NEXT: - String: ''''
// CHECK-NEXT: ...
public func useGlobal() {
let x = getGlobal()
// Make sure that the retain msg is at the beginning of the print and the
// releases are the end of the print.
print(x) // expected-remark @:11 {{heap allocated ref of type}}
// We test the type emission above since FileCheck can handle regex.
// expected-remark @-2:12 {{release of type}}
}
| apache-2.0 |
akisute/ReactiveCocoaSwift | ReactiveCocoaSwiftTests/Models/BaseModelTests.swift | 1 | 632 | //
// BaseModelTests.swift
// ReactiveCocoaSwift
//
// Created by Ono Masashi on 2015/01/23.
// Copyright (c) 2015年 akisute. All rights reserved.
//
import UIKit
import Quick
import Nimble
import ReactiveCocoaSwift
class BaseModelTests: QuickSpec {
override func spec() {
var model: BaseModel!
beforeEach {
model = BaseModel()
}
describe("its basic functionarity") {
context("always") {
it("returns modelType") {
expect(model.modelType).to(equal("BaseModel"))
}
}
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.