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
tkremenek/swift
validation-test/compiler_crashers_2_fixed/0151-rdar-39040593.swift
39
457
// RUN: %target-typecheck-verify-swift class A { func foo() { class B { let question: String = "ultimate question" let answer: Int? = 42 lazy var bar: () -> String = { [weak self] in guard let self = self else { return "Unknown" } if let answer = self.answer { return "\(self.question) = \(answer)" } else { return "<\(self.question) />" } } } } }
apache-2.0
tkremenek/swift
validation-test/compiler_crashers_fixed/25444-swift-archetypebuilder-finalize.swift
65
467
// 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 { enum S<{ enum S{protocol A:A{var b :e typealias e : Boolean
apache-2.0
joerocca/GitHawk
Classes/Bookmark v2/BookmarkHeaderSectionController.swift
1
1434
// // BookmarkHeaderSectionController.swift // Freetime // // Created by Hesham Salman on 11/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import IGListKit protocol BookmarkHeaderSectionControllerDelegate: class { func didTapClear(sectionController: BookmarkHeaderSectionController) } final class BookmarkHeaderSectionController: ListSectionController, ClearAllHeaderCellDelegate { weak var delegate: BookmarkHeaderSectionControllerDelegate? init(delegate: BookmarkHeaderSectionControllerDelegate) { self.delegate = delegate super.init() } override func sizeForItem(at index: Int) -> CGSize { guard let width = collectionContext?.containerSize.width else { fatalError("Missing context") } return CGSize(width: width, height: Styles.Sizes.tableCellHeight) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: ClearAllHeaderCell.self, for: self, at: index) as? ClearAllHeaderCell else { fatalError("Missing context or wrong cell type") } cell.delegate = self cell.configure(title: Constants.Strings.bookmarks.uppercased(with: Locale.current)) return cell } // MARK: ClearAllHeaderCellDelegate func didSelectClear(cell: ClearAllHeaderCell) { delegate?.didTapClear(sectionController: self) } }
mit
mrr1vfe/FBLA
customCellTableViewCell.swift
1
2010
// // customCellTableViewCell.swift // FBLA // // Created by Yi Chen on 15/11/8. // Copyright © 2015年 Yi Chen. All rights reserved. // import UIKit import Parse import ParseUI class customCellTableViewCell: UITableViewCell { @IBOutlet weak var userAvatar: PFImageView! @IBOutlet weak var username: UILabel! @IBOutlet weak var createdAt: UILabel! @IBOutlet weak var composedImage: PFImageView! @IBOutlet weak var composedMessage: UILabel! @IBOutlet weak var topBarView: UIView! @IBOutlet weak var thumbIcon: UIImageView! @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var likeLabel: UILabel! var parseObject:PFObject? override func awakeFromNib() { super.awakeFromNib() thumbIcon.hidden = true userAvatar.layer.cornerRadius = userAvatar.frame.width/2 userAvatar.layer.masksToBounds = true // Initialization code } @IBAction func clickLike(sender: AnyObject) { if(parseObject != nil) { self.thumbIcon?.alpha = 0 if var votes:Int? = parseObject!.objectForKey("Likes") as? Int { votes!++ parseObject!.setObject(votes!, forKey: "Likes"); parseObject!.saveInBackground(); likeLabel?.text = "\(votes!) ♥️"; } } thumbIcon?.hidden = false thumbIcon?.alpha = 1.0 UIView.animateWithDuration(1, delay: 0.5, options:[], animations: { self.thumbIcon?.alpha = 0 }, completion: { (value:Bool) in self.thumbIcon?.hidden = true }) } @IBAction func clickComment(sender: AnyObject) { } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/22090-swift-constraints-constraintgraph-addconstraint.swift
11
270
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d { class a { { } } class a<T where B : C { } var d = 0 as a struct D { class A { protocol c : a
mit
radex/swift-compiler-crashes
crashes-fuzzing/21328-swift-removeshadoweddecls.swift
1
263
// 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 A { var _ = a k { { } { } } var a var b { struct A { class A<d where B : A { let : A.g
mit
radex/swift-compiler-crashes
crashes-fuzzing/22604-swift-constraints-constraintsystem-simplifyfixconstraint.swift
11
216
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<T where g : a func < { d } assert( ) {
mit
ProjectDent/ARKit-CoreLocation
Sources/ARKit-CoreLocation/Location Manager/SceneLocationEstimate.swift
1
458
// // SceneLocationEstimate.swift // ARKit+CoreLocation // // Created by Andrew Hart on 03/07/2017. // Copyright © 2017 Project Dent. All rights reserved. // import Foundation import CoreLocation import SceneKit public class SceneLocationEstimate { public let location: CLLocation public let position: SCNVector3 init(location: CLLocation, position: SCNVector3) { self.location = location self.position = position } }
mit
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/model/registration/RegistrationInfo.swift
1
1269
// // RegistrationInfo.swift // Emby.ApiClient // // Created by Vedran Ozir on 09/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation public struct RegistrationInfo: Codable { let name: String let expirationDate: Date let trial: Bool let registered: Bool // public init?(jSON: JSON_Object) { // // //{"Name":"TV","ExpirationDate":"2015-11-15","IsTrial":true,"IsRegistered":false} // // if let name = jSON["Name"] as? String, // let expirationString = jSON["ExpirationDate"] as? String, // let trial = jSON["IsTrial"] as? Bool, // let registered = jSON["IsRegistered"] as? Bool // { // self.name = name // self.trial = trial // self.registered = registered // // let formatter = DateFormatter() // formatter.dateFormat = "yyyy-MM-dd" // self.expirationDate = formatter.date(from: expirationString)! as NSDate // } // else { // return nil // } // } enum CodingKeys: String, CodingKey { case name = "Name" case expirationDate = "ExpirationDate" case trial = "Trial" case registered = "Registered" } }
mit
mariopavlovic/advent-of-code
2015/advent-of-codeTests/Day7Specs.swift
1
6420
import Quick import Nimble @testable import advent_of_code class Day7Specs: QuickSpec { override func spec() { var sut: Day7! beforeEach { sut = Day7() } describe("Given Day7 task") { describe("when transfering input to instructions (domain)", { it("should read from file", closure: { let results = sut.readInput("day7") expect(results.count).to(equal(339)) if let first = results.first, let last = results.last { expect(first).to(equal("lf AND lq -> ls")) expect(last).to(equal("he RSHIFT 5 -> hh")) } }) it("should map input to instructions", closure: { let input = ["123 -> x", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h"] let result = sut.parseInstructions(input: input) expect(result.count).to(equal(6)) let first = result.first! expect(first.leftWire).to(equal("123")) expect(first.outputWire).to(equal("x")) let last = result.last! expect(last.rightWire).to(equal("x")) expect(last.outputWire).to(equal("h")) }) }) describe("when running single operation systems", { it("should work correctly on direct value", closure: { var instruction = Day7.Instruction() instruction.leftWire = "3" instruction.operation = .AND instruction.rightWire = "3" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(3)) }) it("should work correctly on AND operation", closure: { var instruction = Day7.Instruction() instruction.leftWire = "123" instruction.operation = .AND instruction.rightWire = "456" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(72)) }) it("should work correctly on OR operation", closure: { var instruction = Day7.Instruction() instruction.leftWire = "123" instruction.operation = .OR instruction.rightWire = "456" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(507)) }) it("should work correctly on LSHIFT operation", closure: { var instruction = Day7.Instruction() instruction.leftWire = "123" instruction.operation = .LSHIFT instruction.rightWire = "2" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(492)) }) it("should work correctly on RSHIFT operation", closure: { var instruction = Day7.Instruction() instruction.leftWire = "456" instruction.operation = .RSHIFT instruction.rightWire = "2" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(114)) }) it("should work correctly on NOT operation", closure: { var instruction = Day7.Instruction() instruction.operation = .NOT instruction.rightWire = "123" instruction.outputWire = "x" let result = sut.outputValue(onWire: "x", model: [instruction]) expect(result).to(equal(65412)) }) }) describe("when running the circuit", { it("should give wire output value for desired wire", closure: { let input = ["123 -> x", "456 -> y", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h", "NOT y -> i"] let d = sut.outputSignal(onWire: "d", input: input) let e = sut.outputSignal(onWire: "e", input: input) let f = sut.outputSignal(onWire: "f", input: input) let g = sut.outputSignal(onWire: "g", input: input) let h = sut.outputSignal(onWire: "h", input: input) let i = sut.outputSignal(onWire: "i", input: input) let x = sut.outputSignal(onWire: "x", input: input) let y = sut.outputSignal(onWire: "y", input: input) expect(d).to(equal(72)) expect(e).to(equal(507)) expect(f).to(equal(492)) expect(g).to(equal(114)) expect(h).to(equal(65412)) expect(i).to(equal(65079)) expect(x).to(equal(123)) expect(y).to(equal(456)) }) it("should find a solution for day 7 tasks - part 1", closure: { let result = sut.runCircut(resultOnWire: "a", filePath: "day7") expect(result).to(equal(16076)) }) it("should find a solution for day 7 tasks - part 2", closure: { let result = sut.runCircut(resultOnWire: "a", filePath: "day7-part2") expect(result).to(equal(2797)) }) }) } } }
mit
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/UIKit/TableView/YJUITableViewHeaderFooterView.swift
1
1775
// // YJUITableViewHeaderFooterView.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/5/23. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit @objc extension UITableViewHeaderFooterView { /// 获取 YJUITableCellObject public class func cellObject() -> YJUITableCellObject { return YJUITableCellObject(cellClass: self) } /// 获取YJUITableCellObject并自动填充模型 public class func cellObject(withCellModel cellModel: Any?) -> YJUITableCellObject { let co = self.cellObject() co.cellModel = cellModel return co } /// 获取 header 的显示高 open class func tableViewManager(_ tableViewManager: YJUITableViewManager, heightWith cellObject: YJUITableCellObject) -> CGFloat { return tableViewManager.tableView.sectionHeaderHeight } /// 刷新 UITableViewHeaderFooterView @objc func tableViewManager(_ tableViewManager: YJUITableViewManager, reloadWith cellObject: YJUITableCellObject) {} } open class YJUITableViewHeaderFooterView: UITableViewHeaderFooterView { public private(set) var cellObject: YJUITableCellObject! public private(set) var tableViewManager: YJUITableViewManager! open override var reuseIdentifier: String? { return super.reuseIdentifier ?? NSStringFromClass(self.classForCoder) } open override func tableViewManager(_ tableViewManager: YJUITableViewManager, reloadWith cellObject: YJUITableCellObject) { super.tableViewManager(tableViewManager, reloadWith: cellObject) self.tableViewManager = tableViewManager self.cellObject = cellObject } }
mit
Sharelink/Bahamut
Bahamut/UserGuideAddFriendsController.swift
1
737
// // UserGuideAddFriendsController.swift // Sharelink // // Created by AlexChow on 16/1/29. // Copyright © 2016年 GStudio. All rights reserved. // import Foundation import UIKit class UserGuideAddFriendsController: UIViewController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) MobClick.event("UserGuide_ToAddFriends") dispatch_async(dispatch_get_main_queue()) { () -> Void in ServiceContainer.getService(UserService).shareAddLinkMessageToSNS(self) } } @IBAction func addMore(sender: AnyObject) { MobClick.event("UserGuide_AddFriend") ServiceContainer.getService(UserService).shareAddLinkMessageToSNS(self) } }
mit
GYLibrary/A_Y_T
GYVideo/GYVideo/VideoPlayer/MediaManager.swift
1
2456
// // MediaManager.swift // EZPlayerExample // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import UIKit import EZPlayer class MediaManager { var player: EZPlayer? var mediaItem: MediaItem? var embeddedContentView: UIView? static let sharedInstance = MediaManager() private init(){ NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.EZPlayerPlaybackDidFinish, object: nil) } func playEmbeddedVideo(url: URL, embeddedContentView contentView: UIView? = nil, userinfo: [AnyHashable : Any]? = nil) { var mediaItem = MediaItem() mediaItem.url = url self.playEmbeddedVideo(mediaItem: mediaItem, embeddedContentView: contentView, userinfo: userinfo ) } func playEmbeddedVideo(mediaItem: MediaItem, embeddedContentView contentView: UIView? = nil , userinfo: [AnyHashable : Any]? = nil ) { //stop self.releasePlayer() if let skinView = userinfo?["skin"] as? UIView{ self.player = EZPlayer(controlView: skinView) }else{ self.player = EZPlayer() } if let autoPlay = userinfo?["autoPlay"] as? Bool{ self.player!.autoPlay = autoPlay } if let fullScreenMode = userinfo?["fullScreenMode"] as? EZPlayerFullScreenMode{ self.player!.fullScreenMode = fullScreenMode } self.player!.backButtonBlock = { fromDisplayMode in if fromDisplayMode == .embedded { self.releasePlayer() }else if fromDisplayMode == .fullscreen { if self.embeddedContentView == nil && self.player!.lastDisplayMode != .float{ self.releasePlayer() } }else if fromDisplayMode == .float { self.releasePlayer() } } self.embeddedContentView = contentView self.player!.playWithURL(mediaItem.url! , embeddedContentView: self.embeddedContentView) } func releasePlayer(){ self.player?.stop() self.player?.view.removeFromSuperview() self.player = nil self.embeddedContentView = nil self.mediaItem = nil } @objc func playerDidPlayToEnd(_ notifiaction: Notification) { //结束播放关闭播放器 //self.releasePlayer() } }
mit
wesj/Project105
FirefoxPasswords/ActionRequestHandler.swift
1
4079
// // ActionRequestHandler.swift // FirefoxPasswords // // Created by Wes Johnston on 10/17/14. // Copyright (c) 2014 Wes Johnston. All rights reserved. // import UIKit import MobileCoreServices class ActionRequestHandler: NSObject, NSExtensionRequestHandling { var extensionContext: NSExtensionContext? func beginRequestWithExtensionContext(context: NSExtensionContext) { // Do not call super in an Action extension with no user interface self.extensionContext = context var found = false // Find the item containing the results from the JavaScript preprocessing. outer: for item: AnyObject in context.inputItems { let extItem = item as NSExtensionItem if let attachments = extItem.attachments { for itemProvider: AnyObject in attachments { if itemProvider.hasItemConformingToTypeIdentifier(String(kUTTypePropertyList)) { itemProvider.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (item, error) in let dictionary = item as NSDictionary NSOperationQueue.mainQueue().addOperationWithBlock { self.itemLoadCompletedWithPreprocessingResults(dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as [NSObject: AnyObject]) } found = true }) if found { break outer } } } } } if !found { self.doneWithResults(nil) } } func itemLoadCompletedWithPreprocessingResults(javaScriptPreprocessingResults: [NSObject: AnyObject]) { // Here, do something, potentially asynchronously, with the preprocessing // results. // In this very simple example, the JavaScript will have passed us the // current background color style, if there is one. We will construct a // dictionary to send back with a desired new background color style. let bgColor: AnyObject? = javaScriptPreprocessingResults["currentBackgroundColor"] if bgColor == nil || bgColor! as String == "" { // No specific background color? Request setting the background to red. self.doneWithResults(["newBackgroundColor": "red"]) } else { // Specific background color is set? Request replacing it with green. self.doneWithResults(["newBackgroundColor": "green"]) } } func doneWithResults(resultsForJavaScriptFinalizeArg: [NSObject: AnyObject]?) { if let resultsForJavaScriptFinalize = resultsForJavaScriptFinalizeArg { // Construct an NSExtensionItem of the appropriate type to return our // results dictionary in. // These will be used as the arguments to the JavaScript finalize() // method. var resultsDictionary = [NSExtensionJavaScriptFinalizeArgumentKey: resultsForJavaScriptFinalize] var resultsProvider = NSItemProvider(item: resultsDictionary, typeIdentifier: String(kUTTypePropertyList)) var resultsItem = NSExtensionItem() resultsItem.attachments = [resultsProvider] // Signal that we're complete, returning our results. self.extensionContext!.completeRequestReturningItems([resultsItem], completionHandler: nil) } else { // We still need to signal that we're done even if we have nothing to // pass back. self.extensionContext!.completeRequestReturningItems([], completionHandler: nil) } // Don't hold on to this after we finished with it. self.extensionContext = nil } }
mpl-2.0
LOTUM/EventHub
EventHubTests/EventHubTests.swift
1
6877
import XCTest @testable import LotumEventHub class EventHubTest: XCTestCase { func testEmitEvent() { let e = expectation(description: "hub") let hub = EventHub<String, Void>() hub.once("test") { e.fulfill() } hub.emit("test") waitForExpectations(timeout: 0.1, handler: nil) } func testOnlyFiringMatchingEvents() { let hub = EventHub<String, Void>() hub.once("test") { XCTFail() } hub.emit("not_registered") } func testMutlipleEmit() { let e1 = expectation(description: "expectation1") let e2 = expectation(description: "expectation2") let e3 = expectation(description: "expectation3") let hub = EventHub<String, Void>() hub.once("test1") { e1.fulfill() } hub.once("test1") { e2.fulfill() } hub.once("test2") { e3.fulfill() } hub.emit("test1") hub.emit("test2") waitForExpectations(timeout: 0.1, handler: nil) } func testOnlyOnce() { let e = expectation(description: "hub") let hub = EventHub<String, Void>() hub.once("test") { e.fulfill() } hub.emit("test") hub.emit("test") waitForExpectations(timeout: 0.1, handler: nil) } func testEmitFromWithinOn() { let e = expectation(description: "hub") let hub = EventHub<String, Void>() hub.once("test") { hub.emit("test") } hub.emit("test") e.fulfill() waitForExpectations(timeout: 0.1, handler: nil) } func test_remove_listener() { let e = expectation(description: "remove") let hub = EventHub<String, Void>() hub.once("remove") { e.fulfill() } let disposer = hub.on("remove") { XCTFail() } disposer.dispose() hub.emit("remove") waitForExpectations(timeout: 1.5, handler: nil) } func test_remove_one_of_listener() { let e1 = expectation(description: "one") let e2 = expectation(description: "two") let hub = EventHub<String, Void>() hub.once("event1") { e1.fulfill() } hub.once("event2") { e2.fulfill() } let disposer = hub.on(oneOf: ["event1", "event2"]) { XCTFail() } XCTAssertEqual(hub.numberOfListeners(), 3) disposer.dispose() XCTAssertEqual(hub.numberOfListeners(), 2) hub.emit("event1") hub.emit("event2") waitForExpectations(timeout: 1.5, handler: nil) } func test_schedule_on_queue() { let e = expectation(description: "on_queue") let q = DispatchQueue(label: "my_queue") let hub = EventHub<String, Void>() hub.once("fire") { if #available(iOS 10.0, *) { dispatchPrecondition(condition: .onQueue(q)) } else { // Fallback on earlier versions } e.fulfill() } hub.emit("fire", on: q) waitForExpectations(timeout: 1.5, handler: nil) } func test_number_of_listeners() { let hub = EventHub<String, Void>() XCTAssertEqual(hub.numberOfListeners(), 0) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 0) hub.once("test1") {} XCTAssertEqual(hub.numberOfListeners(), 1) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 1) _ = hub.on("test2") {} XCTAssertEqual(hub.numberOfListeners(), 2) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 1) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 1) _ = hub.on("test1") {} XCTAssertEqual(hub.numberOfListeners(), 3) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 2) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 1) hub.once(oneOf: ["test1", "test2"]) {} XCTAssertEqual(hub.numberOfListeners(), 4) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 3) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 2) _ = hub.on(oneOf: ["test1", "test2"]) {} XCTAssertEqual(hub.numberOfListeners(), 5) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 4) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 3) hub.removeAllListeners(forEvent: "test1") XCTAssertEqual(hub.numberOfListeners(), 3) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 0) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 3) hub.removeAllListeners() XCTAssertEqual(hub.numberOfListeners(), 0) XCTAssertEqual(hub.numberOfListeners(forEvent: "test1"), 0) XCTAssertEqual(hub.numberOfListeners(forEvent: "test2"), 0) } func test_once_one_of() { let e1 = expectation(description: "one") let e2 = expectation(description: "two") let hub = EventHub<String, Void>() hub.once(oneOf: ["test1", "test2"]) { e1.fulfill() } hub.emit("test2") hub.emit("test2") hub.emit("test3") hub.once(oneOf: ["test1", "test2"]) { e2.fulfill() } hub.emit("test1") waitForExpectations(timeout: 0.1, handler: nil) } func test_on_one_of() { let es = [expectation(description: "one"), expectation(description: "two")] let hub = EventHub<String, Void>() var index = 0 _ = hub.on(oneOf: ["test1", "test2"]) { es[index].fulfill() index += 1 } hub.emit("test1") hub.emit("test2") hub.emit("test3") waitForExpectations(timeout: 0.1, handler: nil) } func test_one_of_with_zero_events() { let hub = EventHub<String, Void>() let disposer = hub.once(oneOf: []) { XCTFail() } hub.emit("event") XCTAssertEqual(hub.numberOfListeners(), 0) disposer.dispose() } func test_one_of_with_single_event() { let e = expectation(description: "expectation") let hub = EventHub<String, Void>() hub.once(oneOf: ["event"]) { e.fulfill() } hub.emit("event") waitForExpectations(timeout: 0.1, handler: nil) } }
apache-2.0
wenghengcong/Coderpursue
BeeFun/BeeFun/ToolKit/JSToolKit/JSFoundation/JSUtilis.swift
1
153
// // JSUtilis.swift // BeeFun // // Created by WengHengcong on 05/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit
mit
bignerdranch/DeferredTCPSocket
Examples/ChatServer/ChatServerTests/ChatServerTests.swift
1
915
// // ChatServerTests.swift // ChatServerTests // // Created by John Gallagher on 9/12/14. // Copyright (c) 2014 Big Nerd Ranch. All rights reserved. // import Cocoa import XCTest class ChatServerTests: 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
Asura19/My30DaysOfSwift
BasicAnimation/BasicAnimation/ScaleViewController.swift
1
760
// // ScaleViewController.swift // BasicAnimation // // Created by Phoenix on 2017/4/24. // Copyright © 2017年 Phoenix. All rights reserved. // import UIKit class ScaleViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.imageView.alpha = 0; } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseIn, animations: { self.imageView.transform = CGAffineTransform(scaleX: 2, y: 2) self.imageView.alpha = 1; }, completion: nil) } }
mit
moltin/ios-sdk
Tests/moltin iOS Tests/CartTests.swift
1
9568
// // CartTests.swift // moltin iOS // // Created by Craig Tweedy on 26/02/2018. // import XCTest @testable import moltin class CartTests: XCTestCase { func testGettingANewCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.get(forID: "3333") { (result) in switch result { case .success(let cart): XCTAssert(cart.id == "3333") XCTAssert(type(of: cart) == moltin.Cart.self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testGettingCartItems() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.items(forCartID: "3333") { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems.data?[0].id == "abc123") XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testGettingCartItemsWithTaxes() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsWithTaxesData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.items(forCartID: "3333") { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems.data?[0].id == "abc123") XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self) XCTAssert(cartItems.data?[0].relationships != nil) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testAddingAProductToCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID = "3333" let productID = "12345" _ = request.addProduct(withID: productID, ofQuantity: 5, toCart: cartID) { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems[0].id == "abc123") XCTAssert(type(of: cartItems) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testBuildingACartItem() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let item = request.buildCartItem(withID: "12345", ofQuantity: 5) XCTAssert(item["type"] as? String == "cart_item") XCTAssert(item["id"] as? String == "12345") XCTAssert(item["quantity"] as? Int == 5) } func testAddingACustomItem() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" let customCartPrice = CartItemPrice(amount: 111, includes_tax: false) let customItem = CustomCartItem(withName: "testItem", sku: "1231", quantity: 1, description: "test desc", price: customCartPrice) _ = request.addCustomItem(customItem, toCart: cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testAddingAPromotion() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" _ = request.addPromotion("12345", toCart: cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testBuildingAPromotionItem() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let item = request.buildCartItem(withID: "12345", ofType: .promotionItem) XCTAssert(item["type"] as? String == "promotion_item") XCTAssert(item["code"] as? String == "12345") } func testRemovingAnItemFromCart() { } func testUpdatingAnItemInCart() { } func testCheckingOutCart() { } func testBuildingCheckoutCartDataWithoutShippingAddressWorks() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let customer = Customer(withID: "12345") let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") billingAddress.line1 = "7 Patterdale Terrace" let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: nil) let customerDetails = item["customer"] as? [String: Any] ?? [:] let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:] let billingDetails = item["billing_address"] as? [String: Any] ?? [:] XCTAssert(customerDetails["id"] as? String == "12345") XCTAssert(shippingDetails["line_1"] as? String == "7 Patterdale Terrace") XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace") } func testBuildingCheckoutCartDataWithShippingAddressWorks() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let customer = Customer(withID: "12345") let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") billingAddress.line1 = "7 Patterdale Terrace" let shippingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") shippingAddress.line1 = "8 Patterdale Terrace" let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: shippingAddress) let customerDetails = item["customer"] as? [String: Any] ?? [:] let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:] let billingDetails = item["billing_address"] as? [String: Any] ?? [:] XCTAssert(customerDetails["id"] as? String == "12345") XCTAssert(shippingDetails["line_1"] as? String == "8 Patterdale Terrace") XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace") } func testDeletingCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.deletedCartData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" _ = request.deleteCart(cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.Cart].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } }
mit
zhxnlai/wwdc
Zhixuan Lai/Zhixuan Lai/ZLSectionHeaderView.swift
1
1654
// // ZLCollectionViewHeaderView.swift // Zhixuan Lai // // Created by Zhixuan Lai on 4/25/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit import TTTAttributedLabel class ZLSectionHeaderView: UICollectionReusableView { static let labelInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) static let labelMaxSize = CGSize(width: UIScreen.mainScreen().bounds.width-ZLSectionHeaderView.labelInset.left-ZLSectionHeaderView.labelInset.right, height: CGFloat.max) var label = TTTAttributedLabel() var attributedText: NSAttributedString? { didSet { if let attributedText = attributedText { label.setText(attributedText.string, afterInheritingLabelAttributesAndConfiguringWithBlock: { (string) -> NSMutableAttributedString in NSMutableAttributedString(attributedString: attributedText) }) } } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { label.numberOfLines = 0 label.userInteractionEnabled = true label.enabledTextCheckingTypes = NSDataDetector(types: NSTextCheckingType.Link.rawValue | NSTextCheckingType.Dash.rawValue, error: nil)!.checkingTypes addSubview(label) self.userInteractionEnabled = true } override func layoutSubviews() { super.layoutSubviews() label.frame = UIEdgeInsetsInsetRect(self.bounds, ZLSectionHeaderView.labelInset) } }
mit
inket/stts
stts/Services/Super/CachetService.swift
1
2381
// // CachetService.swift // stts // import Foundation typealias CachetService = BaseCachetService & RequiredServiceProperties class BaseCachetService: BaseService { private enum ComponentStatus: Int, ComparableStatus { // https://docs.cachethq.io/docs/component-statuses case operational = 1 case performanceIssues = 2 case partialOutage = 3 case majorOutage = 4 var description: String { switch self { case .operational: return "Operational" case .performanceIssues: return "Performance Issues" case .partialOutage: return "Partial Outage" case .majorOutage: return "Major Outage" } } var serviceStatus: ServiceStatus { switch self { case .operational: return .good case .performanceIssues: return .notice case .partialOutage: return .minor case .majorOutage: return .major } } } override func updateStatus(callback: @escaping (BaseService) -> Void) { guard let realSelf = self as? CachetService else { fatalError("BaseCachetService should not be used directly.") } let apiComponentsURL = realSelf.url.appendingPathComponent("api/v1/components") loadData(with: apiComponentsURL) { [weak self] data, _, error in guard let strongSelf = self else { return } defer { callback(strongSelf) } guard let data = data else { return strongSelf._fail(error) } let json = try? JSONSerialization.jsonObject(with: data, options: []) guard let components = (json as? [String: Any])?["data"] as? [[String: Any]] else { return strongSelf._fail("Unexpected data") } guard !components.isEmpty else { return strongSelf._fail("Unexpected data") } let statuses = components.compactMap({ $0["status"] as? Int }).compactMap(ComponentStatus.init(rawValue:)) let highestStatus = statuses.max() strongSelf.status = highestStatus?.serviceStatus ?? .undetermined strongSelf.message = highestStatus?.description ?? "Undetermined" } } }
mit
j-pk/grub-api
Sources/App/Models/User.swift
1
5524
// // User.swift // GrubAPI // // Created by Jameson Kirby on 2/8/17. // // import Vapor import Auth import Turnstile import VaporJWT import Foundation final class User: Model { var id: Node? var exists: Bool = false var username: String var password: String var token: String? init(username: String, password: String) { self.id = nil self.username = username self.password = password } init(node: Node, in context: Context) throws { id = try node.extract("id") username = try node.extract("username") password = try node.extract("password") token = try node.extract("token") } init(credentials: UsernamePassword) { self.username = credentials.username self.password = credentials.password } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "username": username, "password": password, "token": token ]) } static func prepare(_ database: Database) throws { try database.create("users") { users in users.id() users.string("username") users.string("password") users.string("token", optional: true) } } static func revert(_ database: Database) throws { try database.delete("users") } } struct Authentication { static let AccessTokenSigningKey = "secret" static func generateExpirationDate() -> Date { return Date() + (60 * 5) // 5 Minutes later } func decodeJWT(_ token: String) -> JWT? { guard let jwt = try? JWT(token: token), let _ = try? jwt.verifySignatureWith(HS256(key: Authentication.AccessTokenSigningKey.makeBytes())) else { return nil } return jwt } } extension User: Auth.User { static func authenticate(credentials: Credentials) throws -> Auth.User { var user: User? switch credentials { case let userNamePassword as UsernamePassword: let fetchedUser = try User.query().filter("username", userNamePassword.username).first() guard let user = fetchedUser else { throw Abort.custom(status: .networkAuthenticationRequired, message: "User does not exist") } if userNamePassword.password == user.password { return user } else { throw Abort.custom(status: .networkAuthenticationRequired, message: "Invalid user name or password") } case let id as Identifier: guard let user = try User.find(id.id) else { throw Abort.custom(status: .forbidden, message: "Invalid user id") } return user case let accessToken as AccessToken: user = try User.query().filter("token", accessToken.string).first() default: throw IncorrectCredentialsError() } if var user = user { // Check if we have an accessToken first, if not, lets create a new one if let accessToken = user.token { // Check if our authentication token has expired, if so, lets generate a new one as this is a fresh login let receivedJWT = try JWT(token: accessToken) // Validate it's time stamp if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) { try user.generateToken() } } else { // We don't have a valid access token try user.generateToken() } try user.save() return user } else { throw IncorrectCredentialsError() } } static func register(credentials: Credentials) throws -> Auth.User { var newUser: User switch credentials { case let credentials as UsernamePassword: newUser = User(credentials: credentials) default: throw UnsupportedCredentialsError() } if try User.query().filter("username", newUser.username).first() == nil { try newUser.generateToken() try newUser.save() return newUser } else { throw AccountTakenError() } } func generateToken() throws { let payload = Node.object(["username": .string(username), "expires" : .number(.double(Authentication.generateExpirationDate().timeIntervalSinceReferenceDate))]) let jwt = try JWT(payload: payload, signer: HS256(key: Authentication.AccessTokenSigningKey.makeBytes())) self.token = try jwt.createToken() } func validateToken() throws -> Bool { guard let token = self.token else { return false } // Validate our current access token let receivedJWT = try JWT(token: token) if try receivedJWT.verifySignatureWith(HS256(key: Authentication.AccessTokenSigningKey.makeBytes())) { // If we need a new token, lets generate one if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) { try self.generateToken() return true } } return false } }
mit
wordpress-mobile/WordPress-iOS
WordPress/Classes/Services/ReaderTopicService+FollowedInterests.swift
1
4906
import Foundation // MARK: - ReaderFollowedInterestsService /// Protocol representing a service that retrieves the users followed interests/tags protocol ReaderFollowedInterestsService: AnyObject { /// Fetches the users locally followed interests /// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void) /// Fetches the users followed interests from the network, then returns the sync'd interests /// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void) /// Follow the provided interests /// If the user is not logged into a WP.com account, the interests will only be saved locally. func followInterests(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void, isLoggedIn: Bool) /// Returns the API path of a given slug func path(slug: String) -> String } // MARK: - CoreData Fetching extension ReaderTopicService: ReaderFollowedInterestsService { public func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void) { completion(followedInterests()) } public func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void) { fetchReaderMenu(success: { [weak self] in self?.fetchFollowedInterestsLocally(completion: completion) }) { [weak self] error in DDLogError("Could not fetch remotely followed interests: \(String(describing: error))") self?.fetchFollowedInterestsLocally(completion: completion) } } func followInterests(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void, isLoggedIn: Bool) { // If the user is logged in, attempt to save the interests on the server // If the user is not logged in, save the interests locally if isLoggedIn { let slugs = interests.map { $0.slug } let topicService = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest()) topicService.followInterests(withSlugs: slugs, success: { [weak self] in self?.fetchFollowedInterestsRemotely(completion: success) }) { error in failure(error) } } else { followInterestsLocally(interests, success: success, failure: failure) } } func path(slug: String) -> String { // We create a "remote" service to get an accurate path for the tag // https://public-api.../tags/_tag_/posts let service = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest()) return service.pathForTopic(slug: slug) } private func followInterestsLocally(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void) { interests.forEach { interest in let topic = ReaderTagTopic(remoteInterest: interest, context: managedObjectContext, isFollowing: true) topic.path = path(slug: interest.slug) } ContextManager.sharedInstance().save(managedObjectContext, withCompletionBlock: { [weak self] in self?.fetchFollowedInterestsLocally(completion: success) }) } private func apiRequest() -> WordPressComRestApi { let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext) let token: String? = defaultAccount?.authToken return WordPressComRestApi.defaultApi(oAuthToken: token, userAgent: WPUserAgent.wordPress()) } // MARK: - Private: Fetching Helpers private func followedInterestsFetchRequest() -> NSFetchRequest<ReaderTagTopic> { let entityName = "ReaderTagTopic" let predicate = NSPredicate(format: "following = YES AND showInMenu = YES") let fetchRequest = NSFetchRequest<ReaderTagTopic>(entityName: entityName) fetchRequest.predicate = predicate return fetchRequest } private func followedInterests() -> [ReaderTagTopic]? { let fetchRequest = followedInterestsFetchRequest() do { return try managedObjectContext.fetch(fetchRequest) } catch { DDLogError("Could not fetch followed interests: \(String(describing: error))") return nil } } }
gpl-2.0
petester42/PMCoreDataStack
Example/Tests/ExampleTests.swift
1
916
// // ExampleTests.swift // ExampleTests // // Created by Pierre-Marc Airoldi on 2014-12-30. // Copyright (c) 2014 Pete App Designs. All rights reserved. // import UIKit import XCTest class ExampleTests: 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
bmichotte/HSTracker
HSTracker/UIs/Preferences/OpponentTrackersPreferences.swift
1
4967
// // TrackersPreferences.swift // HSTracker // // Created by Benjamin Michotte on 29/02/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import MASPreferences class OpponentTrackersPreferences: NSViewController { @IBOutlet weak var showOpponentTracker: NSButton! @IBOutlet weak var showCardHuds: NSButton! @IBOutlet weak var clearTrackersOnGameEnd: NSButton! @IBOutlet weak var showOpponentCardCount: NSButton! @IBOutlet weak var showOpponentDrawChance: NSButton! @IBOutlet weak var showCthunCounter: NSButton! @IBOutlet weak var showSpellCounter: NSButton! @IBOutlet weak var includeCreated: NSButton! @IBOutlet weak var showDeathrattleCounter: NSButton! @IBOutlet weak var showPlayerClass: NSButton! @IBOutlet weak var showBoardDamage: NSButton! @IBOutlet weak var showGraveyard: NSButton! @IBOutlet weak var showGraveyardDetails: NSButton! @IBOutlet weak var showJadeCounter: NSButton! override func viewDidLoad() { super.viewDidLoad() showOpponentTracker.state = Settings.showOpponentTracker ? NSOnState : NSOffState showCardHuds.state = Settings.showCardHuds ? NSOnState : NSOffState clearTrackersOnGameEnd.state = Settings.clearTrackersOnGameEnd ? NSOnState : NSOffState showOpponentCardCount.state = Settings.showOpponentCardCount ? NSOnState : NSOffState showOpponentDrawChance.state = Settings.showOpponentDrawChance ? NSOnState : NSOffState showCthunCounter.state = Settings.showOpponentCthun ? NSOnState : NSOffState showSpellCounter.state = Settings.showOpponentSpell ? NSOnState : NSOffState includeCreated.state = Settings.showOpponentCreated ? NSOnState : NSOffState showDeathrattleCounter.state = Settings.showOpponentDeathrattle ? NSOnState : NSOffState showPlayerClass.state = Settings.showOpponentClassInTracker ? NSOnState : NSOffState showBoardDamage.state = Settings.opponentBoardDamage ? NSOnState : NSOffState showGraveyard.state = Settings.showOpponentGraveyard ? NSOnState : NSOffState showGraveyardDetails.state = Settings.showOpponentGraveyardDetails ? NSOnState : NSOffState showGraveyardDetails.isEnabled = showGraveyard.state == NSOnState showJadeCounter.state = Settings.showOpponentJadeCounter ? NSOnState : NSOffState } @IBAction func checkboxClicked(_ sender: NSButton) { if sender == showOpponentTracker { Settings.showOpponentTracker = showOpponentTracker.state == NSOnState } else if sender == showCardHuds { Settings.showCardHuds = showCardHuds.state == NSOnState } else if sender == clearTrackersOnGameEnd { Settings.clearTrackersOnGameEnd = clearTrackersOnGameEnd.state == NSOnState } else if sender == showOpponentCardCount { Settings.showOpponentCardCount = showOpponentCardCount.state == NSOnState } else if sender == showOpponentDrawChance { Settings.showOpponentDrawChance = showOpponentDrawChance.state == NSOnState } else if sender == showCthunCounter { Settings.showOpponentCthun = showCthunCounter.state == NSOnState } else if sender == showSpellCounter { Settings.showOpponentSpell = showSpellCounter.state == NSOnState } else if sender == includeCreated { Settings.showOpponentCreated = includeCreated.state == NSOnState } else if sender == showDeathrattleCounter { Settings.showOpponentDeathrattle = showDeathrattleCounter.state == NSOnState } else if sender == showPlayerClass { Settings.showOpponentClassInTracker = showPlayerClass.state == NSOnState } else if sender == showBoardDamage { Settings.opponentBoardDamage = showBoardDamage.state == NSOnState } else if sender == showGraveyard { Settings.showOpponentGraveyard = showGraveyard.state == NSOnState if showGraveyard.state == NSOnState { showGraveyardDetails.isEnabled = true } else { showGraveyardDetails.isEnabled = false } } else if sender == showGraveyardDetails { Settings.showOpponentGraveyardDetails = showGraveyardDetails.state == NSOnState } else if sender == showJadeCounter { Settings.showOpponentJadeCounter = showJadeCounter.state == NSOnState } } } // MARK: - MASPreferencesViewController extension OpponentTrackersPreferences: MASPreferencesViewController { override var identifier: String? { get { return "opponent_trackers" } set { super.identifier = newValue } } var toolbarItemImage: NSImage? { return NSImage(named: NSImageNameAdvanced) } var toolbarItemLabel: String? { return NSLocalizedString("Opponent tracker", comment: "") } }
mit
daisysomus/swift-algorithm-club
Radix Sort/radixSort.swift
1
1049
/* Sorting Algorithm that sorts an input array of integers digit by digit. */ // NOTE: This implementation does not handle negative numbers func radixSort(_ array: inout [Int] ) { let radix = 10 //Here we define our radix to be 10 var done = false var index: Int var digit = 1 //Which digit are we on? while !done { //While our sorting is not completed done = true //Assume it is done for now var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets for _ in 1...radix { buckets.append([]) } for number in array { index = number / digit //Which bucket will we access? buckets[index % radix].append(number) if done && index > 0 { //If we arent done, continue to finish, otherwise we are done done = false } } var i = 0 for j in 0..<radix { let bucket = buckets[j] for number in bucket { array[i] = number i += 1 } } digit *= radix //Move to the next digit } }
mit
finder39/Swimgur
Swimgur/Controllers/ImgurLoginController.swift
1
5567
// // ImgurLoginController.swift // Swimgur // // Created by Joseph Neuman on 8/5/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import UIKit import SWNetworking // Type of authentication public enum ImgurLoginAuthType:String { case ImgurLoginAuthTypeToken = "token" case ImgurLoginAuthTypePin = "pin" case ImgurLoginAuthTypeCode = "code" } class ImgurLoginController : NSObject, UIWebViewDelegate { var authorizationClosure:SWBoolBlock? var authType:ImgurLoginAuthType = .ImgurLoginAuthTypeCode var imgurLoginViewController:UIViewController = UIViewController() var webView:UIWebView = UIWebView() override init() { webView.frame = imgurLoginViewController.view.frame imgurLoginViewController.view.addSubview(webView) } func authorizeWithViewController(viewController:UIViewController, completionBlock:SWBoolBlock) { authorizationClosure = completionBlock // https://api.imgur.com/oauth2/authorize?client_id=541fb8cc243d820&response_type=code&state=auth let urlString = "\(SWNetworking.sharedInstance.restConfig.serviceAuthorizeEndpoint)/\(SWNetworking.sharedInstance.restConfig.authorizeURI)?client_id=\(Constants.ImgurControllerConfigClientID)&response_type=\(authType.rawValue)&state=auth" webView.delegate = self webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!)) if viewController.view.window != nil { viewController.presentViewController(imgurLoginViewController, animated: true, completion: nil) } } // TODO: verifyStoredAccountWithCompletionBlock func verifyStoredAccount(#onCompletion:SWBoolBlock) { self.authorizationClosure = onCompletion var token:Token? = SIUserDefaults().token //if code == "" { code = nil } if let token = token { self.getTokensFromRefresh(token) } else { onCompletion(success: false) } } private func authorizationSucceeded(success:Bool) { // remove webview from view controller //webView.removeFromSuperview() //webView = UIWebView() // reinitiate // fire completion block if let authorizationClosureUnwrapped = authorizationClosure { authorizationClosureUnwrapped(success: success) authorizationClosure = nil; } } private func parseQuery(string:String) -> Dictionary<String, String> { let components:[String] = string.componentsSeparatedByString("&") var recievedDict:Dictionary<String, String> = Dictionary() for component in components { let parts = component.componentsSeparatedByString("=") if parts.count == 2 { recievedDict[parts[0]] = parts[1] } } return recievedDict } private func getTokensFromCode(code:String) { var form = CodeForm() form.code = code form.clientID = Constants.ImgurControllerConfigClientID form.clientSecret = Constants.ImgurControllerConfigSecret form.grantType = "authorization_code" SWNetworking.sharedInstance.getTokensWithForm(form, onCompletion: { (token) -> () in self.getAccount() }) { (error, description) -> () in self.authorizationSucceeded(false) } } private func getTokensFromRefresh(token:Token) { var form = RefreshTokenForm() form.refreshToken = token.refreshToken form.clientID = Constants.ImgurControllerConfigClientID form.clientSecret = Constants.ImgurControllerConfigSecret form.grantType = "refresh_token" SWNetworking.sharedInstance.getTokensWithForm(form, onCompletion: { (token) -> () in self.getAccount() }) { (error, description) -> () in self.authorizationSucceeded(false) } } private func getAccount() { SWNetworking.sharedInstance.getAccountWithCompletion({ (account) -> () in SIUserDefaults().account = account self.authorizationSucceeded(true) /*if account != nil { //println("Retrieved account information: \(account.description)") SIUserDefaults().username = account.username // TODO: store the whole account self.authorizationSucceeded(true) } else { self.authorizationSucceeded(false) }*/ }, onError: { (error, description) -> () in println("Failed to retrieve account information") self.authorizationSucceeded(false) }) } private func webView(webView:UIWebView, didAuthenticateWithRedirectURLString redirectURLString:String) { let responseDictionary = parseQuery(redirectURLString) let code = responseDictionary["code"] SIUserDefaults().code = code self.getTokensFromCode(code!) // TODO: check it can explicitly unwrap } // MARK: UIWebViewDelegate func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool { // Once user logs in we will get their goodies in the ridirect URL. Example: // https://imgur.com/?state=auth&code=860381d0651a8c24079aa13c8732567d8a3f7bab let redirectedURLString = request.URL.absoluteString!.URLDecodedString() // explicit unwrap new for beta 6 if redirectedURLString.rangeOfString("code=")?.startIndex != nil { self.webView(webView, didAuthenticateWithRedirectURLString: redirectedURLString) webView.stopLoading() imgurLoginViewController.dismissViewControllerAnimated(true, completion: { () -> Void in }) } return true } func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) { // self.authorizationSucceeded(false) // causing failure of login } }
mit
OneBestWay/EasyCode
Swift/C4iOS/C4iOS/MenuRings.swift
1
244
// // MenuRings.swift // C4iOS // // Created by GK on 2017/2/7. // Copyright © 2017年 GK. All rights reserved. // import Foundation import UIKit class MenuRings { var thickRingFrames: [CGRect]! var thickRing: Circle }
mit
alessandro-martin/SimpleSideController
SimpleSideController/Source/SimpleSideController.swift
1
22594
// // SimpleSideController.swift // SimpleSideController // // Created by Alessandro Martin on 21/08/16. // Copyright © 2016 Alessandro Martin. All rights reserved. // import UIKit public protocol SimpleSideControllerDelegate: class { func sideController(_ sideController: SimpleSideController, willChangeTo state: SimpleSideController.Presenting) func sideController(_ sideController: SimpleSideController, didChangeTo state: SimpleSideController.Presenting) } public struct Border { let thickness: CGFloat let color: UIColor public init(thickness: CGFloat, color: UIColor){ self.thickness = thickness self.color = color } } public struct Shadow { let opacity: CGFloat let radius: CGFloat let width: CGFloat public init(opacity: CGFloat, radius: CGFloat, width: CGFloat) { self.opacity = opacity self.radius = radius self.width = width } } public class SimpleSideController: UIViewController { public enum Presenting { case front case side case transitioning } public enum Background { case opaque(color: UIColor, shadow: Shadow?) case translucent(style: UIBlurEffectStyle, color: UIColor) case vibrant(style: UIBlurEffectStyle, color: UIColor) } static let speedThreshold: CGFloat = 300.0 fileprivate let sideContainerView = UIView() fileprivate var sideContainerWidthConstraint: NSLayoutConstraint? fileprivate var sideContainerHorizontalConstraint: NSLayoutConstraint? fileprivate let borderView = UIView() fileprivate var borderWidthConstraint: NSLayoutConstraint? //MARK: Public properties public weak var delegate: SimpleSideControllerDelegate? public var state: Presenting { return self._state } public var border: Border? { didSet { self.borderView.backgroundColor = (border?.color) ?? .lightGray self.borderWidthConstraint?.constant = (border?.thickness) ?? 0.0 self.sideContainerView.layoutIfNeeded() } } //MARK: Private properties fileprivate(set) var _state: Presenting { willSet(newState) { self.performTransition(to: newState) self.delegate?.sideController(self, willChangeTo: newState) } didSet { switch self._state { case .front: self.disableTapGesture() self.frontController.view.isUserInteractionEnabled = true case .side: self.enablePanGesture() self.frontController.view.isUserInteractionEnabled = false default: break } } } fileprivate var shadow: Shadow? { didSet { if self._state == .side { self.sideContainerView.layer.shadowOpacity = Float((self.shadow?.opacity) ?? 0.3) self.sideContainerView.layer.shadowRadius = (self.shadow?.radius) ?? 5.0 self.sideContainerView.layer.shadowOffset = CGSize(width: ((self.shadow?.width) ?? 7.0) * (self.view.isRightToLeftLanguage() ? -1.0 : 1.0), height: 0.0) } } } fileprivate var background: Background { didSet { switch self.background { case let .opaque(color, shadow): self.sideContainerView.backgroundColor = color self.shadow = shadow case let .translucent(_, color), let .vibrant(_, color): self.sideContainerView.backgroundColor = color } } } fileprivate var frontController: UIViewController fileprivate var sideController: UIViewController fileprivate var panGestureRecognizer: UIPanGestureRecognizer? fileprivate var panPreviousLocation: CGPoint = .zero fileprivate var panPreviousVelocity: CGPoint = .zero fileprivate var tapGestureRecognizer: UITapGestureRecognizer? fileprivate var sideContainerWidth: CGFloat fileprivate var blurView: UIVisualEffectView? fileprivate var vibrancyView: UIVisualEffectView? fileprivate lazy var presentedSideHorizontalPosition: CGFloat = { let isRTL = self.view.isRightToLeftLanguage() return isRTL ? UIScreen.main.bounds.width : self.sideContainerWidth }() fileprivate lazy var initialSideHorizontalPosition: CGFloat = { let isRTL = self.view.isRightToLeftLanguage() return isRTL ? UIScreen.main.bounds.width + self.sideContainerWidth : 0.0 }() required public init(frontController: UIViewController, sideController: UIViewController, sideContainerWidth: CGFloat, background: Background) { self.frontController = frontController self.sideController = sideController self.sideContainerWidth = sideContainerWidth self.background = background self._state = .front super.init(nibName: nil, bundle: nil) } // Objective-C compatible init: public init(frontController: UIViewController, sideController: UIViewController, sideContainerWidth: CGFloat, backgroundColor: UIColor, blurEffectStyle: UIBlurEffectStyle) { self.frontController = frontController self.sideController = sideController self.sideContainerWidth = sideContainerWidth self.background = .translucent(style: blurEffectStyle, color: backgroundColor) self._state = .front super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() self.setup() } } //MARK: Public API extension SimpleSideController { public func showFrontController() { self._state = .front } public func showSideController() { self._state = .side } public func isPanGestureEnabled() -> Bool { return self.panGestureRecognizer?.isEnabled ?? false } public func disablePanGesture() { self.panGestureRecognizer?.isEnabled = false } public func enablePanGesture() { self.panGestureRecognizer?.isEnabled = true } public func isTapGestureEnabled() -> Bool { return self.tapGestureRecognizer?.isEnabled ?? false } public func disableTapGesture() { self.tapGestureRecognizer?.isEnabled = false } public func enableTapGesture() { self.tapGestureRecognizer?.isEnabled = true } @objc public func isSideControllerVisible() -> Bool { return self._state == .side } } //MARK: Gesture management extension SimpleSideController { @objc fileprivate func handleTapGesture(gr: UITapGestureRecognizer) { switch self._state { case .front: self._state = .side case .side: self._state = .front case .transitioning: break } } @objc fileprivate func handlePanGesture(gr: UIPanGestureRecognizer) { switch gr.state { case .began: if let opacity = self.shadow?.opacity, self._state == .front { self.sideContainerView.displayShadow(opacity: opacity) } self._state = .transitioning self.handlePanGestureBegan(with: gr) case .changed: self.handlePanGestureChanged(with: gr) default: self.handlePanGestureEnded(with: gr) } } private func handlePanGestureBegan(with recognizer: UIPanGestureRecognizer) { self.panPreviousLocation = recognizer.location(in: self.view) } private func handlePanGestureChanged(with recognizer: UIPanGestureRecognizer) { guard let constraint = self.sideContainerHorizontalConstraint else { return } let currentLocation = recognizer.location(in: self.view) self.panPreviousVelocity = recognizer.velocity(in: self.view) self.sideContainerHorizontalConstraint?.constant += currentLocation.x - self.panPreviousLocation.x self.sideContainerHorizontalConstraint?.constant = clamp(lowerBound: 0.0, value: constraint.constant, upperBound: self.sideContainerWidth) self.panPreviousLocation = currentLocation } private func handlePanGestureEnded(with recognizer: UIPanGestureRecognizer) { guard let constraint = self.sideContainerHorizontalConstraint else { return } let xSideLocation = constraint.constant let xSpeed = self.panPreviousVelocity.x if xSpeed > SimpleSideController.speedThreshold { self._state = .side } else if xSpeed < -SimpleSideController.speedThreshold { self._state = .front } else if xSideLocation > self.sideContainerWidth / 2.0 { self._state = .side } else { self._state = .front } self.panPreviousLocation = .zero self.panPreviousVelocity = .zero } } //MARK: Setup extension SimpleSideController { fileprivate func setup() { self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(gr:))) self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(gr:))) self.tapGestureRecognizer?.delegate = self self.view.addGestureRecognizer(self.panGestureRecognizer!) self.panGestureRecognizer?.maximumNumberOfTouches = 1 self.view.addGestureRecognizer(self.tapGestureRecognizer!) self.tapGestureRecognizer?.isEnabled = false self.addChildViewController(self.frontController) self.view.addSubview(self.frontController.view) self.frontController.view.frame = self.view.bounds self.frontController.didMove(toParentViewController: self) self.view.addSubview(self.sideContainerView) self.constrainSideContainerView() self.sideContainerView.addSubview(self.borderView) self.constrainBorderView() self.view.bringSubview(toFront: self.sideContainerView) self.sideContainerView.hideShadow(animation: 0.0) switch self.background { case let .translucent(style, color): self.sideContainerView.backgroundColor = color let blurEffect = UIBlurEffect(style: style) self.blurView = UIVisualEffectView(effect: blurEffect) self.sideContainerView.insertSubview(self.blurView!, at: 0) self.pinIntoSideContainer(view: self.blurView!) self.addChildViewController(self.sideController) self.blurView?.contentView.addSubview(self.sideController.view) self.pinIntoSuperView(view: self.sideController.view) self.sideController.didMove(toParentViewController: self) case let .vibrant(style, color): self.sideContainerView.backgroundColor = color let blurEffect = UIBlurEffect(style: style) self.blurView = UIVisualEffectView(effect: blurEffect) let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect) self.vibrancyView = UIVisualEffectView(effect: vibrancyEffect) self.sideContainerView.insertSubview(self.blurView!, at: 0) self.pinIntoSideContainer(view: self.blurView!) self.addChildViewController(self.sideController) self.blurView?.contentView.addSubview(self.vibrancyView!) self.pinIntoSuperView(view: self.vibrancyView!) self.vibrancyView?.contentView.addSubview(self.sideController.view) self.pinIntoSuperView(view: self.sideController.view) self.sideController.didMove(toParentViewController: self) case let .opaque(color, shadow): self.sideController.view.backgroundColor = color self.shadow = shadow self.addChildViewController(self.sideController) self.sideContainerView.addSubview(self.sideController.view) self.pinIntoSideContainer(view: self.sideController.view) self.sideController.didMove(toParentViewController: self) } } } extension SimpleSideController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return gestureRecognizer == self.tapGestureRecognizer && !self.sideContainerView.frame.contains(touch.location(in: self.view)) } } //MARK: Utilities extension SimpleSideController { fileprivate func performTransition(to state: Presenting) { switch state { case .front: self.view.layoutIfNeeded() self.sideContainerHorizontalConstraint?.constant = self.initialSideHorizontalPosition self.tapGestureRecognizer?.isEnabled = false self.sideContainerView.hideShadow() UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseIn, animations: { self.view.layoutIfNeeded() }) { finished in if finished { self.delegate?.sideController(self, didChangeTo: state) } } case .side: self.view.layoutIfNeeded() self.sideContainerHorizontalConstraint?.constant = self.presentedSideHorizontalPosition self.tapGestureRecognizer?.isEnabled = true if let opacity = self.shadow?.opacity { self.sideContainerView.displayShadow(opacity: opacity) } UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseOut, animations: { self.view.layoutIfNeeded() }) { finished in if finished { self.delegate?.sideController(self, didChangeTo: state) } } case .transitioning: break } } fileprivate func pinIntoSideContainer(view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false let top = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self.sideContainerView, attribute: .top, multiplier: 1.0, constant: 0.0) let bottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: self.sideContainerView, attribute: .bottom, multiplier: 1.0, constant: 0.0) let leading = NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: self.sideContainerView, attribute: .leading, multiplier: 1.0, constant: 0.0) let trailing = NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: self.borderView, attribute: .leading, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([top, bottom, leading, trailing]) } fileprivate func pinIntoSuperView(view : UIView) { guard let superView = view.superview else { fatalError("\(view) does not have a superView!") } view.translatesAutoresizingMaskIntoConstraints = false let top = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1.0, constant: 0.0) let bottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1.0, constant: 0.0) let leading = NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: superView, attribute: .leading, multiplier: 1.0, constant: 0.0) let trailing = NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: superView, attribute: .trailing, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([top, bottom, leading, trailing]) } fileprivate func constrainSideContainerView() { self.sideContainerView.translatesAutoresizingMaskIntoConstraints = false let height = NSLayoutConstraint(item: self.sideContainerView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0.0) let centerY = NSLayoutConstraint(item: self.sideContainerView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0) self.sideContainerWidthConstraint = NSLayoutConstraint(item: self.sideContainerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: self.sideContainerWidth) self.sideContainerHorizontalConstraint = NSLayoutConstraint(item: self.sideContainerView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: self.initialSideHorizontalPosition) NSLayoutConstraint.activate([height, centerY, self.sideContainerWidthConstraint!, self.sideContainerHorizontalConstraint!]) } fileprivate func constrainBorderView() { self.borderView.translatesAutoresizingMaskIntoConstraints = false let top = NSLayoutConstraint(item: self.borderView, attribute: .top, relatedBy: .equal, toItem: self.sideContainerView, attribute: .top, multiplier: 1.0, constant: 0.0) let bottom = NSLayoutConstraint(item: self.borderView, attribute: .bottom, relatedBy: .equal, toItem: self.sideContainerView, attribute: .bottom, multiplier: 1.0, constant: 0.0) self.borderWidthConstraint = NSLayoutConstraint(item: self.borderView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: self.border?.thickness ?? 0.0) let side = NSLayoutConstraint(item: self.borderView, attribute: .trailing, relatedBy: .equal, toItem: self.sideContainerView, attribute: .trailing, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([top, bottom, self.borderWidthConstraint!, side]) } }
mit
qiuncheng/for-graduation
SpeechRecognition/Vendor/RxGesture/iOS/UIScreenEdgePanGestureRecognizer+RxGesture.swift
2
3706
// Copyright (c) RxSwiftCommunity // 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 RxSwift import RxCocoa /// Default values for `UIScreenEdgePanGestureRecognizer` configuration private enum Defaults { static var configuration: ((UIScreenEdgePanGestureRecognizer) -> Void)? = nil } /// A `GestureRecognizerFactory` for `UIScreenEdgePanGestureRecognizer` public struct ScreenEdgePanGestureRecognizerFactory: GestureRecognizerFactory { public typealias Gesture = UIScreenEdgePanGestureRecognizer public let configuration: (UIScreenEdgePanGestureRecognizer) -> Void /** Initialiaze a `GestureRecognizerFactory` for `UIScreenEdgePanGestureRecognizer` - parameter edges: The edges on which this gesture recognizes, relative to the current interface orientation - parameter configuration: A closure that allows to fully configure the gesture recognizer */ public init( edges: UIRectEdge, configuration: ((UIScreenEdgePanGestureRecognizer) -> Void)? = Defaults.configuration ){ self.configuration = { gestureRecognizer in gestureRecognizer.edges = edges configuration?(gestureRecognizer) } } } extension AnyGestureRecognizerFactory { /** Returns an `AnyGestureRecognizerFactory` for `UIScreenEdgePanGestureRecognizer` - parameter edges: The edges on which this gesture recognizes, relative to the current interface orientation - parameter configuration: A closure that allows to fully configure the gesture recognizer */ public static func screenEdgePan( edges: UIRectEdge, configuration: ((UIScreenEdgePanGestureRecognizer) -> Void)? = Defaults.configuration ) -> AnyGestureRecognizerFactory { let gesture = ScreenEdgePanGestureRecognizerFactory( edges: edges, configuration: configuration ) return AnyGestureRecognizerFactory(gesture) } } public extension Reactive where Base: UIView { /** Returns an observable `UIScreenEdgePanGestureRecognizer` events sequence - parameter edges: The edges on which this gesture recognizes, relative to the current interface orientation - parameter configuration: A closure that allows to fully configure the gesture recognizer */ public func screenEdgePanGesture( edges: UIRectEdge, configuration: ((UIScreenEdgePanGestureRecognizer) -> Void)? = Defaults.configuration ) -> ControlEvent<UIScreenEdgePanGestureRecognizer> { return gesture(ScreenEdgePanGestureRecognizerFactory( edges: edges, configuration: configuration )) } }
apache-2.0
rnine/AMCoreAudio
Tests/SimplyCoreAudioTests/SimplyCoreAudioTests.swift
1
312
// // SimplyCoreAudioTests.swift // SimplyCoreAudio // // Created by Ruben Nine on 20/3/21. // Copyright © 2021 9Labs. All rights reserved. // import XCTest @testable import SimplyCoreAudio class SimplyCoreAudioTests: XCTestCase { func testInitializer() throws { _ = SimplyCoreAudio() } }
mit
orta/apous
samples/cocoapods/main.swift
2
63
import Argo import Runes print("dependencies import properly")
mit
kirakik/EZSwiftExtensions
EZSwiftExtensionsTests/UIAlertControllerTests.swift
4
232
// // UIAlertControllerTests.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 8/25/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest class UIAlertControllerTests: XCTestCase { }
mit
kcome/SwiftIB
HistoryDataDump/main.swift
1
7884
// // main.swift // HistoryDataDump // // Created by Harry Li on 10/01/2015. // Copyright (c) 2014-2019 Hanfei Li. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import SwiftIB // constants let EXT = "history_raw" let HEADER_LEN = 19 var conf = HDDConfig(arg_array: CommandLine.arguments) var tickers = conf.tickers var fman = FileManager.default var wrapper = HistoryDataWrapper() var client = EClientSocket(p_eWrapper: wrapper, p_anyWrapper: wrapper) func getLastestDate(filename: String) -> Int64 { let fcontent = try! NSString(contentsOfFile: filename, encoding: String.Encoding.utf8.rawValue) var count = 0 fcontent.enumerateLines({ (line: String!, p: UnsafeMutablePointer<ObjCBool>) -> Void in count += 1 }) var ret: Int64 = -1 fcontent.enumerateLines({ (line: String!, p: UnsafeMutablePointer<ObjCBool>) -> Void in count -= 1 if count == 0 { let datestr = (line as NSString).substring(with: NSRange(location: 0, length: HEADER_LEN)) ret = HDDUtil.fastStrToTS(timestamp: datestr, tz_name: wrapper.timezone) } }) return ret } func downloadHistoryData(filename: String, ticker: String, requestId: Int, append: Bool = false, secType: String = "STK", currency: String = "USD", multiplier: String = "", expire: String = "", exchange: String = "SMART", pexchange: String = "ISLAND") { var loc = ticker var wts = "TRADES" if exchange == "IDEALPRO" { loc = "\(ticker).\(currency)" wts = "BID_ASK" } if (conf.sleepInterval < 20.0) && (wts == "BID_ASK") { conf.sleepInterval = 20.0 } let con = Contract(p_conId: 0, p_symbol: ticker, p_secType: secType, p_expiry: expire, p_strike: 0.0, p_right: "", p_multiplier: multiplier, p_exchange: exchange, p_currency: currency, p_localSymbol: loc, p_tradingClass: "", p_comboLegs: nil, p_primaryExch: pexchange, p_includeExpired: false, p_secIdType: "", p_secId: "") var lf: FileHandle? if append { let next = getLastestDate(filename: filename) if next != -1 { wrapper.currentStart = next } if wrapper.currentStart <= wrapper.sinceTS { print("\t[\(ticker)] fully downloaded. Skip.") return } print("\tAppending \(filename), starting date [\(HDDUtil.tsToStr(timestamp: wrapper.currentStart, api: false, tz_name: wrapper.timezone))]") lf = FileHandle(forUpdatingAtPath: filename) if lf != nil { lf?.seekToEndOfFile() } } else { fman.createFile(atPath: filename, contents: nil, attributes: nil) lf = FileHandle(forWritingAtPath: filename) } wrapper.currentTicker = ticker while wrapper.currentStart > wrapper.sinceTS { let begin = NSDate().timeIntervalSinceReferenceDate let localStart = wrapper.currentStart wrapper.currentStart = -1 wrapper.contents.removeAll(keepingCapacity: true) wrapper.reqComplete = false wrapper.broken = false let sdt = conf.sinceDatetime.components(separatedBy: " ")[0] if HDDUtil.equalsDaystart(timestamp: localStart, tz_name: wrapper.timezone, daystart: conf.dayStart, datestart: sdt) { print("(reaching day start \(conf.dayStart), continue next)") break } let ut = HDDUtil.tsToStr(timestamp: localStart, api: true, tz_name: wrapper.timezone) client.reqHistoricalData(requestId, contract: con, endDateTime: "\(ut) \(wrapper.timezone)", durationStr: conf.duration, barSizeSetting: conf.barsize, whatToShow: wts, useRTH: conf.rth, formatDate: 2, chartOptions: nil) print("request (\(conf.duration)) (\(conf.barsize)) bars, until \(ut) \(wrapper.timezone)") while (wrapper.reqComplete == false) && (wrapper.broken == false) && (wrapper.extraSleep <= 0.0) { Thread.sleep(forTimeInterval: TimeInterval(0.05)) } if wrapper.broken { Thread.sleep(forTimeInterval: TimeInterval(2.0)) wrapper.currentStart = localStart client = EClientSocket(p_eWrapper: wrapper, p_anyWrapper: wrapper) client.eConnect(conf.host, p_port: conf.port) wrapper.closing = false continue } if let file = lf { for c in wrapper.contents { file.write(c.data(using: String.Encoding.utf8, allowLossyConversion: true)!) } file.synchronizeFile() } print("(sleep for \(conf.sleepInterval + wrapper.extraSleep) secs)...") Thread.sleep(until: NSDate(timeIntervalSinceReferenceDate: begin + conf.sleepInterval + wrapper.extraSleep) as Date) if wrapper.extraSleep > 0 { wrapper.currentStart = localStart wrapper.extraSleep = 0 } } if lf != nil { lf?.closeFile() } } conf.printConf() print("Connecting to IB API...") client.eConnect(conf.host, port: Int(conf.port), clientId: conf.clientID) wrapper.closing = false for i in 0 ..< tickers.count { var ticker = tickers[i] var ex = conf.exchange var pex = conf.primaryEx let cmp = tickers[i].components(separatedBy: ",") var ins = "STK" var currency = "USD" var multiplier = "" var expire = "" if cmp.count >= 5 { ticker = cmp[0] currency = cmp[1] ins = cmp[2] ex = cmp[3] pex = cmp[4] if cmp.count >= 7 { multiplier = cmp[5] expire = cmp[6] } } wrapper.timezone = "America/New_York" wrapper.sinceTS = HDDUtil.strToTS(timestamp: conf.sinceDatetime, api: true, tz_name: wrapper.timezone) wrapper.currentStart = HDDUtil.strToTS(timestamp: conf.untilDatetime, api: true, tz_name: wrapper.timezone) var lticker = ticker if ins == "CASH" { lticker = "\(ticker).\(currency)" } let fn = conf.outputDir.appending("[\(lticker)][\(ex)-\(pex)][\(conf.sinceDatetime)]-[\(conf.untilDatetime)][\(conf.barsize)].\(EXT)") let fname = conf.normal_filename ? fn.replacingOccurrences(of: ":", with: "") : fn if fman.fileExists(atPath: fname) { if conf.append { downloadHistoryData(filename: fname, ticker: ticker, requestId: i, append: true, secType: ins, currency: currency, multiplier: multiplier, expire: expire, exchange: ex, pexchange: pex) continue } else { print("Skip \(ticker) : File exists") continue } } else { downloadHistoryData(filename: fname, ticker: ticker, requestId: i, secType: ins, currency: currency, multiplier: multiplier, expire: expire, exchange: ex, pexchange: pex) } } Thread.sleep(forTimeInterval: TimeInterval(3.0)) wrapper.closing = true client.eDisconnect() client.close()
mit
fluidsonic/JetPack
Sources/UI/TextInputView.swift
1
6134
import UIKit open class TextInputView: View { public typealias Delegate = _TextInputViewDelegate private var lastLayoutedSize = CGSize.zero private var lastMeasuredNativeHeight = CGFloat(0) private let nativeView = NativeView() private var placeholderView: Label? public weak var delegate: Delegate? public override init() { super.init() setUp() } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open var attributedText: NSAttributedString { get { return nativeView.attributedText ?? NSAttributedString() } set { nativeView.attributedText = newValue } } @discardableResult open override func becomeFirstResponder() -> Bool { return nativeView.becomeFirstResponder() } private func checkIntrinsicContentSize() { let measuredNativeHeight = nativeView.heightThatFitsWidth(nativeView.bounds.width) guard measuredNativeHeight != lastMeasuredNativeHeight else { return } lastMeasuredNativeHeight = measuredNativeHeight invalidateIntrinsicContentSize() } @discardableResult open override func endEditing(_ force: Bool) -> Bool { return nativeView.endEditing(force) } open var font: UIFont { get { return nativeView.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize) } set { nativeView.font = newValue placeholderView?.font = newValue } } open var isScrollEnabled: Bool { get { return nativeView.isScrollEnabled } set { nativeView.isScrollEnabled = newValue } } open override func layoutSubviews() { super.layoutSubviews() let bounds = self.bounds nativeView.frame = CGRect(size: bounds.size) placeholderView?.frame = CGRect(size: bounds.size) if bounds.size != lastLayoutedSize { lastLayoutedSize = bounds.size lastMeasuredNativeHeight = nativeView.heightThatFitsWidth(nativeView.bounds.width) } } open override func measureOptimalSize(forAvailableSize availableSize: CGSize) -> CGSize { return nativeView.sizeThatFitsSize(availableSize) } fileprivate func nativeViewDidChange() { updatePlaceholderView() checkIntrinsicContentSize() delegate?.textInputViewDidChange(self) } fileprivate func nativeViewDidEndEditing() { checkIntrinsicContentSize() } open var padding: UIEdgeInsets { get { return nativeView.textContainerInset } set { nativeView.textContainerInset = newValue } } open var placeholder = "" { didSet { guard placeholder != oldValue else { return } updatePlaceholderView() } } open var placeholderTextColor = UIColor(rgb: 0xC7C7CD) { didSet { placeholderView?.textColor = placeholderTextColor } } @discardableResult open override func resignFirstResponder() -> Bool { return nativeView.resignFirstResponder() } private func setUp() { setUpNativeView() } private func setUpNativeView() { let child = nativeView child.backgroundColor = nil child.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) child.parent = self child.textContainer.lineFragmentPadding = 0 addSubview(child) } private func setUpPlaceholderView() -> Label { if let child = placeholderView { return child } let child = Label() child.font = font child.maximumNumberOfLines = nil child.padding = padding child.textColor = placeholderTextColor placeholderView = child addSubview(child) return child } open override func subviewDidInvalidateIntrinsicContentSize(_ view: UIView) { super.subviewDidInvalidateIntrinsicContentSize(view) guard view !== nativeView else { return // FIXME only text editing } setNeedsLayout() if !isScrollEnabled { invalidateIntrinsicContentSize() } } open var text: String { get { return nativeView.text ?? "" } set { nativeView.text = newValue } } open var textColor: UIColor { get { return nativeView.textColor ?? UIColor.darkText } set { nativeView.textColor = newValue } } open var typingAttributes: [NSAttributedString.Key : Any] { get { return nativeView.typingAttributes } set { nativeView.typingAttributes = newValue } } private func updatePlaceholderView() { if placeholder.isEmpty || !text.isEmpty { placeholderView?.removeFromSuperview() placeholderView = nil } else { let placeholderView = setUpPlaceholderView() placeholderView.text = placeholder } } } public protocol _TextInputViewDelegate: class { func textInputViewDidChange (_ inputView: TextInputView) } private final class NativeView: UITextView { weak var parent: TextInputView? init() { super.init(frame: .zero, textContainer: nil) delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var attributedText: NSAttributedString? { get { return super.attributedText } set { guard newValue != attributedText else { return } super.attributedText = textIncludingDefaultAttributes(for: newValue ?? NSAttributedString()) } } private func textIncludingDefaultAttributes(for attributedText: NSAttributedString) -> NSAttributedString { let defaultAttributes: [NSAttributedString.Key : Any] = [ .font: font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize), .foregroundColor: textColor ?? .darkText ] let textIncludingDefaultAttributes = NSMutableAttributedString(string: attributedText.string, attributes: defaultAttributes) textIncludingDefaultAttributes.beginEditing() attributedText.enumerateAttributes(in: NSRange(forString: attributedText.string), options: [.longestEffectiveRangeNotRequired]) { attributes, range, _ in textIncludingDefaultAttributes.addAttributes(attributes, range: range) } textIncludingDefaultAttributes.endEditing() return textIncludingDefaultAttributes } override var text: String? { get { return super.text } set { attributedText = newValue.map(NSAttributedString.init(string:)) } } } extension NativeView: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { parent?.nativeViewDidChange() } func textViewDidEndEditing(_ textView: UITextView) { parent?.nativeViewDidEndEditing() } }
mit
lkzhao/Hero
LegacyExamples/LegacyExampleViewController.swift
1
2211
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.com> // // 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 UIKit import Hero class LegacyExampleViewController: UITableViewController { var storyboards: [[String]] = [ [], ["Basic", "Navigation", "MusicPlayer", "Menu", "BuiltInTransitions"], ["CityGuide", "ImageViewer", "VideoPlayer"], ["AppleHomePage", "ListToGrid", "ImageGallery"] ] override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomLayoutGuide.length, right: 0) tableView.scrollIndicatorInsets = tableView.contentInset } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.item < storyboards[indexPath.section].count { let storyboardName = storyboards[indexPath.section][indexPath.item] let vc = viewController(forStoryboardName: storyboardName) // iOS bug: https://github.com/lkzhao/Hero/issues/106 https://github.com/lkzhao/Hero/issues/79 DispatchQueue.main.async { self.present(vc, animated: true, completion: nil) } } } }
mit
satorun/designPattern
Singleton/Singleton/ViewController.swift
1
843
// // ViewController.swift // Singleton // // Created by satorun on 2016/01/30. // Copyright © 2016年 satorun. 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. print("Start.") let obj1 = Singleton.getInstance() let obj2 = Singleton.getInstance() if obj1 === obj2 { print("obj1とobj2は同じインスタンスです。") } else { print("obj1とobj2は同じインスタンスではありません。") } print("End.") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
pyngit/SegueAnimationSample
SegueAnimationSample/AppDelegate.swift
1
2100
// // AppDelegate.swift // SegueAnimationSample // // Created by pyngit on 2015/11/30. // // 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
mogol/centrifugo-ios
CentrifugeiOS/Classes/Centrifuge.swift
2
1210
// // Centrifugal.swift // Pods // // Created by German Saprykin on 18/04/16. // // import Foundation import CentrifugeiOS.CommonCryptoBridge public let CentrifugeErrorDomain = "com.Centrifuge.error.domain" public let CentrifugeWebSocketErrorDomain = "com.Centrifuge.error.domain.websocket" public let CentrifugeErrorMessageKey = "com.Centrifuge.error.messagekey" public let CentrifugePrivateChannelPrefix = "$" public enum CentrifugeErrorCode: Int { case CentrifugeMessageWithError } public typealias CentrifugeMessageHandler = (CentrifugeServerMessage?, Error?) -> Void public class Centrifuge { public class func client(url: String, creds: CentrifugeCredentials, delegate: CentrifugeClientDelegate) -> CentrifugeClient { let client = CentrifugeClientImpl() client.builder = CentrifugeClientMessageBuilderImpl() client.parser = CentrifugeServerMessageParserImpl() client.creds = creds client.url = url client.delegate = delegate return client } public class func createToken(string: String, key: String) -> String { return CentrifugeCommonCryptoBridge.hexHMACSHA256(forData: string, withKey: key) } }
mit
mohamede1945/quran-ios
Quran/SearchViewController.swift
1
1039
// // SearchViewController.swift // Quran // // Created by Mohamed Afifi on 4/19/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UIKit class SearchViewController: UIViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.secondaryColor() title = navigationController?.tabBarItem.title } }
gpl-3.0
steve-holmes/music-app-2
MusicApp/Modules/Playlist/PlaylistDetailItem.swift
1
219
// // PlaylistDetailItem.swift // MusicApp // // Created by Hưng Đỗ on 6/19/17. // Copyright © 2017 HungDo. All rights reserved. // enum PlaylistDetailItem { case song(Song) case playlist(Playlist) }
mit
doronkatz/firefox-ios
Client/Frontend/Home/ReaderPanel.swift
2
22492
/* 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 UIKit import SnapKit import Storage import ReadingList import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44) static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035) static let DeleteButtonTitleColor = UIColor.white static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1) static let MarkAsReadButtonTitleColor = UIColor.white static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenHeaderTextColor = UIColor.darkGray static let WelcomeScreenItemTextColor = UIColor.gray static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: UITableViewCell { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url: URL = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor updateAccessibilityLabel() } } let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = UIEdgeInsets.zero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = UIViewContentMode.scaleAspectFit readStatusImageView.snp.makeConstraints { (make) -> Void in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.centerY.equalTo(self.contentView) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) contentView.addSubview(hostnameLabel) titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor titleLabel.numberOfLines = 2 titleLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000) } hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor hostnameLabel.numberOfLines = 1 hostnameLabel.snp.makeConstraints { (make) -> Void in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.leading.trailing.equalTo(self.titleLabel) } setupDynamicFonts() } func setupDynamicFonts() { titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } override func prepareForReuse() { super.prepareForReuse() setupDynamicFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return hostname.substring(from: hostname.characters.index(hostname.startIndex, offsetBy: prefix.characters.count)) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? var profile: Profile! fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(ReadingListPanel.longPress(_:))) }() fileprivate lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() fileprivate var records: [ReadingListClientRecord]? init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationDynamicFontChanged, object: nil) } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "ReadingTable" tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorColor = UIConstants.SeparatorColor tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() view.backgroundColor = UIConstants.PanelBackgroundColor if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue // If no records have been added yet, we display the empty state if records?.count == 0 { tableView.isScrollEnabled = false view.addSubview(emptyStateOverlayView) } } } deinit { NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { context in self.presentedViewController?.dismiss(animated: true, completion: nil) }, completion: nil) } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged: refreshReadingList() break case NotificationDynamicFontChanged: if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverview() refreshReadingList() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue if records?.count == 0 { tableView.isScrollEnabled = false if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) } } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true emptyStateOverlayView.removeFromSuperview() } } self.tableView.reloadData() } } fileprivate func createEmptyStateOverview() -> UIView { let overlayView = UIScrollView(frame: tableView.bounds) overlayView.backgroundColor = UIColor.white // Unknown why this does not work with autolayout overlayView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] let containerView = UIView() overlayView.addSubview(containerView) let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel")) containerView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).priority(1000) // Sets proper top constraint for iPhone 6 in portait and iPads. make.centerY.equalTo(overlayView.snp.centerY).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView.snp.top).offset(50).priority(1000) } let welcomeLabel = UILabel() containerView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = NSTextAlignment.center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) make.top.equalTo(logoImageView.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) // Sets proper center constraint for iPhones in landscape. make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).offset(-40).priority(1000) } let readerModeLabel = UILabel() containerView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readerModeLabel.numberOfLines = 0 readerModeLabel.snp.makeConstraints { make in make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) containerView.addSubview(readerModeImageView) readerModeImageView.snp.makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } let readingListLabel = UILabel() containerView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readingListLabel.numberOfLines = 0 readingListLabel.snp.makeConstraints { make in make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) make.bottom.equalTo(overlayView).offset(-20) // making AutoLayout compute the overlayView's contentSize } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) containerView.addSubview(readingListImageView) readingListImageView.snp.makeConstraints { make in make.centerY.equalTo(readingListLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(logoImageView.snp.top) make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset) make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(overlayView) } return overlayView } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let record = records?[indexPath.row] else { return [] } let delete = UITableViewRowAction(style: .normal, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in self?.deleteItem(atIndex: index) } delete.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in self?.toggleItem(atIndex: index) } unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor return [unreadToggle, delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList?.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.deleteRecord(record), result.isSuccess { records?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) // reshow empty state if no records left if records?.count == 0 { view.addSubview(emptyStateOverlayView) } } } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.updateRecord(record, unread: !record.unread), result.isSuccess { // TODO This is a bit odd because the success value of the update is an optional optional Record if let successValue = result.successValue, let updatedRecord = successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } } } } extension ReadingListPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let record = records?[indexPath.row] else { return nil } return Site(url: record.url, title: record.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? { guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil } let removeAction: ActionOverlayTableViewAction = ActionOverlayTableViewAction(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.deleteItem(atIndex: indexPath) }) actions.append(removeAction) return actions } }
mpl-2.0
shajrawi/swift
test/Constraints/operator.swift
2
4960
// RUN: %target-typecheck-verify-swift // Test constraint simplification of chains of binary operators. // <https://bugs.swift.org/browse/SR-1122> do { let a: String? = "a" let b: String? = "b" let c: String? = "c" let _: String? = a! + b! + c! let x: Double = 1 _ = x + x + x let sr3483: Double? = 1 _ = sr3483! + sr3483! + sr3483! let sr2636: [String: Double] = ["pizza": 10.99, "ice cream": 4.99, "salad": 7.99] _ = sr2636["pizza"]! _ = sr2636["pizza"]! + sr2636["salad"]! _ = sr2636["pizza"]! + sr2636["salad"]! + sr2636["ice cream"]! } // Use operators defined within a type. struct S0 { static func +(lhs: S0, rhs: S0) -> S0 { return lhs } } func useS0(lhs: S0, rhs: S0) { _ = lhs + rhs } // Use operators defined within a generic type. struct S0b<T> { static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() } } func useS0b(s1i: S0b<Int>, s: String) { var s1s = s1i + s s1s = S0b<String>() _ = s1s } // Use operators defined within a protocol extension. infix operator %%% infix operator %%%% protocol P1 { static func %%%(lhs: Self, rhs: Self) -> Bool } extension P1 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP1Directly<T : P1>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1 : P1 { static func %%%(lhs: S1, rhs: S1) -> Bool { return false } } func useP1Model(lhs: S1, rhs: S1) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1b<T> : P1 { static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false } } func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Use operators defined within a protocol extension to satisfy a requirement. protocol P2 { static func %%%(lhs: Self, rhs: Self) -> Bool static func %%%%(lhs: Self, rhs: Self) -> Bool } extension P2 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP2Directly<T : P2>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2 : P2 { static func %%%(lhs: S2, rhs: S2) -> Bool { return false } } func useP2Model(lhs: S2, rhs: S2) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2b<T> : P2 { static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false } } func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Using an extension of one protocol to satisfy another conformance. protocol P3 { } extension P3 { static func ==(lhs: Self, rhs: Self) -> Bool { return true } } struct S3 : P3, Equatable { } // rdar://problem/30220565 func shrinkTooFar(_ : Double, closure : ()->()) {} func testShrinkTooFar() { shrinkTooFar(0*0*0) {} } // rdar://problem/33759839 enum E_33759839 { case foo case bar(String) } let foo_33759839 = ["a", "b", "c"] let bar_33759839 = ["A", "B", "C"] let _: [E_33759839] = foo_33759839.map { .bar($0) } + bar_33759839.map { .bar($0) } + [E_33759839.foo] // Ok // rdar://problem/28688585 class B_28688585 { var value: Int init(value: Int) { self.value = value } func add(_ other: B_28688585) -> B_28688585 { return B_28688585(value: value + other.value) } } class D_28688585 : B_28688585 { } func + (lhs: B_28688585, rhs: B_28688585) -> B_28688585 { return lhs.add(rhs) } let var_28688585 = D_28688585(value: 1) _ = var_28688585 + var_28688585 + var_28688585 // Ok // rdar://problem/35740653 - Fix `LinkedExprAnalyzer` greedy operator linking struct S_35740653 { var v: Double = 42 static func value(_ value: Double) -> S_35740653 { return S_35740653(v: value) } static func / (lhs: S_35740653, rhs: S_35740653) -> Double { return lhs.v / rhs.v } } func rdar35740653(val: S_35740653) { let _ = 0...Int(val / .value(1.0 / 42.0)) // Ok } protocol P_37290898 {} struct S_37290898: P_37290898 {} func rdar37290898(_ arr: inout [P_37290898], _ element: S_37290898?) { arr += [element].compactMap { $0 } // Ok } // SR-8221 infix operator ??= func ??= <T>(lhs: inout T?, rhs: T?) {} var c: Int = 0 c ??= 5 // expected-error{{binary operator '??=' cannot be applied to two 'Int' operands}} // expected-note@-1{{expected an argument list of type '(inout T?, T?)'}} func rdar46459603() { enum E { case foo(value: String) } let e = E.foo(value: "String") var arr = ["key": e] _ = arr.values == [e] // expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'Dictionary<String, E>.Values' and '[E]'}} // expected-note@-2 {{expected an argument list of type '(Self, Self)'}} _ = [arr.values] == [[e]] // expected-error@-1 {{protocol type 'Any' cannot conform to 'Equatable' because only concrete types can conform to protocols}} }
apache-2.0
xedin/swift
test/Driver/Dependencies/fail-new.swift
6
3223
/// bad ==> main | bad --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s // CHECK-NOT: warning // CHECK: Handled main.swift // CHECK: Handled bad.swift // CHECK-NOT: Handled other.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BAD-ONLY %s // CHECK-BAD-ONLY-NOT: warning // CHECK-BAD-ONLY-NOT: Handled // CHECK-BAD-ONLY: Handled bad.swift // CHECK-BAD-ONLY-NOT: Handled // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY %s // CHECK-OKAY: Handled main.swift // CHECK-OKAY: Handled bad.swift // CHECK-OKAY: Handled other.swift // CHECK-OKAY-NOT: Handled // RUN: touch -t 201401240006 %t/bad.swift // RUN: rm %t/bad.swiftdeps // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY-2 %s // CHECK-OKAY-2: Handled bad.swift // CHECK-OKAY-2: Handled other.swift // CHECK-OKAY-2: Handled main.swift // RUN: touch -t 201401240006 %t/main.swift // RUN: rm %t/main.swiftdeps // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY %s // RUN: touch -t 201401240006 %t/other.swift // RUN: rm %t/other.swiftdeps // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s
apache-2.0
domenicosolazzo/practice-swift
AR/ARKitByExample/ARKitByExample/AppDelegate.swift
1
2188
// // AppDelegate.swift // ARKitByExample // // Created by Domenico Solazzo on 8/18/17. // Copyright © 2017 Domenico Solazzo. 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. 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 invalidate graphics rendering callbacks. 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 active 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
advaita13/YouTubeFloatingPlayer
Example/YouTubeFloatingPlayer/AppDelegate.swift
1
2396
// // AppDelegate.swift // YouTubeFloatingPlayer // // Created by adipandya@gmail.com on 03/02/2017. // Copyright (c) 2017 adipandya@gmail.com. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:. } }
gpl-3.0
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/Notifications/NotificationNewChatProtocol.swift
1
375
// // HabiticaNotificationNewChatProtocol.swift // Habitica Models // // Created by Phillip Thelen on 23.04.19. // Copyright © 2019 HabitRPG Inc. All rights reserved. // import Foundation public protocol NotificationNewChatProtocol: NotificationProtocol { var groupID: String? { get set } var groupName: String? { get set } var isParty: Bool { get set } }
gpl-3.0
jmgc/swift
test/Interop/Cxx/implementation-only-imports/check-constructor-visibility.swift
1
582
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/FortyTwo.swiftmodule -I %S/Inputs %s -enable-cxx-interop // Swift should consider all sources for a decl and recognize that the // decl is not hidden behind @_implementationOnly in all modules. // This test, as well as `check-constructor-visibility-inversed.swift` checks // that the constructor decl can be found when at least one of the // modules is not `@_implementationOnly`. import UserA @_implementationOnly import UserB @_inlineable public func createAWrapper() { let _ = MagicWrapper() }
apache-2.0
apple/swift-syntax
lit_tests/print_verify_tree.swift
1
398
// RUN: %empty-directory(%t) // RUN: %lit-test-helper -print-tree -source-file %s > %t.result // RUN: diff -u %t.result %S/output/print_verify_tree.swift.withkind func foo() { #if swift(>=3.2) components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"") #else components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") #endif }
apache-2.0
segmentio/analytics-swift
Sources/Segment/Plugins/Context.swift
1
4006
// // Context.swift // Segment // // Created by Brandon Sneed on 2/23/21. // import Foundation public class Context: PlatformPlugin { public let type: PluginType = .before public weak var analytics: Analytics? internal var staticContext = staticContextData() internal static var device = VendorSystem.current public func execute<T: RawEvent>(event: T?) -> T? { guard var workingEvent = event else { return event } var context = staticContext insertDynamicPlatformContextData(context: &context) // if this event came in with context data already // let it take precedence over our values. if let eventContext = workingEvent.context?.dictionaryValue { context.merge(eventContext) { (_, new) in new } } do { workingEvent.context = try JSON(context) } catch { analytics?.reportInternalError(error) } return workingEvent } internal static func staticContextData() -> [String: Any] { var staticContext = [String: Any]() // library name staticContext["library"] = [ "name": "analytics-swift", "version": __segment_version ] // app info let info = Bundle.main.infoDictionary let localizedInfo = Bundle.main.localizedInfoDictionary var app = [String: Any]() if let info = info { app.merge(info) { (_, new) in new } } if let localizedInfo = localizedInfo { app.merge(localizedInfo) { (_, new) in new } } if app.count != 0 { staticContext["app"] = [ "name": app["CFBundleDisplayName"] ?? "", "version": app["CFBundleShortVersionString"] ?? "", "build": app["CFBundleVersion"] ?? "", "namespace": Bundle.main.bundleIdentifier ?? "" ] } insertStaticPlatformContextData(context: &staticContext) return staticContext } internal static func insertStaticPlatformContextData(context: inout [String: Any]) { // device let device = Self.device // "token" handled in DeviceToken.swift context["device"] = [ "manufacturer": device.manufacturer, "type": device.type, "model": device.model, "name": device.name, "id": device.identifierForVendor ?? "" ] // os context["os"] = [ "name": device.systemName, "version": device.systemVersion ] // screen let screen = device.screenSize context["screen"] = [ "width": screen.width, "height": screen.height ] // user-agent let userAgent = device.userAgent context["userAgent"] = userAgent // locale if Locale.preferredLanguages.count > 0 { context["locale"] = Locale.preferredLanguages[0] } // timezone context["timezone"] = TimeZone.current.identifier } internal func insertDynamicPlatformContextData(context: inout [String: Any]) { let device = Self.device // network let status = device.connection var cellular = false var wifi = false var bluetooth = false switch status { case .online(.cellular): cellular = true case .online(.wifi): wifi = true case .online(.bluetooth): bluetooth = true default: break } // network connectivity context["network"] = [ "bluetooth": bluetooth, // not sure any swift platforms support this currently "cellular": cellular, "wifi": wifi ] // other stuff?? ... } }
mit
ifLab/WeCenterMobile-iOS
WeCenterMobile/View/Comment/CommentCell.swift
3
2432
// // CommentCell.swift // WeCenterMobile // // Created by Darren Liu on 15/2/3. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class CommentCell: UITableViewCell { @IBOutlet weak var userAvatarView: MSRRoundedImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var commentButton: UIButton! @IBOutlet weak var separator: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var commentContainerView: UIView! @IBOutlet weak var containerView: UIView! override func awakeFromNib() { super.awakeFromNib() let theme = SettingsManager.defaultManager.currentTheme msr_scrollView?.delaysContentTouches = false containerView.msr_borderColor = theme.borderColorA separator.backgroundColor = theme.borderColorA for v in [userContainerView, commentContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [userButton, commentButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } userNameLabel.textColor = theme.titleTextColor } func update(comment comment: Comment) { msr_userInfo = comment userAvatarView.wc_updateWithUser(comment.user) userNameLabel.text = comment.user?.name let attributedString = NSMutableAttributedString() let theme = SettingsManager.defaultManager.currentTheme if comment.atUser?.name != nil { attributedString.appendAttributedString(NSAttributedString( string: "@\(comment.atUser!.name!) ", attributes: [ NSForegroundColorAttributeName: theme.footnoteTextColor, NSFontAttributeName: bodyLabel.font])) } attributedString.appendAttributedString(NSAttributedString( string: (comment.body ?? ""), attributes: [ NSForegroundColorAttributeName: theme.bodyTextColor, NSFontAttributeName: bodyLabel.font])) bodyLabel.attributedText = attributedString userButton.msr_userInfo = comment.user commentButton.msr_userInfo = comment setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
coodly/ios-gambrinus
Packages/Sources/KioskCore/Persistence/SyncStatus.swift
1
669
/* * Copyright 2016 Coodly LLC * * 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 CoreData class SyncStatus: NSManagedObject { }
apache-2.0
Prattmi/BecauseWater
AppDelegate.swift
1
2156
// // AppDelegate.swift // iOSBecauseWater // // Created by Michael Pratt on 10/27/14. // Copyright (c) 2014 Michael Pratt. 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
scsonic/cosremote
ios/CosRemote/DeviceScanCell.swift
1
310
// // DeviceScanCell.swift // CosRemote // // Created by 郭 又鋼 on 2016/3/3. // Copyright © 2016年 郭 又鋼. All rights reserved. // import Foundation import UIKit class DeviceScanCell: UITableViewCell { @IBOutlet var lbDeviceName: UILabel! @IBOutlet var lbIsConnect: UILabel! }
mit
VirgilSecurity/virgil-sdk-keys-x
Source/JsonWebToken/AccessProviders/CachingJwtProvider.swift
2
5220
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> // import Foundation // swiftlint:disable trailing_closure /// Implementation of AccessTokenProvider which provides AccessToken using cache+renew callback @objc(VSSCachingJwtProvider) open class CachingJwtProvider: NSObject, AccessTokenProvider { /// Cached Jwt public private(set) var jwt: Jwt? /// Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public let renewJwtCallback: (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void private let semaphore = DispatchSemaphore(value: 1) /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewJwtCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public init(initialJwt: Jwt? = nil, renewJwtCallback: @escaping (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void) { self.jwt = initialJwt self.renewJwtCallback = renewJwtCallback super.init() } /// Typealias for callback used below public typealias JwtStringCallback = (String?, Error?) -> Void /// Typealias for callback used below public typealias RenewJwtCallback = (TokenContext, @escaping JwtStringCallback) -> Void /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewTokenCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT String, or Error @objc public convenience init(initialJwt: Jwt? = nil, renewTokenCallback: @escaping RenewJwtCallback) { self.init(initialJwt: initialJwt, renewJwtCallback: { ctx, completion in renewTokenCallback(ctx) { string, error in do { guard let string = string, error == nil else { completion(nil, error) return } completion(try Jwt(stringRepresentation: string), nil) } catch { completion(nil, error) } } }) } /// Typealias for callback used below public typealias AccessTokenCallback = (AccessToken?, Error?) -> Void /// Provides access token using callback /// /// - Parameters: /// - tokenContext: `TokenContext` provides context explaining why token is needed /// - completion: completion closure @objc public func getToken(with tokenContext: TokenContext, completion: @escaping AccessTokenCallback) { let expirationTime = Date().addingTimeInterval(5) if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { completion(jwt, nil) return } self.semaphore.wait() if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { self.semaphore.signal() completion(jwt, nil) return } self.renewJwtCallback(tokenContext) { token, err in guard let token = token, err == nil else { self.semaphore.signal() completion(nil, err) return } self.jwt = token self.semaphore.signal() completion(token, nil) } } } // swiftlint:enable trailing_closure
bsd-3-clause
Matzo/Edamame
Example/Tests/Tests.swift
1
757
import UIKit import XCTest import Edamame class Tests: 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.measure() { // Put the code you want to measure the time of here. } } }
mit
sschiau/swift
stdlib/public/Darwin/Accelerate/vDSP_Arithmetic.swift
8
128736
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // Vector-vector and vector-scalar arithmetic @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: c[i] = a[i] + b vDSP_vsadd /// Returns the elementwise sum of `vector` and `scalar`, /// single-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Returns: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` and `scalar`, /// single-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Parameter result: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsadd(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise sum of `vector` and `scalar`, /// double-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Returns: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` and `scalar`, /// double-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Parameter result: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsaddD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] + b[i] vDSP_vadd /// Returns the elementwise sum of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Returns: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in add(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vadd(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise sum of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Returns: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in add(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vaddD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] - b[i] vDSP_vsub /// Returns the elementwise difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Returns: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U>(_ vectorA: U, _ vectorB: T) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in subtract(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U, V>(_ vectorA: U, _ vectorB: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorB.withUnsafeBufferPointer { b in vectorA.withUnsafeBufferPointer { a in vDSP_vsub(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Returns: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U>(_ vectorA: U, _ vectorB: T) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in subtract(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U, V>(_ vectorA: U, _ vectorB: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorB.withUnsafeBufferPointer { b in vectorA.withUnsafeBufferPointer { a in vDSP_vsubD(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] * b vDSP_vsmul /// Returns the elementwise product of `vector` and `scalar /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Returns: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of `vector` and `scalar /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Parameter result: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsmul(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise product of `vector` and `scalar /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Returns: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of `vector` and `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Parameter result: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsmulD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] * b[i] vDSP_vmul /// Returns the elementwise product of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in multiply(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmul(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise product of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in multiply(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmulD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] / b vDSP_vsdiv /// Returns the elementwise division of `vector` by `scalar`, /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Returns: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U>(_ vector: U, _ scalar: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(vector, scalar, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `vector` by `scalar`, /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Parameter result: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U, V>(_ vector: U, _ scalar: Float, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsdiv(v.baseAddress!, 1, [scalar], r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `vector` by `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Returns: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U>(_ vector: U, _ scalar: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(vector, scalar, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `vector` by `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Parameter result: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U, V>(_ vector: U, _ scalar: Double, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsdivD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a / b[i] vDSP_svdiv /// Returns the elementwise division of `scalar` by `vector`, /// single-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Returns: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `scalar` by `vector`, /// single-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Parameter result: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_svdiv(s, v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `scalar` by `vector`, /// double-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Returns: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `scalar` by `vector`, /// double-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Parameter result: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_svdivD(s, v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] / b[i] vDSP_vdiv /// Returns the elementwise division of `vectorA` by `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Returns: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in divide(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vdiv(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `vectorA` by `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Returns: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in divide(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vdivD(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i] vDSP_vaddsub /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. @inlinable public static func addSubtract<S, T, U, V>(_ vectorA: S, _ vectorB: T, addResult: inout U, subtractResult: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateMutableBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = addResult.count precondition(vectorA.count == n && vectorB.count == n && subtractResult.count == n) addResult.withUnsafeMutableBufferPointer { o0 in subtractResult.withUnsafeMutableBufferPointer { o1 in vectorA.withUnsafeBufferPointer { i1 in vectorB.withUnsafeBufferPointer { i0 in vDSP_vaddsub(i0.baseAddress!, 1, i1.baseAddress!, 1, o0.baseAddress!, 1, o1.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. @inlinable public static func addSubtract<S, T, U, V>(_ vectorA: S, _ vectorB: T, addResult: inout U, subtractResult: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateMutableBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = addResult.count precondition(vectorA.count == n && vectorB.count == n && subtractResult.count == n) addResult.withUnsafeMutableBufferPointer { o0 in subtractResult.withUnsafeMutableBufferPointer { o1 in vectorA.withUnsafeBufferPointer { i1 in vectorB.withUnsafeBufferPointer { i0 in vDSP_vaddsubD(i0.baseAddress!, 1, i1.baseAddress!, 1, o0.baseAddress!, 1, o1.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] + b[i]) * c vDSP_vasm /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U>(addition: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, scalar, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U, V>(addition: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vasm(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U>(addition: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, scalar, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U, V>(addition: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vasmD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] + b[i]) * c[i] vDSP_vam /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(addition: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(addition: addition, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(addition: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vam(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(addition: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(addition: addition, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(addition: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vamD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] - b[i]) * c vDSP_vsbsm /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U>(subtraction: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: subtraction.a.count) { buffer, initializedCount in multiply(subtraction: subtraction, scalar, result: &buffer) initializedCount = subtraction.a.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U, V>(subtraction: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vsbsm(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U>(subtraction: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: subtraction.a.count) { buffer, initializedCount in multiply(subtraction: subtraction, scalar, result: &buffer) initializedCount = subtraction.a.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U, V>(subtraction: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vsbsmD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] - b[i]) * c[i] vDSP_vsbm /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(subtraction: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(subtraction: subtraction, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(subtraction: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vsbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(subtraction: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(subtraction: subtraction, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(subtraction: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vsbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = a[i]*b[i] + c; vDSP_vmsa /// Returns the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U>(multiplication: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vmsa(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U>(multiplication: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vmsaD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b) + c[i] vDSP_vsma /// Returns the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U>(multiplication: (a: T, b: Float), _ vector: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: Float), _ vector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in vector.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplication.b) { b in vDSP_vsma(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U>(multiplication: (a: T, b: Double), _ vector: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: Double), _ vector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in vector.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplication.b) { b in vDSP_vsmaD(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b[i]) + c[i] vDSP_vma /// Returns the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U>(multiplication: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U, V>(multiplication: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vma(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U>(multiplication: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U, V>(multiplication: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmaD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b[i]) - c[i] vDSP_vmsb /// Returns the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U>(multiplication: (a: T, b: U), _ vector: S) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U, V>(multiplication: (a: T, b: U), _ vector: S, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmsb(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U>(multiplication: (a: T, b: U), _ vector: S) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U, V>(multiplication: (a: T, b: U), _ vector: S, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmsbD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: e[i] = (a[i] * b) + (c[i] * d) vDSP_vsmsma /// Returns the elementwise sum of two elementwise /// vector-scalar products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U>(multiplication multiplicationAB: (a: T, b: Float), multiplication multiplicationCD: (c: U, d: Float)) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-scalar products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U, V>(multiplication multiplicationAB: (a: T, b: Float), multiplication multiplicationCD: (c: U, d: Float), result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationCD.c.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationCD.c.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplicationAB.b) { b in withUnsafePointer(to: multiplicationCD.d) { d in vDSP_vsmsma(a.baseAddress!, 1, b, c.baseAddress!, 1, d, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise sum of two elementwise /// vector-scalar products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U>(multiplication multiplicationAB: (a: T, b: Double), multiplication multiplicationCD: (c: U, d: Double)) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-scalar products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U, V>(multiplication multiplicationAB: (a: T, b: Double), multiplication multiplicationCD: (c: U, d: Double), result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationCD.c.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationCD.c.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplicationAB.b) { b in withUnsafePointer(to: multiplicationCD.d) { d in vDSP_vsmsmaD(a.baseAddress!, 1, b, c.baseAddress!, 1, d, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] * b[i]) + (c[i] * d[i]) vDSP_vmma /// Returns the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U, V>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmma(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U, V>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmaD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] + b[i]) * (c[i] + d[i]) vDSP_vaam /// Returns the elementwise product of two elementwise /// vector-vector sums, single-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U)) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: additionAB.a.count) { buffer, initializedCount in multiply(addition: additionAB, addition: additionCD, result: &buffer) initializedCount = additionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector sums, single-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U, V>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U), result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(additionAB.a.count == n && additionAB.b.count == n && additionCD.c.count == n && additionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in additionAB.a.withUnsafeBufferPointer { a in additionAB.b.withUnsafeBufferPointer { b in additionCD.c.withUnsafeBufferPointer { c in additionCD.d.withUnsafeBufferPointer { d in vDSP_vaam(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of two elementwise /// vector-vector sums, double-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U)) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: additionAB.a.count) { buffer, initializedCount in multiply(addition: additionAB, addition: additionCD, result: &buffer) initializedCount = additionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector sums, double-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U, V>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U), result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(additionAB.a.count == n && additionAB.b.count == n && additionCD.c.count == n && additionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in additionAB.a.withUnsafeBufferPointer { a in additionAB.b.withUnsafeBufferPointer { b in additionCD.c.withUnsafeBufferPointer { c in additionCD.d.withUnsafeBufferPointer { d in vDSP_vaamD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] * b[i]) - (c[i] * d[i]) vDSP_vmmsb /// Returns the elementwise difference of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in subtract(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise difference of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U, V>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmsb(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise difference of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in subtract(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise difference of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U, V>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmsbD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] - b[i]) * (c[i] - d[i]) vDSP_vsbsbm /// Returns the elementwise product of two elementwise /// vector-vector differences, single-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: subtractionAB.a.count) { buffer, initializedCount in multiply(subtraction: subtractionAB, subtraction: subtractionCD, result: &buffer) initializedCount = subtractionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector differences, single-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtractionAB.a.count == n && subtractionAB.b.count == n && subtractionCD.c.count == n && subtractionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in subtractionAB.a.withUnsafeBufferPointer { a in subtractionAB.b.withUnsafeBufferPointer { b in subtractionCD.c.withUnsafeBufferPointer { c in subtractionCD.d.withUnsafeBufferPointer { d in vDSP_vsbsbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of two elementwise /// vector-vector differences, double-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: subtractionAB.a.count) { buffer, initializedCount in multiply(subtraction: subtractionAB, subtraction: subtractionCD, result: &buffer) initializedCount = subtractionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector differences, double-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtractionAB.a.count == n && subtractionAB.b.count == n && subtractionCD.c.count == n && subtractionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in subtractionAB.a.withUnsafeBufferPointer { a in subtractionAB.b.withUnsafeBufferPointer { b in subtractionCD.c.withUnsafeBufferPointer { c in subtractionCD.d.withUnsafeBufferPointer { d in vDSP_vsbsbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] + b[i]) * (c[i] - d[i]) vDSP_vasbm /// Returns the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, single-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(addition: (a: R, b: S), subtraction: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, subtraction: subtraction, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, single-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(addition: (a: R, b: S), subtraction: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n && subtraction.c.count == n && subtraction.d.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in subtraction.c.withUnsafeBufferPointer { c in subtraction.d.withUnsafeBufferPointer { d in vDSP_vasbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, double-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(addition: (a: R, b: S), subtraction: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, subtraction: subtraction, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, double-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(addition: (a: R, b: S), subtraction: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n && subtraction.c.count == n && subtraction.d.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in subtraction.c.withUnsafeBufferPointer { c in subtraction.d.withUnsafeBufferPointer { d in vDSP_vasbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: d[n] = a[n]*b + c vDSP_vsmsa /// Returns the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Returns: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U>(multiplication: (a: U, b: Float), _ scalar: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U, V>(multiplication: (a: U, b: Float), _ scalar: Float, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in withUnsafePointer(to: scalar) { c in vDSP_vsmsa(a.baseAddress!, 1, b, c, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Returns: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U>(multiplication: (a: U, b: Double), _ scalar: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c`in `d[n] = a[n]*b + c`. /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U, V>(multiplication: (a: U, b: Double), _ scalar: Double, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in withUnsafePointer(to: scalar) { c in vDSP_vsmsaD(a.baseAddress!, 1, b, c, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: D[n] = A[n]*B - C[n]; vDSP_vsmsb /// Returns the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U>(multiplication: (a: U, b: Float), _ vector: T) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U, V>(multiplication: (a: U, b: Float), _ vector: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in vector.withUnsafeBufferPointer { c in vDSP_vsmsb(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U>(multiplication: (a: U, b: Double), _ vector: T) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U, V>(multiplication: (a: U, b: Double), _ vector: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in vector.withUnsafeBufferPointer { c in vDSP_vsmsbD(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } }
apache-2.0
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/Promise.swift
111
1271
//===--- Promise.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 Boilerplate import Result import ExecutionContext public class Promise<V> : MutableFutureType { public typealias Value = V private let _future:MutableFuture<V> public var future:Future<V> { get { return _future } } public init() { _future = MutableFuture(context: immediate) } public func tryComplete<E : ErrorProtocol>(result:Result<Value, E>) -> Bool { return _future.tryComplete(result) } }
mit
zapdroid/RXWeather
Pods/RxCocoa/RxCocoa/iOS/UIViewController+Rx.swift
1
563
// // UIViewController+Rx.swift // RxCocoa // // Created by Kyle Fuller on 27/05/2016. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif extension Reactive where Base: UIViewController { /// Bindable sink for `title`. public var title: UIBindingObserver<Base, String> { return UIBindingObserver(UIElement: self.base) { viewController, title in viewController.title = title } } } #endif
mit
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/Extensions/UIColor+SimpleInit.swift
1
2877
// // Created by Pierluigi Cifani. // Copyright © 2018 TheLeftBit SL. All rights reserved. // #if canImport(UIKit) import UIKit public extension UIColor { /** Initializes and returns a color given the current trait environment, but if, iOS 13 is not available it'll return the light color. - parameter light: The version of the color to use with `UIUserInterfaceStyle.light`. - parameter dark: The version of the color to use with `UIUserInterfaceStyle.dark`. */ convenience init(light: UIColor, dark: UIColor) { if #available(iOS 13.0, *) { self.init(dynamicProvider: { traitCollection in switch traitCollection.userInterfaceStyle { case .dark: return dark default: return light } }) } else { self.init(cgColor: light.cgColor) } } /** Initializes and returns a color object using the specified opacity and RGB component values. - parameter r: The red component of the color object, specified as a value from 0 to 255. - parameter g: The green component of the color object, specified as a value from 0 to 255. - parameter b: The blue component of the color object, specified as a value from 0 to 255. - returns: An initialized color object. The color information represented by this object is in the device RGB colorspace. */ convenience init(r: Int, g: Int, b: Int) { self.init( red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha:1 ) } /** Initializes and returns a color object using the specified opacity and HSB component values. - parameter h: The hue component of the color object, specified as a value from 0 to 360. - parameter s: The saturation component of the color object, specified as a value from 0 to 100. - parameter b: The brightness component of the color object, specified as a value from 0 to 100. - returns: An initialized color object. The color information represented by this object is in the device HSB colorspace. */ convenience init(h: Int, s: Int, b: Int) { self.init( hue: CGFloat(h)/360.0, saturation: CGFloat(s)/100.0, brightness: CGFloat(b)/100.0, alpha: 1 ) } convenience init(rgb: UInt, alphaVal: CGFloat = 1) { self.init( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: alphaVal ) } class func randomColor() -> UIColor { return RandomColorFactory.randomColor() } } #endif
mit
vbudhram/firefox-ios
Client/Frontend/Settings/LoginDetailViewController.swift
2
15344
/* 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 import Storage import Shared import SwiftKeychainWrapper enum InfoItem: Int { case websiteItem = 0 case usernameItem = 1 case passwordItem = 2 case lastModifiedSeparator = 3 case deleteItem = 4 var indexPath: IndexPath { return IndexPath(row: rawValue, section: 0) } } private struct LoginDetailUX { static let InfoRowHeight: CGFloat = 58 static let DeleteRowHeight: CGFloat = 44 static let SeparatorHeight: CGFloat = 44 } class LoginDetailViewController: SensitiveViewController { fileprivate let profile: Profile fileprivate let tableView = UITableView() fileprivate var login: Login { didSet { tableView.reloadData() } } fileprivate var editingInfo: Bool = false { didSet { if editingInfo != oldValue { tableView.reloadData() } } } fileprivate let LoginCellIdentifier = "LoginCell" fileprivate let DefaultCellIdentifier = "DefaultCellIdentifier" fileprivate let SeparatorIdentifier = "SeparatorIdentifier" // Used to temporarily store a reference to the cell the user is showing the menu controller for fileprivate var menuControllerCell: LoginTableViewCell? fileprivate weak var websiteField: UITextField? fileprivate weak var usernameField: UITextField? fileprivate weak var passwordField: UITextField? fileprivate var deleteAlert: UIAlertController? weak var settingsDelegate: SettingsDelegate? init(profile: Profile, login: Login) { self.login = login self.profile = profile super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(dismissAlertController), name: .UIApplicationDidEnterBackground, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(SELedit)) tableView.register(LoginTableViewCell.self, forCellReuseIdentifier: LoginCellIdentifier) tableView.register(UITableViewCell.self, forCellReuseIdentifier: DefaultCellIdentifier) tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SeparatorIdentifier) view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.separatorColor = SettingsUX.TableViewSeparatorColor tableView.backgroundColor = SettingsUX.TableViewHeaderBackgroundColor tableView.accessibilityIdentifier = "Login Detail List" tableView.delegate = self tableView.dataSource = self // Add empty footer view to prevent seperators from being drawn past the last item. tableView.tableFooterView = UIView() // Add a line on top of the table view so when the user pulls down it looks 'correct'. let topLine = UIView(frame: CGRect(width: tableView.frame.width, height: 0.5)) topLine.backgroundColor = SettingsUX.TableViewSeparatorColor tableView.tableHeaderView = topLine // Normally UITableViewControllers handle responding to content inset changes from keyboard events when editing // but since we don't use the tableView's editing flag for editing we handle this ourselves. KeyboardHelper.defaultHelper.addDelegate(self) } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // The following hacks are to prevent the default cell seperators from displaying. We want to // hide the default seperator for the website/last modified cells since the last modified cell // draws its own separators. The last item in the list draws its seperator full width. // Prevent seperators from showing by pushing them off screen by the width of the cell let itemsToHideSeperators: [InfoItem] = [.passwordItem, .lastModifiedSeparator] itemsToHideSeperators.forEach { item in let cell = tableView.cellForRow(at: IndexPath(row: item.rawValue, section: 0)) cell?.separatorInset = UIEdgeInsets(top: 0, left: cell?.bounds.width ?? 0, bottom: 0, right: 0) } // Rows to display full width seperator let itemsToShowFullWidthSeperator: [InfoItem] = [.deleteItem] itemsToShowFullWidthSeperator.forEach { item in let cell = tableView.cellForRow(at: IndexPath(row: item.rawValue, section: 0)) cell?.separatorInset = .zero cell?.layoutMargins = .zero cell?.preservesSuperviewLayoutMargins = false } } } // MARK: - UITableViewDataSource extension LoginDetailViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch InfoItem(rawValue: indexPath.row)! { case .usernameItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("username", tableName: "LoginManager", comment: "Label displayed above the username row in Login Detail View.") loginCell.descriptionLabel.text = login.username loginCell.descriptionLabel.keyboardType = .emailAddress loginCell.descriptionLabel.returnKeyType = .next loginCell.editingDescription = editingInfo usernameField = loginCell.descriptionLabel usernameField?.accessibilityIdentifier = "usernameField" return loginCell case .passwordItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("password", tableName: "LoginManager", comment: "Label displayed above the password row in Login Detail View.") loginCell.descriptionLabel.text = login.password loginCell.descriptionLabel.returnKeyType = .default loginCell.displayDescriptionAsPassword = true loginCell.editingDescription = editingInfo passwordField = loginCell.descriptionLabel passwordField?.accessibilityIdentifier = "passwordField" return loginCell case .websiteItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("website", tableName: "LoginManager", comment: "Label displayed above the website row in Login Detail View.") loginCell.descriptionLabel.text = login.hostname websiteField = loginCell.descriptionLabel websiteField?.accessibilityIdentifier = "websiteField" return loginCell case .lastModifiedSeparator: let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: SeparatorIdentifier) as! SettingsTableSectionHeaderFooterView footer.titleAlignment = .top let lastModified = NSLocalizedString("Last modified %@", tableName: "LoginManager", comment: "Footer label describing when the current login was last modified with the timestamp as the parameter.") let formattedLabel = String(format: lastModified, Date.fromMicrosecondTimestamp(login.timePasswordChanged).toRelativeTimeString()) footer.titleLabel.text = formattedLabel let cell = wrapFooter(footer, withCellFromTableView: tableView, atIndexPath: indexPath) return cell case .deleteItem: let deleteCell = tableView.dequeueReusableCell(withIdentifier: DefaultCellIdentifier, for: indexPath) deleteCell.textLabel?.text = NSLocalizedString("Delete", tableName: "LoginManager", comment: "Label for the button used to delete the current login.") deleteCell.textLabel?.textAlignment = .center deleteCell.textLabel?.textColor = UIConstants.DestructiveRed deleteCell.accessibilityTraits = UIAccessibilityTraitButton return deleteCell } } fileprivate func dequeueLoginCellForIndexPath(_ indexPath: IndexPath) -> LoginTableViewCell { let loginCell = tableView.dequeueReusableCell(withIdentifier: LoginCellIdentifier, for: indexPath) as! LoginTableViewCell loginCell.selectionStyle = .none loginCell.delegate = self return loginCell } fileprivate func wrapFooter(_ footer: UITableViewHeaderFooterView, withCellFromTableView tableView: UITableView, atIndexPath indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DefaultCellIdentifier, for: indexPath) cell.selectionStyle = .none cell.addSubview(footer) footer.snp.makeConstraints { make in make.edges.equalTo(cell) } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } } // MARK: - UITableViewDelegate extension LoginDetailViewController: UITableViewDelegate { private func showMenuOnSingleTap(forIndexPath indexPath: IndexPath) { guard let item = InfoItem(rawValue: indexPath.row) else { return } if ![InfoItem.passwordItem, InfoItem.websiteItem, InfoItem.usernameItem].contains(item) { return } guard let cell = tableView.cellForRow(at: indexPath) as? LoginTableViewCell else { return } cell.becomeFirstResponder() let menu = UIMenuController.shared menu.setTargetRect(cell.frame, in: self.tableView) menu.setMenuVisible(true, animated: true) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath == InfoItem.deleteItem.indexPath { deleteLogin() } else if !editingInfo { showMenuOnSingleTap(forIndexPath: indexPath) } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch InfoItem(rawValue: indexPath.row)! { case .usernameItem, .passwordItem, .websiteItem: return LoginDetailUX.InfoRowHeight case .lastModifiedSeparator: return LoginDetailUX.SeparatorHeight case .deleteItem: return LoginDetailUX.DeleteRowHeight } } } // MARK: - KeyboardHelperDelegate extension LoginDetailViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(tableView) tableView.contentInset.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } } // MARK: - Selectors extension LoginDetailViewController { @objc func dismissAlertController() { self.deleteAlert?.dismiss(animated: false, completion: nil) } func deleteLogin() { profile.logins.hasSyncedLogins().uponQueue(.main) { yes in self.deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in self.profile.logins.removeLoginByGUID(self.login.guid).uponQueue(.main) { _ in _ = self.navigationController?.popViewController(animated: true) } }, hasSyncedLogins: yes.successValue ?? true) self.present(self.deleteAlert!, animated: true, completion: nil) } } func SELonProfileDidFinishSyncing() { // Reload details after syncing. profile.logins.getLoginDataForGUID(login.guid).uponQueue(.main) { result in if let syncedLogin = result.successValue { self.login = syncedLogin } } } func SELedit() { editingInfo = true let cell = tableView.cellForRow(at: InfoItem.usernameItem.indexPath) as! LoginTableViewCell cell.descriptionLabel.becomeFirstResponder() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(SELdoneEditing)) } func SELdoneEditing() { editingInfo = false navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(SELedit)) defer { // Required to get UI to reload with changed state tableView.reloadData() } // We only care to update if we changed something guard let username = usernameField?.text, let password = passwordField?.text, username != login.username || password != login.password else { return } // Keep a copy of the old data in case we fail and need to revert back let oldPassword = login.password let oldUsername = login.username login.update(password: password, username: username) if login.isValid.isSuccess { profile.logins.updateLoginByGUID(login.guid, new: login, significant: true) } else if let oldUsername = oldUsername { login.update(password: oldPassword, username: oldUsername) } } } // MARK: - Cell Delegate extension LoginDetailViewController: LoginTableViewCellDelegate { fileprivate func cellForItem(_ item: InfoItem) -> LoginTableViewCell? { return tableView.cellForRow(at: item.indexPath) as? LoginTableViewCell } func didSelectOpenAndFillForCell(_ cell: LoginTableViewCell) { guard let url = (self.login.formSubmitURL?.asURL ?? self.login.hostname.asURL) else { return } navigationController?.dismiss(animated: true, completion: { self.settingsDelegate?.settingsOpenURLInNewTab(url) }) } func shouldReturnAfterEditingDescription(_ cell: LoginTableViewCell) -> Bool { let usernameCell = cellForItem(.usernameItem) let passwordCell = cellForItem(.passwordItem) if cell == usernameCell { passwordCell?.descriptionLabel.becomeFirstResponder() } return false } func infoItemForCell(_ cell: LoginTableViewCell) -> InfoItem? { if let index = tableView.indexPath(for: cell), let item = InfoItem(rawValue: index.row) { return item } return nil } }
mpl-2.0
klaaspieter/Letters
Sources/Recorder/Extensions/FileManager.swift
1
353
import Foundation extension FileManager { func uniqueTemporaryFile(pathExtension: String? = .none) -> URL { var url = temporaryDirectory.appendingPathComponent( ProcessInfo.processInfo.globallyUniqueString ) if let pathExtension = pathExtension { url = url.appendingPathExtension(pathExtension) } return url } }
mit
jopamer/swift
test/multifile/multiconformanceimpls/main.swift
2
1064
// RUN: %empty-directory(%t) // RUN: %target-build-swift-dylib(%t/libA.%target-dylib-extension) %S/Inputs/A.swift -emit-module -emit-module-path %t/A.swiftmodule -module-name A // RUN: %target-codesign %t/libA.%target-dylib-extension // RUN: %target-build-swift-dylib(%t/libB.%target-dylib-extension) %S/Inputs/B.swift -emit-module -emit-module-path %t/B.swiftmodule -module-name B -I%t -L%t -lA // RUN: %target-codesign %t/libB.%target-dylib-extension // RUN: %target-build-swift-dylib(%t/libC.%target-dylib-extension) %S/Inputs/C.swift -emit-module -emit-module-path %t/C.swiftmodule -module-name C -I%t -L%t -lA // RUN: %target-codesign %t/libC.%target-dylib-extension // RUN: %target-build-swift %s -I %t -o %t/a.out -L %t -Xlinker -rpath -Xlinker %t -lA -lB -lC // RUN: %target-run %t/a.out %t/libA.%target-dylib-extension %t/libB.%target-dylib-extension %t/libC.%target-dylib-extension | %FileCheck %s import A import B import C func runTheTest() { setAnyWithImplFromB() // CHECK: check returned not Container<Impl> in C checkAnyInC() } runTheTest()
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Modules/Checkout/Sources/FeatureCheckoutUI/CountdownView.swift
1
2010
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainUI import SwiftUI import SwiftUIExtensions @MainActor struct CountdownView: View { private var deadline: Date private let formatter: DateComponentsFormatter = .shortCountdownFormatter @Environment(\.scheduler) private var scheduler @State private var remaining: String? @State private var progress: Double = 0.0 @State private var opacity: Double = 1 init(deadline: Date) { self.deadline = deadline } var body: some View { HStack(spacing: 0) { Spacer() ProgressView(value: progress) .progressViewStyle(.determinate) .frame(width: 14.pt, height: 14.pt) .padding(.trailing, 8.pt) Text(LocalizationConstants.Checkout.Label.countdown) ZStack(alignment: .leading) { if let remaining = remaining { Text(remaining) } Text("MM:SS").opacity(0) // hack to fix alignment of the counter } Spacer() } .typography(.caption2) .task(id: deadline, priority: .userInitiated) { let start = deadline.timeIntervalSinceNow for seconds in stride(from: start, to: 0, by: -1) where seconds > 0 { withAnimation { remaining = formatter.string(from: seconds) progress = min(1 - seconds / start, 1) } do { try await scheduler.sleep(for: .seconds(1)) } catch /* a */ { break } } } } } extension DateComponentsFormatter { static var shortCountdownFormatter: DateComponentsFormatter { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.minute, .second] formatter.unitsStyle = .positional formatter.zeroFormattingBehavior = .pad return formatter } }
lgpl-3.0
hibento/MessagePack.swift
MessagePackTests/ConvenienceInitializersTests.swift
1
2638
@testable import MessagePack import XCTest class ConvenienceInitializersTests: XCTestCase { func testNil() { XCTAssertEqual(MessagePackValue(), MessagePackValue.nothing) } func testBool() { XCTAssertEqual(MessagePackValue(true), MessagePackValue.bool(true)) XCTAssertEqual(MessagePackValue(false), MessagePackValue.bool(false)) } func testUInt() { XCTAssertEqual(MessagePackValue(0 as UInt), MessagePackValue.uint(0)) XCTAssertEqual(MessagePackValue(0xff as UInt8), MessagePackValue.uint(0xff)) XCTAssertEqual(MessagePackValue(0xffff as UInt16), MessagePackValue.uint(0xffff)) XCTAssertEqual(MessagePackValue(0xffff_ffff as UInt32), MessagePackValue.uint(0xffff_ffff)) XCTAssertEqual(MessagePackValue(0xffff_ffff_ffff_ffff as UInt64), MessagePackValue.uint(0xffff_ffff_ffff_ffff)) } func testInt() { XCTAssertEqual(MessagePackValue(-1 as Int), MessagePackValue.int(-1)) XCTAssertEqual(MessagePackValue(-0x7f as Int8), MessagePackValue.int(-0x7f)) XCTAssertEqual(MessagePackValue(-0x7fff as Int16), MessagePackValue.int(-0x7fff)) XCTAssertEqual(MessagePackValue(-0x7fff_ffff as Int32), MessagePackValue.int(-0x7fff_ffff)) XCTAssertEqual(MessagePackValue(-0x7fff_ffff_ffff_ffff as Int64), MessagePackValue.int(-0x7fff_ffff_ffff_ffff)) } func testFloat() { XCTAssertEqual(MessagePackValue(0 as Float), MessagePackValue.float(0)) XCTAssertEqual(MessagePackValue(1.618 as Float), MessagePackValue.float(1.618)) XCTAssertEqual(MessagePackValue(3.14 as Float), MessagePackValue.float(3.14)) } func testDouble() { XCTAssertEqual(MessagePackValue(0 as Double), MessagePackValue.double(0)) XCTAssertEqual(MessagePackValue(1.618 as Double), MessagePackValue.double(1.618)) XCTAssertEqual(MessagePackValue(3.14 as Double), MessagePackValue.double(3.14)) } func testString() { XCTAssertEqual(MessagePackValue("Hello, world!"), MessagePackValue.string("Hello, world!")) } func testArray() { XCTAssertEqual(MessagePackValue([.uint(0), .uint(1), .uint(2), .uint(3), .uint(4)]), MessagePackValue.array([.uint(0), .uint(1), .uint(2), .uint(3), .uint(4)])) } func testMap() { XCTAssertEqual(MessagePackValue([.string("c"): .string("cookie")]), MessagePackValue.map([.string("c"): .string("cookie")])) } func testBinary() { let data: [UInt8] = [0x00, 0x01, 0x02, 0x03, 0x04] XCTAssertEqual(MessagePackValue(data), MessagePackValue.binary([0x00, 0x01, 0x02, 0x03, 0x04])) } }
mit
huonw/swift
test/IRGen/type_layout.swift
1
4590
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize class C {} struct SSing { var x: Int64 } struct SMult { var x, y: Int64 } struct SMult2 { var x, y: C } struct SMult3 { var x, y: C } struct GSing<T> { var x: T } struct GMult<T> { var x, y: T } enum ESing { case X(Int64) } enum EMult { case X(Int64), Y(Int64) } @_alignment(4) struct CommonLayout { var x,y,z,w: Int8 } struct FourInts { var x,y,z,w: Int32 } @_alignment(16) struct AlignedFourInts { var x: FourInts } // CHECK: @"$S11type_layout14TypeLayoutTestVMn" = hidden constant {{.*}} @"$S11type_layout14TypeLayoutTestVMP" // CHECK: define internal %swift.type* @"$S11type_layout14TypeLayoutTestVMi" // CHECK: define internal swiftcc %swift.metadata_response @"$S11type_layout14TypeLayoutTestVMr" struct TypeLayoutTest<T> { // -- dynamic layout, projected from metadata // CHECK: [[T0:%.*]] = call{{( tail)?}} swiftcc %swift.metadata_response @swift_checkMetadataState([[INT]] 319, %swift.type* %T) // CHECK: [[T_CHECKED:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[T_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK: [[T_OK:%.*]] = icmp ule [[INT]] [[T_STATUS]], 63 // CHECK: br i1 [[T_OK]], // CHECK: [[T0:%.*]] = bitcast %swift.type* [[T_CHECKED]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1 // CHECK: [[T_VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]] // CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[T_LAYOUT]] var z: T // -- native class, use standard NativeObject value witness // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBoWV", i32 8) var a: C // -- Single-element struct, shares layout of its field (Builtin.Int64) // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBi64_WV", i32 8) var c: SSing // -- Multi-element structs use open-coded layouts // CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_16_8_0_pod, i32 0, i32 0) var d: SMult // CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_[[REF_XI:[0-9a-f]+]]_bt, i32 0, i32 0) // CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_[[REF_XI:[0-9a-f]+]]_bt, i32 0, i32 0) var e: SMult2 // CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_[[REF_XI]]_bt, i32 0, i32 0) // CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_[[REF_XI]]_bt, i32 0, i32 0) var f: SMult3 // -- Single-case enum, shares layout of its field (Builtin.Int64) // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$SBi64_WV", i32 8) var g: ESing // -- Multi-case enum, open-coded layout // CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_9_8_0_pod, i32 0, i32 0) var h: EMult // -- Single-element generic struct, shares layout of its field (T) // CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[T_LAYOUT]] var i: GSing<T> // -- Multi-element generic struct, need to derive from metadata // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$S11type_layout5GMultVMa"([[INT]] 319, %swift.type* [[T_CHECKED]]) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_STATUS:%.*]] = extractvalue %swift.metadata_response [[TMP]], 1 // CHECK: [[METADATA_OK:%.*]] = icmp ule [[INT]] [[METADATA_STATUS]], 63 // CHECK: br i1 [[METADATA_OK]], // CHECK: [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1 // CHECK: [[VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]] // CHECK: [[LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[VALUE_WITNESSES]], i32 8 // CHECK: store i8** [[LAYOUT]] var j: GMult<T> // -- Common layout, reuse common value witness table layout // CHECK: store i8** getelementptr (i8*, i8** @"$SBi32_WV", i32 8) var k: CommonLayout // -- Single-field aggregate with alignment // CHECK: store i8** getelementptr (i8*, i8** @"$SBi128_WV", i32 8) var l: AlignedFourInts }
apache-2.0
ddgold/Cathedral
Cathedral/Model/Building.swift
1
9356
// // Building.swift // Cathedral // // Created by Doug Goldstein on 1/29/19. // Copyright © 2019 Doug Goldstein. All rights reserved. // import Foundation /// A building type. enum Building: UInt8 { //MARK: - Values case tavern case stable case inn case bridge case square case abbey case manor case tower case infirmary case castle case academy case cathedral //MARK: - Properties /// Set of all player buildings. static var playerBuildings: Set<Building> { return [self.tavern, self.stable, self.inn, self.bridge, self.square, self.abbey, self.manor, self.tower, self.infirmary, self.castle, self.academy] } /// The number if tiles wide this building type covers. private var width: UInt8 { switch self { case .tavern: return 1 case .stable: return 1 case .inn: return 2 case .bridge: return 1 case .square: return 2 case .abbey: return 2 case .manor: return 2 case .tower: return 3 case .infirmary: return 3 case .castle: return 2 case .academy: return 3 case .cathedral: return 3 } } /// The number of tiles tall this building type covers. private var height: UInt8 { switch self { case .tavern: return 1 case .stable: return 2 case .inn: return 2 case .bridge: return 3 case .square: return 2 case .abbey: return 3 case .manor: return 3 case .tower: return 3 case .infirmary: return 3 case .castle: return 3 case .academy: return 3 case .cathedral: return 4 } } /// The number of tiles this building type covers. var size: UInt8 { switch self { case .tavern: return 1 case .stable: return 2 case .inn: return 3 case .bridge: return 3 case .square: return 4 case .abbey: return 4 case .manor: return 4 case .tower: return 5 case .infirmary: return 5 case .castle: return 5 case .academy: return 5 case .cathedral: return 6 } } /// The log entry for this building. var log: String { switch self { case .tavern: return "TA" case .stable: return "ST" case .inn: return "IN" case .bridge: return "BR" case .square: return "SQ" case .abbey: return "AB" case .manor: return "MA" case .tower: return "TO" case .infirmary: return "IF" case .castle: return "CS" case .academy: return "AC" case .cathedral: return "CA" } } //MARK: - Initialization /// Initializes a building from a log entry. /// /// - Parameter log: The log entry. init?(_ log: String) { switch log { case "TA": self = .tavern case "ST": self = .stable case "IN": self = .inn case "BR": self = .bridge case "SQ": self = .square case "AB": self = .abbey case "MA": self = .manor case "TO": self = .tower case "IF": self = .infirmary case "CS": self = .castle case "AC": self = .academy case "CA": self = .cathedral default: return nil } } //MARK: - Functions /// Builds the blueprints for this building type based on owner, direction, and address. /// /// - Parameters: /// - owner: The owner of the building. /// - direction: The direction of the building. /// - address: The origin of the building. Defaults to (0, 0). /// - Returns: A set of addresses that make up the blueprint. func blueprint(owner: Owner, facing direction: Direction, at address: Address = Address(0, 0)) -> Set<Address> { assert(owner.isChurch == (self == .cathedral), "Can't get blueprint for \(owner) \(self)") // Get the base blueprint base on owner and building type let base: Set<Address> switch self { case .tavern: base = [Address(0, 0)] case .stable: base = [Address(0, 0), Address(0, 1)] case .inn: base = [Address(0, 0), Address(0, 1), Address(1, 0)] case .bridge: base = [Address(0, 0), Address(0, 1), Address(0, 2)] case .square: base = [Address(0, 0), Address(0, 1), Address(1, 0), Address(1, 1)] case .abbey: if (owner == .light) { base = [Address(0, 0), Address(0, 1), Address(1, 1), Address(1, 2)] } else { base = [Address(0, 1), Address(0, 2), Address(1, 0), Address(1, 1)] } case .manor: base = [Address(0, 0), Address(0, 1), Address(0, 2), Address(1, 1)] case .tower: base = [Address(0, 0), Address(0, 1), Address(1, 1), Address(1, 2), Address(2, 2)] case .infirmary: base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 1)] case .castle: base = [Address(0, 0), Address(0, 1), Address(0, 2), Address(1, 0), Address(1, 2)] case .academy: if (owner == .light) { base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 2)] } else { base = [Address(0, 2), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 1)] } case .cathedral: base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(1, 3), Address(2, 1)] } // Rotate and translate blueprint based on direction and origin var final = Set<Address>() base.forEach { (offset) in let rotated = offset.rotated(direction) final.insert(Address(address.col + rotated.col, address.row + rotated.row)) } return final } /// Get the tile width and height for this building facing a given direction. /// /// - Parameter direction: The direction. /// - Returns: A tuple, where the fist element is the width, and the second element is the height. func dimensions(direction: Direction) -> (width: Int8, height: Int8) { let width: Int8 let height: Int8 if (direction == .north) || (direction == .south) { width = Int8(self.width) height = Int8(self.height) } else { width = Int8(self.height) height = Int8(self.width) } return (width: width, height: height) } //MARK: - Descriptions /// Description of the building enum. static var description: String { return "Building" } /// Description of a particular building. var description: String { switch self { case .tavern: return "Tavern" case .stable: return "Stable" case .inn: return "Inn" case .bridge: return "Bridge" case .square: return "Square" case .abbey: return "Abbey" case .manor: return "Manor" case .tower: return "Tower" case .infirmary: return "Infirmary" case .castle: return "Castle" case .academy: return "Academy" case .cathedral: return "Cathedral" } } }
apache-2.0
Jnosh/swift
test/SILOptimizer/devirt_materializeForSet.swift
6
1352
// RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s // Check that compiler does not crash on the devirtualization of materializeForSet methods // and produces a correct code. // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T024devirt_materializeForSet7BaseFooCAA0F0A2aDP3barSSfmTW // CHECK: checked_cast_br [exact] %{{.*}} : $BaseFoo to $ChildFoo // CHECK: thin_function_to_pointer %{{.*}} : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout ChildFoo, @thick ChildFoo.Type) -> () to $Builtin.RawPointer // CHECK: enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, %{{.*}} : $Builtin.RawPointer // CHECK: tuple (%{{.*}} : $Builtin.RawPointer, %{{.*}} : $Optional<Builtin.RawPointer>) public protocol Foo { var bar: String { get set } } open class BaseFoo: Foo { open var bar: String = "hello" } open class ChildFoo: BaseFoo { private var _bar: String = "world" override open var bar: String { get { return _bar } set { _bar = newValue } } } @inline(never) public func test1(bf: BaseFoo) { bf.bar = "test1" print(bf.bar) } @inline(never) public func test2(f: Foo) { var f = f f.bar = "test2" print(f.bar) } //test1(BaseFoo()) //test1(ChildFoo()) //test2(BaseFoo()) //test2(ChildFoo())
apache-2.0
martinomamic/CarBooking
CarBooking/Helpers/Extensions/UIExtensions.swift
1
9177
// // UIExtensions.swift // CarBooking // // Created by Martino Mamic on 29/07/2017. // Copyright © 2017 Martino Mamic. All rights reserved. // import UIKit //MARK: CarBooking colors extension UIColor { class var primaryColor: UIColor { return UIColor(red: 172.0, green: 207.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0) } class var secondaryColor: UIColor { return UIColor(red: 89.0 / 255.0, green: 82.0 / 255.0, blue: 65.0 / 255.0, alpha: 1.0) } class var accentColor: UIColor { return UIColor(red: 138.0 / 255.0, green: 9.0 / 255.0, blue: 23.0 / 255.0, alpha: 1.0) } } //MARK: Storyboard enum, used in custom initializer enum Storyboard: String { // Current storyboard name case Main } //MARK: UIStoryboard extension - custom storyboard init, and generic controller instatiation extension UIStoryboard { /// Convenience init used with Storyboard enum to shorten syntax. /// /// - Parameters: /// - storyboard: Storyboard enum value. /// - bundle: Bundle containing the storyboard, optional - defaults to nil. convenience init(storyboard: Storyboard, bundle: Bundle? = nil) { self.init(name: storyboard.rawValue, bundle: bundle) } /// Generic UIViewController initializer /// /// - Returns: StoryboardIdentifiable view controller func instantiateVC<T: UIViewController>() -> T where T: StoryboardIdentifiable { let optionalViewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) guard let vc = optionalViewController as? T else { fatalError("Couldn’t instantiate view controller with identifier \(T.storyboardIdentifier)") } return vc } } //MARK: StoryboardIdentifiable initializers, alert handling. extension UIViewController : StoryboardIdentifiable { /// Instantiates generic controller from storyboard. /// Extracts storyboard identifier from view controller class. /// View controller class has to be implicit. /// /// - Parameters: /// - type: Controller class. /// - storyboard: Parent storyboard. /// - Returns: Generic view controller. func instantiateFromStoryboard<T>(type: T.Type, storyboard: UIStoryboard) -> T? { let controllerIdentifier = String(describing: type) return storyboard.instantiateViewController(withIdentifier: controllerIdentifier) as? T } /// Generic view controller initializer /// Uses generic instantiation method convenience init<T>(type: T.Type, storyboard: UIStoryboard) { self.init() _ = self.instantiateFromStoryboard(type: type, storyboard: storyboard) } /// Creates alert view controller and displays it on self /// Only dismiss action is currently provided /// /// - Parameters: /// - title: Alert title. /// - message: Alert message. func showAlert(title: String, message: String) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Alert.dismiss".localized, style: .default, handler: nil) alertVC.addAction(dismissAction) DispatchQueue.main.async { self.present(alertVC, animated: true, completion: nil) } } } //MARK: Generic cell and nib registration, generic dequeueing with and without indexpath or identifier. extension UITableView { /// Registers cell class for table view /// /// - Parameter cellClass: UITableViewCell type func register<T: UITableViewCell>(cellClass: T.Type) where T: Reusable { register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } /// Register cell view class For UITableView /// /// - Parameter _: class type func registerNib<T: UITableViewCell>(_: T.Type) where T: Reusable, T: NibLoadable { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } /// Dequeues generic table view cell type for optional indexPath and/or identifier /// If no identifier is provided idenitfier is extracted from immplicit cell type(defaultReuseIdentifier) /// /// - Parameters: /// - indexPath: IndexPath of current cell, optional - defaults to nil /// - identifier: String identifier, optional - defaults to nil, if nil defaultReuseIdentifier is used /// - Returns: Generic reusable cell func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath? = nil, identifier: String? = nil) -> T where T: Reusable { guard let indexPth = indexPath else { guard let idt = identifier else { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } guard let cell = dequeueReusableCell(withIdentifier: idt) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(idt)") } return cell } guard let idt = identifier else { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPth) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } guard let cell = dequeueReusableCell(withIdentifier: idt, for: indexPth) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } /// Used just to conform to Reusable and NibLoadable protocols extension UITableViewCell:Reusable, NibLoadable {} //MARK: UIImageView extension, handling image download extension UIImageView { /// Checks if image string is valid, then adds encoding, creates URL and starts download /// /// - Parameter imageString: Absolute URL string func loadImage(imageString: String?) { guard var imgURLString = imageString, imageString != "" else { return } imgURLString = imgURLString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)! print(imgURLString) guard let imgURL = URL(string: imgURLString) else { return } fetchImageFromURL(url: imgURL) } /// Checks if image exists in cache and returns it /// If it doesn't exist in cache attempts download /// /// - Parameter url: Image URL private func fetchImageFromURL(url: URL) { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.center = self.center activityIndicator.startAnimating() DispatchQueue.main.async { [unowned self] in self.addSubview(activityIndicator) } if let image = url.cachedImage { DispatchQueue.main.async { [unowned self] in activityIndicator.removeFromSuperview() self.image = image } } else { url.fetchImage(completion: { (image) in DispatchQueue.main.async { [unowned self] in activityIndicator.removeFromSuperview() self.image = image } }) } } } /// UIWindow extenison, activity indicator handling during requests extension UIApplication { /// Checks if window contains a view with tag 137 /// If it doesnt, creates shadow view for background and activity indicator /// If status is provided, a status label is shown under activity indicator /// /// - Parameter status: optional status string, defaults to nil func addActivityIndicator(status: String? = nil) { if let act = self.keyWindow?.subviews.filter({ $0.tag == 42 }) { if act.count == 0 { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true let shadowView = UIView(frame: self.keyWindow!.frame) shadowView.tag = 42 shadowView.backgroundColor = UIColor(red: 0.003, green: 0.003, blue: 0.003, alpha: 0.4) let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) shadowView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() activityIndicatorView.center = shadowView.center self.keyWindow!.addSubview(shadowView) } } } } /// Filters window subview for viewwith tag 137 and removes the view if it exists func removeActivityIndicator() { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.keyWindow?.subviews.filter({ $0.tag == 42 }).first?.removeFromSuperview() } } }
mit
MarioIannotta/SplitViewDragAndDrop
SplitViewDragAndDrop/SplitViewDragAndDrop+Dragger.swift
1
8151
// // SplitViewDragAndDrop+Dragger.swift // DragAndDropDemo // // Created by Mario on 26/05/2017. // Copyright © 2017 Mario. All rights reserved. // import UIKit extension SplitViewDragAndDrop { internal class Dragger: NSObject { private struct StoreKeys { static let draggingValidation = "storeKeysDraggingValidation" struct DraggingValidation { static let result = "storeKeysDraggingValidationResult" static let initialDragPoint = "storeKeysDraggingValidationInitialDragPoint" } } private var dragAndDropManager: SplitViewDragAndDrop private var initialDragPoint: CGPoint! private var viewToDragSnapshotImageView = UIImageView(frame: CGRect.zero) private var updateTriggered = false private var updateTriggeredToRight = false private var dataToTransfers = [UIView: Data]() private var identifiers = [UIView: String]() internal var draggingEndedClosure: ((_ isValid: Bool) -> Void)? internal init(dragAndDropManager: SplitViewDragAndDrop) { self.dragAndDropManager = dragAndDropManager super.init() dragAndDropManager.groupDefaults.addObserver(self, forKeyPath: StoreKeys.draggingValidation, options: .new, context: nil) } func notifyDraggingValidationResult(_ result: Bool, initialDragPoint: CGPoint) { let draggingValidationDictionary: [String: Any] = [ StoreKeys.DraggingValidation.result: result, StoreKeys.DraggingValidation.initialDragPoint: initialDragPoint ] dragAndDropManager.groupDefaults.set(NSKeyedArchiver.archivedData(withRootObject: draggingValidationDictionary), forKey: StoreKeys.draggingValidation) dragAndDropManager.groupDefaults.synchronize() } deinit { dragAndDropManager.groupDefaults.removeObserver(self, forKeyPath: StoreKeys.draggingValidation) } private func setupViewToDragSnapshotImageView(from view: UIView, centerPoint: CGPoint) { let image = view.getSnapshot() viewToDragSnapshotImageView.frame = view.frame viewToDragSnapshotImageView.center = centerPoint viewToDragSnapshotImageView.image = image UIApplication.shared.keyWindow?.addSubview(viewToDragSnapshotImageView) } internal func handleDrag(viewToDrag: UIView, identifier: String, dataToTransfer: Data? = nil) { viewToDrag.addGestureRecognizer( UIPanGestureRecognizer(target: self, action: #selector(handleGestureRecognizer(_:))) ) self.dataToTransfers[viewToDrag] = dataToTransfer self.identifiers[viewToDrag] = identifier } @objc private func handleGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) { guard let draggedView = gestureRecognizer.view, let keyWindow = UIApplication.shared.keyWindow else { return } let dragPoint = gestureRecognizer.location(in: keyWindow) switch gestureRecognizer.state { case .began: initialDragPoint = dragPoint updateTriggered = false updateTriggeredToRight = false setupViewToDragSnapshotImageView(from: draggedView, centerPoint: dragPoint) if let viewToDragSnapshotImage = viewToDragSnapshotImageView.image { dragAndDropManager.prepareForDraggingUpdate( identifier: identifiers[draggedView] ?? "", viewToDragSnapshotImage: viewToDragSnapshotImage, dataToTransfer: dataToTransfers[draggedView] ) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .began, isTriggeredToRight: updateTriggeredToRight) case .ended: if !updateTriggered { SplitViewDragAndDrop.completeDragging(isFallBack: true, draggingView: self.viewToDragSnapshotImageView, targetCenterPoint: self.initialDragPoint, completion: nil) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .ended, isTriggeredToRight: updateTriggeredToRight) default: let isToRight = gestureRecognizer.velocity(in: keyWindow).x > 0 viewToDragSnapshotImageView.center = dragPoint let shouldTriggerUpdate = isToRight ? viewToDragSnapshotImageView.frame.origin.x + viewToDragSnapshotImageView.frame.size.width >= UIWindow.width : viewToDragSnapshotImageView.frame.origin.x <= 0 if updateTriggered || shouldTriggerUpdate { if updateTriggered == false { updateTriggeredToRight = isToRight } updateTriggered = true let frame = CGRect( x: SplitViewDragAndDrop.transformXCoordinate(viewToDragSnapshotImageView.frame.origin.x, updateTriggeredToRight: updateTriggeredToRight), y: viewToDragSnapshotImageView.frame.origin.y, width: viewToDragSnapshotImageView.frame.size.width, height: viewToDragSnapshotImageView.frame.size.height ) var initialDragPoint = self.initialDragPoint ?? .zero initialDragPoint.x = SplitViewDragAndDrop.transformXCoordinate(initialDragPoint.x, updateTriggeredToRight: updateTriggeredToRight) dragAndDropManager.notifyDraggingUpdate(frame: frame, initialDragPoint: initialDragPoint) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .changed, isTriggeredToRight: updateTriggeredToRight) } } internal override func observeValue( forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath, let changedData = change?[.newKey] as? Data else { return } switch keyPath { case StoreKeys.draggingValidation: if let draggingValidation = NSKeyedUnarchiver.unarchiveObject(with: changedData) as? [String: Any], let validationResult = draggingValidation[StoreKeys.DraggingValidation.result] as? Bool, validationResult == false, let initialDragPoint = draggingValidation[StoreKeys.DraggingValidation.initialDragPoint] as? CGPoint, initialDragPoint.x > 0, initialDragPoint.x < UIWindow.width { SplitViewDragAndDrop.completeDragging(isFallBack: true, draggingView: self.viewToDragSnapshotImageView, targetCenterPoint: initialDragPoint, completion: nil) dragAndDropManager.groupDefaults.removeObject(forKey: StoreKeys.draggingValidation) } default: break } } } }
mit
samodom/FoundationSwagger
FoundationSwagger/Object/AssociatingObject.swift
1
1984
// // AssociatingObject.swift // FoundationSwagger // // Created by Sam Odom on 2/7/15. // Copyright (c) 2015 Swagger Soft. All rights reserved. // /// Common protocol for object association with pure Swift classes or `NSObject` /// (and its subclasses). public protocol AssociatingObject: class {} /// Type alias for object association keys public typealias ObjectAssociationKey = UnsafeRawPointer public extension AssociatingObject { /// Creates an association between the implementing and provided objects using the specified /// key and policy. /// - parameter value: The object or value to associate with `self`. /// - parameter key: The identifying key to use for the association. /// - parameter policy: The association policy to use for the association. public func associate( _ value: Any, with key: ObjectAssociationKey, usingPolicy policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) { objc_setAssociatedObject(self, key, value, policy) } /// Retrieves the object associated with `self` using the specified key, if any. /// - parameter for: The key identifying the association to retrieve. /// - returns: The object or value associated with `self` using the specified key, /// if such an association exist. public func association(for key: ObjectAssociationKey) -> Any? { return objc_getAssociatedObject(self, key) } /// Clears an object association for the specified key. /// - parameter key: The key identifying the association to clear. public func removeAssociation(for key: ObjectAssociationKey) { objc_setAssociatedObject(self, key, nil, .OBJC_ASSOCIATION_ASSIGN) } /// Clears all object associations on `self`. public func removeAllAssociations() { objc_removeAssociatedObjects(self) } } /// Makes all Objective-C objects object associating extension NSObject: AssociatingObject {}
mit
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/Views/FilterSliderViewModel.swift
1
1979
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// This class represents the view model for a slider filter view class FilterSliderViewModel: NSObject { var filterTitle: String! private var unitLabel: String! var minimumValue: Int! var maximumValue: Int! private var stepAmount: Int! dynamic var currentValue: NSNumber! var minimumValueText: String { return String(minimumValue) + unitLabel } var maximumValueText: String { return String(maximumValue) + unitLabel } var currentValueText: String { return currentValue.stringValue + unitLabel } var acceptedValues : [Int] = [] required init(filterTitle: String, unitLabel: String, minimumValue: Int, maximumValue: Int, stepAmount: Int, startingValue: Int) { super.init() self.filterTitle = filterTitle self.unitLabel = unitLabel self.minimumValue = minimumValue self.maximumValue = maximumValue self.stepAmount = stepAmount self.currentValue = startingValue self.calculateAcceptedValues() } /** Based on the minimum, maximum, and step amount values, this calculates the number of accepted values on the slider */ private func calculateAcceptedValues() { for var i = minimumValue; i <= maximumValue; i = i + self.stepAmount { acceptedValues.append(i) } } /** Based on the current amount, round to the nearest accepted value - parameter value: The current value of the slider */ func updateCurrentAmount(value: Float) { let roundedValue = Int(floor(value)) let remainder = roundedValue % stepAmount let middleValue = stepAmount / 2 if remainder <= middleValue { currentValue = roundedValue - remainder } else { currentValue = roundedValue + stepAmount - remainder } } }
epl-1.0
apple/swift-nio-extras
Tests/NIOExtrasTests/DebugOutboundEventsHandlerTest.swift
1
3454
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore import NIOEmbedded import NIOExtras class DebugOutboundEventsHandlerTest: XCTestCase { private var channel: EmbeddedChannel! private var lastEvent: DebugOutboundEventsHandler.Event! private var handlerUnderTest: DebugOutboundEventsHandler! override func setUp() { super.setUp() channel = EmbeddedChannel() handlerUnderTest = DebugOutboundEventsHandler { event, _ in self.lastEvent = event } try? channel.pipeline.addHandler(handlerUnderTest).wait() } override func tearDown() { channel = nil lastEvent = nil handlerUnderTest = nil super.tearDown() } func testRegister() { channel.pipeline.register(promise: nil) XCTAssertEqual(lastEvent, .register) } func testBind() throws { let address = try SocketAddress(unixDomainSocketPath: "path") channel.bind(to: address, promise: nil) XCTAssertEqual(lastEvent, .bind(address: address)) } func testConnect() throws { let address = try SocketAddress(unixDomainSocketPath: "path") channel.connect(to: address, promise: nil) XCTAssertEqual(lastEvent, .connect(address: address)) } func testWrite() { let data = NIOAny(" 1 2 3 ") channel.write(data, promise: nil) XCTAssertEqual(lastEvent, .write(data: data)) } func testFlush() { channel.flush() XCTAssertEqual(lastEvent, .flush) } func testRead() { channel.read() XCTAssertEqual(lastEvent, .read) } func testClose() { channel.close(mode: .all, promise: nil) XCTAssertEqual(lastEvent, .close(mode: .all)) } func testTriggerUserOutboundEvent() { let event = "user event" channel.triggerUserOutboundEvent(event, promise: nil) XCTAssertEqual(lastEvent, .triggerUserOutboundEvent(event: event)) } } extension DebugOutboundEventsHandler.Event: Equatable { public static func == (lhs: DebugOutboundEventsHandler.Event, rhs: DebugOutboundEventsHandler.Event) -> Bool { switch (lhs, rhs) { case (.register, .register): return true case (.bind(let address1), .bind(let address2)): return address1 == address2 case (.connect(let address1), .connect(let address2)): return address1 == address2 case (.write(let data1), .write(let data2)): return "\(data1)" == "\(data2)" case (.flush, .flush): return true case (.read, .read): return true case (.close(let mode1), .close(let mode2)): return mode1 == mode2 case (.triggerUserOutboundEvent(let event1), .triggerUserOutboundEvent(let event2)): return "\(event1)" == "\(event2)" default: return false } } }
apache-2.0
trujillo138/MyExpenses
MyExpenses/MyExpenses/Scenes/ExpensePeriod/ExpensesDataSource.swift
1
2119
// // ExpensesDataSource.swift // MyExpenses // // Created by Tomas Trujillo on 6/27/17. // Copyright © 2017 TOMApps. All rights reserved. // import UIKit class ExpensesDataSource: NSObject, UITableViewDataSource { //MARK: Properties var expensePeriod: ExpensePeriod var cellIdentifier: String var expenses: [Expense] { if let filterAtt = filterAttribute, let sortAtt = sortAttribute { return expensePeriod.filterAndSortExpensesBy(filter: filterAtt, fromValue: ascendingValue, toValue: descendingValue, option: sortAtt, ascending: ascending) } else if let filterAtt = filterAttribute { return expensePeriod.filterExpensesBy(filter: filterAtt, fromValue: ascendingValue, toValue: descendingValue) } else if let sortAtt = sortAttribute { return expensePeriod.sortExpensesBy(option: sortAtt, ascending: ascending) } else { return expensePeriod.expenses } } var sortAttribute: ExpensePeriodSortOption? var ascending = true var filterAttribute: ExpensePeriodFilterOption? var ascendingValue: Any? var descendingValue: Any? //MARK: Initializers init(expensePeriod: ExpensePeriod, cellIdentifier: String) { self.expensePeriod = expensePeriod self.cellIdentifier = cellIdentifier } //MARK: Tableview datasource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return expenses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let expenseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? ExpenseCell else { return UITableViewCell() } let expense = expenses[indexPath.row] let expenseCellModel = ExpenseCellModel(expense: expense) expenseCell.model = expenseCellModel return expenseCell } }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/09427-swift-archetypetype-setnestedtypes.swift
11
272
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { class A { struct B { { } protocol P { extension A { extension A { B protocol A { class case c, var f
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/10092-swift-sourcemanager-getmessage.swift
11
218
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol B { class a { func g { ( { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/04863-swift-sourcemanager-getmessage.swift
11
219
// 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 A { let end = compose([Void{ class case c,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09956-swift-archetypetype-setnestedtypes.swift
11
287
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { if true { class b { struct S { protocol A { protocol b { { { } } } func e<I : e func b<I : A protocol A : e
mit
austinzheng/swift-compiler-crashes
fixed/26990-swift-importdecl-findbestimportkind.swift
4
221
// 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 a{{{for{}{{}{{}var{let a{f=a{let:{let a{class B
mit
kuler90/OrangeFramework
Source/Extensions/Core/Array/Array+OFExtension.swift
1
361
public extension Array { public func of_safeElement(index: Int) -> Element? { return index < count ? self[index] : nil } } public extension Array where Element: Equatable { public mutating func of_remove(element: Element) { for index in (0..<count).reverse() where self[index] == element { self.removeAtIndex(index) } } }
mit
devcarlos/RappiApp
RappiApp/Classes/Managers/API/AppRouter.swift
1
1093
// // PlaceRouter.swift // RappiApp // // Created by Carlos Alcala on 7/1/16. // Copyright © 2016 Carlos Alcala. All rights reserved. // import Foundation import Alamofire enum AppEndpoint { case GetApps(limit: Int) } class AppRouter : BaseRouter { var endpoint: AppEndpoint init(endpoint: AppEndpoint) { self.endpoint = endpoint } override var method: Alamofire.Method { switch endpoint { case .GetApps: return .GET } } override var path: String { switch endpoint { //we can make this URL more dynamic sending parameters case .GetApps(let limit): let path = "limit=\(limit)/json" return path } } override var parameters: APIParams { switch endpoint { case .GetApps(let limit): NSLog("LIMIT \(limit)") return [:] } } override var encoding: Alamofire.ParameterEncoding? { switch endpoint { case .GetApps: return .URL } } }
mit
brave/browser-ios
Client/Frontend/Browser/URLBarView.swift
1
24956
/* 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 import UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger struct URLBarViewUX { static let TextFieldContentInset = UIOffsetMake(9, 5) static let LocationLeftPadding = 5 static let LocationHeight = 34 static let LocationInset = 5 static let LocationContentOffset: CGFloat = 8 static let TextFieldCornerRadius: CGFloat = 6 static let TextFieldBorderWidth: CGFloat = 0 // offset from edge of tabs button static let URLBarCurveOffset: CGFloat = 46 static let URLBarCurveOffsetLeft: CGFloat = -10 // buffer so we dont see edges when animation overshoots with spring static let URLBarCurveBounceBuffer: CGFloat = 8 static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1) static let TabsButtonRotationOffset: CGFloat = 1.5 static let TabsButtonHeight: CGFloat = 18.0 static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.tintColor = UIConstants.PrivateModePurple theme.textColor = .white theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor theme.backgroundColor = BraveUX.LocationContainerBackgroundColor_PrivateMode themes[Theme.PrivateMode] = theme theme = Theme() theme.tintColor = URLBarViewUX.ProgressTintColor theme.textColor = BraveUX.LocationBarTextColor theme.buttonTintColor = BraveUX.ActionButtonTintColor theme.backgroundColor = BraveUX.LocationContainerBackgroundColor themes[Theme.NormalMode] = theme return themes }() static func backgroundColorWithAlpha(_ alpha: CGFloat) -> UIColor { return UIConstants.AppBackgroundColor.withAlphaComponent(alpha) } } protocol URLBarDelegate: class { func urlBarDidPressTabs(_ urlBar: URLBarView) func urlBarDidPressReaderMode(_ urlBar: URLBarView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool func urlBarDidPressStop(_ urlBar: URLBarView) func urlBarDidPressReload(_ urlBar: URLBarView) func urlBarDidEnterSearchMode(_ urlBar: URLBarView) func urlBarDidLeaveSearchMode(_ urlBar: URLBarView) func urlBarDidLongPressLocation(_ urlBar: URLBarView) func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? func urlBarDidPressScrollToTop(_ urlBar: URLBarView) func urlBar(_ urlBar: URLBarView, didEnterText text: String) func urlBar(_ urlBar: URLBarView, didSubmitText text: String) func urlBarDisplayTextForURL(_ url: URL?) -> String? } class URLBarView: UIView { weak var delegate: URLBarDelegate? weak var browserToolbarDelegate: BrowserToolbarDelegate? var helper: BrowserToolbarHelper? var isTransitioning: Bool = false { didSet { if isTransitioning { } } } fileprivate var currentTheme: String = Theme.NormalMode var bottomToolbarIsHidden = false var locationTextField: ToolbarTextField? /// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown, /// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode /// is *not* tied to the location text field's editing state; for instance, when selecting /// a panel, the first responder will be resigned, yet the overlay mode UI is still active. var inSearchMode = false lazy var locationView: BrowserLocationView = { let locationView = BrowserLocationView() locationView.translatesAutoresizingMaskIntoConstraints = false locationView.readerModeState = ReaderModeState.Unavailable locationView.delegate = self return locationView }() lazy var locationContainer: UIView = { let locationContainer = UIView() locationContainer.translatesAutoresizingMaskIntoConstraints = false // Enable clipping to apply the rounded edges to subviews. locationContainer.clipsToBounds = true locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth return locationContainer }() lazy var tabsButton: TabsButton = { let tabsButton = TabsButton() tabsButton.titleLabel.text = "0" tabsButton.addTarget(self, action: #selector(URLBarView.SELdidClickAddTab), for: UIControlEvents.touchUpInside) tabsButton.accessibilityIdentifier = "URLBarView.tabsButton" tabsButton.accessibilityLabel = Strings.Show_Tabs return tabsButton }() lazy var cancelButton: UIButton = { let cancelButton = InsetButton() cancelButton.setTitleColor(BraveUX.GreyG, for: .normal) let cancelTitle = Strings.Cancel cancelButton.setTitle(cancelTitle, for: UIControlState.normal) cancelButton.titleLabel?.font = UIConstants.DefaultChromeFont cancelButton.addTarget(self, action: #selector(URLBarView.SELdidClickCancel), for: UIControlEvents.touchUpInside) cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12) cancelButton.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: UILayoutConstraintAxis.horizontal) cancelButton.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: UILayoutConstraintAxis.horizontal) cancelButton.alpha = 0 return cancelButton }() lazy var scrollToTopButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(URLBarView.SELtappedScrollToTopArea), for: UIControlEvents.touchUpInside) return button }() // TODO: After protocol removal, check what is necessary here lazy var shareButton: UIButton = { return UIButton() }() lazy var pwdMgrButton: UIButton = { return UIButton() }() lazy var forwardButton: UIButton = { return UIButton() }() lazy var backButton: UIButton = { return UIButton() }() // Required solely for protocol conforming lazy var addTabButton = { return UIButton() }() var actionButtons: [UIButton] { return [self.shareButton, self.forwardButton, self.backButton, self.pwdMgrButton, self.addTabButton] } // Used to temporarily store the cloned button so we can respond to layout changes during animation fileprivate weak var clonedTabsButton: TabsButton? fileprivate var rightBarConstraint: Constraint? fileprivate let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer var currentURL: URL? { get { return locationView.url } set(newURL) { locationView.url = newURL } } func updateTabsBarShowing() {} override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { backgroundColor = BraveUX.ToolbarsBackgroundSolidColor addSubview(scrollToTopButton) addSubview(tabsButton) addSubview(cancelButton) addSubview(shareButton) addSubview(pwdMgrButton) addSubview(forwardButton) addSubview(backButton) locationContainer.addSubview(locationView) addSubview(locationContainer) helper = BrowserToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForSearchModeAndToolbarChanges() } func setupConstraints() {} override func updateConstraints() { super.updateConstraints() } func createLocationTextField() { guard locationTextField == nil else { return } locationTextField = ToolbarTextField() guard let locationTextField = locationTextField else { return } locationTextField.translatesAutoresizingMaskIntoConstraints = false locationTextField.autocompleteDelegate = self locationTextField.keyboardType = UIKeyboardType.webSearch locationTextField.keyboardAppearance = .dark locationTextField.autocorrectionType = UITextAutocorrectionType.no locationTextField.autocapitalizationType = UITextAutocapitalizationType.none locationTextField.returnKeyType = UIReturnKeyType.go locationTextField.clearButtonMode = UITextFieldViewMode.whileEditing locationTextField.font = UIConstants.DefaultChromeFont locationTextField.accessibilityIdentifier = "address" locationTextField.accessibilityLabel = Strings.Address_and_Search locationTextField.attributedPlaceholder = NSAttributedString(string: self.locationView.placeholder.string, attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray]) locationContainer.addSubview(locationTextField) locationTextField.snp.makeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } locationTextField.applyTheme(currentTheme) } func removeLocationTextField() { locationTextField?.removeFromSuperview() locationTextField = nil } // Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without // However, switching views dynamically at runtime is a difficult. For now, we just use one view // that can show in either mode. func hideBottomToolbar(_ isHidden: Bool) { bottomToolbarIsHidden = isHidden setNeedsUpdateConstraints() // when we transition from portrait to landscape, calling this here causes // the constraints to be calculated too early and there are constraint errors if !bottomToolbarIsHidden { updateConstraintsIfNeeded() } updateViewsForSearchModeAndToolbarChanges() } func updateAlphaForSubviews(_ alpha: CGFloat) { self.tabsButton.alpha = alpha self.locationContainer.alpha = alpha self.actionButtons.forEach { $0.alpha = alpha } } func updateTabCount(_ count: Int, animated: Bool = true) { URLBarView.updateTabCount(tabsButton, clonedTabsButton: &clonedTabsButton, count: count, animated: animated) } class func updateTabCount(_ tabsButton: TabsButton, clonedTabsButton: inout TabsButton?, count: Int, animated: Bool = true) { let newCount = "\(getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.count)" tabsButton.accessibilityValue = newCount tabsButton.titleLabel.text = newCount } func updateProgressBar(_ progress: Float, dueToTabChange: Bool = false) { return // use Brave override only } func updateReaderModeState(_ state: ReaderModeState) { locationView.readerModeState = state // Brave uses custom reader mode toolbar attached to the bottom of URL bar, // after each reader mode change the toolbar needs to be toggled (self as! BraveURLBarView).readerModeToolbar.isHidden = state != .Active } func setAutocompleteSuggestion(_ suggestion: String?) { locationTextField?.setAutocompleteSuggestion(suggestion) } func enterSearchMode(_ locationText: String?, pasted: Bool) { createLocationTextField() // Show the overlay mode UI, which includes hiding the locationView and replacing it // with the editable locationTextField. animateToSearchState(searchMode: true) delegate?.urlBarDidEnterSearchMode(self) // Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens // won't take the initial frame of the label into consideration, which makes the label // look squished at the start of the animation and expand to be correct. As a workaround, // we becomeFirstResponder as the next event on UI thread, so the animation starts before we // set a first responder. if pasted { // Clear any existing text, focus the field, then set the actual pasted text. // This avoids highlighting all of the text. self.locationTextField?.text = "" DispatchQueue.main.async { self.locationTextField?.becomeFirstResponder() self.locationTextField?.text = locationText } } else { // Copy the current URL to the editable text field, then activate it. self.locationTextField?.text = locationText // something is resigning the first responder immediately after setting it. A short delay for events to process fixes it. postAsyncToMain(0.1) { self.locationTextField?.becomeFirstResponder() } } } func leaveSearchMode(didCancel cancel: Bool = false) { locationTextField?.resignFirstResponder() animateToSearchState(searchMode: false, didCancel: cancel) delegate?.urlBarDidLeaveSearchMode(self) } func prepareSearchAnimation() { // Make sure everything is showing during the transition (we'll hide it afterwards). self.bringSubview(toFront: self.locationContainer) self.cancelButton.isHidden = false self.shareButton.isHidden = !self.bottomToolbarIsHidden self.forwardButton.isHidden = !self.bottomToolbarIsHidden self.backButton.isHidden = !self.bottomToolbarIsHidden } func transitionToSearch(_ didCancel: Bool = false) { self.cancelButton.alpha = inSearchMode ? 1 : 0 self.shareButton.alpha = inSearchMode ? 0 : 1 self.forwardButton.alpha = inSearchMode ? 0 : 1 self.backButton.alpha = inSearchMode ? 0 : 1 if inSearchMode { self.cancelButton.transform = CGAffineTransform.identity let tabsButtonTransform = CGAffineTransform(translationX: self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, y: 0) self.tabsButton.transform = tabsButtonTransform self.clonedTabsButton?.transform = tabsButtonTransform self.rightBarConstraint?.update(offset: URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width) // Make the editable text field span the entire URL bar, covering the lock and reader icons. self.locationTextField?.snp.remakeConstraints { make in make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset) make.top.bottom.trailing.equalTo(self.locationContainer) } } else { self.tabsButton.transform = CGAffineTransform.identity self.clonedTabsButton?.transform = CGAffineTransform.identity self.cancelButton.transform = CGAffineTransform(translationX: self.cancelButton.frame.width, y: 0) self.rightBarConstraint?.update(offset: defaultRightOffset) // Shrink the editable text field back to the size of the location view before hiding it. self.locationTextField?.snp.remakeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } } } func updateViewsForSearchModeAndToolbarChanges() { self.cancelButton.isHidden = !inSearchMode self.shareButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode self.forwardButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode self.backButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode } func animateToSearchState(searchMode search: Bool, didCancel cancel: Bool = false) { prepareSearchAnimation() layoutIfNeeded() inSearchMode = search if !search { removeLocationTextField() } UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { self.transitionToSearch(cancel) self.setNeedsUpdateConstraints() self.layoutIfNeeded() }, completion: { _ in self.updateViewsForSearchModeAndToolbarChanges() }) } @objc func SELdidClickAddTab() { delegate?.urlBarDidPressTabs(self) } @objc func SELdidClickCancel() { leaveSearchMode(didCancel: true) } @objc func SELtappedScrollToTopArea() { delegate?.urlBarDidPressScrollToTop(self) } } extension URLBarView: BrowserToolbarProtocol { func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } @objc func updateBookmarkStatus(_ isBookmarked: Bool) { getApp().braveTopViewController.updateBookmarkStatus(isBookmarked) } func updateReloadStatus(_ isLoading: Bool) { locationView.stopReloadButtonIsLoading(isLoading) } func updatePageStatus(_ isWebPage: Bool) { locationView.stopReloadButton.isEnabled = isWebPage shareButton.isEnabled = isWebPage } override var accessibilityElements: [Any]? { get { if inSearchMode { guard let locationTextField = locationTextField else { return nil } return [locationTextField, cancelButton] } else { if bottomToolbarIsHidden { return [backButton, forwardButton, locationView, shareButton, tabsButton] } else { return [locationView, tabsButton] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: BrowserLocationViewDelegate { func browserLocationViewDidLongPressReaderMode(_ browserLocationView: BrowserLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func browserLocationViewDidTapLocation(_ browserLocationView: BrowserLocationView) { let locationText = delegate?.urlBarDisplayTextForURL(locationView.url) enterSearchMode(locationText, pasted: false) } func browserLocationViewDidLongPressLocation(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidLongPressLocation(self) } func browserLocationViewDidTapReload(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReload(self) } func browserLocationViewDidTapStop(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressStop(self) } func browserLocationViewDidTapReaderMode(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReaderMode(self) } func browserLocationViewLocationAccessibilityActions(_ browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool { guard let text = locationTextField?.text else { return true } delegate?.urlBar(self, didSubmitText: text) return true } func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) { delegate?.urlBar(self, didEnterText: text) } func autocompleteTextFieldDidBeginEditing(_ autocompleteTextField: AutocompleteTextField) { autocompleteTextField.highlightAll() } func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didEnterText: "") return true } } // MARK: UIAppearance extension URLBarView { @objc dynamic var cancelTextColor: UIColor? { get { return cancelButton.titleColor(for: .normal) } set { return cancelButton.setTitleColor(newValue, for: .normal) } } @objc dynamic var actionButtonTintColor: UIColor? { get { return helper?.buttonTintColor } set { guard let value = newValue else { return } helper?.buttonTintColor = value } } } extension URLBarView: Themeable { func applyTheme(_ themeName: String) { locationView.applyTheme(themeName) locationTextField?.applyTheme(themeName) guard let theme = URLBarViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } currentTheme = themeName cancelTextColor = theme.textColor actionButtonTintColor = theme.buttonTintColor locationContainer.backgroundColor = theme.backgroundColor tabsButton.applyTheme(themeName) } } /* Code for drawing the urlbar curve */ class CurveView: UIView {} class ToolbarTextField: AutocompleteTextField { static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.backgroundColor = BraveUX.LocationBarEditModeBackgroundColor_Private theme.textColor = BraveUX.LocationBarEditModeTextColor_Private theme.buttonTintColor = UIColor.white theme.highlightColor = UIConstants.PrivateModeTextHighlightColor themes[Theme.PrivateMode] = theme theme = Theme() theme.backgroundColor = BraveUX.LocationBarEditModeBackgroundColor theme.textColor = BraveUX.LocationBarEditModeTextColor theme.highlightColor = AutocompleteTextFieldUX.HighlightColor themes[Theme.NormalMode] = theme return themes }() @objc dynamic var clearButtonTintColor: UIColor? { didSet { // Clear previous tinted image that's cache and ask for a relayout tintedClearImage = nil setNeedsLayout() } } fileprivate var tintedClearImage: UIImage? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // Since we're unable to change the tint color of the clear image, we need to iterate through the // subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip: // http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield for view in subviews as [UIView] { if let button = view as? UIButton { if let image = button.image(for: .normal) { if tintedClearImage == nil { tintedClearImage = tintImage(image, color: clearButtonTintColor) } if button.imageView?.image != tintedClearImage { button.setImage(tintedClearImage, for: .normal) } } } } } fileprivate func tintImage(_ image: UIImage, color: UIColor?) -> UIImage { guard let color = color else { return image } let size = image.size UIGraphicsBeginImageContextWithOptions(size, false, 2) let context = UIGraphicsGetCurrentContext() image.draw(at: CGPoint.zero, blendMode: CGBlendMode.normal, alpha: 1.0) context!.setFillColor(color.cgColor) context!.setBlendMode(CGBlendMode.sourceIn) context!.setAlpha(1.0) let rect = CGRect( x: CGPoint.zero.x, y: CGPoint.zero.y, width: image.size.width, height: image.size.height) UIGraphicsGetCurrentContext()!.fill(rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage! } } extension ToolbarTextField: Themeable { func applyTheme(_ themeName: String) { guard let theme = ToolbarTextField.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } backgroundColor = theme.backgroundColor textColor = theme.textColor clearButtonTintColor = theme.buttonTintColor highlightColor = theme.highlightColor! } }
mpl-2.0
brave/browser-ios
brave/src/frontend/PicklistSetting.swift
1
5359
/* 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 Shared protocol PicklistSettingOptionsViewDelegate { func picklistSetting(_ setting: PicklistSettingOptionsView, pickedOptionId: Int) } class PicklistSettingOptionsView: UITableViewController { var options = [(displayName: String, id: Int)]() var headerTitle = "" var delegate: PicklistSettingOptionsViewDelegate? var initialIndex = -1 var footerMessage = "" convenience init(options: [(displayName: String, id: Int)], title: String, current: Int, footerMessage: String) { self.init(style: UITableViewStyle.grouped) self.options = options self.headerTitle = title self.initialIndex = current self.footerMessage = footerMessage } override init(style: UITableViewStyle) { super.init(style: style) } // Here due to 8.x bug: https://openradar.appspot.com/23709930 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.textLabel?.text = options[indexPath.row].displayName // cell.tag = options[indexPath.row].uniqueId --> if we want to decouple row order from option order in future if initialIndex == indexPath.row { cell.accessoryType = .checkmark } return cell } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return footerMessage } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return headerTitle } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { navigationController?.popViewController(animated: true) delegate?.picklistSetting(self, pickedOptionId: options[indexPath.row].id) return nil } // Don't show delete button on the left. override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.none } // Don't reserve space for the delete button on the left. override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } } //typealias PicklistSettingChoice = (displayName: String, internalObject: AnyObject, optionId: Int) struct Choice<T> { let item: (Void) -> (displayName: String, object: T, optionId: Int) } class PicklistSettingMainItem<T>: Setting, PicklistSettingOptionsViewDelegate { let profile: Profile let prefName: String let displayName: String let options: [Choice<T>] var picklistFooterMessage = "" override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { let currentId = getCurrent() let option = lookupOptionById(Int(currentId)) return NSAttributedString(string: option?.item(()).displayName ?? "", attributes: [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13)]) } func lookupOptionById(_ id: Int) -> Choice<T>? { for option in options { if option.item(()).optionId == id { return option } } return nil } func getCurrent() -> Int { return Int(BraveApp.getPrefs()?.intForKey(prefName) ?? 0) } init(profile: Profile, displayName: String, prefName: String, options: [Choice<T>]) { self.profile = profile self.displayName = displayName self.prefName = prefName self.options = options super.init(title: NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } var picklist: PicklistSettingOptionsView? // on iOS8 there is a crash, seems like it requires this to be retained override func onClick(_ navigationController: UINavigationController?) { picklist = PicklistSettingOptionsView(options: options.map { ($0.item(()).displayName, $0.item(()).optionId) }, title: displayName, current: getCurrent(), footerMessage: picklistFooterMessage) navigationController?.pushViewController(picklist!, animated: true) picklist!.delegate = self } func picklistSetting(_ setting: PicklistSettingOptionsView, pickedOptionId: Int) { profile.prefs.setInt(Int32(pickedOptionId), forKey: prefName) } }
mpl-2.0
squarefrog/dailydesktop
DailyDesktop/Extensions/DateFormatter+bing.swift
1
322
// Copyright © 2019 Paul Williamson. All rights reserved. import Foundation /// A date formatter for the dates returned by the Bing API extension DateFormatter { static let bing: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" return formatter }() }
mit
gvzq/iOS-Twitter
Twitter/ComposeViewController.swift
1
4048
// // ComposeViewController.swift // Twitter // // Created by Gerardo Vazquez on 2/23/16. // Copyright © 2016 Gerardo Vazquez. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var charsLeftLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.barTintColor = UIColor(red: 0.5, green: 0.8, blue: 1.0, alpha: 1.0) self.navigationController!.navigationBar.tintColor = UIColor.whiteColor() self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] textView.delegate = self if (textView.text == "") { textViewDidEndEditing(textView) } let tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard") self.view.addGestureRecognizer(tapDismiss) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard(){ textView.resignFirstResponder() } func textViewDidEndEditing(textView: UITextView) { if (textView.text == "") { textView.text = "Tweet something!" textView.textColor = UIColor.lightGrayColor() } textView.resignFirstResponder() } func textViewDidBeginEditing(textView: UITextView){ if (textView.textColor == UIColor.lightGrayColor()){ textView.text = "" textView.textColor = UIColor.blackColor() } textView.becomeFirstResponder() } func textViewDidChange(textView: UITextView) { checkRemainingCharacters() } func checkRemainingCharacters() { let allowedChars = 140 let charsInTextView = textView.text.characters.count let remainingChars = allowedChars - charsInTextView charsLeftLabel.text = "\(remainingChars)" if remainingChars <= 10 { charsLeftLabel.textColor = UIColor.redColor() } else if remainingChars <= 20 { charsLeftLabel.textColor = UIColor.orangeColor() } else { charsLeftLabel.textColor = UIColor.blackColor() } } @IBAction func onCancelButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onTweetButton(sender: AnyObject) { let allowedChars = 140 let charsInTextView = textView.text.characters.count let remainingChars = allowedChars - charsInTextView if remainingChars < 0 { let alert = UIAlertController(title: "Too many words in this tweet.", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { var message = textView.text!.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) message = message.stringByReplacingOccurrencesOfString("#", withString: "%23", options: NSStringCompareOptions.LiteralSearch, range: nil) message = message.stringByReplacingOccurrencesOfString("'", withString: "%27", options: NSStringCompareOptions.LiteralSearch, range: nil) TwitterClient.sharedInstance.tweet(message) dismissViewControllerAnimated(true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
welbesw/BigcommerceApi
Example/BigcommerceApi/EditInvetoryViewController.swift
1
2518
// // EditInvetoryViewController.swift // BigcommerceApi // // Created by William Welbes on 10/1/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import BigcommerceApi class EditInvetoryViewController: UIViewController { @IBOutlet weak var textField:UITextField! var product:BigcommerceProduct! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let inventoryLevel = product.inventoryLevel { self.textField.text = inventoryLevel.stringValue } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapSaveButton() { if let newLevelString = self.textField.text { if let newLevel = Int(newLevelString) { if let productIdString = self.product.productId?.stringValue { if let inventoryTrackingType = InventoryTrackingType(rawValue: self.product.inventoryTracking) { BigcommerceApi.sharedInstance.updateProductInventory(productIdString, trackInventory: inventoryTrackingType, newInventoryLevel: newLevel, newLowLevel: nil, completion: { (error) -> () in DispatchQueue.main.async(execute: { () -> Void in //Handle error if(error == nil) { self.product.inventoryLevel = NSNumber(value: newLevel) self.dismiss(animated: true, completion: nil) } else { print("Error updating inventory level: \(error!.localizedDescription)") } }) }) } } } } } @IBAction func didTapCancelButton() { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
rsmoz/swift-corelibs-foundation
Foundation/NSDecimalNumber.swift
1
6641
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /*************** Exceptions ***********/ public let NSDecimalNumberExactnessException: String = "NSDecimalNumberExactnessException" public let NSDecimalNumberOverflowException: String = "NSDecimalNumberOverflowException" public let NSDecimalNumberUnderflowException: String = "NSDecimalNumberUnderflowException" public let NSDecimalNumberDivideByZeroException: String = "NSDecimalNumberDivideByZeroException" /*************** Rounding and Exception behavior ***********/ public protocol NSDecimalNumberBehaviors { func roundingMode() -> NSRoundingMode func scale() -> Int16 // The scale could return NO_SCALE for no defined scale. } // Receiver can raise, return a new value, or return nil to ignore the exception. /*************** NSDecimalNumber: the class ***********/ public class NSDecimalNumber : NSNumber { public convenience init(mantissa: UInt64, exponent: Int16, isNegative flag: Bool) { NSUnimplemented() } public init(decimal dcm: NSDecimal) { NSUnimplemented() } public convenience init(string numberValue: String?) { NSUnimplemented() } public convenience init(string numberValue: String?, locale: AnyObject?) { NSUnimplemented() } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public required convenience init(floatLiteral value: Double) { NSUnimplemented() } public required convenience init(booleanLiteral value: Bool) { NSUnimplemented() } public required convenience init(integerLiteral value: Int) { NSUnimplemented() } public func descriptionWithLocale(locale: AnyObject?) -> String { NSUnimplemented() } // TODO: "declarations from extensions cannot be overridden yet" // Although it's not clear we actually need to redeclare this here when the extension adds it to the superclass of this class // public var decimalValue: NSDecimal { NSUnimplemented() } public class func zero() -> NSDecimalNumber { NSUnimplemented() } public class func one() -> NSDecimalNumber { NSUnimplemented() } public class func minimumDecimalNumber() -> NSDecimalNumber { NSUnimplemented() } public class func maximumDecimalNumber() -> NSDecimalNumber { NSUnimplemented() } public class func notANumber() -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByAdding(decimalNumber: NSDecimalNumber) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByAdding(decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberBySubtracting(decimalNumber: NSDecimalNumber) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberBySubtracting(decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByMultiplyingBy(decimalNumber: NSDecimalNumber) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByMultiplyingBy(decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByDividingBy(decimalNumber: NSDecimalNumber) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByDividingBy(decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByRaisingToPower(power: Int) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByRaisingToPower(power: Int, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByMultiplyingByPowerOf10(power: Int16) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByMultiplyingByPowerOf10(power: Int16, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } public func decimalNumberByRoundingAccordingToBehavior(behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber { NSUnimplemented() } // Round to the scale of the behavior. public override func compare(decimalNumber: NSNumber) -> NSComparisonResult { NSUnimplemented() } // compare two NSDecimalNumbers public class func setDefaultBehavior(behavior: NSDecimalNumberBehaviors) { NSUnimplemented() } public class func defaultBehavior() -> NSDecimalNumberBehaviors { NSUnimplemented() } // One behavior per thread - The default behavior is // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException // raise on overflow, underflow and divide by zero. public var objCType: UnsafePointer<Int8> { NSUnimplemented() } // return 'd' for double public override var doubleValue: Double { NSUnimplemented() } } // return an approximate double value /*********** A class for defining common behaviors *******/ public class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding { public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public class func defaultDecimalNumberHandler() -> NSDecimalNumberHandler{ NSUnimplemented() } // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException (return nil) // raise on overflow, underflow and divide by zero. public init(roundingMode: NSRoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) { NSUnimplemented() } public func roundingMode() -> NSRoundingMode { NSUnimplemented() } public func scale() -> Int16 { NSUnimplemented() } // The scale could return NO_SCALE for no defined scale. } extension NSNumber { public var decimalValue: NSDecimal { NSUnimplemented() } } // Could be silently inexact for float and double. extension NSScanner { public func scanDecimal(dcm: UnsafeMutablePointer<NSDecimal>) -> Bool { NSUnimplemented() } }
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01073-swift-constraints-constraintgraphnode-addconstraint.swift
1
525
// 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 class A : Sequence> (Any) -> Any in var d { protocol a { protocol a { } var e!((t.Type) { class a".init(T! { typealias b : b.E
apache-2.0
appsembler/edx-app-ios
Test/SnapshotTestCase.swift
1
5243
// // SnapshotTestCase // edX // // Created by Akiva Leffert on 5/14/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation private let StandardTolerance : CGFloat = 0.005 protocol SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws var snapshotSize : CGSize { get } } extension UIView : SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfView(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } var snapshotSize : CGSize { return bounds.size } } extension CALayer : SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfLayer(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } var snapshotSize : CGSize { return bounds.size } } extension UIViewController : SnapshotTestable { func prepareForSnapshot() { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = self window.makeKeyAndVisible() } func snapshotTestWithCase(testCase: FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfView(self.view, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } func finishSnapshot() { view.window?.removeFromSuperview() } var snapshotSize : CGSize { return view.bounds.size } } class SnapshotTestCase : FBSnapshotTestCase { override func setUp() { super.setUp() // Run "./gradlew recordSnapshots --continue" to regenerate all snapshots #if RECORD_SNAPSHOTS recordMode = true #endif } var screenSize : CGSize { // Standardize on a size so we don't have to worry about different simulators // etc. // Pick a non standard width so we can catch width assumptions. return CGSizeMake(380, 568) } private var majorVersion : Int { return NSProcessInfo.processInfo().operatingSystemVersion.majorVersion } private final func qualifyIdentifier(identifier : String?, content : SnapshotTestable) -> String { let rtl = UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft ? "_rtl" : "" let suffix = "ios\(majorVersion)\(rtl)_\(Int(content.snapshotSize.width))x\(Int(content.snapshotSize.height))" if let identifier = identifier { return identifier + suffix } else { return suffix } } // Asserts that a snapshot matches expectations // This is similar to the objc only FBSnapshotTest macros // But works in swift func assertSnapshotValidWithContent(content : SnapshotTestable, identifier : String? = nil, message : String? = nil, file : StaticString = #file, line : UInt = #line) { let qualifiedIdentifier = qualifyIdentifier(identifier, content : content) do { try content.snapshotTestWithCase(self, referenceImagesDirectory: SNAPSHOT_TEST_DIR, identifier: qualifiedIdentifier) } catch let error as NSError { let unknownError = "Unknown Error" XCTFail("Snapshot comparison failed (\(qualifiedIdentifier)): \(error.localizedDescription ?? unknownError)", file : file, line : line) if let message = message { XCTFail(message, file : file, line : line) } else { XCTFail(file : file, line : line) } } XCTAssertFalse(recordMode, "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file : file, line : line) } func inScreenNavigationContext(controller : UIViewController, @noescape action : () -> ()) { let container = UINavigationController(rootViewController: controller) inScreenDisplayContext(container, action: action) } /// Makes a window and adds the controller to it /// to ensure that our controller actually loads properly /// Otherwise, sometimes viewWillAppear: type methods don't get called func inScreenDisplayContext(controller : UIViewController, @noescape action : () -> ()) { let window = UIWindow(frame: CGRectZero) window.rootViewController = controller window.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height) window.makeKeyAndVisible() controller.view.frame = window.bounds controller.view.updateConstraintsIfNeeded() controller.view.setNeedsLayout() controller.view.layoutIfNeeded() action() window.removeFromSuperview() } }
apache-2.0
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-014/Trax MapKit/Trax/ImageViewController.swift
5
3985
// // ImageViewController.swift // Trax // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { // our Model // publicly settable // when it changes (but only if we are on screen) // we'll fetch the image from the imageURL // if we're off screen when this happens (view.window == nil) // viewWillAppear will get it for us later var imageURL: NSURL? { didSet { image = nil if view.window != nil { fetchImage() } } } // fetches the image at imageURL // does so off the main thread // then puts a closure back on the main queue // to handle putting the image in the UI // (since we aren't allowed to do UI anywhere but main queue) private func fetchImage() { if let url = imageURL { spinner?.startAnimating() let qos = Int(QOS_CLASS_USER_INITIATED.value) dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in let imageData = NSData(contentsOfURL: url) // this blocks the thread it is on dispatch_async(dispatch_get_main_queue()) { // only do something with this image // if the url we fetched is the current imageURL we want // (that might have changed while we were off fetching this one) if url == self.imageURL { // the variable "url" is capture from above if imageData != nil { // this might be a waste of time if our MVC is out of action now // which it might be if someone hit the Back button // or otherwise removed us from split view or navigation controller // while we were off fetching the image self.image = UIImage(data: imageData!) } else { self.image = nil } } } } } } @IBOutlet private weak var spinner: UIActivityIndicatorView! @IBOutlet private weak var scrollView: UIScrollView! { didSet { scrollView.contentSize = imageView.frame.size // critical to set this! scrollView.delegate = self // required for zooming scrollView.minimumZoomScale = 0.03 // required for zooming scrollView.maximumZoomScale = 1.0 // required for zooming } } // UIScrollViewDelegate method // required for zooming func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } private var imageView = UIImageView() // convenience computed property // lets us get involved every time we set an image in imageView // we can do things like resize the imageView, // set the scroll view's contentSize, // and stop the spinner private var image: UIImage? { get { return imageView.image } set { imageView.image = newValue imageView.sizeToFit() scrollView?.contentSize = imageView.frame.size spinner?.stopAnimating() } } // put our imageView into the view hierarchy // as a subview of the scrollView // (will install it into the content area of the scroll view) override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(imageView) } // for efficiency, we will only actually fetch the image // when we know we are going to be on screen override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if image == nil { fetchImage() } } }
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/20626-no-stacktrace.swift
11
260
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a { let P { init { extension g { struct c { func g { case { ( [ ] var { class case ,
mit
heitara/swift-3
playgrounds/Lecture7.playground/Contents.swift
1
8168
//: Playground - noun: a place where people can play import UIKit /* Какво е playground? Това вид проект, който се изпозлва от xCode. Интерактивно показва какво е състоянието на паметта на компютъра във всеки един ред на изпълнение на код-а. Позволява лесно онагледяване на примерния код. Много по-лесно може да се анализира кода. Можем да скицираме проблеми и техните решения, които да използваме за напред. */ //: # Въпроси от лекция №6 //: 1. Какво е ```mutating``` и кога се ползва? //: 2. Какво е read–only пропърти? //: 3. Какво е наследяване? //: 4. Кога можем да използваме запазената дума super? //: 5. Кога изпозлваме ```override```? //: ## След контролното ще разглеждаме проектите и прогреса по тях //: # Лекция 7: Протоколи (Класове и Структури) //: ## курс: Увод в прогрмаирането със Swift //: Наследяване - преговор //: Предефиниране (overriding) //: Достъп до базовите методи, пропъртита и subscript-s, става чрез ```super``` //: - Note: //: В Swift, изпозлваме запазената дума ```override``` за да обозначим, че предефинираме дадена функци, пропърти (get & set). //: Можем да обявим функция или пропърти, че няма да се променят. За целта използваме ```final```. //: Можем да обявим дори и цял клас. ```final class``` - класът няма да може да бъде наследяван. //: Инициализатори (init методи) //: наследяване на инициализаторите инициализатори //: ```required``` инициализатори //: init? инициализатори struct StructBook { var pageCount = 0 var title = "no title" var publishDate:Date? = nil init(title:String) { self.title = title } } extension StructBook { init() { self.init(title: "No title") } } class Book { var pageCount = 0 var title = "no title" var publishDate:Date? = nil convenience init(pages:Int) { self.init() self.pageCount = pages } convenience init(pages:Int, title:String) { self.init(pages:pages) self.title = title } } class TechnicalBook:Book { var isBlackAndWhite = true } class CartoonBook : Book { var isBlackAndWhite = true } extension Book { convenience init(title:String) { self.init() self.title = title } convenience init(pages:Int, title:String, date: Date?) { self.init(pages:pages, title:title) self.publishDate = date } } //var tb = TechnicalBook( //var book = Book() //book.pageCount = 100 var book100 = Book(pages: 100) //var book2 = StructBook(pageCount: 1000, title: "Swift 3", publishDate: nil) //var doc = TechnicalBook( //: ## Протоколи //: Какво са протоколите? //: - Note: //: Протокола е "договор", който всеки тип се съгласява да удволетвори. "Договор", е списък от изисквания, който определят начина по който ще изгледжа даденият тип. //: ### Синтаксис protocol Sellable { var pricePerUnit: Double { get } var isAvailable: Bool { set get } mutating func updatePrice(newPrice: Double) } protocol TechnicalDocumented { //конструктори init(documentation:Book) var technicalDocumentation: Book { get } func getTechnicalDocs() -> Book } protocol Printable { var description: String { get } static var version: String { get set} init() init(a:Int, b:Int) } extension Printable { //default version var description: String { return "No descriprion." } //default version static var version: String { return "v. 1.0" } } //extension Int:Printable { // var description: String { // return "седем" // } // //} //var i = 7 //print(i.description) //пример за клас, който имплементира техникал интерфейс class Machine: Printable { var powerConsumption = 0 var name = "Missing name" //имаме неявен конструкту по подразбиране // var description: String { // return "Machine" // } static var version: String = "v. 2.0" required init() { } required init(a:Int, b:Int) { print("Machine") } } var m = Machine() print(m.description) //struct StructBook2:Printable { // var pageCount = 0 // var title = "no title" // var publishDate:Date? = nil // // var description: String { // return "Structure Book!" // } //} class WashingMachine : Machine, TechnicalDocumented { var technicalDocumentation: Book func getTechnicalDocs() -> Book { return TechnicalBook() } required init() { technicalDocumentation = TechnicalBook() super.init() } required init(documentation: Book) { technicalDocumentation = documentation super.init() } required init(a:Int, b:Int) { technicalDocumentation = TechnicalBook() print("W.Machine") super.init() } // override var description: String { // // return " W Machine" // } // var technicalDocumentation: CartoonBook } protocol PersonalComputer: class { func getRamSize() -> Int /** * Convert X bytes to "KB" or "MB" or "GB" or "TB" **/ static func convert(bytes: Int, to:String) -> Double } class MacBookPro : PersonalComputer { func getRamSize() -> Int { return 1024 } static func convert(bytes: Int, to:String) -> Double { return 0 } } //: ## Задачи: //: ### Да се направи модел на по следното задание: // //Задание 1 // //Да се имплементира мобилно приложение, което //представя информация за времето. Времето да има две представяния //- по целзии, по фаренхайт. Да може да се съставя списък от //градове, който да представя информация за времето в //определените локации. // //Задание 2 // //Да се имплементира мобилно приложение, което //представя списък от снимки, които всеки потребител може да upload-ва. //Всеки потребител да има списък от снимки, които се формира от снимките на всички //потребители, на които е последовател. Всеки да може да стане //последвател на друг потребител, но да може и да се откаже да е последовател. //Под всяка снимка потребителите да могат да коментират. Да я отбелязват като любима. //Или да я споделят с други потребители. Всеки потребител да има списък с //последователи. Да има вход в системата с потребителско име и парола.
mit
airbnb/lottie-ios
Example/iOS/Views/AnimatedSwitchRow.swift
2
3379
// Created by Cal Stephens on 1/4/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import Epoxy import Lottie import UIKit // MARK: - AnimatedSwitchRow final class AnimatedSwitchRow: UIView, EpoxyableView { // MARK: Lifecycle init() { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false layoutMargins = UIEdgeInsets(top: 16, left: 24, bottom: 16, right: 24) group.install(in: self) group.constrainToMarginsWithHighPriorityBottom() backgroundColor = .systemBackground } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal struct Content: Equatable { var animationName: String var title: String var onTimeRange: ClosedRange<CGFloat> var offTimeRange: ClosedRange<CGFloat> var colorValueProviders: [String: [Keyframe<LottieColor>]] = [:] } func setContent(_ content: Content, animated _: Bool) { self.content = content updateGroup() } // MARK: Private private enum DataID { case animatedSwitch case title } private var content: Content? private let group = HGroup(alignment: .fill, spacing: 24) private var isEnabled = false { didSet { updateGroup() } } private func updateGroup() { guard let content = content else { return } group.setItems { if let animationName = content.animationName { GroupItem<AnimatedSwitch>( dataID: DataID.animatedSwitch, content: content, make: { let animatedSwitch = AnimatedSwitch() animatedSwitch.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ animatedSwitch.widthAnchor.constraint(equalToConstant: 80), animatedSwitch.heightAnchor.constraint(equalToConstant: 80), ]) animatedSwitch.addTarget(self, action: #selector(self.switchWasToggled), for: .touchUpInside) return animatedSwitch }, setContent: { context, content in context.constrainable.animation = .named(animationName) context.constrainable.contentMode = .scaleAspectFit context.constrainable.setProgressForState( fromProgress: content.offTimeRange.lowerBound, toProgress: content.offTimeRange.upperBound, forOnState: false) context.constrainable.setProgressForState( fromProgress: content.onTimeRange.lowerBound, toProgress: content.onTimeRange.upperBound, forOnState: true) for (keypath, color) in content.colorValueProviders { context.constrainable.animationView.setValueProvider( ColorValueProvider(color), keypath: AnimationKeypath(keypath: keypath)) } }) } GroupItem<UILabel>( dataID: DataID.title, content: isEnabled, make: { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }, setContent: { context, _ in context.constrainable.text = "\(content.title): \(self.isEnabled ? "On" : "Off")" }) } } @objc private func switchWasToggled(_ sender: AnimatedSwitch) { isEnabled = sender.isOn } }
apache-2.0
andreacremaschi/GEOSwift
GEOSwift/GEOS/GeometryConvertible+GEOS.swift
1
15571
import geos public extension GeometryConvertible { // MARK: - Misc Functions func length() throws -> Double { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var length: Double = 0 // returns 0 on exception guard GEOSLength_r(context.handle, geosObject.pointer, &length) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return length } func distance(to geometry: GeometryConvertible) throws -> Double { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) var dist: Double = 0 // returns 0 on exception guard GEOSDistance_r(context.handle, geosObject.pointer, otherGeosObject.pointer, &dist) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return dist } func area() throws -> Double { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var area: Double = 0 // returns 0 on exception guard GEOSArea_r(context.handle, geosObject.pointer, &area) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return area } func nearestPoints(with geometry: GeometryConvertible) throws -> [Point] { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let coordSeq = GEOSNearestPoints_r( context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSCoordSeq_destroy_r(context.handle, coordSeq) } var point0 = Point(x: 0, y: 0) GEOSCoordSeq_getX_r(context.handle, coordSeq, 0, &point0.x) GEOSCoordSeq_getY_r(context.handle, coordSeq, 0, &point0.y) var point1 = Point(x: 0, y: 0) GEOSCoordSeq_getX_r(context.handle, coordSeq, 1, &point1.x) GEOSCoordSeq_getY_r(context.handle, coordSeq, 1, &point1.y) return [point0, point1] } // MARK: - Unary Predicates internal typealias UnaryPredicate = (GEOSContextHandle_t, OpaquePointer) -> Int8 internal func evaluateUnaryPredicate(_ predicate: UnaryPredicate) throws -> Bool { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = predicate(context.handle, geosObject.pointer) guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func isEmpty() throws -> Bool { try evaluateUnaryPredicate(GEOSisEmpty_r) } func isRing() throws -> Bool { try evaluateUnaryPredicate(GEOSisRing_r) } func isValid() throws -> Bool { try evaluateUnaryPredicate(GEOSisValid_r) } func isValidReason() throws -> String { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) guard let cString = GEOSisValidReason_r(context.handle, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSFree_r(context.handle, cString) } return String(cString: cString) } func isValidDetail(allowSelfTouchingRingFormingHole: Bool = false) throws -> IsValidDetailResult { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let flags: Int32 = allowSelfTouchingRingFormingHole ? Int32(GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE.rawValue) : 0 var optionalReason: UnsafeMutablePointer<Int8>? var optionalLocation: OpaquePointer? switch GEOSisValidDetail_r( context.handle, geosObject.pointer, flags, &optionalReason, &optionalLocation) { case 1: // Valid if let reason = optionalReason { GEOSFree_r(context.handle, reason) } if let location = optionalLocation { GEOSGeom_destroy_r(context.handle, location) } return .valid case 0: // Invalid let reason = optionalReason.map { (reason) -> String in defer { GEOSFree_r(context.handle, reason) } return String(cString: reason) } let location = try optionalLocation.map { (location) -> Geometry in let locationGEOSObject = GEOSObject(context: context, pointer: location) return try Geometry(geosObject: locationGEOSObject) } return .invalid(reason: reason, location: location) default: // Error throw GEOSError.libraryError(errorMessages: context.errors) } } // MARK: - Binary Predicates private typealias BinaryPredicate = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> Int8 private func evaluateBinaryPredicate(_ predicate: BinaryPredicate, with geometry: GeometryConvertible) throws -> Bool { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = predicate(context.handle, geosObject.pointer, otherGeosObject.pointer) guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func isTopologicallyEquivalent(to geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSEquals_r, with: geometry) } func isDisjoint(with geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSDisjoint_r, with: geometry) } func touches(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSTouches_r, with: geometry) } func intersects(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSIntersects_r, with: geometry) } func crosses(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCrosses_r, with: geometry) } func isWithin(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSWithin_r, with: geometry) } func contains(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSContains_r, with: geometry) } func overlaps(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSOverlaps_r, with: geometry) } func covers(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCovers_r, with: geometry) } func isCovered(by geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCoveredBy_r, with: geometry) } // MARK: - Dimensionally Extended 9 Intersection Model Functions /// Parameter mask: A DE9-IM mask pattern func relate(_ geometry: GeometryConvertible, mask: String) throws -> Bool { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = mask.withCString { GEOSRelatePattern_r(context.handle, geosObject.pointer, otherGeosObject.pointer, $0) } guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func relate(_ geometry: GeometryConvertible) throws -> String { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let cString = GEOSRelate_r(context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSFree_r(context.handle, cString) } return String(cString: cString) } // MARK: - Topology Operations internal typealias UnaryOperation = (GEOSContextHandle_t, OpaquePointer) -> OpaquePointer? internal func performUnaryTopologyOperation<T>(_ operation: UnaryOperation) throws -> T where T: GEOSObjectInitializable { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) guard let pointer = operation(context.handle, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try T(geosObject: GEOSObject(context: context, pointer: pointer)) } private typealias BinaryOperation = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> OpaquePointer? private func performBinaryTopologyOperation(_ operation: BinaryOperation, geometry: GeometryConvertible) throws -> Geometry { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let pointer = operation(context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: GEOSObject(context: context, pointer: pointer)) } func envelope() throws -> Envelope { let geometry: Geometry = try performUnaryTopologyOperation(GEOSEnvelope_r) switch geometry { case let .point(point): return Envelope(minX: point.x, maxX: point.x, minY: point.y, maxY: point.y) case let .polygon(polygon): var minX = Double.nan var maxX = Double.nan var minY = Double.nan var maxY = Double.nan for point in polygon.exterior.points { minX = .minimum(minX, point.x) maxX = .maximum(maxX, point.x) minY = .minimum(minY, point.y) maxY = .maximum(maxY, point.y) } return Envelope(minX: minX, maxX: maxX, minY: minY, maxY: maxY) default: throw GEOSwiftError.unexpectedEnvelopeResult(geometry) } } func intersection(with geometry: GeometryConvertible) throws -> Geometry? { do { return try performBinaryTopologyOperation(GEOSIntersection_r, geometry: geometry) } catch GEOSwiftError.tooFewPoints { return nil } catch { throw error } } func makeValid() throws -> Geometry { try performUnaryTopologyOperation(GEOSMakeValid_r) } func normalized() throws -> Geometry { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // GEOSNormalize_r returns -1 on exception guard GEOSNormalize_r(context.handle, geosObject.pointer) != -1 else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: geosObject) } func convexHull() throws -> Geometry { try performUnaryTopologyOperation(GEOSConvexHull_r) } func minimumRotatedRectangle() throws -> Geometry { try performUnaryTopologyOperation(GEOSMinimumRotatedRectangle_r) } func minimumWidth() throws -> LineString { try performUnaryTopologyOperation(GEOSMinimumWidth_r) } func difference(with geometry: GeometryConvertible) throws -> Geometry? { do { return try performBinaryTopologyOperation(GEOSDifference_r, geometry: geometry) } catch GEOSwiftError.tooFewPoints { return nil } catch { throw error } } func union(with geometry: GeometryConvertible) throws -> Geometry { try performBinaryTopologyOperation(GEOSUnion_r, geometry: geometry) } func unaryUnion() throws -> Geometry { try performUnaryTopologyOperation(GEOSUnaryUnion_r) } func pointOnSurface() throws -> Point { try performUnaryTopologyOperation(GEOSPointOnSurface_r) } func centroid() throws -> Point { try performUnaryTopologyOperation(GEOSGetCentroid_r) } func minimumBoundingCircle() throws -> Circle { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var radius: Double = 0 var optionalCenterPointer: OpaquePointer? guard let geometryPointer = GEOSMinimumBoundingCircle_r( context.handle, geosObject.pointer, &radius, &optionalCenterPointer) else { // if we somehow end up with a non-null center and a null geometry, // we must still destroy the center before throwing an error if let centerPointer = optionalCenterPointer { GEOSGeom_destroy_r(context.handle, centerPointer) } throw GEOSError.libraryError(errorMessages: context.errors) } // For our purposes, we only care about the center and radius. GEOSGeom_destroy_r(context.handle, geometryPointer) guard let centerPointer = optionalCenterPointer else { throw GEOSError.noMinimumBoundingCircle } let center = try Point(geosObject: GEOSObject(context: context, pointer: centerPointer)) return Circle(center: center, radius: radius) } func polygonize() throws -> GeometryCollection { try [self].polygonize() } // MARK: - Buffer Functions func buffer(by width: Double) throws -> Geometry { guard width >= 0 else { throw GEOSwiftError.negativeBufferWidth } let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // returns nil on exception guard let resultPointer = GEOSBuffer_r(context.handle, geosObject.pointer, width, 0) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: GEOSObject(context: context, pointer: resultPointer)) } } public extension Collection where Element: GeometryConvertible { func polygonize() throws -> GeometryCollection { let context = try GEOSContext() let geosObjects = try map { try $0.geometry.geosObject(with: context) } guard let pointer = GEOSPolygonize_r( context.handle, geosObjects.map { $0.pointer }, UInt32(geosObjects.count)) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try GeometryCollection(geosObject: GEOSObject(context: context, pointer: pointer)) } } public enum IsValidDetailResult: Equatable { case valid case invalid(reason: String?, location: Geometry?) }
mit
rebeloper/SwiftyPlistManager
SwiftyPlistManager/ViewController.swift
1
22312
/** MIT License Copyright (c) 2017 Alex Nagy 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 UIKit //////////////////////////////////////////////////////////////////////////////////// // // For a detailed tutorial with images visit: // // http://rebeloper.com/read-write-plist-file-swift/ // //////////////////////////////////////////////////////////////////////////////////// // First of all drag and drop these 2 helper files into your project: // MyData.plist // MySecondPlist.plist // //////////////////////////////////////////////////////////////////////////////////// // // INSTALATION: // // I. CocoaPods: // // 1. run in Terminal on the root of your project: pod init // 2. add to your Podfile: pod 'SwiftyPlistManager' // 3. run in Terminal on the root of your project: pod install // 4. import SwiftyPlistManager by commenting out the line below //import SwiftyPlistManager // or II. Manualy: // // Drag and drop SwiftyPlistManager.swift into your project //////////////////////////////////////////////////////////////////////////////////// class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //////////////////////////////////////////////////////////////////////////////////// // Now let's start coding! // It is always a good practice to make our keys typo-proof // Comment out the lines below by deleting the '/*' and '*/' // For now don't worry about Xcode complaining about them /* let dataPlistName = "Data" let otherDataPlistName = "OtherData" let nonExistentPlistName = "NonExistent" let newKey = "newKey" let firstKey = "firstKey" let secondKey = "secondKey" let thirdKey = "thirdKey" let fourthKey = "fourthKey" let nonExistentKey = "nonExistentKey" let helloNewValue = "Hello New Value" let rebeloperValue = "Rebeloper" let intValue = 17 let boolValue = true let anotherIntValue = 28 let stringValue = "Alex" var dict = ["name": "John", "age": 34] as [String : Any]*/ //////////////////////////////////////////////////////////////////////////////////// // Now go to 'Data.plist' and add a new item with this key: 'newKey' and with // a String value: 'Hello SwiftyPlistManager' // // IMPORTANT: You always have to "start" SwiftyPlistManager on every launch of your app. // Add the next line of code to your 'application(_:didFinishLaunchingWithOptions:)' function // in AppDelegate.swift // // For the sake of this tutorial let's just add it here. This is fine too, as long as it is fired on every launch. // // Set 'logging' to 'true' if you want to log what's going on under the hood. Optionaly set it to 'false' // before release or when you are fed up with too much text in the console. //SwiftyPlistManager.shared.start(plistNames: [dataPlistName], logging: true) // Bulid & Run. Stop. Never comment back this line of code. // What this did is copy your existing Data.plist file into the app's Documents directory. // From now on the app will interact with this newly created file and NOT with the plist file you see in Xcode. // This is why if you change a value (or add a new item) to your plist now (after the first launch) // than changes will not be reflected in the MyData.plist file you see in Xcode. Instead changes // will be saved to the plist file created in the Documents directory. Consider this Data.plist // file (that one you see in Xcode) as a 'starting' file in witch you set up all of your needed // keys with some default values. // // IMPORTANT: After you first launch your app and than add/remove items in the Data.plist file the changes // will not be reflected in the file in the Documents directory. To add more key-value pairs // to your Data.plist file or change the value of any key-value pair do the following steps: // // 1. Add your desired new items to the Data.plist file // 2. Delete your app from the simulator/device // 3. Build & Run the app // // You will always have to repeat these steps if you wish to add new key-value pairs through // the Data.plist file. You can easily skip these steps if you add key-value pair through code. // The downside of this is that you can't actually see or edit the key-value pairs in the file // you see in Xcode. //////////////////////////////////////////////////////////////////////////////////// // You can 'start' as many plist files as you'd like as long as you have them in your project bundle already. // Of course if the plist does not exist SwiftyPlistManger will gently warn you in the log. // Try starting SwiftyPlistManager with these 3 items: "Data", "OtherData" and "NonExistent". // Of course, use the constants that you have set up above. //SwiftyPlistManager.shared.start(plistNames: [dataPlistName, otherDataPlistName, nonExistentPlistName], logging: true) //////////////////////////////////////////////////////////////////////////////////// // Comment the line back again. In this example we will work on the 'Data.plist' file only. //////////////////////////////////////////////////////////////////////////////////// // Let's test if the item with the 'newKey' key exits and print it out in the Log. // SwiftyPlistManager uses completion handlers. You'll get back your 'result' as an Any? object. // For now let's just check if the error is nil. We'll talk about in depth error handling later on. // After adding the call Build and Run your app again. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------------> The Value for Key '\(newKey)' actually exists in the '\(dataPlistName).plist' file. It is: '\(result ?? "No Value Fetched")'") } }*/ // Hurray! Comment back that call. //////////////////////////////////////////////////////////////////////////////////// // Now let's change the value of this item. We want to avoid the cumbersome 3 step process detailed above, // so we are going to do it in code. /* SwiftyPlistManager.shared.save(helloNewValue, forKey: newKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------------> Value '\(helloNewValue)' successfully saved at Key '\(newKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run. Stop. // Note that you don't see any changes in the Data.plist file. This is how it should be, because the app // saved the new value to the file in the Documents directory, remember? So now let's get back the changed // value. Comment out the call below. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result!)'") } }*/ // Build & Run and take a look at the Log. Stop. Comment back the lines from above. // Note that the value you get back is an optional. Retrieveng it with the 'bang operator' (!) is quite risky // because you might get back nil and that would crash your app! My suggestion is to never ever use the // 'bang operator'. It's risky, crash-prone and shouts that you are a lazy, clueless (or both) developer. // There are better ways to write code. For a start let's add a default value. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result ?? "No Value")'") } }*/ // Build & Run and take a look at the Log. Stop. Comment back the lines from above. // At this point the optional value will default to the "No Value" Sting. I personally hate working with default // values because they might pop up and would ruin the user experience of any app. To enhance your code let's // unwrap the 'result' with a guard-let statement. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { guard let result = result else { print("-------------> The Value for Key '\(newKey)' does not exists.") return } print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result)'") } }*/ // Or you can unwrap it with an if-let statement if you do not wish to return from the completion handler right away /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { if let result = result { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result)'") } else { print("-------------> The Value for Key '\(newKey)' does not exists.") } print("-------------> This line will be printed out regardless if the Value for Key '\(newKey)' exists or not.") } }*/ // Congratulations! You have learned how and when to use (or not to use) the 'bang operator', 'guard-let statements' // and 'if-let' statements. You now have solid knowledge of how to deal with optionals. // Most of the times you want to cast your result into a constant right away and not wait for the // completion handler to finish. You can use the following call to do just that. For this example we'll // unwrap it with a guard-let statement. /* guard let fetchedValue = SwiftyPlistManager.shared.fetchValue(for: newKey, fromPlistWithName: dataPlistName) else { return } print("-------------> The Fetched Value for Key '\(newKey)' actually exists. It is: '\(fetchedValue)'")*/ //////////////////////////////////////////////////////////////////////////////////// // Of course if you try to fetch a value with a non-existent key, 'SwiftyPlistManager' has your back. // It will show a WARNING in the log that the key does not exist AND it will not crash the app. Sweet! /* guard let nonExistentValue = SwiftyPlistManager.shared.fetchValue(for: nonExistentKey, fromPlistWithName: dataPlistName) else { print("-------------> The Value does not exist so going to return now!") return } print("-------------> This line will never be executed because the Key is: '\(nonExistentKey)' so the Value is '\(nonExistentValue)'")*/ //////////////////////////////////////////////////////////////////////////////////// // Now let's take a look at some other awesome powers that come with SwiftyPlistManager. // You can add a new key-value pair like so: /* SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(rebeloperValue)' successfully added at Key '\(firstKey)' into '\(dataPlistName).plist'") } }*/ // Now Build & Run your project... Congratulations! You have just created and saved your first // key-value pair into your plist file. Stop the project from running. //////////////////////////////////////////////////////////////////////////////////// // Now add a next value with an Int /* SwiftyPlistManager.shared.addNew(intValue, key: secondKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(intValue)' successfully added at Key '\(secondKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run again. Take a look at your progress in the Log. Stop. //////////////////////////////////////////////////////////////////////////////////// // And finally add an item that has a Bool value /* SwiftyPlistManager.shared.addNew(boolValue, key: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(boolValue)' successfully added at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run again. Take a look at your progress in the Log. Notice that 'true' is represented // with a '1' and 'false' is represented with a '0'. Stop your project from running. // As in real life examples you just can't comment out these 3 calls after the first launch of the // app, but you don't have to. 'SwiftyPlistManager' takes care of not creating a new item for the same key. // Do not comment out this last call and Build & Run again. Take a look at the Log. //////////////////////////////////////////////////////////////////////////////////// // Remember, you don't have to add your items through code at all. // You can add them into the Data.plist file; it's much easier, but it has a downside: // Once you run and test your code for the first time you cannot add or delete any entries using the plist file. // Changes made will not be reflected. You will have to delete your app from the simulator, // Clean your project (Product/Clean) and Build & Run again to see your changes. However adding/saving/deleting will // work when done in code. //////////////////////////////////////////////////////////////////////////////////// // Great! So now you know that 'adding' a new key-value pair is not the same as 'updating'/'saving a new value' // for a key. Let's do that now. // Change and at the same time Save the second key's value to '28' (anotherIntValue) /* SwiftyPlistManager.shared.save(anotherIntValue, forKey: secondKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(anotherIntValue)' successfully saved at Key '\(secondKey)' into '\(dataPlistName).plist'") } }*/ // Of course, Build & Run again. And after you take a look at your progress. Stop. // And comment back the line. From now on do it on every new task. :) // Awesome! //////////////////////////////////////////////////////////////////////////////////// // 'SwiftyPlistManager' is Semi Type Safe. What this means is that for example if you try to save // a String value for a non-String value, let's say to save 'Alex' (stringValue) for the 'thirdKey' // witch already has a Bool value, than 'SwiftyPlistManager' will give you a Warning but let you // make the save anyway. It is your responsibility that you save the right types of values. Try it out. /* SwiftyPlistManager.shared.save(stringValue, forKey: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(stringValue)' successfully saved at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ //////////////////////////////////////////////////////////////////////////////////// // Better change back the value to a Bool for the Item with key 'thirdKey' before you forget it. /* SwiftyPlistManager.shared.save(boolValue, forKey: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(boolValue)' successfully saved at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ // The warning will come up this time too, but now you know that it is set back the way you need it. //////////////////////////////////////////////////////////////////////////////////// // Of course, you may add Dictionaries, Arrays, Dates and Data items too. Try it out // by adding a new dictionary. /* SwiftyPlistManager.shared.addNew(dict, key: fourthKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(dict)' successfully saved at Key '\(fourthKey)' into '\(dataPlistName).plist'") } }*/ //////////////////////////////////////////////////////////////////////////////////// // Now just to have some fun with it, change the age of John to 56. /* dict["age"] = 56 SwiftyPlistManager.shared.save(dict, forKey: fourthKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(dict)' successfully saved at Key '\(fourthKey)' into '\(dataPlistName).plist'") } }*/ // Well done! Now comment back the calls. //////////////////////////////////////////////////////////////////////////////////// // Once in a while you might want to remove a value-key pair /* SwiftyPlistManager.shared.removeKeyValuePair(for: thirdKey, fromPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Key-Value pair successfully removed at Key '\(thirdKey)' from '\(dataPlistName).plist'") } }*/ // Of course, if this line is executed several times 'SwiftyPlistManager' realises that the item // was already removed and does not exist. Try it out! //////////////////////////////////////////////////////////////////////////////////// // Or you might want to delete all the data from your plist file /* SwiftyPlistManager.shared.removeAllKeyValuePairs(fromPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Successfully removed all Key-Value pairs from '\(dataPlistName).plist'") } }*/ // Of course, if this line is executed several times 'SwiftyPlistManager' realises that the plist // is empty and cancels the operation. Try it out. //////////////////////////////////////////////////////////////////////////////////// // Remember: Your plist file is saved and updated inside the application's Documents folder // This is why you will not see any changes at all in the MyData.plist file that you see in the // Xcode project. That file is there as a 'starter' file. Once you start the app and make // the 'startPlistManager()' call a copy is created in the app's Documents folder and from that new file is used // for all your data till you delete your app from simulator/device and Clean (Product/Clean) your project. //////////////////////////////////////////////////////////////////////////////////// // Let's talk about error-handling. When performing calls with 'SwiftyPlistManager' you get access // to possible errors in the completion handlers. Let's dive deep into learning all about them. // // For a start let's write a function that interprets the error types you might get. We will simply log the error, // but you can do whatever you want. /* func logSwiftyPlistManager(_ error: SwiftyPlistManagerError?) { guard let err = error else { return } print("-------------> SwiftyPlistManager error: '\(err)'") }*/ //////////////////////////////////////////////////////////////////////////////////// // Now let's take a look at the most common use cases and their errors //////////////////////////////////////////////////////////////////////////////////// // fileUnavailable /* SwiftyPlistManager.shared.addNew(helloNewValue, key: newKey, toPlistWithName: nonExistentPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // fileAlreadyEmpty /* SwiftyPlistManager.shared.removeAllKeyValuePairs(fromPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // keyValuePairAlreadyExists /* SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } else { print("-------------> Value '\(rebeloperValue)' successfully added at Key '\(firstKey)' into '\(dataPlistName).plist'") } } SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // keyValuePairDoesNotExist /* SwiftyPlistManager.shared.getValue(for: nonExistentKey, fromPlistWithName: dataPlistName) { (result, err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
relayrides/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/Tweak.swift
1
5729
// // Tweak.swift // KATweak // // Created by Bryan Clark on 11/4/15. // Copyright © 2015 Khan Academy. All rights reserved. // import Foundation import CoreGraphics import UIKit /// Tweaks let you adjust things on the fly. /// Because each T needs a UI component, we have to restrict what T can be - hence T: TweakableType. /// If T: SignedNumberType, you can declare a min / max for a Tweak. public struct Tweak<T: TweakableType> { internal let collectionName: String internal let groupName: String internal let tweakName: String internal let defaultValue: T internal let minimumValue: T? // Only supported for T: SignedNumberType internal let maximumValue: T? // Only supported for T: SignedNumberType internal let stepSize: T? // Only supported for T: SignedNumberType internal init(tweakName: String, defaultValue: T, minimumValue: T? = nil, maximumValue: T? = nil, stepSize: T? = nil, collectionName: String = "Mixpanel", groupName: String = "Mixpanel") { [collectionName, groupName, tweakName].forEach { if $0.contains(TweakIdentifierSeparator) { assertionFailure("The substring `\(TweakIdentifierSeparator)` can't be used in a tweak name, group name, or collection name.") } } self.collectionName = collectionName self.groupName = groupName self.tweakName = tweakName self.defaultValue = defaultValue self.minimumValue = minimumValue self.maximumValue = maximumValue self.stepSize = stepSize } } internal let TweakIdentifierSeparator = "|" extension Tweak { /** Initializer for a Tweak for A/B Testing - parameter tweakName: name of the tweak - parameter defaultValue: the default value set for the tweak - parameter collectionName: the collection name of the tweak (do not set, optional) - parameter groupName: the group name of the tweak (do not set, optional) */ public init(tweakName: String, defaultValue: T, _ collectionName: String = "Mixpanel", _ groupName: String = "Mixpanel") { self.init( tweakName: tweakName, defaultValue: defaultValue, collectionName: collectionName, groupName: groupName ) } } extension Tweak where T: SignedNumber { /** Creates a Tweak<T> where T: SignedNumberType You can optionally provide a min / max / stepSize to restrict the bounds and behavior of a tweak. - parameter tweakName: name of the tweak - parameter defaultValue: the default value set for the tweak - parameter minimumValue: minimum value to allow for the tweak - parameter maximumValue: maximum value to allow for the tweak - parameter stepSize: step size for the tweak (do not set, optional) - parameter collectionName: the collection name of the tweak (do not set, optional) - parameter groupName: the group name of the tweak (do not set, optional) */ public init(tweakName: String, defaultValue: T, min minimumValue: T? = nil, max maximumValue: T? = nil, stepSize: T? = nil, _ collectionName: String = "Mixpanel", _ groupName: String = "Mixpanel") { // Assert that the tweak's defaultValue is between its min and max (if they exist) if clip(defaultValue, minimumValue, maximumValue) != defaultValue { assertionFailure("A tweak's default value must be between its min and max. Your tweak \"\(tweakName)\" doesn't meet this requirement.") } self.init( tweakName: tweakName, defaultValue: defaultValue, minimumValue: minimumValue, maximumValue: maximumValue, stepSize: stepSize, collectionName: collectionName, groupName: groupName ) } } extension Tweak: TweakType { var tweak: TweakType { return self } var tweakDefaultData: TweakDefaultData { switch T.tweakViewDataType { case .boolean: return .boolean(defaultValue: (defaultValue as! Bool)) case .integer: return .integer( defaultValue: defaultValue as! Int, min: minimumValue as? Int, max: maximumValue as? Int, stepSize: stepSize as? Int ) case .cgFloat: return .float( defaultValue: defaultValue as! CGFloat, min: minimumValue as? CGFloat, max: maximumValue as? CGFloat, stepSize: stepSize as? CGFloat ) case .double: return .doubleTweak( defaultValue: defaultValue as! Double, min: minimumValue as? Double, max: maximumValue as? Double, stepSize: stepSize as? Double ) case .uiColor: return .color(defaultValue: defaultValue as! UIColor) case .string: return .string(defaultValue: defaultValue as! String) } } var tweakViewDataType: TweakViewDataType { return T.tweakViewDataType } } extension Tweak: Hashable { /** Hashing for a Tweak for A/B Testing in order for it to be stored. */ public var hashValue: Int { return tweakIdentifier.hashValue } } /** Comparator between two tweaks for A/B Testing. - parameter lhs: the left hand side tweak to compare - parameter rhs: the right hand side tweak to compare - returns: a boolean telling if both tweaks are equal */ public func == <T>(lhs: Tweak<T>, rhs: Tweak<T>) -> Bool { return lhs.tweakIdentifier == rhs.tweakIdentifier } /// Extend Tweak to support identification in bindings extension Tweak: TweakIdentifiable { var persistenceIdentifier: String { return tweakIdentifier } } /// Extend Tweak to support easy initialization of a TweakStore extension Tweak: TweakClusterType { public var tweakCluster: [AnyTweak] { return [AnyTweak.init(tweak: self)] } }
apache-2.0
prot3ct/Ventio
Ventio/Ventio/Controllers/CreateEventViewController.swift
1
1976
import UIKit import RxSwift class CreateEventViewController: UIViewController { @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextField! @IBOutlet weak var timeTextField: UITextField! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var isPublicSwitch: UISwitch! internal var eventData: EventDataProtocol! private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onCreateClicked(_ sender: UIButton) { self.startLoading() let title = self.titleTextField.text let description = self.descriptionTextField.text let time = self.timeTextField.text let date = self.dateTextField.text //let isPublic = self.isPublicSwitch.isOn eventData .create(title: title!, description: description!, date: date!, time: time!) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default)) .observeOn(MainScheduler.instance) .subscribe(onNext: { res in self.changeInitialViewController(identifier: "eventsTableViewController") self.showSuccess(withStatus: "You have saved your event successfully.") }, onError: { error in print(error) self.showError(withStatus: "Saving event ran into problem. Please try again later.") }) .disposed(by: disposeBag) } private func changeInitialViewController(identifier: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard .instantiateViewController(withIdentifier: identifier) UIApplication.shared.keyWindow?.rootViewController = initialViewController }}
apache-2.0
openHPI/xikolo-ios
WidgetExtension/ContinueLearningWidget.swift
1
1013
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import SwiftUI import WidgetKit struct ContinueLearningWidgetEntryView: View { var entry: ContinueLearningWidgetProvider.Entry var body: some View { if !entry.userIsLoggedIn { EmptyStateView.notLoggedIn } else if let course = entry.course { CourseView(course: course) .padding() } else { EmptyStateView.noCourses } } } struct ContinueLearningWidget: Widget { let kind = "continue-learning" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: ContinueLearningWidgetProvider()) { entry in ContinueLearningWidgetEntryView(entry: entry) } .configurationDisplayName("widget-metadata.continue-learning.title") .description("widget-metadata.continue-learning.description") .supportedFamilies([.systemSmall, .systemMedium]) } }
gpl-3.0
felix91gr/swift
test/stdlib/StringDiagnostics_without_Foundation.swift
1
1558
// RUN: %target-typecheck-verify-swift // Positive and negative tests for String index types func acceptsCollection<I: Collection>(_: I) {} func acceptsBidirectionalCollection<I: BidirectionalCollection>(_: I) {} func acceptsRandomAccessCollection<I: RandomAccessCollection>(_: I) {} func testStringCollectionTypes(s: String) { acceptsCollection(s.utf8) acceptsBidirectionalCollection(s.utf8) acceptsRandomAccessCollection(s.utf8) // expected-error{{argument type 'String.UTF8View' does not conform to expected type 'RandomAccessCollection'}} // UTF16View is random-access with Foundation, bidirectional without acceptsCollection(s.utf16) acceptsBidirectionalCollection(s.utf16) acceptsRandomAccessCollection(s.utf16) // expected-error{{argument type 'String.UTF16View' does not conform to expected type 'RandomAccessCollection'}} acceptsCollection(s.unicodeScalars) acceptsBidirectionalCollection(s.unicodeScalars) acceptsRandomAccessCollection(s.unicodeScalars) // expected-error{{argument type 'String.UnicodeScalarView' does not conform to expected type 'RandomAccessCollection'}} acceptsCollection(s.characters) acceptsBidirectionalCollection(s.characters) acceptsRandomAccessCollection(s.characters) // expected-error{{argument type 'String.CharacterView' does not conform to expected type 'RandomAccessCollection'}} } struct NotLosslessStringConvertible {} func testStringInitT() { _ = String(NotLosslessStringConvertible()) // expected-error{{'init' has been renamed to 'init(describing:)}}{{14-14=describing: }} }
apache-2.0
CocoaheadsSaar/Treffen
Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/AppDelegate.swift
1
1703
// // AppDelegate.swift // AutolayoutTests // // Created by Markus Schmitt on 11.01.16. // Copyright © 2016 Insecom - Markus Schmitt. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let tabBarController = UITabBarController() let mainViewController = MainViewController() mainViewController.title = "Simple" let mainWithAnchorsViewController = MainWithAnchorsViewController() mainWithAnchorsViewController.title = "Anchors" let mainVisualViewController = MainVisualViewController() mainVisualViewController.title = "Visual" let mainStackViewController = MainStackViewController() mainStackViewController.title = "Stacks" let mainStackButtonsViewController = MainStackButtonsViewController() mainStackButtonsViewController.title = "Buttons" tabBarController.viewControllers = [ UINavigationController(rootViewController: mainViewController), UINavigationController(rootViewController: mainWithAnchorsViewController), UINavigationController(rootViewController: mainVisualViewController), UINavigationController(rootViewController: mainStackViewController), UINavigationController(rootViewController: mainStackButtonsViewController) ] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } }
gpl-2.0