repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
chengang/iMei
iMei/Regex/PlatformTypes.swift
1
1246
//===--- PlatformTypes.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 #if !os(Linux) //here we use NSRegularExpression typealias CompiledPattern = NSRegularExpression typealias CompiledMatchContext = [NSTextCheckingResult] typealias CompiledPatternMatch = NSTextCheckingResult typealias GroupRange = NSRange #else typealias CompiledPattern = NSRegularExpression typealias CompiledMatchContext = [TextCheckingResult] typealias CompiledPatternMatch = TextCheckingResult typealias GroupRange = NSRange #endif
lgpl-3.0
367d0e37cd27e84eb2f48402012537ce
40.533333
81
0.690209
5.324786
false
false
false
false
mdmsua/Ausgaben.iOS
Ausgaben/Ausgaben/AccountAmountViewController.swift
1
809
// // AccountAmountViewController.swift // Ausgaben // // Created by Dmytro Morozov on 27.02.16. // Copyright © 2016 Dmytro Morozov. All rights reserved. // import Foundation class AccountAmountViewController : UIViewController { private var picker : Picker? var amount : Double? @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var doneButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.doneButton.enabled = false self.picker = Picker(4, value: self.amount) { self.handleUpdate($0) } pickerView.dataSource = self.picker pickerView.delegate = self.picker } func handleUpdate(value : Double) { self.amount = value self.doneButton.enabled = value > 0.0 } }
mit
ded9953b1d5649cdffcf6011060fafe4
25.096774
77
0.659653
4.230366
false
false
false
false
andr3a88/TryNetworkLayer
TryNetworkLayerTests/Mocks/MockGHUser.swift
1
1367
// // MockGHUser.swift // TryNetworkLayerTests // // Created by Andrea Stevanato on 05/03/2020. // Copyright © 2020 Andrea Stevanato. All rights reserved. // import Foundation struct MockGHUser { static let organizationsUrl = "url" static let score = 1 static let reposUrl = "url" static let htmlUrl = "url" static let gravatarId = "id" static let avatarUrl = "url" static let type = "user" static let login = "url" static let followersUrl = "url" static let subscriptionsUrl = "url" static let receivedEventsUrl = "url" static let url = "url" var id = 123456 init(id: Int) { self.id = id } func JSON() -> [String: Any] { return ["organizations_url": MockGHUser.organizationsUrl, "score": MockGHUser.score, "repos_url": MockGHUser.reposUrl, "html_url": MockGHUser.htmlUrl, "gravatar_id": MockGHUser.gravatarId, "avatar_url": MockGHUser.avatarUrl, "type": MockGHUser.type, "login": MockGHUser.login, "followers_url": MockGHUser.followersUrl, "id": id, "subscriptions_url": MockGHUser.subscriptionsUrl, "received_events_url": MockGHUser.receivedEventsUrl, "url": MockGHUser.url] } }
mit
2623869148ea2b93aa1e64510c2f5aec
28.695652
68
0.584919
3.891738
false
false
false
false
kingslay/KSSwiftExtension
Core/Source/Extension/UINavigationItem.swift
1
985
// // UINavigationItem.swift // Pods // // Created by king on 16/9/8. // // import Foundation private var backBarButtonItemAssociationKey: UInt8 = 0 public extension UINavigationItem { public override static func initialize() { struct Static { static var token: dispatch_once_t = 0 } // 确保不是子类 if self !== UINavigationItem.self { return } dispatch_once(&Static.token) { KS.swizzleInstanceMethod(self, sel1: "backBarButtonItem", sel2: "ksbackBarbuttonItem") } } public func ksbackBarbuttonItem() -> UIBarButtonItem? { var item = self.ksbackBarbuttonItem() if item == nil { item = objc_getAssociatedObject(self, &backBarButtonItemAssociationKey) as? UIBarButtonItem if (item == nil) { item = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) } } return item } }
mit
4fc2d6d64c37c1548accd031c9c4ff30
27.647059
103
0.593011
4.442922
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Profile/Login/View/CountryTableViewController.swift
1
3605
// // CountryTableViewController.swift // Floral // // Created by 孙林 on 16/5/4. // Copyright © 2016年 ALin. All rights reserved. // import UIKit let ChangeCountyNotifyName = "ChangeCountyNotifyName" // 重用标识符 private let CountryCellIdentifier = "CountryCellIdentifier" class CountryTableViewController: UITableViewController { // 国家名数组 var countries : [[String]]? { didSet{ self.tableView.reloadData() } } // 索引keys var keys : [NSString]? { didSet{ self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() setup() getList() } private func setup() { tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: CountryCellIdentifier) navigationItem.title = "选择国家和地区" navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .Done, target: self, action: #selector(CountryTableViewController.back)) } func back() { dismissViewControllerAnimated(true, completion: nil) } private func getList() { // 获取plist的路径 let path = NSBundle.mainBundle().pathForResource("country.plist", ofType: nil) // 获得 let dic = NSDictionary.init(contentsOfFile: path!) // 索引排序 keys = dic!.allKeys.sort({ (obj1, obj2) -> Bool in return (obj1 as! String) < (obj2 as! String) }) as? [NSString] // 获取国家名 var values = [[String]]() if let rkeys = keys { for key in rkeys { if let value = dic![key] { values.append(value as! [String]) } } countries = values } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return keys?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = countries?.count ?? 0 if count == 0 { return 0 } let array = countries![section] return array.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(CountryCellIdentifier)! let count = countries?.count ?? 0 if count > 1 { let countryCount = countries![indexPath.section].count ?? 0 if countryCount > 1 { cell.textLabel?.text = countries![indexPath.section][indexPath.row] } } return cell } // 设置左边的索引 override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let count = keys?.count ?? 0 return count > 0 ? keys![section] as String : nil } // 设置每组的title override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return keys as? [String] } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let country = countries![indexPath.section][indexPath.row] NSNotificationCenter.defaultCenter().postNotificationName(ChangeCountyNotifyName, object: nil, userInfo: ["country" : country]) back() } }
mit
82a46aaee2ab1cbb32abfbb51477e23f
28.2
169
0.600457
4.826446
false
false
false
false
tkareine/MiniFuture
Source/Future.swift
1
6575
import Dispatch struct FutureExecution { private static let sharedQueue = DispatchQueue.global() typealias Group = DispatchGroup static func makeGroup() -> Group { return DispatchGroup() } static func async(_ block: @escaping () -> Void) { sharedQueue.async(execute: block) } static func async(_ group: Group, block: @escaping () -> Void) { sharedQueue.async(group: group, execute: block) } static func sync(_ block: () -> Void) { sharedQueue.sync(execute: block) } static func notify(_ group: Group, block: @escaping () -> Void) { group.notify(queue: sharedQueue, execute: block) } static func wait(_ group: Group) { group.wait() } } public class Future<T> { /** - note: Eventually, `block` closure parameter gets called from a concurrent queue. Use proper synchronization when accessing shared state via references captured in the closure. */ public static func async(_ block: @escaping () throws -> Try<T>) -> AsyncFuture<T> { return AsyncFuture(block) } public static func succeeded(_ val: T) -> ImmediateFuture<T> { return fromTry(.success(val)) } public static func failed(_ error: Error) -> ImmediateFuture<T> { return fromTry(.failure(error)) } public static func fromTry(_ val: Try<T>) -> ImmediateFuture<T> { return ImmediateFuture(val) } public static func promise() -> PromiseFuture<T> { return PromiseFuture() } public typealias CompletionCallback = (Try<T>) -> Void fileprivate var result: Try<T>? public var isCompleted: Bool { fatalError("must be overridden") } fileprivate var futureName: String { fatalError("must be overridden") } fileprivate init(_ val: Try<T>?) { result = val } public func get() -> Try<T> { fatalError("must be overridden") } /** - note: Eventually, `block` closure parameter gets called from a concurrent queue. Use proper synchronization when accessing shared state via references captured in the closure. */ public func onComplete(_ block: @escaping CompletionCallback) { fatalError("must be overridden") } /** - note: Eventually, `f` closure parameter gets called from a concurrent queue. Use proper synchronization when accessing shared state via references captured in the closure. */ public func flatMap<U>(_ f: @escaping (T) throws -> Future<U>) -> Future<U> { let promise = PromiseFuture<U>() onComplete { res in switch res { case .success(let value): let fut: Future<U> do { fut = try f(value) } catch { fut = Future<U>.failed(error) } fut.onComplete(promise.complete) case .failure(let error): // we cannot cast dynamically with generic types, so let's create a // new value promise.complete(.failure(error)) } } return promise } /** - note: Eventually, `f` closure parameter gets called from a concurrent queue. Use proper synchronization when accessing shared state via references captured in the closure. */ public func map<U>(_ f: @escaping (T) throws -> U) -> Future<U> { return flatMap { e in do { return Future<U>.succeeded(try f(e)) } catch { return Future<U>.failed(error) } } } } public class ImmediateFuture<T>: Future<T> { override public var isCompleted: Bool { return result != nil } override fileprivate var futureName: String { return "ImmediateFuture" } fileprivate init(_ val: Try<T>) { super.init(val) } override public func get() -> Try<T> { return result! } override public func onComplete(_ block: @escaping CompletionCallback) { let res = result! FutureExecution.async { block(res) } } } public class AsyncFuture<T>: Future<T> { private let Group = FutureExecution.makeGroup() override public var isCompleted: Bool { var res = false FutureExecution.sync { [unowned self] in res = self.result != nil } return res } override fileprivate var futureName: String { return "AsyncFuture" } fileprivate init(_ block: @escaping () throws -> Try<T>) { super.init(nil) FutureExecution.async(Group) { let res: Try<T> do { res = try block() } catch { res = Try<T>.failure(error) } self.result = res } } override public func get() -> Try<T> { FutureExecution.wait(Group) return result! } override public func onComplete(_ block: @escaping CompletionCallback) { FutureExecution.notify(Group) { block(self.result!) } } } public class PromiseFuture<T>: Future<T> { private let condition = Condition() private var completionCallbacks: [CompletionCallback] = [] override public var isCompleted: Bool { return condition.synchronized { _ in result != nil } } override fileprivate var futureName: String { return "PromiseFuture" } fileprivate init() { super.init(nil) } public func resolve(_ value: T) { complete(.success(value)) } public func reject(_ error: Error) { complete(.failure(error)) } public func complete(_ value: Try<T>) { let callbacks: [CompletionCallback] = condition.synchronized { _ in if result != nil { fatalError("Tried to complete PromiseFuture with \(value.value), but " + "the future is already completed with \(result!)") } result = value let callbacks = completionCallbacks completionCallbacks = [] condition.signal() return callbacks } for block in callbacks { FutureExecution.async { block(value) } } } public func completeWith(_ future: Future<T>) { future.onComplete { self.complete($0) } } override public func get() -> Try<T> { return condition.synchronized { wait in while result == nil { wait() } return result! } } override public func onComplete(_ block: @escaping CompletionCallback) { let res: Try<T>? = condition.synchronized { _ in let res = result if res == nil { completionCallbacks.append(block) } return res } if let r = res { FutureExecution.async { block(r) } } } } extension Future: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(futureName)(\(String(describing: result)))" } public var debugDescription: String { return "\(futureName)(\(String(reflecting: result)))" } }
mit
f0556a08b8f00c0aa9fd66cff8c946f2
22.482143
86
0.63635
4.190567
false
false
false
false
netprotections/atonecon-ios
AtoneCon/Sources/PaymentViewController.swift
1
6903
// // PaymentViewController.swift // AtoneCon // // Created by Pham Ngoc Hanh on 6/28/17. // Copyright © 2017 AsianTech Inc. All rights reserved. // import UIKit import WebKit import SAMKeychain internal protocol PaymentViewControllerDelegate: class { func controller(_ controller: PaymentViewController, didReceiveScriptEvent event: ScriptEvent) } final internal class PaymentViewController: UIViewController { // MARK: - Delegate weak var delegate: PaymentViewControllerDelegate? // MARK: - Properties private var payment: AtoneCon.Payment? internal var webView: WKWebView! internal var indicator: UIActivityIndicatorView! internal var scriptHandler: ScriptHandler! fileprivate var closeButton: UIButton! func atoneHTML() throws -> String { var atoneJSURL = "" guard let options = AtoneCon.shared.options else { let error: [String: Any] = [Define.String.Key.title: Define.String.options, Define.String.Key.message: Define.String.Error.options] throw AtoneConError.option(error) } switch options.environment { case .development: atoneJSURL = "https://ct-auth.a-to-ne.jp/v1/atone.js" case .production: atoneJSURL = "https://auth.atone.be/v1/atone.js" case .staging: atoneJSURL = "https://ct-auth.a-to-ne.jp/v1/atone.js" } let publicKey = options.publicKey var preToken = "" var terminalId = "" if let accessToken = Session.shared.credential.authToken { preToken = accessToken } if let id = AtoneCon.shared.options?.terminalId { terminalId = id } let handlerScript = String(format: Define.Scripts.atoneJS, preToken, publicKey, terminalId) guard let paymentJSON = payment?.toJSONString(prettyPrint: true) else { let error: [String: Any] = [Define.String.Key.title: Define.String.paymentInfo, Define.String.Key.message: Define.String.Error.payment] throw AtoneConError.payment(error) } let paymentScript = "var data = " + paymentJSON let deviceScale = Define.Helper.Ratio.horizontal let atoneHTML = String(format: Define.Scripts.atoneHTML, "\(deviceScale)", atoneJSURL, paymentScript, handlerScript) return atoneHTML } convenience init(payment: AtoneCon.Payment) { self.init() self.payment = payment } // MARK: - Cycle Life override func viewDidLoad() { super.viewDidLoad() setupWebView() setupIndicator() setupCloseButton() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } // MARK: - Private Functions private func setupWebView() { do { webView = WKWebView(frame: view.bounds) webView.contentMode = .scaleToFill webView.autoresizingMask = .flexibleWidth webView.backgroundColor = Define.Color.blackAlpha90 view.addSubview(webView) let html = try atoneHTML() webView.loadHTMLString(html, baseURL: nil) webView.navigationDelegate = self webView.uiDelegate = self scriptHandler = ScriptHandler(forWebView: webView) scriptHandler.addEvents() scriptHandler.delegate = self } catch AtoneConError.payment(let error) { let event = ScriptEvent.failed(error) delegate?.controller(self, didReceiveScriptEvent: event) } catch AtoneConError.option(let error) { let event = ScriptEvent.failed(error) delegate?.controller(self, didReceiveScriptEvent: event) } catch { let error: [String: Any] = [Define.String.Key.message: Define.String.Error.undefine] let event = ScriptEvent.failed(error) delegate?.controller(self, didReceiveScriptEvent: event) } } private func setupCloseButton() { // Client will supply icon and size for button. let width: CGFloat = 36 * Define.Helper.Ratio.horizontal let statusBarHeight = UIApplication.shared.statusBarFrame.height let edgeInset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 5) let frame = CGRect(x: view.frame.width - width - edgeInset.right, y: edgeInset.top + statusBarHeight, width: width, height: width) closeButton = UIButton(frame: frame) let imageCloseButton = UIImage(named: Define.String.Image.close, in: Bundle.current, compatibleWith: nil) closeButton.setBackgroundImage(imageCloseButton, for: .normal) closeButton.addTarget(self, action: #selector(closeWebView), for: .touchUpInside) view.addSubview(closeButton) } private func setupIndicator() { indicator = UIActivityIndicatorView(activityIndicatorStyle: .white) indicator.hidesWhenStopped = true indicator.startAnimating() indicator.center = view.center view.addSubview(indicator) } @objc private func closeWebView() { let alert = UIAlertController(title: Define.String.quitPayment, message: nil, preferredStyle: .alert) let cancel = UIAlertAction(title: Define.String.cancel, style: .cancel, handler: nil) let ok = UIAlertAction(title: Define.String.okay, style: .default, handler: { _ in AtoneCon.shared.dismiss() }) alert.addAction(ok) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } } // MARK: - WKNavigationDelegate extension PaymentViewController: WKNavigationDelegate { internal func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { decisionHandler(.cancel) return } if url.absoluteString.contains(Define.String.Key.loading) { indicator.stopAnimating() closeButton.isHidden = true } decisionHandler(.allow) } } extension PaymentViewController: WKUIDelegate { internal func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if let url = navigationAction.request.url { UIApplication.shared.openURL(url) } return nil } } // MARK: - ScriptHandlerDelegate extension PaymentViewController: ScriptHandlerDelegate { func scriptHandler(_ scriptHandler: ScriptHandler, didReceiveScriptEvent event: ScriptEvent) { delegate?.controller(self, didReceiveScriptEvent: event) } }
mit
ca223af092c8e88ea41e6d26e8e15487
37.99435
196
0.657346
4.682497
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00222-swift-modulefile-modulefile.swift
11
960
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func f() { ({}) } a } s: X.Type) { } } class c { func b((Any, c))(a: { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } prtocolAny) -> Any in return p }) } b(a(1, a(2, 3))) func f Boolean>(b: T) { } f( func b( d { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F fu { o } } s m { class func s() } class p: m{ cl
apache-2.0
511d515a03d2c4dbcb25a8da6c7d9c5b
16.142857
78
0.533333
2.651934
false
false
false
false
mleiv/MEGameTracker
MEGameTrackerTests/CoreData/ShepardTests.swift
1
17886
// // ShepardTests.swift // MEGameTracker // // Created by Emily Ivie on 2/23/17. // Copyright © 2017 Emily Ivie. All rights reserved. // import XCTest import Nuke @testable import MEGameTracker final class ShepardTests: MEGameTrackerTests { // swiftlint:disable line_length let broShepGameSequenceUuid = UUID(uuidString: "7BF05BF6-386A-4429-BC18-2A60F2D29520")! let broShep1Json = "{\"uuid\" : \"B6D0BD56-9CA9-4060-8F2E-E4DFE4EEE8A2\",\"gameVersion\" : \"1\",\"paragon\" : 0,\"createdDate\" : \"2017-02-26 01:59:19\",\"level\" : 1,\"gameSequenceUuid\" : \"7BF05BF6-386A-4429-BC18-2A60F2D29520\",\"reputation\" : \"Sole Survivor\",\"renegade\" : 0,\"modifiedDate\" : \"2017-02-26 05:15:40\",\"origin\" : \"Earthborn\",\"isSavedToCloud\" : false,\"appearance\" : \"432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.217.65\",\"class\" : \"Soldier\",\"gender\" : \"M\",\"name\" : \"John\", \"loveInterestId\": \"S1.Ashley\"}" // femal equivalent game 1 432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.671.XXX.X // game 2 432.FLC.JCI.F6F.JHI.I7I.JHK.4KE.FJ8.HH7.216.5 let femShepGameSequenceUuid = UUID(uuidString: "7BF05BF6-386A-4429-BC18-2A60F2D29519")! let femShep1Json = "{\"uuid\" : \"BC0D3009-3385-4132-851A-DF472CBF9EFD\",\"gameVersion\" : \"1\",\"paragon\" : 0,\"createdDate\" : \"2017-02-15 07:40:32\",\"level\" : 1,\"gameSequenceUuid\" : \"7BF05BF6-386A-4429-BC18-2A60F2D29519\",\"reputation\" : \"Sole Survivor\",\"renegade\" : 0,\"modifiedDate\" : \"2017-02-23 07:13:39\",\"origin\" : \"Earthborn\",\"isSavedToCloud\" : false,\"appearance\" : \"XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.X\",\"class\" : \"Soldier\",\"gender\" : \"F\",\"name\" : \"Xoe\"}" let femShep2Json = "{\"uuid\" : \"BC0D3009-3385-4132-851A-DF472CBF9EFE\",\"gameVersion\" : \"2\",\"paragon\" : 0,\"createdDate\" : \"2017-02-25 09:10:15\",\"level\" : 1,\"gameSequenceUuid\" : \"7BF05BF6-386A-4429-BC18-2A60F2D29519\",\"reputation\" : \"Sole Survivor\",\"renegade\" : 0,\"modifiedDate\" : \"2017-02-25 09:10:15\",\"origin\" : \"Earthborn\",\"isSavedToCloud\" : false,\"appearance\" : \"XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.X\",\"class\" : \"Soldier\",\"gender\" : \"F\",\"name\" : \"Xoe\"}" let ashleyJson = "{\"id\": \"S1.Ashley\",\"name\": \"Ashley Williams\",\"personType\": \"Squad\",\"isMaleLoveInterest\": true,\"race\": \"Human\",\"profession\": \"Soldier\",\"organization\": \"Systems Alliance\",\"loveInterestDecisionId\": \"D1.LoveAshley\"}" let liaraJson = "{\"id\": \"S1.Liara\",\"name\": \"Liara T\'soni\",\"personType\": \"Squad\",\"isMaleLoveInterest\": true,\"isFemaleLoveInterest\": true,\"race\": \"Asari\",\"profession\": \"Scientist\",\"organization\": null,\"loveInterestDecisionId\": \"D1.LoveLiara\"}" let loveInterestDecision1Json = "{\"id\": \"D1.LoveAshley\",\"gameVersion\": \"1\",\"name\": \"Romanced Ashley\",\"description\": \"Provides a Paramour achievement. Only one romantic partner is allowed.\",\"loveInterestId\": \"S1.Ashley\",\"blocksDecisionIds\": [\"D1.LoveKaidan\", \"D1.LoveLiara\"],\"sortIndex\": 100}" let loveInterestDecision2Json = "{\"id\": \"D1.LoveLiara\",\"gameVersion\": \"1\",\"name\": \"Romanced Liara\",\"description\": \"Provides a Paramour achievement. Only one romantic partner is allowed.\",\"loveInterestId\": \"S1.Liara\",\"blocksDecisionIds\": [\"D1.LoveKaidan\", \"D1.LoveAshley\"],\"sortIndex\": 100}" override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testEquality() { let shepard1 = create(Shepard.self, from: femShep1Json) let shepard2 = create(Shepard.self, from: femShep1Json) XCTAssert(shepard1 == shepard2, "Equality not working") } // TODO: signal test for current shepard /// Test Shepard get methods. func testGetOne() { initializeCurrentGame(femShepGameSequenceUuid) // needed for game version App.current.changeGame { game in var game = game _ = game?.shepard?.delete() game?.shepard = create(Shepard.self, from: femShep1Json) return game } let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! let shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.fullName == "Xoe Shepard", "Failed to load by id") } /// Test Shepard getAll methods. func testGetAll() { _ = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = create(Shepard.self, from: broShep1Json) let shepards = Shepard.getAll() XCTAssert(shepards.count == 3, "Failed to get all shepards") } /// Test Shepard get last played func testGetByLastPlayed() { _ = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) let shepard = Shepard.lastPlayed(gameSequenceUuid: femShepGameSequenceUuid) XCTAssert(shepard?.gameVersion == .game2, "Failed to get correct last played shepard") } /// Test Shepard loaded by parent game func testGetByGame() { _ = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) let shepards = Shepard.getAll(gameSequenceUuid: femShepGameSequenceUuid) XCTAssert(shepards.count == 2, "Failed to get game shepards") } /// Test Shepard change action. func testChangeName() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(name: "Xena") let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.fullName == "Xena Shepard", "Failed to change name") // make sure change was propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.fullName == "Xena Shepard", "Failed to change name on other version") // make sure custom names aren't changed when gender changes: _ = shepard?.changed(gender: .male) shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.fullName == "Xena Shepard", "Incorrectly gender-changed name") } /// Test Shepard change action. func testChangeClass() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(class: .adept) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.classTalent == .adept, "Failed to change class") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.classTalent == .soldier, "Incorrectly changed class on other version") } /// Test Shepard change action. func testChangeOrigin() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(origin: .colonist) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.origin == .colonist, "Failed to change origin") // make sure change was propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.origin == .colonist, "Failed to change origin on other version") } /// Test Shepard change action. func testChangeReputation() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(reputation: .ruthless) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.reputation == .ruthless, "Failed to change reputation") // make sure change was propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.reputation == .ruthless, "Failed to change reputation on other version") } /// Test Shepard photo change action. func testChangePhoto() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid // #1) Share custom image across shepard var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) guard let image = UIImage(named: "Heart Filled") else { return XCTAssert(false, "Failed to create an image") } _ = shepard?.savePhoto(image: image, isSave: true) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.photo?.isCustomSavedPhoto == true, "Failed to customize photo") // check change was propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) let lastChanged = shepard?.modifiedDate XCTAssert(shepard?.photo?.isCustomSavedPhoto == true, "Failed to customize photo on other version") sleep(1) // #2) Don't share if other version already has a custom image guard let image2 = UIImage(named: "Heart Empty") else { return XCTAssert(false, "Failed to create an image") } shepard = Shepard.get(uuid: uuid) _ = shepard?.savePhoto(image: image2, isSave: true) // check change was NOT propogated to other versions: shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.modifiedDate == lastChanged, "Incorrectly customized photo on other version") } /// Test Shepard change action. func testChangeAppearance() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) let appearance = Shepard.Appearance("432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.671.XXX.X") _ = shepard?.changed(appearance: appearance) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.appearance.format() == "432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.671.XXX.X", "Failed to change appearance") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.appearance.format() == "XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX", "Incorrectly changed appearance on other version") } /// Test Shepard change action. func testChangeLevel() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(level: 10) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.level == 10, "Failed to change level") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.level == 1, "Incorrectly changed level on other version") } /// Test Shepard change action. func testChangeParagon() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(paragon: 80) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.paragon == 80, "Failed to change paragon") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.paragon == 0, "Incorrectly changed paragon on other version") } /// Test Shepard change action. func testChangeRenegade() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(renegade: 80) let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.renegade == 80, "Failed to change renegade") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.renegade == 0, "Incorrectly changed renegade on other version") } /// Test Shepard change action. func testChangeLoveInterest() { initializeCurrentGame(femShepGameSequenceUuid) // needed for saving with game uuid _ = create(Decision.self, from: loveInterestDecision1Json) _ = create(Person.self, from: ashleyJson) var shepard = create(Shepard.self, from: femShep1Json) _ = create(Shepard.self, from: femShep2Json) _ = shepard?.changed(loveInterestId: "D1.LoveAshley") let uuid = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFD")! shepard = Shepard.get(uuid: uuid) XCTAssert(shepard?.loveInterestId == "D1.LoveAshley", "Failed to change love interest") // make sure change was NOT propogated to other versions: let uuid2 = UUID(uuidString: "BC0D3009-3385-4132-851A-DF472CBF9EFE")! shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.loveInterestId == nil, "Incorrectly changed love interest on other version") } /// Test Shepard change action. func testChangeGender() { initializeCurrentGame(broShepGameSequenceUuid) // needed for saving with game uuid _ = create(Decision.self, from: loveInterestDecision1Json) _ = create(Decision.self, from: loveInterestDecision2Json) _ = create(Person.self, from: ashleyJson) _ = create(Person.self, from: liaraJson) // set up App.current.changeGame { game in var game = game _ = game?.shepard?.delete() game?.shepard = create(Shepard.self, from: broShep1Json) return game } var shepard = App.current.game?.shepard // male values XCTAssert(shepard?.gender == .male, "Incorrect initial gender") XCTAssert(shepard?.fullName == "John Shepard", "Incorrect initial name") XCTAssert(shepard?.photo?.filePath == "http://urdnot.com/megametracker/app/images/Game1/1_BroShep.png", "Incorrect initial photo") XCTAssert(shepard?.loveInterestId == "S1.Ashley", "Incorrect initial love interest") XCTAssert(shepard?.appearance.format() == "432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.217.65", "Incorrect initial appearance") // change _ = shepard?.changed(gender: .female) let uuid2 = UUID(uuidString: "B6D0BD56-9CA9-4060-8F2E-E4DFE4EEE8A2")! shepard = Shepard.get(uuid: uuid2) // female values XCTAssert(shepard?.gender == .female, "Failed to change gender") XCTAssert(shepard?.fullName == "Jane Shepard", "Failed to gender-change default name") XCTAssert(shepard?.photo?.filePath == "http://urdnot.com/megametracker/app/images/Game1/1_FemShep.png", "Failed to gender-change default photo") XCTAssert(shepard?.loveInterestId == nil, "Failed to gender-change love interest") XCTAssert(shepard?.appearance.format() == "432.4FL.CJC.IF6.FJH.II7.IJH.K4K.EFJ.8HH.671.XXX.X", "Failed to gender-change appearance") // verify love interest is not changed when love interest is bisexual _ = shepard?.changed(loveInterestId: "S1.Liara").changed(gender: .male) shepard = Shepard.get(uuid: uuid2) XCTAssert(shepard?.loveInterestId == "S1.Liara", "Incorrect gender-change love interest") } /// Test Shepard change action. func testCreateNewVersion() { initializeCurrentGame(broShepGameSequenceUuid) // needed for saving with game uuid // set up App.current.changeGame { game in var game = game _ = game?.shepard?.delete() game?.shepard = create(Shepard.self, from: broShep1Json) return game } let shepard1 = App.current.game?.shepard App.current.game?.change(gameVersion: .game2) let shepard2 = App.current.game?.shepard // female values XCTAssert(shepard2?.gender == shepard1?.gender, "New game version shepard has incorrect gender") XCTAssert(shepard2?.fullName == shepard1?.fullName, "New game version shepard has incorrect name") XCTAssert(shepard2?.photo?.filePath == "http://urdnot.com/megametracker/app/images/Game2/2_BroShep.png", "New game version shepard has incorrect photo") XCTAssert(shepard2?.loveInterestId == nil, "New game version shepard has incorrect love interest") XCTAssert(shepard2?.appearance.format() == "432.FLC.JCI.F6F.JHI.I7I.JHK.4KE.FJ8.HH7.216.5", "New game version shepard has incorrect appearance") XCTAssert(shepard2?.classTalent == shepard1?.classTalent, "New game version shepard has incorrect class") XCTAssert(shepard2?.reputation == shepard1?.reputation, "New game version shepard has incorrect reputation") XCTAssert(shepard2?.origin == shepard1?.origin, "New game version shepard has incorrect origin") XCTAssert(shepard2?.level == 1, "New game version shepard has incorrect level") XCTAssert(shepard2?.renegade == 0, "New game version shepard has incorrect renegade") XCTAssert(shepard2?.paragon == 0, "New game version shepard has incorrect paragon") } // swiftlint:enable line_length }
mit
74fd2eecd04584d6e14de8b34f176889
46.820856
550
0.699469
3.248275
false
true
false
false
nickplee/Aestheticam
Aestheticam/Vendor/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift
2
25947
// // Integer+RandomKit.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // // The '>>' and '<<' operators are covered by FixedWidthInteger #if !swift(>=3.2) import ShiftOperations #endif extension ExpressibleByIntegerLiteral where Self: UnsafeRandom { /// The base randomizable value for `Self`. Always zero. public static var randomizableValue: Self { return 0 } } extension ExpressibleByIntegerLiteral where Self: RandomToValue & RandomThroughValue { /// The random base from which to generate. public static var randomBase: Self { return 0 } } #if swift(>=3.2) private extension FixedWidthInteger where Self: Random { @inline(__always) static func _randomGreater<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { var result: Self repeat { result = random(using: &randomGenerator) } while result < max % value return result % value } @inline(__always) static func _randomLess<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { var result: Self repeat { result = random(using: &randomGenerator) } while result > min % value return result % value } } #else private extension Integer where Self: RandomWithMax { @inline(__always) static func _randomGreater<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { var result: Self repeat { result = random(using: &randomGenerator) } while result < max % value return result % value } } private extension Integer where Self: RandomWithMin { @inline(__always) static func _randomLess<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { var result: Self repeat { result = random(using: &randomGenerator) } while result > min % value return result % value } } #endif #if swift(>=3.2) extension SignedInteger where Self: FixedWidthInteger & Random & RandomToValue & RandomThroughValue { /// Generates a random value of `Self` from `randomBase` to `value`. public static func random<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { if value == randomBase { return value } else if value < randomBase { return _randomLess(to: value, using: &randomGenerator) } else { return _randomGreater(to: value, using: &randomGenerator) } } /// Generates a random value of `Self` from `randomBase` through `value`. public static func random<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> Self { switch value { case randomBase: return value case min: var result: Self repeat { result = random(using: &randomGenerator) } while result > 0 return result case max: var result: Self repeat { result = random(using: &randomGenerator) } while result < 0 return result default: if value < randomBase { return _randomLess(to: value &- 1, using: &randomGenerator) } else { return _randomGreater(to: value &+ 1, using: &randomGenerator) } } } } #else extension SignedInteger where Self: RandomWithMax & RandomWithMin & RandomToValue & RandomThroughValue { /// Generates a random value of `Self` from `randomBase` to `value`. public static func random<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { if value == randomBase { return value } else if value < randomBase { return _randomLess(to: value, using: &randomGenerator) } else { return _randomGreater(to: value, using: &randomGenerator) } } /// Generates a random value of `Self` from `randomBase` through `value`. public static func random<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> Self { switch value { case randomBase: return value case min: var result: Self repeat { result = random(using: &randomGenerator) } while result > 0 return result case max: var result: Self repeat { result = random(using: &randomGenerator) } while result < 0 return result default: if value < randomBase { return _randomLess(to: value &- 1, using: &randomGenerator) } else { return _randomGreater(to: value &+ 1, using: &randomGenerator) } } } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger & Random & RandomToValue { /// Generates a random value of `Self` from `randomBase` to `value`. public static func random<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { switch value { case 0: return value default: return _randomGreater(to: value, using: &randomGenerator) } } } #else extension UnsignedInteger where Self: Random & RandomToValue & RandomWithMax { /// Generates a random value of `Self` from `randomBase` to `value`. public static func random<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> Self { switch value { case randomBase: return value default: return _randomGreater(to: value, using: &randomGenerator) } } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger & RandomToValue & RandomInRange { /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Self>, using randomGenerator: inout R) -> Self { return range.lowerBound &+ random(to: range.upperBound &- range.lowerBound, using: &randomGenerator) } } #else extension UnsignedInteger where Self: RandomToValue & RandomInRange { /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Self>, using randomGenerator: inout R) -> Self { return range.lowerBound &+ random(to: range.upperBound &- range.lowerBound, using: &randomGenerator) } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger & Random & RandomThroughValue { /// Generates a random value of `Self` from `randomBase` through `value`. public static func random<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> Self { switch value { case randomBase: return value case max: return random(using: &randomGenerator) default: return _randomGreater(to: value &+ 1, using: &randomGenerator) } } } #else extension UnsignedInteger where Self: RandomWithMax & RandomThroughValue { /// Generates a random value of `Self` from `randomBase` through `value`. public static func random<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> Self { switch value { case randomBase: return value case max: return random(using: &randomGenerator) default: return _randomGreater(to: value &+ 1, using: &randomGenerator) } } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger & RandomThroughValue & RandomInClosedRange { /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> Self { let bound = closedRange.upperBound &- closedRange.lowerBound let value = random(through: bound, using: &randomGenerator) return closedRange.lowerBound &+ value } } #else extension UnsignedInteger where Self: RandomThroughValue & RandomInClosedRange { /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> Self { let bound = closedRange.upperBound &- closedRange.lowerBound let value = random(through: bound, using: &randomGenerator) return closedRange.lowerBound &+ value } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger & Random & RandomWithMaxWidth { /// Generates a random value of `Self` with a maximum width using `randomGenerator`. public static func random<R: RandomGenerator>(withMaxWidth width: Int, using randomGenerator: inout R) -> Self { guard width > 0 else { return 0 } let result = random(using: &randomGenerator) let typeWidth = MemoryLayout<Self>.size * 8 if width > typeWidth { return result } else { if (width % typeWidth) != 0 { return result & (max &>> Self(typeWidth - width)) } else { return result } } } } #else extension UnsignedInteger where Self: ShiftOperations & RandomWithMax & RandomWithMaxWidth { /// Generates a random value of `Self` with a maximum width using `randomGenerator`. public static func random<R: RandomGenerator>(withMaxWidth width: Int, using randomGenerator: inout R) -> Self { guard width > 0 else { return 0 } let result = random(using: &randomGenerator) let typeWidth = MemoryLayout<Self>.size * 8 if width > typeWidth { return result } else { if (width % typeWidth) != 0 { return result & (max >> Self(UIntMax(typeWidth - width))) } else { return result } } } } #endif #if swift(>=3.2) extension UnsignedInteger where Self: RandomWithMaxWidth & RandomWithExactWidth { /// Generates a random value of `Self` with an exact width using `randomGenerator`. public static func random<R: RandomGenerator>(withExactWidth width: Int, using randomGenerator: inout R) -> Self { guard width > 0 else { return 0 } return random(withMaxWidth: width, using: &randomGenerator) | Self(1 &<< Self(width - 1)) } } #else extension UnsignedInteger where Self: ShiftOperations & RandomWithMaxWidth & RandomWithExactWidth { /// Generates a random value of `Self` with an exact width using `randomGenerator`. public static func random<R: RandomGenerator>(withExactWidth width: Int, using randomGenerator: inout R) -> Self { guard width > 0 else { return 0 } return random(withMaxWidth: width, using: &randomGenerator) | (1 << Self(UIntMax(width - 1))) } } #endif extension Int: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { @inline(__always) private static func _resignedRange(from range: Range<Int>) -> Range<UInt> { let lo = UInt(bitPattern: range.lowerBound)._resigned let hi = UInt(bitPattern: range.upperBound)._resigned return Range(uncheckedBounds: (lo, hi)) } /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Int { return Int(bitPattern: UInt.random(using: &randomGenerator)) } /// Returns an optional random value of `Self` inside of the range using `randomGenerator`. public static func random<R: RandomGenerator>(in range: Range<Int>, using randomGenerator: inout R) -> Int? { guard let random = UInt.random(in: _resignedRange(from: range), using: &randomGenerator) else { return nil } return Int(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Int>, using randomGenerator: inout R) -> Int { let random = UInt.uncheckedRandom(in: _resignedRange(from: range), using: &randomGenerator) return Int(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Int>, using randomGenerator: inout R) -> Int { let lo = UInt(bitPattern: closedRange.lowerBound)._resigned let hi = UInt(bitPattern: closedRange.upperBound)._resigned let closedRange = ClosedRange(uncheckedBounds: (lo, hi)) return Int(bitPattern: UInt.random(in: closedRange, using: &randomGenerator)._resigned) } } extension Int64: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { @inline(__always) private static func _resignedRange(from range: Range<Int64>) -> Range<UInt64> { let lo = UInt64(bitPattern: range.lowerBound)._resigned let hi = UInt64(bitPattern: range.upperBound)._resigned return Range(uncheckedBounds: (lo, hi)) } /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Int64 { return Int64(bitPattern: UInt64.random(using: &randomGenerator)) } /// Returns an optional random value of `Self` inside of the range using `randomGenerator`. public static func random<R: RandomGenerator>(in range: Range<Int64>, using randomGenerator: inout R) -> Int64? { guard let random = UInt64.random(in: _resignedRange(from: range), using: &randomGenerator) else { return nil } return Int64(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Int64>, using randomGenerator: inout R) -> Int64 { let lo = UInt64(bitPattern: range.lowerBound)._resigned let hi = UInt64(bitPattern: range.upperBound)._resigned let range = Range(uncheckedBounds: (lo, hi)) let random = UInt64.uncheckedRandom(in: range, using: &randomGenerator) return Int64(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Int64>, using randomGenerator: inout R) -> Int64 { let lo = UInt64(bitPattern: closedRange.lowerBound)._resigned let hi = UInt64(bitPattern: closedRange.upperBound)._resigned let closedRange = ClosedRange(uncheckedBounds: (lo, hi)) return Int64(bitPattern: UInt64.random(in: closedRange, using: &randomGenerator)._resigned) } } extension Int32: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { @inline(__always) private static func _resignedRange(from range: Range<Int32>) -> Range<UInt32> { let lo = UInt32(bitPattern: range.lowerBound)._resigned let hi = UInt32(bitPattern: range.upperBound)._resigned return Range(uncheckedBounds: (lo, hi)) } /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Int32 { return Int32(bitPattern: UInt32.random(using: &randomGenerator)) } /// Returns an optional random value of `Self` inside of the range using `randomGenerator`. public static func random<R: RandomGenerator>(in range: Range<Int32>, using randomGenerator: inout R) -> Int32? { guard let random = UInt32.random(in: _resignedRange(from: range), using: &randomGenerator) else { return nil } return Int32(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Int32>, using randomGenerator: inout R) -> Int32 { let lo = UInt32(bitPattern: range.lowerBound)._resigned let hi = UInt32(bitPattern: range.upperBound)._resigned let range = Range(uncheckedBounds: (lo, hi)) let random = UInt32.uncheckedRandom(in: range, using: &randomGenerator) return Int32(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Int32>, using randomGenerator: inout R) -> Int32 { let lo = UInt32(bitPattern: closedRange.lowerBound)._resigned let hi = UInt32(bitPattern: closedRange.upperBound)._resigned let closedRange = ClosedRange(uncheckedBounds: (lo, hi)) return Int32(bitPattern: UInt32.random(in: closedRange, using: &randomGenerator)._resigned) } } extension Int16: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { @inline(__always) private static func _resignedRange(from range: Range<Int16>) -> Range<UInt16> { let lo = UInt16(bitPattern: range.lowerBound)._resigned let hi = UInt16(bitPattern: range.upperBound)._resigned return Range(uncheckedBounds: (lo, hi)) } /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Int16 { return Int16(bitPattern: UInt16.random(using: &randomGenerator)) } /// Returns an optional random value of `Self` inside of the range using `randomGenerator`. public static func random<R: RandomGenerator>(in range: Range<Int16>, using randomGenerator: inout R) -> Int16? { guard let random = UInt16.random(in: _resignedRange(from: range), using: &randomGenerator) else { return nil } return Int16(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Int16>, using randomGenerator: inout R) -> Int16 { let lo = UInt16(bitPattern: range.lowerBound)._resigned let hi = UInt16(bitPattern: range.upperBound)._resigned let range = Range(uncheckedBounds: (lo, hi)) let random = UInt16.uncheckedRandom(in: range, using: &randomGenerator) return Int16(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Int16>, using randomGenerator: inout R) -> Int16 { let lo = UInt16(bitPattern: closedRange.lowerBound)._resigned let hi = UInt16(bitPattern: closedRange.upperBound)._resigned let closedRange = ClosedRange(uncheckedBounds: (lo, hi)) return Int16(bitPattern: UInt16.random(in: closedRange, using: &randomGenerator)._resigned) } } extension Int8: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange { @inline(__always) private static func _resignedRange(from range: Range<Int8>) -> Range<UInt8> { let lo = UInt8(bitPattern: range.lowerBound)._resigned let hi = UInt8(bitPattern: range.upperBound)._resigned return Range(uncheckedBounds: (lo, hi)) } /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Int8 { return Int8(bitPattern: UInt8.random(using: &randomGenerator)) } /// Returns an optional random value of `Self` inside of the range using `randomGenerator`. public static func random<R: RandomGenerator>(in range: Range<Int8>, using randomGenerator: inout R) -> Int8? { guard let random = UInt8.random(in: _resignedRange(from: range), using: &randomGenerator) else { return nil } return Int8(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the unchecked range using `randomGenerator`. public static func uncheckedRandom<R: RandomGenerator>(in range: Range<Int8>, using randomGenerator: inout R) -> Int8 { let lo = UInt8(bitPattern: range.lowerBound)._resigned let hi = UInt8(bitPattern: range.upperBound)._resigned let range = Range(uncheckedBounds: (lo, hi)) let random = UInt8.uncheckedRandom(in: range, using: &randomGenerator) return Int8(bitPattern: random._resigned) } /// Returns a random value of `Self` inside of the closed range. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<Int8>, using randomGenerator: inout R) -> Int8 { let lo = UInt8(bitPattern: closedRange.lowerBound)._resigned let hi = UInt8(bitPattern: closedRange.upperBound)._resigned let closedRange = ClosedRange(uncheckedBounds: (lo, hi)) return Int8(bitPattern: UInt8.random(in: closedRange, using: &randomGenerator)._resigned) } } #if swift(>=3.2) extension UnsignedInteger where Self: FixedWidthInteger { fileprivate var _resigned: Self { let bits = Self(truncatingIfNeeded: MemoryLayout<Self>.size * 8 - 1) return self ^ (1 &<< bits) } } #endif extension UInt: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange, RandomWithMaxWidth, RandomWithExactWidth { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UInt { if MemoryLayout<Int>.size == 8 { return UInt(randomGenerator.random64()) } else { return UInt(randomGenerator.random32()) } } #if !swift(>=3.2) fileprivate var _resigned: UInt { let bits: UInt #if arch(i386) || arch(arm) bits = 31 #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) bits = 63 #else bits = UInt(bitPattern: MemoryLayout<UInt>.size * 8 - 1) #endif return self ^ (1 << bits) } #endif } extension UInt64: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange, RandomWithMaxWidth, RandomWithExactWidth { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UInt64 { return randomGenerator.random64() } #if !swift(>=3.2) fileprivate var _resigned: UInt64 { return self ^ (1 << 63) } #endif } extension UInt32: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange, RandomWithMaxWidth, RandomWithExactWidth { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UInt32 { return randomGenerator.random32() } #if !swift(>=3.2) fileprivate var _resigned: UInt32 { return self ^ (1 << 31) } #endif } extension UInt16: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange, RandomWithMaxWidth, RandomWithExactWidth { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UInt16 { return randomGenerator.random16() } #if !swift(>=3.2) fileprivate var _resigned: UInt16 { return self ^ (1 << 15) } #endif } extension UInt8: UnsafeRandom, RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomInRange, RandomInClosedRange, RandomWithMaxWidth, RandomWithExactWidth { /// Generates a random value of `Self` using `randomGenerator`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UInt8 { return randomGenerator.random8() } #if !swift(>=3.2) fileprivate var _resigned: UInt8 { return self ^ (1 << 7) } #endif }
mit
04201fa50ef486614d8315693a4898cc
37.669151
175
0.667129
4.429327
false
false
false
false
russbishop/swift
test/SILOptimizer/mandatory_nil_comparison_inlining.swift
1
908
// RUN: %target-swift-frontend -primary-file %s -emit-sil -o - -verify | FileCheck %s // CHECK-LABEL: sil {{.*}} @{{.*}}generic_func // CHECK: switch_enum_addr // CHECK: return func generic_func<T>(x: [T]?) -> Bool { return x == nil } // CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_nil // CHECK: switch_enum_addr // CHECK: return func array_func_rhs_nil(x: [Int]?) -> Bool { return x == nil } // CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_nil // CHECK: switch_enum_addr // CHECK: return func array_func_lhs_nil(x: [Int]?) -> Bool { return nil == x } // CHECK-LABEL: sil {{.*}} @{{.*}}array_func_rhs_non_nil // CHECK: switch_enum_addr // CHECK: return func array_func_rhs_non_nil(x: [Int]?) -> Bool { return x != nil } // CHECK-LABEL: sil {{.*}} @{{.*}}array_func_lhs_non_nil // CHECK: switch_enum_addr // CHECK: return func array_func_lhs_non_nil(x: [Int]?) -> Bool { return nil != x }
apache-2.0
093d289e4202ab239e801d3d3cb36186
22.894737
85
0.590308
2.919614
false
false
false
false
ZhengQingchen/ContactList
Contacts/ViewController.swift
1
3825
// // ViewController.swift // Contacts // // Created by mac on 15/11/21. // Copyright © 2015年 mac. All rights reserved. // import UIKit import Fakery struct Person { var name: String? var phone: String? var color: UIColor? init(){ } } let arrayPrefix = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"] class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var searchController: UISearchController! var people: [Person] = [] var newPeople:[(String, [Person])]! override func viewDidLoad() { super.viewDidLoad() getFakerDate() let resultViewController = storyboard?.instantiateViewControllerWithIdentifier("SearchResult") as! SearchResultViewController resultViewController.searchModel = people searchController = UISearchController(searchResultsController: resultViewController) searchController.searchResultsUpdater = resultViewController tableView.tableHeaderView = searchController.searchBar } func getFakerDate(){ let faker = Faker(locale: "nb-NO") var morePeople: [String: [Person]] = [:] for _ in 0...100 { var person = Person() person.name = faker.name.name() person.phone = faker.phoneNumber.phoneNumber() person.color = UIColor.randomColor() people.append(person) } // Do any additional setup after loading the view, typically from a nib. people.sortInPlace{ $0.name < $1.name } for item in people { for prefix in arrayPrefix { if item.name!.hasPrefix(prefix) { if var innerPerson = morePeople[prefix] { innerPerson.append(item) morePeople.updateValue(innerPerson, forKey: prefix) }else { var new = [Person]() new.append(item) morePeople.updateValue(new, forKey: prefix) } } } } let newarray = morePeople.sort { (item1, item2) -> Bool in item1.0 < item2.0 } newPeople = newarray } } extension ViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return newPeople.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newPeople[section].1.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.imageView?.image = imageOfSize(CGSize(width: 40, height: 40)){ () -> () in let con = UIGraphicsGetCurrentContext()! CGContextAddEllipseInRect(con, CGRectMake(0,0,40,40)) CGContextSetFillColorWithColor(con, UIColor.randomColor().CGColor) CGContextFillPath(con) } cell.imageView?.frame = CGRect(x: 0, y: 0, width: 40, height: 40) let userSection = newPeople[indexPath.section] let user = userSection.1[indexPath.row] cell.textLabel?.text = user.name cell.detailTextLabel?.text = user.phone return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return newPeople[section].0 } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { // var stringArray = [String]() // for item in newPeople { // stringArray.append(item.0) // } // return stringArray return arrayPrefix } } func imageOfSize(size: CGSize, _ opaque: Bool = false, @noescape _ closuer:() -> ()) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, opaque, 0) closuer() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result }
mit
513521328438fba7f1dfdb11fb237cac
28.627907
129
0.659341
4.418497
false
false
false
false
rduan8/Aerial
Aerial/Source/Views/AerialView.swift
1
8930
// // AerialView.swift // Aerial // // Created by John Coates on 10/22/15. // Copyright © 2015 John Coates. All rights reserved. // import Foundation import ScreenSaver import AVFoundation import AVKit @objc(AerialView) class AerialView : ScreenSaverView { // var playerView: AVPlayerView! var playerLayer:AVPlayerLayer! var preferencesController:PreferencesWindowController? static var players:[AVPlayer] = [AVPlayer]() static var previewPlayer:AVPlayer? static var previewView:AerialView? var player:AVPlayer? static let defaults:NSUserDefaults = ScreenSaverDefaults(forModuleWithName: "com.JohnCoates.Aerial")! as ScreenSaverDefaults static var sharingPlayers:Bool { defaults.synchronize(); return !defaults.boolForKey("differentDisplays"); } static var sharedViews:[AerialView] = [] // MARK: - Shared Player static var singlePlayerAlreadySetup:Bool = false; class var sharedPlayer: AVPlayer { struct Static { static let instance: AVPlayer = AVPlayer(); static var _player:AVPlayer?; static var player:AVPlayer { if let activePlayer = _player { return activePlayer; } _player = AVPlayer(); return _player!; } } return Static.player; } // MARK: - Init / Setup override init?(frame: NSRect, isPreview: Bool) { super.init(frame: frame, isPreview: isPreview) self.animationTimeInterval = 1.0 / 30.0 setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } deinit { debugLog("deinit AerialView"); NSNotificationCenter.defaultCenter().removeObserver(self); // set player item to nil if not preview player if player != AerialView.previewPlayer { player?.rate = 0; player?.replaceCurrentItemWithPlayerItem(nil); } guard let player = self.player else { return; } // Remove from player index let indexMaybe = AerialView.players.indexOf(player) guard let index = indexMaybe else { return; } AerialView.players.removeAtIndex(index); } func setupPlayerLayer(withPlayer player:AVPlayer) { self.layer = CALayer() guard let layer = self.layer else { NSLog("Aerial Errror: Couldn't create CALayer"); return; } self.wantsLayer = true layer.backgroundColor = NSColor.blackColor().CGColor layer.delegate = self; layer.needsDisplayOnBoundsChange = true; layer.frame = self.bounds // layer.backgroundColor = NSColor.greenColor().CGColor debugLog("setting up player layer with frame: \(self.bounds) / \(self.frame)"); playerLayer = AVPlayerLayer(player: player); if #available(OSX 10.10, *) { playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill }; playerLayer.autoresizingMask = [CAAutoresizingMask.LayerWidthSizable, CAAutoresizingMask.LayerHeightSizable] playerLayer.frame = layer.bounds; layer.addSublayer(playerLayer); } func setup() { var localPlayer:AVPlayer? if (!self.preview) { // check if we should share preview's player if (AerialView.players.count == 0) { if AerialView.previewPlayer != nil { localPlayer = AerialView.previewPlayer; } } } else { AerialView.previewView = self; } if AerialView.sharingPlayers { AerialView.sharedViews.append(self); } if localPlayer == nil { if AerialView.sharingPlayers { if AerialView.previewPlayer != nil { localPlayer = AerialView.previewPlayer } else { localPlayer = AerialView.sharedPlayer; } } else { localPlayer = AVPlayer(); } } guard let player = localPlayer else { NSLog("Aerial Error: Couldn't create AVPlayer!"); return; } self.player = player; if (self.preview) { AerialView.previewPlayer = player; } else if (AerialView.sharingPlayers == false) { // add to player list AerialView.players.append(player); } setupPlayerLayer(withPlayer: player); if (AerialView.sharingPlayers == true && AerialView.singlePlayerAlreadySetup) { self.playerLayer.player = AerialView.sharedViews[0].player return; } AerialView.singlePlayerAlreadySetup = true; ManifestLoader.instance.addCallback { (videos:[AerialVideo]) -> Void in self.playNextVideo(); }; } // MARK: - AVPlayerItem Notifications func playerItemFailedtoPlayToEnd(aNotification: NSNotification) { NSLog("AVPlayerItemFailedToPlayToEndTimeNotification \(aNotification)"); playNextVideo(); } func playerItemNewErrorLogEntryNotification(aNotification: NSNotification) { NSLog("AVPlayerItemNewErrorLogEntryNotification \(aNotification)"); } func playerItemPlaybackStalledNotification(aNotification: NSNotification) { NSLog("AVPlayerItemPlaybackStalledNotification \(aNotification)"); } func playerItemDidReachEnd(aNotification: NSNotification) { debugLog("played did reach end"); debugLog("notification: \(aNotification)"); playNextVideo() debugLog("playing next video for player \(player)"); } // MARK: - Playing Videos func playNextVideo() { let notificationCenter = NSNotificationCenter.defaultCenter() // remove old entries notificationCenter.removeObserver(self); let player = AVPlayer() // play another video let oldPlayer = self.player self.player = player self.playerLayer.player = self.player if self.preview { AerialView.previewPlayer = player } debugLog("Setting player for all player layers in \(AerialView.sharedViews)"); for view in AerialView.sharedViews { view.playerLayer.player = player } if (oldPlayer == AerialView.previewPlayer) { AerialView.previewView?.playerLayer.player = self.player } let randomVideo = ManifestLoader.instance.randomVideo(); guard let video = randomVideo else { NSLog("Aerial: Error grabbing random video!"); return; } let videoURL = video.url; let asset = CachedOrCachingAsset(videoURL) // let asset = AVAsset(URL: videoURL); let item = AVPlayerItem(asset: asset); player.replaceCurrentItemWithPlayerItem(item); debugLog("playing video: \(video.url)"); if player.rate == 0 { player.play(); } guard let currentItem = player.currentItem else { NSLog("Aerial Error: No current item!"); return; } debugLog("observing current item \(currentItem)"); notificationCenter.addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: currentItem); notificationCenter.addObserver(self, selector: "playerItemNewErrorLogEntryNotification:", name: AVPlayerItemNewErrorLogEntryNotification, object: currentItem); notificationCenter.addObserver(self, selector: "playerItemFailedtoPlayToEnd:", name: AVPlayerItemFailedToPlayToEndTimeNotification, object: currentItem); notificationCenter.addObserver(self, selector: "playerItemPlaybackStalledNotification:", name: AVPlayerItemPlaybackStalledNotification, object: currentItem); player.actionAtItemEnd = AVPlayerActionAtItemEnd.None; } // MARK: - Preferences override func hasConfigureSheet() -> Bool { return true; } override func configureSheet() -> NSWindow? { if let controller = preferencesController { return controller.window } let controller = PreferencesWindowController(windowNibName: "PreferencesWindow"); preferencesController = controller; return controller.window; } }
mit
71190ca3c6a70edc2781b7ab0dddab77
30.333333
167
0.592564
5.539082
false
false
false
false
MukeshKumarS/Swift
stdlib/public/core/Optional.swift
1
7535
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // The compiler has special knowledge of Optional<Wrapped>, including the fact // that it is an enum with cases named 'None' and 'Some'. public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible { case None case Some(Wrapped) @available(*, unavailable, renamed="Wrapped") public typealias T = Wrapped /// Construct a `nil` instance. @_transparent public init() { self = .None } /// Construct a non-`nil` instance that stores `some`. @_transparent public init(_ some: Wrapped) { self = .Some(some) } /// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`. @warn_unused_result public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U? { switch self { case .Some(let y): return .Some(try f(y)) case .None: return .None } } /// Returns `nil` if `self` is `nil`, `f(self!)` otherwise. @warn_unused_result public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U? { switch self { case .Some(let y): return try f(y) case .None: return .None } } /// Returns a mirror that reflects `self`. @warn_unused_result public func _getMirror() -> _MirrorType { return _OptionalMirror(self) } /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { self = .None } } extension Optional : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { switch self { case .Some(let value): var result = "Optional(" debugPrint(value, terminator: "", toStream: &result) result += ")" return result case .None: return "nil" } } } // While this free function may seem obsolete, since an optional is // often expressed as (x as Wrapped), it can lead to cleaner usage, i.e. // // map(x as Wrapped) { ... } // vs // (x as Wrapped).map { ... } // /// Haskell's fmap for Optionals. @available(*, unavailable, message="call the 'map()' method on the optional value") public func map<T, U>(x: T?, @noescape _ f: (T)->U) -> U? { fatalError("unavailable function can't be called") } /// Returns `f(self)!` iff `self` and `f(self)` are not `nil`. @available(*, unavailable, message="call the 'flatMap()' method on the optional value") public func flatMap<T, U>(x: T?, @noescape _ f: (T)->U?) -> U? { fatalError("unavailable function can't be called") } // Intrinsics for use by language features. @_transparent public // COMPILER_INTRINSIC func _doesOptionalHaveValueAsBool<Wrapped>(v: Wrapped?) -> Bool { return v != nil } @_transparent public // COMPILER_INTRINSIC func _diagnoseUnexpectedNilOptional() { _preconditionFailure( "unexpectedly found nil while unwrapping an Optional value") } @_transparent public // COMPILER_INTRINSIC func _getOptionalValue<Wrapped>(v: Wrapped?) -> Wrapped { switch v { case let x?: return x case .None: _preconditionFailure( "unexpectedly found nil while unwrapping an Optional value") } } @_transparent public // COMPILER_INTRINSIC func _injectValueIntoOptional<Wrapped>(v: Wrapped) -> Wrapped? { return .Some(v) } @_transparent public // COMPILER_INTRINSIC func _injectNothingIntoOptional<Wrapped>() -> Wrapped? { return .None } // Comparisons @warn_unused_result public func == <T: Equatable> (lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l == r case (nil, nil): return true default: return false } } @warn_unused_result public func != <T : Equatable> (lhs: T?, rhs: T?) -> Bool { return !(lhs == rhs) } // Enable pattern matching against the nil literal, even if the element type // isn't equatable. public struct _OptionalNilComparisonType : NilLiteralConvertible { /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { } } @_transparent @warn_unused_result public func ~= <T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool { switch rhs { case .Some(_): return false case .None: return true } } // Enable equality comparisons against the nil literal, even if the // element type isn't equatable @warn_unused_result public func == <T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool { switch lhs { case .Some(_): return false case .None: return true } } @warn_unused_result public func != <T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool { switch lhs { case .Some(_): return true case .None: return false } } @warn_unused_result public func == <T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool { switch rhs { case .Some(_): return false case .None: return true } } @warn_unused_result public func != <T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool { switch rhs { case .Some(_): return true case .None: return false } } internal struct _OptionalMirror<Wrapped> : _MirrorType { let _value : Optional<Wrapped> init(_ x : Optional<Wrapped>) { _value = x } var value: Any { return _value } var valueType: Any.Type { return (_value as Any).dynamicType } var objectIdentifier: ObjectIdentifier? { return .None } var count: Int { return (_value != nil) ? 1 : 0 } subscript(i: Int) -> (String, _MirrorType) { switch (_value, i) { case (.Some(let contents), 0) : return ("Some", _reflect(contents)) default: _preconditionFailure("cannot extract this child index") } } var summary: String { switch _value { case let contents?: return _reflect(contents).summary default: return "nil" } } var quickLookObject: PlaygroundQuickLook? { return .None } var disposition: _MirrorDisposition { return .Optional } } @warn_unused_result public func < <T : Comparable> (lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } @warn_unused_result public func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } @warn_unused_result public func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } @warn_unused_result public func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } @_transparent @warn_unused_result public func ?? <T> (optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T { switch optional { case .Some(let value): return value case .None: return try defaultValue() } } @_transparent @warn_unused_result public func ?? <T> (optional: T?, @autoclosure defaultValue: () throws -> T?) rethrows -> T? { switch optional { case .Some(let value): return value case .None: return try defaultValue() } }
apache-2.0
f92ce47a961d2137fb0cc23043bedc96
22.844937
87
0.626808
3.75436
false
false
false
false
AlexMobile/AGChart
AGChart/AGChart/Data/AGChartCustomizer.swift
1
871
// // AGChartCustomizer.swift // AGChart // // Created by Alexey Golovenkov on 20.12.14. // Copyright (c) 2014 Alexey Golovenkov. All rights reserved. // import UIKit public class AGChartCustomizer: NSObject { @IBOutlet weak var view: AGChartView? = nil @IBInspectable var chartLineWidth: CGFloat = 1.0 @IBInspectable var chartColor: UIColor = UIColor.redColor() @IBInspectable var horizontalAxe: Bool = false @IBInspectable var horizontalAxeAreaWidth: CGFloat = 5.0 @IBInspectable var horizontalAxeColor: UIColor = UIColor.clearColor() @IBInspectable var horizontalAxeWidth: CGFloat = 1.0 @IBInspectable var verticalAxe: Bool = false @IBInspectable var verticalAxeAreaWidth: CGFloat = 5.0 @IBInspectable var verticalAxeColor: UIColor = UIColor.clearColor() @IBInspectable var verticalAxeWidth: CGFloat = 1.0 }
mit
004619a282bb650bfe614da35c3dc94e
33.84
73
0.734788
4.1875
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/LaunchSequenceOperation.swift
1
7626
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // 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. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSyncEngine import WireCommonComponents import AppCenter #if DISABLE_APPCENTER_CRASH_LOGGING #else import AppCenterCrashes #endif import AppCenterDistribute import avs // MARK: - LaunchSequenceOperation protocol LaunchSequenceOperation { func execute() } // MARK: - BackendEnvironmentOperation final class BackendEnvironmentOperation: LaunchSequenceOperation { func execute() { guard let backendTypeOverride = AutomationHelper.sharedHelper.backendEnvironmentTypeOverride() else { return } AutomationHelper.sharedHelper.persistBackendTypeOverrideIfNeeded(with: backendTypeOverride) } } // MARK: - PerformanceDebuggerOperation final class PerformanceDebuggerOperation: LaunchSequenceOperation { func execute() { PerformanceDebugger.shared.start() } } // MARK: - ZMSLogOperation final class ZMSLogOperation: LaunchSequenceOperation { func execute() { ZMSLog.switchCurrentLogToPrevious() } } // MARK: - ZMSLogOperation final class AVSLoggingOperation: LaunchSequenceOperation { func execute() { SessionManager.startAVSLogging() } } // MARK: - AutomationHelperOperation final class AutomationHelperOperation: LaunchSequenceOperation { func execute() { AutomationHelper.sharedHelper.installDebugDataIfNeeded() } } // MARK: - MediaManagerOperation final class MediaManagerOperation: LaunchSequenceOperation { private let mediaManagerLoader = MediaManagerLoader() func execute() { mediaManagerLoader.send(message: .appStart) } } // MARK: - TrackingOperation final class TrackingOperation: LaunchSequenceOperation { func execute() { let containsConsoleAnalytics = ProcessInfo.processInfo .arguments.contains(AnalyticsProviderFactory.ZMConsoleAnalyticsArgumentKey) AnalyticsProviderFactory.shared.useConsoleAnalytics = containsConsoleAnalytics Analytics.shared = Analytics(optedOut: TrackingManager.shared.disableAnalyticsSharing) } } // MARK: - FileBackupExcluderOperation final class FileBackupExcluderOperation: LaunchSequenceOperation { private let fileBackupExcluder = FileBackupExcluder() func execute() { guard let appGroupIdentifier = Bundle.main.appGroupIdentifier else { return } let sharedContainerURL = FileManager.sharedContainerDirectory(for: appGroupIdentifier) fileBackupExcluder.excludeLibraryFolderInSharedContainer(sharedContainerURL: sharedContainerURL) } } // MARK: - AppCenterOperation final class AppCenterOperation: NSObject, LaunchSequenceOperation { private var zmLog: ZMSLog { return ZMSLog(tag: "UI") } func execute() { guard AutomationHelper.sharedHelper.useAppCenter || Bundle.useAppCenter else { AppCenter.setTrackingEnabled(false) return } UserDefaults.standard.set(true, forKey: "kBITExcludeApplicationSupportFromBackup") // check guard !TrackingManager.shared.disableCrashSharing else { AppCenter.setTrackingEnabled(false) return } #if DISABLE_APPCENTER_CRASH_LOGGING #else Crashes.delegate = self #endif Distribute.delegate = self AppCenter.start() AppCenter.logLevel = .verbose // This method must only be used after Services have been started. AppCenter.setTrackingEnabled(true) } } extension AppCenterOperation: DistributeDelegate { func distribute(_ distribute: Distribute, releaseAvailableWith details: ReleaseDetails) -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window, let rootViewController = appDelegate.appRootRouter?.rootViewController else { return false } let alertController = UIAlertController(title: "Update available \(details.shortVersion ?? "") (\(details.version ?? ""))", message: "Release Note:\n\n\(details.releaseNotes ?? "")\n\nDo you want to update?", preferredStyle: .actionSheet) alertController.configPopover(pointToView: window) alertController.addAction(UIAlertAction(title: "Update", style: .cancel) {_ in Distribute.notify(.update) }) alertController.addAction(UIAlertAction(title: "Postpone", style: .default) {_ in Distribute.notify(.postpone) }) if let url = details.releaseNotesUrl { alertController.addAction(UIAlertAction(title: "View release note", style: .default) {_ in UIApplication.shared.open(url, options: [:]) }) } alertController.addAction(UIAlertAction(title: "Cancel", style: .default) {_ in }) window.endEditing(true) rootViewController.present(alertController, animated: true) return true } } #if DISABLE_APPCENTER_CRASH_LOGGING #else extension AppCenterOperation: CrashesDelegate { func crashes(_ crashes: Crashes, shouldProcess errorReport: ErrorReport) -> Bool { return !TrackingManager.shared.disableCrashSharing } internal func crashes(_ crashes: Crashes, didSucceedSending errorReport: ErrorReport) { zmLog.error("AppCenter: finished sending the crash report") } internal func crashes(_ crashes: Crashes, didFailSending errorReport: ErrorReport, withError error: Error?) { zmLog.error("AppCenter: failed sending the crash report with error: \(String(describing: error?.localizedDescription))") } } #endif // MARK: - BackendInfoOperation final class BackendInfoOperation: LaunchSequenceOperation { func execute() { BackendInfo.storage = .applicationGroup } } final class FontSchemeOperation: LaunchSequenceOperation { func execute() { FontScheme.configure(with: UIApplication.shared.preferredContentSizeCategory) } } final class VoIPPushHelperOperation: LaunchSequenceOperation { func execute() { VoIPPushHelper.storage = .applicationGroup } } /// This operation cleans up any state that may have been set in debug builds so that /// release builds don't exhibit any debugging behaviour. /// /// This is a safety precaution: users of release builds likely won't ever run a debug /// build, but it's better to be sure. final class CleanUpDebugStateOperation: LaunchSequenceOperation { func execute() { guard !Bundle.developerModeEnabled else { return } // Clearing this ensures that the api version is negotiated with the backend // and not set explicitly. BackendInfo.preferredAPIVersion = nil // Clearing all developer flags ensures that no custom behavior is // present in the app. DeveloperFlag.clearAllFlags() } }
gpl-3.0
0d546a1fa82dc18b76449569ce0fbcb5
30.254098
132
0.704957
4.857325
false
false
false
false
tinrobots/Mechanica
Sources/AppKit/NSImage+Utils.swift
1
979
#if os(macOS) import AppKit extension NSImage { /// **Mechanica** /// /// - Parameters: /// - name: The name of the image. /// - bundle: The bundle containing the image file or asset catalog, if nil the behavior is identical to `init(named:)`. /// - Returns: The image object associated with the specified filename. public class func imageNamed(name: String, in bundle: Bundle?) -> NSImage? { let name = NSImage.Name(name) guard let bundle = bundle else { return NSImage(named: name) } if let image = bundle.image(forResource: name) { image.setName(name) return image } return nil } /// **Mechanica** /// /// Returns a CGImage object for the associated image data. public var cgImage: CGImage? { let imageData = self.tiffRepresentation guard let source = CGImageSourceCreateWithData(imageData! as CFData, nil) else { return nil } return CGImageSourceCreateImageAtIndex(source, 0, nil) } } #endif
mit
70a49282be616efcb31268c94e103572
25.459459
124
0.66905
4.256522
false
false
false
false
erlandranvinge/swift-mini-json
legacy/Json-2.2.swift
1
1126
import Foundation class Json: SequenceType { let data:AnyObject? init(data:AnyObject?) { if (data is NSData) { self.data = try? NSJSONSerialization.JSONObjectWithData( data as! NSData, options: .AllowFragments) } else { self.data = data } } func string() -> String { return data as? String ?? "" } func int() -> Int { return data as? Int ?? 0 } func float() -> Float { return data as? Float ?? 0.0 } func double() -> Double { return data as? Double ?? 0.0 } func bool() -> Bool { return data as? Bool ?? false } subscript(name:String) -> Json { let hash = data as? NSDictionary return Json(data: hash?.valueForKey(name)) } func generate() -> AnyGenerator<Json> { var index = 0 let items = data as? [AnyObject] return AnyGenerator { guard let items = items else { return nil } guard index < items.count else { return nil } defer { index += 1 } return Json(data: items[index]) } } }
mit
6b23f81c8c556e1242032d043055d7d0
29.432432
68
0.533748
4.415686
false
false
false
false
ksco/swift-algorithm-club-cn
Merge Sort/MergeSort.playground/Contents.swift
1
2329
/* Top-down recursive version */ func mergeSort(array: [Int]) -> [Int] { guard array.count > 1 else { return array } let middleIndex = array.count / 2 let leftArray = mergeSort(Array(array[0..<middleIndex])) let rightArray = mergeSort(Array(array[middleIndex..<array.count])) return merge(leftPile: leftArray, rightPile: rightArray) } func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] { var leftIndex = 0 var rightIndex = 0 var orderedPile = [Int]() while leftIndex < leftPile.count && rightIndex < rightPile.count { if leftPile[leftIndex] < rightPile[rightIndex] { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } else if leftPile[leftIndex] > rightPile[rightIndex] { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } else { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } } while leftIndex < leftPile.count { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } while rightIndex < rightPile.count { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } return orderedPile } let array = [2, 1, 5, 4, 9] let sortedArray = mergeSort(array) /* Bottom-up iterative version */ func mergeSortBottomUp<T>(a: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { let n = a.count var z = [a, a] // the two working arrays var d = 0 // z[d] is used for reading, z[1 - d] for writing var width = 1 while width < n { var i = 0 while i < n { var j = i var l = i var r = i + width let lmax = min(l + width, n) let rmax = min(r + width, n) while l < lmax && r < rmax { if isOrderedBefore(z[d][l], z[d][r]) { z[1 - d][j] = z[d][l] l += 1 } else { z[1 - d][j] = z[d][r] r += 1 } j += 1 } while l < lmax { z[1 - d][j] = z[d][l] j += 1 l += 1 } while r < rmax { z[1 - d][j] = z[d][r] j += 1 r += 1 } i += width*2 } width *= 2 // in each step, the subarray to merge becomes larger d = 1 - d // swap active array } return z[d] } mergeSortBottomUp(array, <)
mit
926d798f43d0b6504e94249d06a1bc1c
22.525253
77
0.553027
3.425
false
false
false
false
danpratt/Simply-Zen
Simply Zen/StoreKit/SZAppStoreReview.swift
1
1091
// // SZAppStoreReview.swift // Simply Zen // // Created by Daniel Pratt on 11/10/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation struct SZAppStoreReview: RateInAppStore { // Properties var timesUserHasOpenedApp: Int? = UserDefaults.standard.integer(forKey: "timesUserHasOpenedApp_") let openTimesToCheck: Int = 5 init() { // get rid of old doNotBugToRate key (will not be used anymore) // NOTE: REMOVE THIS IN FOLLOWING RELEASE UserDefaults.standard.removeObject(forKey: "doNotBugToRate_") updateTimesUserHasOpenedApp() } mutating func updateTimesUserHasOpenedApp() { if timesUserHasOpenedApp == nil || timesUserHasOpenedApp! > openTimesToCheck { timesUserHasOpenedApp = 1 } else { timesUserHasOpenedApp = timesUserHasOpenedApp! + 1 } setTimesUserHasOpenedApp() } func setTimesUserHasOpenedApp() { UserDefaults.standard.set(timesUserHasOpenedApp, forKey: "timesUserHasOpenedApp_") } }
apache-2.0
1284d87ebe060ecf519659c0e63766c2
27.684211
101
0.662385
4.176245
false
false
false
false
niuxinghua/beauties
beauties/HistoryViewController.swift
9
7725
// // HistoryViewController.swift // beauties // // Created by Shuai Liu on 15/7/1. // Copyright (c) 2015年 Shuai Liu. All rights reserved. // import Foundation import UIKit class HistoryViewController: UIViewController, CHTCollectionViewDelegateWaterfallLayout, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate { // ---------------- Views var beautyCollectionView: UICollectionView! var refreshControl: UIRefreshControl! var collectionViewLayout :CHTCollectionViewWaterfallLayout! // ---------------- Data var beauties: [BeautyImageEntity] let sharedMargin = 10 var page = 1 var isLoadingNow = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { beauties = [] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { beauties = [] super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.view.backgroundColor = ThemeColor self.automaticallyAdjustsScrollViewInsets = true let statusBarHeight: CGFloat = 20 collectionViewLayout = CHTCollectionViewWaterfallLayout() collectionViewLayout.columnCount = 2 collectionViewLayout.minimumColumnSpacing = CGFloat(sharedMargin) collectionViewLayout.minimumInteritemSpacing = CGFloat(sharedMargin) collectionViewLayout.sectionInset = UIEdgeInsets(top: 10, left: CGFloat(sharedMargin), bottom: CGRectGetHeight(self.tabBarController!.tabBar.frame) + statusBarHeight + 10 + 10, right: CGFloat(sharedMargin)) collectionViewLayout.footerHeight = 50 var frame = self.view.bounds frame.origin.y += statusBarHeight self.beautyCollectionView = UICollectionView(frame: frame, collectionViewLayout: collectionViewLayout) self.beautyCollectionView.alwaysBounceVertical = true self.beautyCollectionView.backgroundColor = UIColor.clearColor() self.beautyCollectionView.collectionViewLayout = collectionViewLayout self.beautyCollectionView.delegate = self self.beautyCollectionView.dataSource = self self.beautyCollectionView.registerClass(BeautyCollectionViewCell.self, forCellWithReuseIdentifier: "BeautyCollectionViewCell") self.beautyCollectionView.registerClass(BeautyCollectionViewFooter.self, forSupplementaryViewOfKind:collectionViewLayout.CHTCollectionElementKindSectionFooter, withReuseIdentifier: "BeautyCollectionViewFoooter") self.view.addSubview(self.beautyCollectionView!) self.refreshControl = UIRefreshControl() self.refreshControl.addTarget(self, action: Selector("refreshData"), forControlEvents: .ValueChanged) self.beautyCollectionView.addSubview(self.refreshControl) // start loading data self.refreshData() } // MARK: fetch DATA func refreshData() { page = 1 self.beauties.removeAll(keepCapacity: false) self.fetchNextPage(page) } func fetchData(args: (dispatch_queue_t, String)) { dispatch_async(args.0) { var beauty = NetworkUtil.getImageByDateSync(args.1) if beauty != nil { self.beauties.append(beauty!) } } } func fetchNextPage(page: Int) { if (self.page > BeautyDateUtil.MAX_PAGE) { collectionViewLayout.footerHeight = 0 return } if (self.isLoadingNow) { return } self.isLoadingNow = true println("---------- Starting Page \(page) ----------") let historyDates = BeautyDateUtil.generateHistoryDateString(page) var queue: dispatch_queue_t = dispatch_queue_create("Beauty", DISPATCH_QUEUE_CONCURRENT) historyDates.map({return (queue, $0)}).map(fetchData) dispatch_barrier_async(queue) { println("---------- Finished Page \(page) ----------") // ----- increment page by 1 self.page += 1 // ----- set background blur image if count(self.beauties) > 0 { var beautyEntity = self.beauties[0] var bgi = UIImageView(frame: self.view.bounds) bgi.contentMode = .ScaleToFill self.view.addSubview(bgi) self.view.sendSubviewToBack(bgi) bgi.kf_setImageWithURL(NSURL(string: beautyEntity.imageUrl!)!, placeholderImage: nil, optionsInfo: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in bgi.applyBlurEffect() }) } // ----- reload data self.refreshControl.endRefreshing() self.beautyCollectionView.reloadData() self.isLoadingNow = false } } // MARK: UIScrollViewDelegate func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if (scrollView.contentOffset.y + CGRectGetHeight(scrollView.bounds) > scrollView.contentSize.height) { self.fetchNextPage(self.page) } } // MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return count(beauties) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("BeautyCollectionViewCell", forIndexPath: indexPath) as! BeautyCollectionViewCell if (indexPath.row < count(beauties)) { var entity = beauties[indexPath.row] cell.bindData(entity) } return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let footer: BeautyCollectionViewFooter = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "BeautyCollectionViewFoooter", forIndexPath: indexPath) as! BeautyCollectionViewFooter if (kind == collectionViewLayout.CHTCollectionElementKindSectionFooter) { footer.startAnimating() } return footer } // MARK: UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if (indexPath.row < count(self.beauties)) { var entity = self.beauties[indexPath.row] var todayViewController = TodayViewController() todayViewController.todayBeauty = entity todayViewController.canBeClosed = true self.presentViewController(todayViewController, animated: true, completion: nil) } } // MARK: CHTCollectionViewDelegateWaterfallLayout func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var entity = beauties[indexPath.row] let width: Float = (Float(collectionView.bounds.size.width) - Float(sharedMargin) * 3) / 2 var height:Float = 200.0 if entity.imageHeight != nil && entity.imageWidth != nil { height = (Float(entity.imageHeight!) * width) / Float(entity.imageWidth!) } return CGSize(width: CGFloat(width), height: CGFloat(height)) } }
mit
de573da53ca5a6b2b45e7d26590b6a46
41.20765
219
0.661142
5.560115
false
false
false
false
MediaBrowser/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/BaseApiClient.swift
1
23851
// // BaseApiClient.swift // Emby.ApiClient // // Created by Vedran Ozir on 03/11/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.apiinteraction; // //import mediabrowser.apiinteraction.device.IDevice; //import mediabrowser.apiinteraction.http.HttpHeaders; //import mediabrowser.model.apiclient.ApiHelpers; //import mediabrowser.model.extensions.*; //import mediabrowser.model.drawing.*; //import mediabrowser.model.dto.*; //import mediabrowser.model.entities.*; //import mediabrowser.model.livetv.*; //import mediabrowser.model.logging.*; //import mediabrowser.model.querying.*; //import mediabrowser.model.serialization.*; // //import java.text.DateFormat; //import java.text.SimpleDateFormat; //import java.util.Date; //import java.util.TimeZone; /** Provides api methods that are usable on all platforms */ //public abstract class BaseApiClient implements IDisposable public class BaseApiClient// implements IDisposable { // //C# TO JAVA CONVERTER TODO TASK: Events are not available in Java: // // public event EventHandler ServerLocationChanged; // private void OnServerLocationChanged() // { // //if (ServerLocationChanged != null) // //{ // //ServerLocationChanged(this, EventArgs.Empty); // //} // } // private var logger: ILogger private var jsonSerializer: IJsonSerializer private var clientName: String? private var device: DeviceProtocol? private var privateApplicationVersion: String? private var privateServerAddress: String private var privateAccessToken: String? private var privateImageQuality: Int? private var privateCurrentUserId: String? let httpHeaders = HttpHeaders() internal init(logger: ILogger, jsonSerializer: IJsonSerializer, serverAddress: String, clientName: String, device: DeviceProtocol, applicationVersion: String) { self.logger = logger self.jsonSerializer = jsonSerializer self.clientName = clientName self.device = device self.privateApplicationVersion = applicationVersion self.privateServerAddress = serverAddress } internal init(logger: ILogger, jsonSerializer: IJsonSerializer, serverAddress: String, accessToken: String) { self.logger = logger self.jsonSerializer = jsonSerializer self.privateServerAddress = serverAddress self.privateAccessToken = accessToken } public final func setJsonSerializer(value: IJsonSerializer) { self.jsonSerializer = value } public final func getJsonSerializer() -> IJsonSerializer? { return jsonSerializer } public final func setClientName(value: String) { self.clientName = value } public final func getClientName() -> String? { return clientName } public final func setApplicationVersion(value: String) { self.privateApplicationVersion = value } public final func getApplicationVersion() -> String? { return privateApplicationVersion } public final func setServerAddress(value: String) { self.privateServerAddress = value } public final func getServerAddress() -> String { return privateServerAddress } public final func setAccessToken(value: String?) { self.privateAccessToken = value } public final func getAccessToken() -> String? { return privateAccessToken } public final func getDevice() -> DeviceProtocol? { return device } public final func getDeviceName() -> String? { return getDevice()?.deviceName } public final func getDeviceId() -> String? { return getDevice()?.deviceId } public final func setImageQuality(value: Int) { self.privateImageQuality = value } public final func getImageQuality() -> Int? { return privateImageQuality } public final func setCurrentUserId(value: String?) { self.privateCurrentUserId = value } public final func getCurrentUserId() -> String? { return privateCurrentUserId } public final func getApiUrl() -> String { return getServerAddress() + "/mediabrowser" } internal final func getAuthorizationScheme() -> String { return "MediaBrowser" } public final func changeServerLocation(address: String) { setServerAddress(value: address) setAuthenticationInfo(accessToken: nil, userId: nil) } public func setAuthenticationInfo(accessToken: String?, userId: String?) { setCurrentUserId(value: userId) setAccessToken(value: accessToken) resetHttpHeaders() } public func setAuthenticationInfo(accessToken: String?) { setCurrentUserId(value: nil) setAccessToken(value: accessToken) resetHttpHeaders() } public func clearAuthenticationInfo() { setCurrentUserId(value: nil) setAccessToken(value: nil) resetHttpHeaders() } internal func resetHttpHeaders() { httpHeaders.setAccessToken(token: getAccessToken()) if let authValue = getAuthorizationParameter() { setAuthorizationHttpRequestHeader(scheme: getAuthorizationScheme(), parameter: authValue) } else { clearHttpRequestHeader(name: "Authorization") setAuthorizationHttpRequestHeader(scheme: nil, parameter: nil) } } internal func setAuthorizationHttpRequestHeader(scheme: String?, parameter: String?) { httpHeaders.authorizationScheme = scheme httpHeaders.authorizationParameter = parameter } private func clearHttpRequestHeader(name: String) { httpHeaders[name] = nil } internal func getAuthorizationParameter() -> String? { if let clientName = getClientName(), let deviceId = getDeviceId(), let deviceName = getDeviceName() { var header = "Client=\"\(clientName)\", DeviceId=\"\(deviceId)\", Device=\"\(deviceName)\", Version=\"\(getApplicationVersion())\"" if let currentUserId = getCurrentUserId() { header += ", UserId=\"\(currentUserId)\"" } return header } else { return nil } } internal final func getSlugName(name: String?) -> String { return ApiHelpers.getSlugName(name: name) } // // /** // Changes the server location. // // @param address The address. // */ // public final void ChangeServerLocation(String address) // { // setServerAddress(address); // // SetAuthenticationInfo(null, null); // // OnServerLocationChanged(); // } // public final func getApiUrl(handler: String?) -> String { return getApiUrl(handler: handler, queryString: nil) } internal final func getApiUrl(handler: String?, queryString: QueryStringDictionary?) -> String { let base = getApiUrl() + "/" + handler! return queryString != nil ? queryString!.getUrl(prefix: base) : base } public final func getSubtitleUrl(options: SubtitleDownloadOptions) -> String { let partialUrl: String = "Videos/\(options.itemId)/\(options.mediaSourceId)/Subtitles/\(options.streamIndex)/Stream.\(options.format)" return getApiUrl(handler: partialUrl) } internal final func getItemListUrl(query: ItemQuery) -> String { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("ParentId", value: query.parentId) dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("Limit", value: query.limit) dict.add("SortBy", value: query.sortBy) dict.addIfNotNil("SortOrder", value: query.sortOrder?.rawValue) dict.add("SeriesStatues", value: query.seriesStatus?.map({$0.rawValue})) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.add("Filters", value: query.filters?.map({$0.rawValue})) dict.add("ImageTypes", value: query.imageTypes?.map({$0.rawValue})) dict.addIfNotNil("Is3d", value: query.is3d) dict.add("AirDays", value: query.airDays) dict.add("VideoTypes", value: query.videoTypes?.map({$0.rawValue})) dict.addIfNotNilOrEmpty("MinOfficialRating", value: query.minOfficialRating) dict.addIfNotNilOrEmpty("MaxOfficialRating", value: query.maxOfficialRating) dict.addIfNotNil("recursive", value: query.recursive) dict.addIfNotNil("MinIndexNumber", value: query.minIndexNumber) dict.add("MediaTypes", value: query.mediaTypes) dict.addIfNotNil("Genres", value: query.genres?.joined(separator: "|")) dict.add("Ids", value: query.ids) dict.addIfNotNil("StudioIds", value: query.studioIds?.joined(separator: "|")) dict.add("ExcludeItemTypes", value: query.excludeItemTypes) dict.add("IncludeItemTypes", value: query.includeItemTypes) dict.add("ArtistIds", value: query.artistIds) dict.addIfNotNil("IsPlayed", value: query.isPlayed) dict.addIfNotNil("IsInBoxSet", value: query.isInBoxSet) dict.add("PersonIds", value: query.personIds) dict.add("PersonTypes", value: query.personTypes) dict.add("Years", value: query.years) dict.addIfNotNil("ParentIndexNumber", value: query.parentIndexNumber) dict.addIfNotNil("IsHD", value: query.isHd) dict.addIfNotNil("HasParentalRating", value: query.hasParentRating) dict.addIfNotNilOrEmpty("SearchTerm", value: query.searchTerm) dict.addIfNotNil("MinCriticRating", value: query.minCriticRating) dict.addIfNotNil("MinCommunityRating", value: query.minCommunityRating) dict.addIfNotNil("MinPlayers", value: query.minPlayers) dict.addIfNotNil("MaxPlayers", value: query.maxPlayers) dict.addIfNotNilOrEmpty("NameStartsWithOrGreater", value: query.nameStartsWithOrGreater) dict.addIfNotNilOrEmpty("NameStartsWith", value: query.nameStartsWith) dict.addIfNotNilOrEmpty("NameLessThan", value: query.nameLessThan) dict.addIfNotNilOrEmpty("AlbumArtistStartsWithOrGreater", value: query.albumArtistStartsWithOrGreater) dict.addIfNotNil("LocationTypes", value: query.locationTypes.map({String(describing: $0)})) dict.addIfNotNil("ExcludeLocationTypes", value: query.excludeLocationTypes.map({String(describing: $0)})) dict.addIfNotNil("IsMissing", value: query.isMissing) dict.addIfNotNil("IsUnaired", value: query.isUnaired) dict.addIfNotNil("IsVirtualUnaired", value: query.isVirtualUnaired) dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("EnableTotalRecordCount", value: query.enableTotalRecordCount) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) dict.addIfNotNil("AiredDuringSeason", value: query.airedDuringSeasion) return getApiUrl(handler: "Users/\(query.userId!)/Items", queryString: dict) } internal final func getNextUpUrl(query: NextUpQuery) -> String { let dict = QueryStringDictionary() dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("UserId", value: query.userId); dict.addIfNotNilOrEmpty("SeriesId", value: query.seriesId); dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) return getApiUrl(handler: "Shows/NextUp", queryString: dict) } internal final func getSimilarItemListUrl(query: SimilarItemsQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) return getApiUrl(handler: "\(type!)/\(query.id!)/Similar", queryString: dict) } internal final func getInstantMixUrl(query: SimilarItemsQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) return getApiUrl(handler: "\(type!)/\(query.id!)/InstantMix", queryString: dict) } internal final func getItemByNameListUrl(query: ItemsByNameQuery, type: String?) -> String { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("ParentId", value: query.parentId) dict.addIfNotNil("UserId", value: query.userId); dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("Limit", value: query.limit) dict.add("SortBy", value: query.sortBy) dict.addIfNotNil("sortOrder", value: query.sortOrder?.rawValue) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("IsPlayed", value: query.isPlayed) dict.add("Filters", value: query.filters?.map({$0.rawValue})) dict.add("ImageTypes", value: query.imageTypes?.map({$0.rawValue})) dict.addIfNotNil("recursive", value: query.recursive) dict.add("MediaTypes", value: query.mediaTypes) dict.add("ExcludeItemTypes", value: query.excludeItemTypes) dict.add("IncludeItemTypes", value: query.includeItemTypes) dict.addIfNotNilOrEmpty("NameStartsWithOrGreater", value: query.nameStartsWithOrGreater) dict.addIfNotNilOrEmpty("NameStartsWith", value: query.nameStartsWith) dict.addIfNotNilOrEmpty("NameLessThan", value: query.nameLessThan) dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) return getApiUrl(handler: type, queryString: dict) } private func getImageUrl(baseUrl: String, options: ImageOptions, queryParams: QueryStringDictionary) -> String { queryParams.addIfNotNil("Width", value: options.width) queryParams.addIfNotNil("Height", value: options.height) queryParams.addIfNotNil("MaxWidth", value: options.maxWidth) queryParams.addIfNotNil("MaxHeight", value: options.maxHeight) if let quality = options.quality ?? getImageQuality() { queryParams.addIfNotNil("Quality", value: quality) } queryParams.addIfNotNilOrEmpty("Tag", value: options.tag) queryParams.addIfNotNil("CropWhitespace", value: options.cropWhiteSpace) queryParams.addIfNotNil("EnableImageEnhancers", value: options.enableImageEnhancers) queryParams.addIfNotNil("Format", value: options.imageFormat?.rawValue) queryParams.addIfNotNil("AddPlayedIndicator", value: options.addPlayedIndicator) queryParams.addIfNotNil("UnPlayedCount", value: options.unplayedCount); queryParams.addIfNotNil("PercentPlayed", value: options.percentPlayed); queryParams.addIfNotNilOrEmpty("BackgroundColor", value: options.backgroundColor); return getApiUrl(handler: baseUrl, queryString: queryParams); } public final func getImageUrl(item: BaseItemDto, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = getImageTag(item: item, options: newOptions) return getImageUrl(itemId: item.id, options: newOptions) } public final func getImageUrl(itemId: String?, options: ImageOptions) -> String? { if let id = itemId { let url = "Items/\(id)/Images/\(options.imageType)"; return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } return nil } public final func getUserImageUrl(user: UserDto, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = user.primaryImageTag return getUserImageUrl(userId: user.id, options: newOptions) } public final func getUserImageUrl(userId: String?, options: ImageOptions) -> String? { if let id = userId { let url = "Users/\(id)/Images/\(options.imageType)"; return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } return nil } public final func getPersonImageUrl(item: BaseItemPerson, options: ImageOptions) -> String? { var newOptions = options newOptions.tag = item.primaryImageTag return getImageUrl(itemId: item.id, options: newOptions) } private func getImageTag(item: BaseItemDto, options: ImageOptions) -> String? { switch options.imageType { case .Backdrop: return item.backdropImageTags?[options.imageIndex ?? 0] case .Screenshot: return item.screenshotImageTags?[options.imageIndex ?? 0] case .Chapter: return item.chapters?[options.imageIndex ?? 0].imageTag default: return item.imageTags?[options.imageType] } } public final func getGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Genres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getMusicGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "MusicGenres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getGameGenreImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "GameGenres/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getStudioImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Studios/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getArtistImageUrl(name: String, options: ImageOptions) throws -> String { guard !name.isEmpty else { throw IllegalArgumentError.EmptyString(argumentName: "name") } let url = "Artists/\(getSlugName(name: name))/Images/\(options.imageType)" return getImageUrl(baseUrl: url, options: options, queryParams: QueryStringDictionary()) } public final func getBackdropImageUrls(item: BaseItemDto, options: ImageOptions) -> [String]? { var newOptions = options newOptions.imageType = ImageType.Backdrop var backdropItemId: String? var backdropImageTags: [String]? if item.backdropCount == 0 { backdropItemId = item.parentBackdropItemId backdropImageTags = item.parentBackdropImageTags } else { backdropItemId = item.id backdropImageTags = item.backdropImageTags } if backdropItemId == nil { return [String]() } if let bImageTags = backdropImageTags { var files = [String]() /*for var i = 0; i < bImageTags.count; ++i { newOptions.imageIndex = i newOptions.tag = bImageTags[i] files[i] = getImageUrl(backdropItemId, options: newOptions)! }*/ for i in 0..<bImageTags.count { newOptions.imageIndex = i newOptions.tag = bImageTags[i] files[i] = getImageUrl(itemId: backdropItemId, options: newOptions)! } return files } return nil } public final func getLogoImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let logoItemId = item.hasLogo ? item.id : item.parentLogoItemId let imageTag = item.hasLogo ? item.imageTags?[ImageType.Logo] : item.parentLogoImageTag if let lItemId = logoItemId { newOptions.tag = imageTag return getImageUrl(itemId: lItemId, options: newOptions) } return nil } public final func getThumbImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let thumbItemId = item.hasThumb ? item.id : item.seriesThumbImageTag != nil ? item.seriesId : item.parentThumbItemId let imageTag = item.hasThumb ? item.imageTags?[ImageType.Thumb] : item.seriesThumbImageTag != nil ? item.seriesThumbImageTag : item.parentThumbImageTag if let tItemId = thumbItemId { newOptions.tag = imageTag return getImageUrl(itemId: tItemId, options: newOptions) } return nil } public final func getArtImageUrl(item: BaseItemDto, options: ImageOptions) throws -> String? { var newOptions = options newOptions.imageType = ImageType.Logo let artItemId = item.hasArtImage ? item.id : item.parentArtItemId let imageTag = item.hasArtImage ? item.imageTags?[ImageType.Art] : item.parentArtImageTag if let aItemId = artItemId { newOptions.tag = imageTag return getImageUrl(itemId: aItemId, options: newOptions) } return nil } internal final func serializeToJson(obj: AnyObject) -> String { return getJsonSerializer()!.serializeToString(obj: obj) } internal final func addDataFormat(url: String) -> String { let format = "json" var newUrl = url if url.contains("?") { newUrl += "&format=" + format } else { newUrl += "?format=" + format } return newUrl } public func getIsoString(date: NSDate) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone! return formatter.string(from: date as Date) } }
mit
d058193f1a76bfef2863437b3206518d
38.486755
159
0.649015
4.597147
false
false
false
false
OscarSwanros/swift
test/Constraints/function_conversion.swift
13
751
// RUN: %target-typecheck-verify-swift -swift-version 3 // RUN: %target-typecheck-verify-swift -swift-version 4 // rdar://problem/31969605 class Base {} class Derived : Base {} protocol Refined {} protocol Proto : Refined {} extension Base : Refined {} func baseFn(_: Base) {} func superclassConversion(fn: @escaping (Base) -> ()) { let _: (Derived) -> () = fn } func existentialConversion(fn: @escaping (Refined) -> ()) { let _: (Proto) -> () = fn let _: (Base) -> () = fn let _: (Derived) -> () = fn } // rdar://problem/31725325 func a<b>(_: [(String, (b) -> () -> Void)]) {} func a<b>(_: [(String, (b) -> () throws -> Void)]) {} class c { func e() {} static var d = [("", e)] } a(c.d) func b<T>(_: (T) -> () -> ()) {} b(c.e)
apache-2.0
9c954da1bc7526f035fce9b95e9686d1
18.763158
59
0.551265
2.933594
false
false
false
false
Perfect-Server-Swift-LearnGuide/Today-News-Admin
Sources/Model/AddArticleModel.swift
1
1036
// // AddArticleModel.swift // Today-News-Admin // // Created by Mac on 17/7/17. // // import DataBase import PerfectMongoDB import PerfectLib public class AddArticleModel { public init() { } public func add(data: [String: Any]) -> String { let db = DB(db: "today_news").collection(name: "article") let collection: MongoCollection? = db.collection var datas = data if let type = data["type"] as? String { datas["type"] = Int(type) } let doc = try! BSON(json: try! datas.jsonEncodedString()) doc.append(key: "isDelete", bool: false) let result: MongoResult = collection!.insert(document: doc) var response = [String:Any]() switch result { case .success: response["result"] = "success" default: response["result"] = "error" } db.close() return try! response.jsonEncodedString() } }
apache-2.0
4c9cb61740be6f1dd9c7313decc85055
21.521739
67
0.532819
4.334728
false
false
false
false
HTWDD/htwcampus
HTWDD/Components/Onboarding/Studygroup/OnboardStudygroupSelectionController.swift
1
6527
// // OnboardStudygroupSelectionController.swift // HTWDD // // Created by Benjamin Herzog on 05.11.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit import RxSwift private enum Const { static let itemHeight: CGFloat = 80 static let margin: CGFloat = 15 } class OnboardStudygroupSelectionController<Data: Identifiable>: CollectionViewController, AnimatedViewControllerTransitionAnimator { // MARK: - Properties private let layout = CollectionViewFlowLayout() private let dataSource: GenericBasicCollectionViewDataSource<Data> private let visualEffectView = UIVisualEffectView(effect: nil) private let selection: (Data?) -> Void @available(iOS 10.0, *) private lazy var animator: UIViewPropertyAnimator = { let a = UIViewPropertyAnimator(duration: 0.4, curve: .linear, animations: { self.visualEffectView.effect = UIBlurEffect(style: .extraLight) }) return a }() // MARK: - Init init(data: [Data], selection: @escaping (Data?) -> Void) { self.dataSource = GenericBasicCollectionViewDataSource(data: data) self.selection = selection super.init(layout: self.layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Observable API static func show(controller: UIViewController, data: [Data]) -> Observable<Data> { return Observable.create { observer in let selectionController = OnboardStudygroupSelectionController(data: data) { item in guard let item = item else { return observer.onCompleted() } return observer.onNext(item) } selectionController.modalPresentationStyle = .overCurrentContext selectionController.transition = AnimatedViewControllerTransition(duration: 0.4, back: controller, front: selectionController) controller.present(selectionController, animated: true, completion: nil) return Disposables.create { selectionController.dismiss(animated: true, completion: nil) } } } // MARK: - View Controller Lifecyle override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override func initialSetup() { super.initialSetup() self.dataSource.collectionView = self.collectionView self.dataSource.register(type: OnboardingStudygroupSelectionYearCell.self) self.dataSource.register(type: OnboardingStudygroupSelectionCourseCell.self) self.dataSource.register(type: OnboardingStudygroupSelectionGroupCell.self) } private var collectionViewHeight: CGFloat { return min(520.0, CGFloat(self.dataSource.numberOfItems(in: 0)) * (Const.margin + Const.itemHeight) + Const.margin) } override func viewDidLoad() { super.viewDidLoad() self.collectionView.contentInset = UIEdgeInsets(top: 0, left: Const.margin, bottom: Const.margin, right: Const.margin) self.layout.itemSize = CGSize(width: self.itemWidth(collectionView: self.collectionView), height: Const.itemHeight) self.collectionView.backgroundColor = .clear self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.view.backgroundColor = .clear self.visualEffectView.isUserInteractionEnabled = true self.visualEffectView.translatesAutoresizingMaskIntoConstraints = false self.view.insertSubview(self.visualEffectView, belowSubview: self.collectionView) NSLayoutConstraint.activate([ self.visualEffectView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.visualEffectView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.visualEffectView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), self.visualEffectView.topAnchor.constraint(equalTo: self.view.topAnchor), self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor) ]) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(cancel)) self.collectionView.backgroundView = UIView() self.collectionView.backgroundView?.addGestureRecognizer(tapGesture) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let top = (self.view.height - self.collectionView.contentSize.height - (self.view.htw.safeAreaInsets.bottom + 54)) self.collectionView.contentInset = UIEdgeInsets(top: max(44, top), left: Const.margin, bottom: Const.margin, right: Const.margin) } @objc func cancel(gesture: UITapGestureRecognizer) { self.selection(nil) self.dismiss(animated: true, completion: nil) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let item = self.dataSource.data(at: indexPath) self.selection(item) self.dismiss(animated: true, completion: nil) } func animate(source: CGRect, sourceView: UIView?, duration: TimeInterval, direction: Direction, completion: @escaping (Bool) -> Void) { if #available(iOS 11.0, *) { self.animator.pausesOnCompletion = true } self.animator.isReversed = direction == .dismiss self.animator.startAnimation() if direction == .present { DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { self.animator.pauseAnimation() } } UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [.curveEaseIn], animations: { self.collectionView.alpha = direction == .present ? 1 : 0 self.collectionView.contentOffset.y += direction == .present ? 150 : -150 }, completion: { completed in if direction == .dismiss { self.animator.stopAnimation(false) self.animator.finishAnimation(at: .current) } completion(completed) }) } }
mit
f354e54e661789f24b27ef36e39d9a89
37.615385
146
0.68909
4.855655
false
false
false
false
jaynakus/Signals
SwiftSignalKit/Atomic.swift
1
814
import Foundation public final class Atomic<T> { private var lock: OSSpinLock = 0 private var value: T public init(value: T) { self.value = value } public func with<R>(_ f: (T) -> R) -> R { OSSpinLockLock(&self.lock) let result = f(self.value) OSSpinLockUnlock(&self.lock) return result } public func modify(_ f: (T) -> T) -> T { OSSpinLockLock(&self.lock) let result = f(self.value) self.value = result OSSpinLockUnlock(&self.lock) return result } public func swap(_ value: T) -> T { OSSpinLockLock(&self.lock) let previous = self.value self.value = value OSSpinLockUnlock(&self.lock) return previous } }
mit
a77e32110f9f6797431098253a6d0c0d
21.611111
45
0.531941
4.329787
false
false
false
false
daodaoliang/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/BubbleLayouts.swift
5
9414
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class MessagesLayouting { class func measureHeight(message: ACMessage, group: Bool, setting: CellSetting, layoutCache: LayoutCache) -> CGFloat { var content = message.content! var layout = layoutCache.pick(message.rid) if (layout == nil) { // Usually never happens layout = buildLayout(message, layoutCache: layoutCache) layoutCache.cache(message.rid, layout: layout!) } var height = layout!.height if content is ACServiceContent { height += AABubbleCell.bubbleTop height += AABubbleCell.bubbleBottom } else { height += (setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop) height += (setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom) } // Sender name let isIn = message.senderId != Actor.myUid() if group && isIn && !(content is ACServiceContent) && !(content is ACPhotoContent) && !(content is ACDocumentContent) { height += CGFloat(20.0) } // Date separator if (setting.showDate) { height += AABubbleCell.dateSize } return height } class func buildLayout(message: ACMessage, layoutCache: LayoutCache) -> CellLayout { var content = message.content! var res: CellLayout if (content is ACTextContent) { res = TextCellLayout(message: message) } else if (content is ACPhotoContent) { res = CellLayout(message: message) res.height = AABubbleMediaCell.measureMediaHeight(message) } else if (content is ACServiceContent) { res = CellLayout(message: message) res.height = AABubbleServiceCell.measureServiceHeight(message) } else if (content is ACDocumentContent) { res = CellLayout(message: message) res.height = AABubbleDocumentCell.measureDocumentHeight(message) } else { // Unsupported res = TextCellLayout(message: message) } return res } } class CellSetting { let showDate: Bool let clenchTop: Bool let clenchBottom: Bool init(showDate: Bool, clenchTop: Bool, clenchBottom: Bool) { self.showDate = showDate self.clenchTop = clenchTop self.clenchBottom = clenchBottom } } class CellLayout { var height: CGFloat = 0 var date: String init(message: ACMessage) { self.date = CellLayout.formatDate(Int64(message.date)) } class func formatDate(date: Int64) -> String { var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(Double(date) / 1000.0))) } } class TextCellLayout: CellLayout { private static let stringOutPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}"; private static let stringInPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}"; private static let maxTextWidth = isIPad ? 400 : 210 static let fontSize: CGFloat = isIPad ? 17 : 16 static let fontRegular = UIFont(name: "HelveticaNeue", size: fontSize)! static let fontItalic = UIFont(name: "HelveticaNeue-Italic", size: fontSize)! static let fontBold = UIFont(name: "HelveticaNeue-Bold", size: fontSize)! static let bubbleFont = fontRegular static let bubbleFontUnsupported = fontItalic var text: String var attrText: NSAttributedString? var isUnsupported: Bool var textSizeWithPadding: CGSize var textSize: CGSize var sources = [String]() override init(message: ACMessage) { var isOut = message.isOut if let content = message.content as? ACTextContent { text = content.text isUnsupported = false } else { text = NSLocalizedString("UnsupportedContent", comment: "Unsupported text") isUnsupported = true } // Markdown processing var parser = ARMarkdownParser(int: ARMarkdownParser_MODE_LITE) var doc = parser.processDocumentWithNSString(text) if !doc.isTrivial() { var sections: [ARMDSection] = doc.getSections().toSwiftArray() var nAttrText = NSMutableAttributedString() var isFirst = true for s in sections { if !isFirst { nAttrText.appendAttributedString(NSAttributedString(string: "\n")) } isFirst = false if s.getType() == ARMDSection_TYPE_CODE { var attributes = [NSLinkAttributeName: NSURL(string: "source:///\(sources.count)") as! AnyObject, NSFontAttributeName: TextCellLayout.fontRegular] nAttrText.appendAttributedString(NSAttributedString(string: "Open Code", attributes: attributes)) sources.append(s.getCode().getCode()) } else if s.getType() == ARMDSection_TYPE_TEXT { var child: [ARMDText] = s.getText().toSwiftArray() for c in child { nAttrText.appendAttributedString(TextCellLayout.buildText(c)) } } else { fatalError("Unsupported section type") } } self.attrText = nAttrText } // Measure text var size = CGSize(width: TextCellLayout.maxTextWidth - 2, height: 100000); var style = NSMutableParagraphStyle(); style.lineBreakMode = NSLineBreakMode.ByWordWrapping; if self.attrText == nil { var measureText = (text + (isOut ? TextCellLayout.stringOutPadding : TextCellLayout.stringInPadding)) as NSString; var rect = measureText.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: isUnsupported ? TextCellLayout.bubbleFontUnsupported : TextCellLayout.bubbleFont, NSParagraphStyleAttributeName: style], context: nil); textSizeWithPadding = CGSizeMake(ceil(rect.width + 2), ceil(rect.height)) rect = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: isUnsupported ? TextCellLayout.bubbleFontUnsupported : TextCellLayout.bubbleFont, NSParagraphStyleAttributeName: style], context: nil); textSize = CGSizeMake(ceil(rect.width + 2), ceil(rect.height)) } else { var measureText = NSMutableAttributedString() measureText.appendAttributedString(self.attrText!) if isOut { measureText.appendAttributedString(NSAttributedString(string: TextCellLayout.stringOutPadding, attributes: [NSFontAttributeName: TextCellLayout.fontRegular])) } else { measureText.appendAttributedString(NSAttributedString(string: TextCellLayout.stringInPadding, attributes: [NSFontAttributeName: TextCellLayout.fontRegular])) } var rect = measureText.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin|NSStringDrawingOptions.UsesFontLeading, context: nil) textSizeWithPadding = CGSizeMake(ceil(rect.width + 2), ceil(rect.height - 1)) rect = self.attrText!.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin|NSStringDrawingOptions.UsesFontLeading, context: nil) textSize = CGSizeMake(ceil(rect.width + 2), ceil(rect.height + 8)) } super.init(message: message) height = textSizeWithPadding.height + AABubbleCell.bubbleContentTop + AABubbleCell.bubbleContentBottom } class func buildText(text: ARMDText) -> NSAttributedString { if let raw = text as? ARMDRawText { return NSAttributedString(string: raw.getRawText(), attributes: [NSFontAttributeName: fontRegular]) } else if let span = text as? ARMDSpan { var res = NSMutableAttributedString() res.beginEditing() // Processing child texts var child: [ARMDText] = span.getChild().toSwiftArray() for c in child { res.appendAttributedString(buildText(c)) } // Setting span elements if span.getSpanType() == ARMDSpan_TYPE_BOLD { res.addAttribute(NSFontAttributeName, value: fontBold, range: NSMakeRange(0, res.length)) } else if span.getSpanType() == ARMDSpan_TYPE_ITALIC { res.addAttribute(NSFontAttributeName, value: fontItalic, range: NSMakeRange(0, res.length)) } else { fatalError("Unsupported span type") } res.endEditing() return res } else { fatalError("Unsupported text type") } } }
mit
1767b2ab7bcd611e6f9eeb574a4d3ca3
40.289474
288
0.615997
4.986229
false
false
false
false
petester42/RxMoya
Example/RxMoyaExample/UIViewControllerExtensions.swift
1
1722
// // UIViewControllerExtensions.swift // ReactiveMoyaExample // // Created by Justin Makaila on 8/9/15. // Copyright (c) 2015 Justin Makaila. All rights reserved. // import Foundation import UIKit extension UIViewController { func showErrorAlert(title: String, error: NSError, action: (Void -> Void)? = nil) { showAlert(title, message: error.description, action: action) } func showAlert(title: String, message: String, action: (Void -> Void)? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: { _ in action?() }) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } func showInputPrompt(title: String, message: String, action: (String -> Void)? = nil) { var inputTextField: UITextField? let promptController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: { _ in if let input = inputTextField?.text { action?(input) } }) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) promptController.addAction(okAction) promptController.addAction(cancelAction) promptController.addTextFieldWithConfigurationHandler { textField in inputTextField = textField } presentViewController(promptController, animated: true, completion: nil) } }
mit
a4791a3a675ed675abe0583b81ba8b27
34.163265
104
0.639954
4.92
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/CloudKit/CloudKitManager.swift
1
1588
// // CloudKitManager.swift // Pods // // Created by Mohssen Fathi on 6/3/16. // // import UIKit import CloudKit let publicDatabase = CKContainer.default().publicCloudDatabase public class CloudKitManager: NSObject { static let sharedManager = CloudKitManager() func allRecords() -> [CKRecord]? { return nil } func upload(_ filterGroup: FilterGroup, container: CKContainer, completion: ((_ record: CKRecord?, _ error: Error?) -> ())?) { let record = filterGroup.ckRecord() container.publicCloudDatabase.save(record) { (record, error) in completion?(record, error) } } } public extension FilterGroup { public func ckRecord() -> CKRecord { let record = CKRecord(recordType: "FilterGroup") record["identifier"] = self.identifier as CKRecordValue record["title"] = self.title as CKRecordValue record["category"] = self.category as CKRecordValue record["description"] = self.filterDescription as CKRecordValue record["filterData"] = filterDataAsset(MTLImage.archive(self)!) return record } func filterDataAsset(_ data: Data) -> CKAsset { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first let url = URL(fileURLWithPath: path!).appendingPathComponent(identifier) try! data.write(to: url, options: .atomicWrite) // Handle later return CKAsset(fileURL: url) } }
mit
fedbf7261ae6a2a2f3b8dc898635d41b
25.466667
130
0.622796
4.886154
false
false
false
false
SoneeJohn/WWDC
WWDC/ActionLabel.swift
1
1220
// // ActionLabel.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa final class ActionLabel: NSTextField { private var cursorTrackingArea: NSTrackingArea! override func updateTrackingAreas() { super.updateTrackingAreas() if cursorTrackingArea != nil { removeTrackingArea(cursorTrackingArea) } cursorTrackingArea = NSTrackingArea(rect: bounds, options: [NSTrackingArea.Options.cursorUpdate, NSTrackingArea.Options.inVisibleRect, NSTrackingArea.Options.activeInActiveApp], owner: self, userInfo: nil) addTrackingArea(cursorTrackingArea) } override func cursorUpdate(with event: NSEvent) { if event.trackingArea == cursorTrackingArea { NSCursor.pointingHand.push() } else { super.cursorUpdate(with: event) } } override func mouseDown(with event: NSEvent) { if let action = action { NSApp.sendAction(action, to: target, from: self) } } }
bsd-2-clause
74f34f2d1373717498f62c824f09e3a7
27.348837
171
0.593109
5.23176
false
false
false
false
ReSwift/ReSwift-Todo-Example
ReSwift-Todo/ToDoID.swift
1
787
// // ToDoID.swift // ReSwift-Todo // // Created by Christian Tietze on 05/02/16. // Copyright © 2016 ReSwift. All rights reserved. // import Foundation struct ToDoID { let identifier: String init() { self.identifier = UUID().uuidString } init(UUID: Foundation.UUID) { self.identifier = UUID.uuidString } init?(identifier: String) { guard let UUID = UUID(uuidString: identifier) else { return nil } self.identifier = UUID.uuidString } } extension ToDoID: Equatable { } func ==(lhs: ToDoID, rhs: ToDoID) -> Bool { return lhs.identifier == rhs.identifier } extension ToDoID: Hashable { } extension ToDoID: CustomStringConvertible { var description: String { return identifier } }
mit
b8b96f4740ac571a264a7483a7e3581b
15.723404
60
0.631043
3.989848
false
false
false
false
oscarvgg/calorie-counter
CalorieCounter/Adapter.swift
1
8071
// // ParseAdapter.swift // CalorieCounter // // Created by Oscar Vicente González Greco on 17/5/15. // Copyright (c) 2015 Oscarvgg. All rights reserved. // import Parse public class Adapter<T: Model>: NSObject { /** Transforms a PFObject to Dictionary ob objects compatible with MIModel :param: raw the raw object (PFObject) :returns: A Dictionary type from raw object */ public static func rawToDictionary(raw: AnyObject) -> [String: AnyObject] { var dictionary: [String: AnyObject] = [String: AnyObject]() if let raw = raw as? PFObject { if let id = raw.objectId { dictionary["objectId"] = id } for key in raw.allKeys() { dictionary[key as! String] = raw.objectForKey(key as! String)! } if let createdAt = raw.createdAt, updatedAt = raw.updatedAt { dictionary["createdAt"] = createdAt dictionary["updatedAt"] = updatedAt } } return dictionary } public static func save(model: Model, completion: (Bool, NSError?) -> Void) { var rawModel = PFObject( withoutDataWithClassName: T.tableName(), objectId: model.objectId != "" ? model.objectId : nil) if rawModel.objectId == PFUser.currentUser()?.objectId { rawModel = PFUser.currentUser()! } // Build PFObject from model for (key, value) in model.toDictionary() { if key != "objectId" && key != "password" && key != "createdAt" && key != "updatedAt" { // if value is an object if let idValue = value["objectId"] as? String { let association = PFObject( withoutDataWithClassName: T.tableNameForAssociation(key), objectId: idValue) rawModel.setObject(association, forKey: key) } else { rawModel.setObject(value, forKey: key) } } } rawModel.saveInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in // set the id of the just inserted object to the model if model.objectId == "" && error == nil { model.objectId = rawModel.objectId! } completion(true, error); } } public static func findWithId(id: String, completion: (T?, NSError?) -> Void) { var query = PFQuery(className: T.tableName()) query.whereKey("objectId", equalTo: id) query.findObjectsInBackgroundWithBlock { (result: [AnyObject]?, error: NSError?) -> Void in if let result = result where error == nil { var firstResult = result.first as! PFObject completion(T.modelFromRaw(self.rawToDictionary(firstResult)) as? T, error) } else { completion(nil, error) } } } public static func find(query: [String:AnyObject]?, completion: ([T], NSError?) -> Void) { var parseQuery = PFQuery(className: T.tableName()) if let query = query { parseQuery = self.buildQuery(query, parseQuery: parseQuery) } parseQuery.findObjectsInBackgroundWithBlock { (result: [AnyObject]?, error: NSError?) -> Void in if let result = result where error == nil { var items:[T] = [] for aResult in result { var item = aResult as! PFObject items.append(T.modelFromRaw(self.rawToDictionary(item)) as! T) } completion(items, error) } else { completion([], error) } } } public static func delete(model: Model, completion: (Bool, NSError?) -> Void) { let rawModel: PFObject = PFObject( withoutDataWithClassName: T.tableName(), objectId: model.objectId) rawModel.deleteInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in completion(succeeded, error); } } public static func buildRaw(id: String) -> AnyObject { return PFObject(withoutDataWithClassName: T.tableName(), objectId: id) as AnyObject } public static func buildRaw(values: [String:AnyObject]) -> AnyObject { return PFObject(className: T.tableName(), dictionary: values) as AnyObject } // MARK: - Query /** Transforms a query into a Parse query :param: query the query :param: parseQuery the parse query :returns: a Parse query */ public static func buildQuery(query: [String:AnyObject], parseQuery: PFQuery) -> PFQuery { self.parseWhere(query["where"] as? [String:[String:AnyObject]], parseQuery: parseQuery) self.parsePopulate(query["populate"] as? [String], parseQuery: parseQuery) return parseQuery } /** Adds the conditions from the where part of a query to a Parse query :param: whereClause a dictionary with the values in a where clause :param: parseQuery the parse query to add the converted conditions :returns: a Parse query */ public static func parseWhere(whereClause: [String:[String:AnyObject]]?, parseQuery: PFQuery) -> PFQuery { if let whereClause = whereClause { for (property, condition) in whereClause { for (theOperator, value) in condition { switch theOperator { case "=": parseQuery.whereKey(property, equalTo: value) case ">": parseQuery.whereKey(property, greaterThan: value) case ">=": parseQuery.whereKey(property, greaterThanOrEqualTo: value) case "<": parseQuery.whereKey(property, lessThan: value) case "<=": parseQuery.whereKey(property, lessThanOrEqualTo: value) case "!=": parseQuery.whereKey(property, notEqualTo: value) case "in": parseQuery.whereKey(property, containedIn: value as! [AnyObject]) default: break } } } } return parseQuery } /** Adds the `include` clause to a parse query :param: populateClause Array of property names to be populated :param: parseQuery The parse query to add the conditions :returns: The resulting parse query */ public static func parsePopulate(populateClause: [String]?, parseQuery: PFQuery) -> PFQuery { if let populateClause = populateClause { for property in populateClause { parseQuery.includeKey(property) } } return parseQuery } }
mit
563c3fb6c147c13828cc7ec1254fb7d3
29.801527
110
0.485006
5.731534
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Common/TableAbstraction/DetailController.swift
1
7287
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit protocol DetailScreen { var id: Int { get } } // TODO: This does more than just Details, used for lists, rename class DetailController: UITableViewController { var database = Database() var sections = [DetailSection]() var isToolBarHidden = true var hackyButtonRetains = [Any]() init() { super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func add(section: DetailSection) { section.index = sections.count sections.append(section) section.tableView = tableView // Commenting this line out doesn't break anything, why?! } override func loadView() { super.loadView() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 300 // This makes collapse/expand animations very glitchy //tableView.sectionHeaderHeight = UITableViewAutomaticDimension //tableView.estimatedSectionHeaderHeight = 100 navigationItem.rightBarButtonItem = UIBarButtonItem( image: UIImage(named: "home"), style: .plain, target: self, action: #selector(popToRoot)) addLongPressGesture() } @objc func popToRoot() { self.navigationController?.popToRootViewController(animated: true) } func push(_ vc: UIViewController) { self.navigationController?.pushViewController(vc, animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let page = String.init(describing: type(of: self)) if let ic = self as? DetailScreen { Log(page: page, event: "View", details: "\(ic.id)") } else { Log(page: page) } navigationController?.isToolbarHidden = isToolBarHidden // TODO: Shouldn't be here? for section in sections { section.initialize() } } func populateToolbarSegment(items: [String]) -> UISegmentedControl { let segment = UISegmentedControl(items: items) segment.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 300, height: 30)) segment.addTarget(self, action: #selector(reloadData), for: .valueChanged) let segmentButton = UIBarButtonItem.init(customView: segment) let flexible = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) setToolbarItems([flexible, segmentButton, flexible], animated: false) return segment } func addButton(title: String, options: [String], selected: (@escaping (Int, String) -> Void)) -> UIBarButtonItem { let manager = SelectionManager(title: title, options: options, parentController: self, selected: selected) hackyButtonRetains.append(manager) return manager.button } // Placeholder for segment action @objc func reloadData() { tableView.reloadData() } } // MARK - TableView Protocol extension DetailController { override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = sections[section] return section.isCollapsed ? 0 : section.numberOfRows } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = sections[indexPath.section].cell(row: indexPath.row) ?? UITableViewCell() sections[indexPath.section].populate(cell: cell, row: indexPath.row) return cell } // TODO: Would rather populate here but Auto Layout not working right override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { //sections[indexPath.section].populate(cell: cell, row: indexPath.row) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { sections[indexPath.section].selected(row: indexPath.row, navigationController: navigationController) } } // MARK - Collapsabile Sections extension DetailController: UIGestureRecognizerDelegate { func addLongPressGesture() { let lp = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture)) lp.minimumPressDuration = 0.3 // Seconds lp.delegate = self tableView.addGestureRecognizer(lp) } func sectionHasNoHeader(index: Int) -> Bool { let section = sections[index] return (section.headerView == nil && section.title == nil) || section.numberOfRows == 0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sectionHasNoHeader(index: section) ? 0 : 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionObject = sections[section] if sectionHasNoHeader(index: section) { return nil } let headerView = sectionObject.headerView ?? HeaderView() if sectionObject.headerView == nil { sectionObject.headerView = headerView headerView.text = sectionObject.title headerView.isCollapsed = sectionObject.isCollapsed } headerView.section = section let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerTapped)) gestureRecognizer.delegate = self headerView.addGestureRecognizer(gestureRecognizer) return headerView } @objc func longPressGesture(gestureRecognizer: UILongPressGestureRecognizer) { let point = gestureRecognizer.location(in: tableView) if let indexPath = tableView.indexPathForRow(at: point), gestureRecognizer.state == .began { //print("Long press on row \(indexPath.row)") longPress(indexPath: indexPath) } } func longPress(indexPath: IndexPath) { sections[indexPath.section].longPress(row: indexPath.row) } @objc func headerTapped(gestureRecognizer: UIGestureRecognizer) { if let headerView = gestureRecognizer.view as? HeaderView { let section = sections[headerView.section ?? 0] toggleSection(section) headerView.isCollapsed = section.isCollapsed } } func toggleSection(_ section: DetailSection) { section.isCollapsed = !section.isCollapsed let indexPaths = NSIndexPath.indexPathsFor(section: section.index ?? 0, startRow: 0, count: section.numberOfRows - 1) tableView.beginUpdates() if section.isCollapsed { tableView.deleteRows(at: indexPaths, with: .automatic) } else { tableView.insertRows(at: indexPaths, with: .automatic) } tableView.endUpdates() } }
mit
24a5766a1fb321a488efc77a9ece1965
34.373786
125
0.646219
5.284264
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document13.playgroundchapter/Pages/Exercise3.playgroundpage/Contents.swift
1
2005
//#-hidden-code // // Contents.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // //#-end-hidden-code /*: **Goal:** Add stairs to solve the puzzle. Your next world-building element is a set of stairs. Unlike simple blocks, stairs need to face the right direction from low to high. You can use the same `place` [parameters](glossary://parameter) you used for your character and expert. * callout(Placing a stair): Here's how you would place north-facing stair at coordinate (2,3): `let newStair = Stair()`\ `world.place(newStair, facing: north, atColumn: 2, row: 3)` However, you can use a *shortcut* to place stairs more quickly! Just [initialize](glossary://initialization) an [instance](glossary://instance) at the same time you place it. * callout(Shortcut): Instead of initializing your stair instance separately, this code creates an unnamed instance of [type](glossary://type) `Stair` and places it all with the same line of code: `world.place(Stair(), facing: north, atColumn: 1, row: 1)` 1. steps: Use the code above as a guide to place stairs into the puzzle. Try using the shortcut to place the stairs more efficiently. 2. Solve the puzzle using the rest of the coding skills you've learned so far. */ //#-code-completion(everything, hide) //#-code-completion(currentmodule, show) //#-code-completion(identifier, show, isOnOpenSwitch, if, func, for, while, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, Expert, Character, (, ), (), Block, Stair, turnLockUp(), turnLockDown(), isOnClosedSwitch, var, let, ., =, <, >, ==, !=, +, -, isBlocked, move(distance:), jump(), true, false, turnLock(up:numberOfTimes:), world, place(_:facing:atColumn:row:), place(_:atColumn:row:), isBlockedLeft, &&, ||, !, isBlockedRight) //#-hidden-code playgroundPrologue() typealias Character = Actor //#-end-hidden-code //#-editable-code Tap to enter code //#-end-editable-code //#-hidden-code playgroundEpilogue() //#-end-hidden-code
mit
6d2aa11f71ff66f18c217462e3173448
49.125
463
0.710723
3.994024
false
false
false
false
kosicki123/eidolon
Kiosk/Bid Fulfillment/PlaceBidViewController.swift
1
6809
import UIKit import Artsy_UILabels public class PlaceBidViewController: UIViewController { public dynamic var bidDollars: Int = 0 public var hasAlreadyPlacedABid: Bool = false @IBOutlet public var bidAmountTextField: TextField! @IBOutlet public var cursor: CursorView! @IBOutlet public var keypadContainer: KeypadContainerView! @IBOutlet public var currentBidTitleLabel: UILabel! @IBOutlet public var currentBidAmountLabel: UILabel! @IBOutlet public var nextBidAmountLabel: UILabel! @IBOutlet public var artworkImageView: UIImageView! @IBOutlet public var artistNameLabel: ARSerifLabel! @IBOutlet public var artworkTitleLabel: ARSerifLabel! @IBOutlet public var artworkPriceLabel: ARSerifLabel! @IBOutlet public var bidButton: Button! lazy public var conditionsOfSaleAddress = "http://artsy.net/conditions-of-sale" lazy public var privacyPolicyAddress = "http://artsy.net/privacy" lazy public var keypadSignal: RACSignal! = self.keypadContainer.keypad?.keypadSignal lazy public var clearSignal: RACSignal! = self.keypadContainer.keypad?.rightSignal lazy public var deleteSignal: RACSignal! = self.keypadContainer.keypad?.leftSignal public class func instantiateFromStoryboard() -> PlaceBidViewController { return UIStoryboard.fulfillment().viewControllerWithID(.PlaceYourBid) as PlaceBidViewController } override public func viewDidLoad() { super.viewDidLoad() if !hasAlreadyPlacedABid { self.fulfillmentNav().reset() } let keypad = self.keypadContainer!.keypad! let bidDollarsSignal = RACObserve(self, "bidDollars") let bidIsZeroSignal = bidDollarsSignal.map { return ($0 as Int == 0) } for button in [keypad.rightButton, keypad.leftButton] { RAC(button, "enabled") <~ bidIsZeroSignal.not() } let formattedBidTextSignal = RACObserve(self, "bidDollars").map(dollarsToCurrencyString) RAC(bidAmountTextField, "text") <~ RACSignal.`if`(bidIsZeroSignal, then: RACSignal.defer{ RACSignal.`return`("") }, `else`: formattedBidTextSignal) keypadSignal.subscribeNext(addDigitToBid) deleteSignal.subscribeNext(deleteBid) clearSignal.subscribeNext(clearBid) if let nav = self.navigationController as? FulfillmentNavigationController { RAC(nav.bidDetails, "bidAmountCents") <~ bidDollarsSignal.map { $0 as Float * 100 }.takeUntil(dissapearSignal()) if let saleArtwork:SaleArtwork = nav.bidDetails.saleArtwork { let minimumNextBidSignal = RACObserve(saleArtwork, "minimumNextBidCents") let bidCountSignal = RACObserve(saleArtwork, "bidCount") let openingBidSignal = RACObserve(saleArtwork, "openingBidCents") let highestBidSignal = RACObserve(saleArtwork, "highestBidCents") RAC(currentBidTitleLabel, "text") <~ bidCountSignal.map(toCurrentBidTitleString) RAC(nextBidAmountLabel, "text") <~ minimumNextBidSignal.map(toNextBidString) RAC(currentBidAmountLabel, "text") <~ RACSignal.combineLatest([bidCountSignal, highestBidSignal, openingBidSignal]).map { let tuple = $0 as RACTuple let bidCount = tuple.first as? Int ?? 0 return (bidCount > 0 ? tuple.second : tuple.third) ?? 0 }.map(centsToPresentableDollarsString).takeUntil(dissapearSignal()) RAC(bidButton, "enabled") <~ RACSignal.combineLatest([bidDollarsSignal, minimumNextBidSignal]).map { let tuple = $0 as RACTuple return (tuple.first as? Int ?? 0) * 100 >= (tuple.second as? Int ?? 0) } if let artist = saleArtwork.artwork.artists?.first { RAC(artistNameLabel, "text") <~ RACObserve(artist, "name") } RAC(artworkTitleLabel, "attributedText") <~ RACObserve(saleArtwork.artwork, "titleAndDate").takeUntil(rac_willDeallocSignal()) RAC(artworkPriceLabel, "text") <~ RACObserve(saleArtwork.artwork, "price").takeUntil(dissapearSignal()) RACObserve(saleArtwork, "artwork").subscribeNext { [weak self] (artwork) -> Void in if let url = (artwork as? Artwork)?.images?.first?.thumbnailURL() { self?.artworkImageView.sd_setImageWithURL(url) } else { self?.artworkImageView.image = nil } } } } } func dissapearSignal() -> RACSignal { return rac_signalForSelector("viewDidDisappear:") } @IBAction func bidButtonTapped(sender: AnyObject) { let identifier = hasAlreadyPlacedABid ? SegueIdentifier.PlaceAnotherBid : SegueIdentifier.ConfirmBid performSegue(identifier) } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .PlaceAnotherBid { let nextViewController = segue.destinationViewController as LoadingViewController nextViewController.placingBid = true } } @IBAction func conditionsTapped(sender: AnyObject) { (UIApplication.sharedApplication().delegate as? AppDelegate)?.showConditionsOfSale() } @IBAction func privacyTapped(sender: AnyObject) { (UIApplication.sharedApplication().delegate as? AppDelegate)?.showPrivacyPolicy() } } /// These are for RAC only private extension PlaceBidViewController { func dollarsToCurrencyString(input: AnyObject!) -> AnyObject! { let formatter = NSNumberFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US") formatter.numberStyle = .DecimalStyle return formatter.stringFromNumber(input as Int) } func addDigitToBid(input: AnyObject!) -> Void { let inputInt = input as? Int ?? 0 let newBidDollars = (10 * self.bidDollars) + inputInt if (newBidDollars >= 1_000_000) { return } self.bidDollars = newBidDollars } func deleteBid(input: AnyObject!) -> Void { self.bidDollars = self.bidDollars/10 } func clearBid(input: AnyObject!) -> Void { self.bidDollars = 0 } func toCurrentBidTitleString(input: AnyObject!) -> AnyObject! { if let count = input as? Int { return count > 0 ? "Current Bid:" : "Opening Bid:" } else { return "" } } func toNextBidString(cents: AnyObject!) -> AnyObject! { if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) { return "Enter \(dollars) or more" } return "" } }
mit
0c4d542caf03f505127cb7cf2e31c676
40.018072
155
0.653253
4.959213
false
false
false
false
Appudo/Appudo.github.io
static/dashs/probe/c/s/7/4.swift
1
24538
import libappudo import libappudo_run import libappudo_env import Foundation typealias ErrorResult = Int let ErrorDefault = 1 let ErrorNone = 0 func debug(_ msg : String) { if var f = <!Dir.tmp.open("debug.txt", [.O_CREAT, .O_RDWR]) { if let s = <!f.stat, s.size > 32000 { _ = <!f.truncate(0) } _ = <!f.append("\(msg)\n") } } enum PostType : Int32, Codable { case DISSASSEMBLY_ADD = 1 case MODULE_ADD = 2 case MODULE_CODE_SAVE = 3 case MODULE_GEN_CODE_SAVE = 4 case MODULE_PACKAGE_ADD = 5 case MODULE_PACKAGE_INIT = 6 } struct PostParam : FastCodable { let cmd : PostType let id : UInt32? let data : String? let x : Int? let y : Int? } struct PostInfo { let param : PostParam let file : FileItem let uid : Int32 } struct UserPermissions: OptionSet { let rawValue: Int32 static let NONE = UserPermissions(rawValue: 0) static let ADMIN_ALL = UserPermissions(rawValue: 1 << 0) static let RUN_ADD = UserPermissions(rawValue: 1 << 1) static let DISASSEMBLER_USE = UserPermissions(rawValue: 1 << 2) static let PROBE_ADD = UserPermissions(rawValue: 1 << 3) static let MODULE_ADD = UserPermissions(rawValue: 1 << 4) static let MODULE_SHARE = UserPermissions(rawValue: 1 << 5) static let USER_EDIT = UserPermissions(rawValue: 1 << 6) static let SETTING_EDIT = UserPermissions(rawValue: 1 << 7) static let ACCOUNT_EDIT = UserPermissions(rawValue: 1 << 8) static let ACCOUNT_REMOVE = UserPermissions(rawValue: 1 << 9) static let REPO_EDIT = UserPermissions(rawValue: 1 << 10) static let CHAT_USE = UserPermissions(rawValue: 1 << 11) static let MODULE_SOURCE = UserPermissions(rawValue: 1 << 12) static let USER_CHANGE_LOGIN = UserPermissions(rawValue: 1 << 13) static let REPO_ADD = UserPermissions(rawValue: 1 << 14) func has(_ perm : UserPermissions) -> Bool { return contains(.ADMIN_ALL) || contains(perm) } } struct GroupPermissions: OptionSet { let rawValue: Int32 static let RUN_EDIT = GroupPermissions(rawValue: 1 << 0) static let PROBE_EDIT = GroupPermissions(rawValue: 1 << 1) static let PROBE_VIEW_KEY = GroupPermissions(rawValue: 1 << 2) static let MODULE_EDIT = GroupPermissions(rawValue: 1 << 3) static let MODULE_SOURCE_EDIT = GroupPermissions(rawValue: 1 << 4) static let MODULE_SETUP = GroupPermissions(rawValue: 1 << 5) static let REPO_EDIT = GroupPermissions(rawValue: 1 << 6) } struct LoginParam : FastCodable { let l : String // login let k : String // key let p : UInt // probe or user let t : Int? // time let n : Int? // nonce let r : String? // random data let i : String? // child_id let v : String? // version } struct LoginTicket : FastCodable { let r : Int32 let p : Int let n : Int let t : Int } struct LoginInfo { let id : Int32 let perm : UserPermissions let keep : Bool } struct SignData : FastCodable { let uId : UInt32 let ticket : Int64 let time : Int64 let nonce : Int32 let sign : UInt64 } func user_ticket_toInfo(_ p : Int) -> LoginInfo { let _p = UInt(bitPattern:p) return LoginInfo(id:Int32(bitPattern:UInt32(_p & 0xFFFFFFFF)), perm:UserPermissions(rawValue:Int32(bitPattern:UInt32((_p >> 32) & 0x7FFFFFFF))), keep:(_p & ~0x7FFFFFFFFFFFFFFF) != 0) } func user_login_check(uinfo : inout LoginInfo) -> Bool { let ticket = Cookie.lt.value if ticket != "", let info = LoginTicket.from(json:ticket) { uinfo = user_ticket_toInfo(info.p) let qry = SQLQry("SELECT id FROM users WHERE id = $1 AND login_cookie = $2 AND locked = FALSE;") qry.values = [uinfo.id, ticket] if <!qry.exec() != false && qry.numRows != 0 { return true } } return false } func probe_validate_user(userId : UInt32, ticket : Int64, time : Int64, nonce : Int32, data : UInt64, sign : UInt64) -> Bool { let outBuffer = ManagedCharBuffer.create(64) let qry = SQLQry("SELECT login_cookie FROM users WHERE id = $1 AND locked = FALSE;") qry.values = [userId] if <!qry.exec() != false && qry.numRows != 0, let login_cookie = qry.getAsText(0, 0), let login = LoginTicket.from(json:login_cookie) { if let hmac = HMAC.begin("\(login.n)", flags:.SHA256), <!hmac.update(Int(userId)) != false, <!hmac.update(Int(ticket)) != false, <!hmac.update(Int(time)) != false, <!hmac.update(Int(nonce)) != false, <!hmac.update(Int(Int64(bitPattern:data))) != false, let _ = <!hmac.finish(outBuffer), let v = outBuffer.toInt(0) { return UInt64(bitPattern:Int64(v)) == sign } } return false } func getBase64len(_ buffer : inout ManagedCharBuffer, _ bufferLen : Int) -> Int { var len = bufferLen len -= 1 len -= buffer.data[len] == 61 ? 1 : 0 len -= buffer.data[len] == 61 ? 1 : 0 return len + 1 } func probe_login_check(id : UInt32, login : String) -> Bool { if let param = LoginParam.from(json:login, customValueParser:LoginParam.sizedValueParser) { let qry = SQLQry("SELECT key FROM probes WHERE id = $1 AND login = $2;") qry.values = [id, param.l] if <!qry.exec() != false && qry.numRows != 0 { let key = qry.getAsText(0, 0) ?? "" let outBuffer = ManagedCharBuffer.create(64) var resBuffer = ManagedCharBuffer.create(64) if let hmac = HMAC.begin(key, flags:.SHA256), <!hmac.update(param.r ?? "") != false, <!hmac.update(param.t ?? -1) != false, <!hmac.update(param.l) != false, <!hmac.update(param.n ?? -1) != false, param.i == nil || <!hmac.update(param.i ?? "") != false, let m = <!hmac.finish(outBuffer), let s = <!Base64.encode(outBuffer, resBuffer, inSizeLimit:m), param.k == resBuffer.toString(getBase64len(&resBuffer, s)) { return true } } } return false } func login_check(param : PostParam, data : String, uinfo : inout LoginInfo) -> Bool { let login = String(data.dropFirst(Int(strtoul(param.data ?? "", nil, 16)))) switch(param.cmd) { case .DISSASSEMBLY_ADD: if let id = param.id { return probe_login_check(id:id, login:login) } case .MODULE_ADD: fallthrough case .MODULE_CODE_SAVE: fallthrough case .MODULE_PACKAGE_ADD: fallthrough case .MODULE_PACKAGE_INIT: fallthrough case .MODULE_GEN_CODE_SAVE: return user_login_check(uinfo:&uinfo) } return false } /* ----------------------------------------------- */ /* disassembly handling */ /* ----------------------------------------------- */ func disassembly_add(_ param : PostParam, _ upload : UploadData, _ out : inout FileItem?) -> ErrorResult { var err = AsyncError() if let sdata = SignData.from(json:Post.sign.value), let id = param.id, let erase = param.x, probe_validate_user(userId:sdata.uId, ticket:sdata.ticket, time:sdata.time, nonce:sdata.nonce, data:UInt64(id) << 32 | UInt64(erase), sign:sdata.sign) != false, let f = err <! Dir.out.open("\(id)") { var path = (upload.parent ?? "") + "/" + upload.name let qry = SQLQry(""" INSERT INTO disassembly_files AS d (path, probes_id) VALUES ($1, $2) ON CONFLICT (path, probes_id) DO UPDATE SET id = d.id RETURNING id """); qry.values = [path, id] if (err <! qry.exec()) != false && qry.numRows == 1 { let id = qry.getAsInt(0, 0) ?? -1 path = "\(id)" if(erase != 0) { _ = <!f.remove(path) } let mode : FileItem.Mode = [ .U0600, .G0060 ] out = err <! f.open(path, [.O_CREAT, .O_EXCL, .O_RDWR], mode) if(out != nil) { print(#"{"r":0,"d":"\#(path)"}"#) return ErrorNone } } } if(err.hasError) { return Int(err.errValue) as ErrorResult } return ErrorDefault } /* ----------------------------------------------- */ /* module handling */ /* ----------------------------------------------- */ func module_package_add_begin(_ param : PostParam, _ upload : UploadData, _ uinfo : LoginInfo, _ out : inout FileItem?) -> ErrorResult { if let f = <!FileItem.create_tmp() { out = f Page.userData = PostInfo(param:param, file:f, uid:uinfo.id) return uinfo.perm.has(.MODULE_ADD) ? ErrorNone : ErrorDefault } return ErrorDefault } func module_package_init_begin(_ param : PostParam, _ uinfo : LoginInfo, _ out : inout FileItem?) -> ErrorResult { if let f = <!Dir.init_packages.open("init.probem", .O_RDONLY) { Page.userData = PostInfo(param:param, file:f, uid:uinfo.id) let res = uinfo.perm.has(.ADMIN_ALL) ? ErrorNone : ErrorDefault if(res == ErrorNone) { out = <!FileItem.create_tmp() } return res } return ErrorDefault } struct ModuleAddParam : FastCodable { let n : String let d : String let l : Int let g : Int? } func package_extract(dir : FileItem, file : FileItem) -> Bool { var err = AsyncError() if let bin = err <! Dir.bin.open("appudo_archiver", .O_RDONLY) { if let _ = err <! Process.exec(bin, args:["appudo_archiver", "-x", file], env:["PATH=/usr/lib"], cwd:dir, flags:.SUID) { return true } } return false } func module_package_add_end( _ _file : FileItem, _ uid : Int32, fromModule : Bool = false) -> ErrorResult { var file = _file if var tmp = <!FileItem.create_tmp(Dir.tmp, "pkgXXXXXX", flags:[.O_DIRECTORY, .O_RDONLY], mode:[.S_IRWXU, .S_IRWXG, .S_IXOTH]) { defer { _ = <!tmp.remove(outer:true) } let _data : ModuleAddParam? = fromModule ? nil : ModuleAddParam.from(json:Post.ext_data.value) if fromModule || _data != nil, package_extract(dir:tmp, file:file), var minfo = <!tmp.open("minfo", .O_RDONLY) { var err = AsyncError() var buffer = ManagedCharBuffer.create(64) var cbor = CBOR(buffer:buffer) var fail = true var moduleId : Int32 = -1 var nm = "" var desc = "" var mopt = "{}" var locked = 0 var g : Int? = nil _ = <!SQLQry.begin() defer { if fail { if moduleId != -1 { _ = Dir.module_source.remove("\(moduleId)") _ = Dir.module_gen_source.remove("\(moduleId)") } _ = <!SQLQry.rollback() } } if var _ = err <! minfo.read(to:buffer, offset:0) { var offset = 0 if (cbor.popMapSize() ?? -1) == 2, cbor.pop(sstring:"m"), let num = cbor.popMapSize() { for _ in 0..<num { let i = cbor.pop(sstrings:"n", "d", "o", "l") if i < 0 { break } else if i < 3 { let s = cbor.popStringSize() ?? 0 if(fromModule || i == 2) { let v = <!minfo.readAsText(s, offset:cbor.count + offset) switch(i) { case 0: nm = v ?? "" case 1: desc = v ?? "" case 2: mopt = v ?? "{}" default: break } } offset += cbor.count + s cbor.reset() _ = <!minfo.read(to:buffer, offset:offset) } else { _ = cbor.popBool() } } if fromModule == false { if let data = _data { nm = data.n desc = data.d locked = data.l g = data.g } } var qry = SQLQry(""" INSERT INTO modules(name, options, description, groups_id, users_id, locked) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id; """) qry.values = [nm, mopt == "{}" ? Optional<String>.none as Any : mopt, desc, g ?? Optional<Int>.none as Any, uid, locked] if (err <! qry.exec()) != false { moduleId = qry.getAsInt32(0, 0) ?? -1 } else { return ErrorResult(err.asSQL.rawValue) } if var ms = err <! tmp.open("source", .O_PATH), err <! ms.rename("\(moduleId)", Dir.module_source), let nms = err <! Dir.module_source.open("\(moduleId)", .O_PATH), err <! nms.setMode([.U0700, .G0050, .O0001]), let gen = err <! Dir.module_gen_source.mkpath("\(moduleId)", [.U0700, .G0050, .O0001]), cbor.pop(sstring:"i"), cbor.popArray() { var ok = true while(!cbor.popEnd()) { if cbor.popMapSize() ?? -1 != 3 { ok = false break } _ = cbor.pop(sstring:"r") let iid = cbor.popInt() ?? -1 _ = cbor.pop(sstring:"n") var s = cbor.popStringSize() ?? 0 let nm = <!minfo.readAsText(s, offset:cbor.count + offset) ?? "" offset += cbor.count + s cbor.reset() _ = <!minfo.read(to:buffer, offset:offset) _ = cbor.pop(sstring:"o") s = cbor.popStringSize() ?? 0 let opt = <!minfo.readAsText(s, offset:cbor.count + offset) ?? "{}" offset += cbor.count + s cbor.reset() _ = <!minfo.read(to:buffer, offset:offset) qry = SQLQry(""" INSERT INTO module_instances (modules_id, name, options) SELECT $1, $2, $3 RETURNING id; """) qry.values = [moduleId, nm, opt == "{}" ? Optional<String>.none as Any : opt] if (err <! qry.exec()) == false { return ErrorResult(err.asSQL.rawValue) } let niid = qry.getAsInt32(0, 0) ?? -1 if var d = err <! tmp.open("gen/\(iid)", .O_PATH), err <! d.rename("\(niid)", gen), let nd = err <! gen.open("\(niid)", .O_PATH), err <! nd.setMode([.U0700, .G0050, .O0001]) { } else { ok = false break } } if(ok) { fail = false _ = <!SQLQry.end() print(#"{"r":0, "d": \#(moduleId)}"#) return ErrorNone } } } } if(err.hasError) { return ErrorResult(err.errValue) } } } return ErrorDefault } func module_save_begin(_ param : PostParam, _ upload : UploadData, _ uinfo : LoginInfo, _ out : inout FileItem?) -> ErrorResult { var err = AsyncError() if let moduleId = param.id { let admin = uinfo.perm.has(.ADMIN_ALL) let qryStr = """ WITH perm AS ( SELECT bit_or(perm) AS perm FROM users_groups g, modules m WHERE g.users_id = $1 AND m.id = $2 AND m.groups_id = g.groups_id ) SELECT m.users_id FROM modules m LEFT OUTER JOIN perm p ON((p.perm & \(GroupPermissions.MODULE_SOURCE_EDIT.rawValue)) != 0) WHERE (m.users_id = $1 OR $3::Boolean IS TRUE) AND m.id = $2; """ if let qry = try? SQLQry(dirty_and_dangerous:qryStr) { qry.values = [uinfo.id, moduleId, admin] if(err <! qry.exec()) != false && qry.numRows != 0 { if let o = <!FileItem.create_tmp() { out = o Page.userData = PostInfo(param:param, file:o, uid:-1) return ErrorNone } } } } if(err.hasError) { return Int(err.errValue) as ErrorResult } return ErrorDefault } func module_save_code_end(_ param : PostParam, _ file : FileItem) -> ErrorResult { var err = AsyncError() if let type = param.x, let moduleId = param.id { var f = "" switch(type) { case 0: f = "setup.html" case 1: f = "config.html" case 3: f = "setup.tmpl" case 4: f = "config.tmpl" case 5: f = "run.tmpl" default: // 2 f = "run.html" } if type < 3 { let tmp = f + ".tmp" if let dir = err <! Dir.module_source.open("\(moduleId)", .O_DIRECTORY) { _ = <!dir.remove(tmp) if let bin = err <! Dir.bin.open("xdelta3", .O_RDONLY), var target = err <! FileItem.create_tmp(), let _ = err <! Process.exec(bin, args:["xdelta3", f, file, target], env:["PATH=/usr/lib"], cwd:dir, flags:.SUID), var out = err <! dir.open(tmp), (err <! target.link_open(out.path, hard:true)) != false, (err <! out.rename(f)) != false { print(#"{"r":0}"#) return ErrorNone } } } else { var inFile = file if let dir = err <! Dir.module_source.open("\(moduleId)", .O_DIRECTORY) { _ = <!dir.remove(f) if (err <! inFile.rename(f, dir)) != false || (err <! inFile.link_open(f, dir, hard:true)) { print(#"{"r":0}"#) return ErrorNone } } } if(err.hasError) { return Int(err.errValue) as ErrorResult } } return ErrorDefault } func module_save_gen_code_end(_ param : PostParam, _ file : FileItem) -> ErrorResult { var err = AsyncError() if let type = param.x, let moduleId = param.id, let instanceId = param.y { var f = "" switch(type) { case 0: f = "ebpf.h" case 1: f = "ebpf.c" case 2: f = "user.h" default: f = "user.cpp" } var inFile = file _ = <!Dir.module_gen_source.mkpath("\(moduleId)/\(instanceId)", [.U0700, .G0050, .O0001]) if let dir = err <! Dir.module_gen_source.open("\(moduleId)/\(instanceId)", .O_DIRECTORY) { _ = <!dir.remove(f) if (err <! inFile.rename(f, dir)) != false || (err <! inFile.link_open(f, dir, hard:true)) { print(#"{"r":0}"#) let qry = SQLQry(""" SELECT runs_id FROM run_instances WHERE module_instances_id = $1; """); qry.values = [instanceId] if (err <! qry.exec()) != false { for i in 0 ..< qry.numRows { let runId = qry.getAsInt32(i, 0) ?? -1 if let dir = <!Dir.run_binary.open("\(runId)", .O_DIRECTORY), let list = <!dir.listDir() { for item in list { if item.name != "settings.json" { _ = <!item.remove(outer:true) } } } } } return ErrorNone } } if(err.hasError) { return Int(err.errValue) as ErrorResult } } return ErrorDefault } func onUpload(ev : PageEvent) -> UploadResult { var out : FileItem? = nil var res = ErrorDefault Page.userData = 1 let data = Post.data.value if let param = PostParam.from(json:data), let upload = ev.data as? UploadData { var uinfo = LoginInfo(id:-1, perm:.NONE, keep:false) if(login_check(param:param, data:data, uinfo:&uinfo)) { switch(param.cmd) { case .DISSASSEMBLY_ADD: res = disassembly_add(param, upload, &out) case .MODULE_PACKAGE_ADD: res = module_package_add_begin(param, upload, uinfo, &out) case .MODULE_PACKAGE_INIT: res = module_package_init_begin(param, uinfo, &out) case .MODULE_CODE_SAVE: fallthrough case .MODULE_GEN_CODE_SAVE: res = module_save_begin(param, upload, uinfo, &out) default: break } if(out != nil) { return .OK(out!) } } else { print(#"{"r":1,"l":1}"#) return .ABORT } } print(#"{"r":\#(res)}"#) return .ABORT } func main() { if(Page.userData == nil) { print(#"{"r":\#(ErrorDefault)}"#) } else { if let info = Page.userData as? PostInfo { var res = ErrorDefault switch(info.param.cmd) { case .MODULE_PACKAGE_INIT: res = module_package_add_end(info.file, info.uid, fromModule:true) case .MODULE_PACKAGE_ADD: res = module_package_add_end(info.file, info.uid) case .MODULE_CODE_SAVE: res = module_save_code_end(info.param, info.file) case .MODULE_GEN_CODE_SAVE: res = module_save_gen_code_end(info.param, info.file) default: break } if(res == ErrorNone) { return } print(#"{"r":\#(res)}"#) } } }
apache-2.0
b54f56069b94b312eacb43437f4113b8
36.752308
186
0.44319
4.145633
false
false
false
false
MaxHasADHD/TraktKit
Common/Models/Structures.swift
1
4802
// // Structures.swift // TraktKit // // Created by Maximilian Litteral on 1/4/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public typealias RawJSON = [String: Any] // Dictionary // MARK: - TV & Movies public struct ID: Codable, Hashable { public let trakt: Int public let slug: String public let tvdb: Int? public let imdb: String? public let tmdb: Int? public let tvRage: Int? enum CodingKeys: String, CodingKey { case trakt case slug case tvdb case imdb case tmdb case tvRage = "tvrage" } } public struct SeasonId: Codable, Hashable { public let trakt: Int public let tvdb: Int? public let tmdb: Int? public let tvRage: Int? enum CodingKeys: String, CodingKey { case trakt case tvdb case tmdb case tvRage = "tvrage" } } public struct EpisodeId: Codable, Hashable { public let trakt: Int public let tvdb: Int? public let imdb: String? public let tmdb: Int? public let tvRage: Int? enum CodingKeys: String, CodingKey { case trakt case tvdb case imdb case tmdb case tvRage = "tvrage" } } public struct ListId: Codable, Hashable { public let trakt: Int public let slug: String enum CodingKeys: String, CodingKey { case trakt case slug } } // MARK: - Stats public struct TraktStats: Codable, Hashable { public let watchers: Int public let plays: Int public let collectors: Int public let collectedEpisodes: Int? public let comments: Int public let lists: Int public let votes: Int enum CodingKeys: String, CodingKey { case watchers case plays case collectors case collectedEpisodes = "collected_episodes" case comments case lists case votes } } // MARK: - Last Activities public struct TraktLastActivities: Codable, Hashable { public let all: Date public let movies: TraktLastActivityMovies public let episodes: TraktLastActivityEpisodes public let shows: TraktLastActivityShows public let seasons: TraktLastActivitySeasons public let comments: TraktLastActivityComments public let lists: TraktLastActivityLists } public struct TraktLastActivityMovies: Codable, Hashable { public let watchedAt: Date public let collectedAt: Date public let ratedAt: Date public let watchlistedAt: Date public let commentedAt: Date public let pausedAt: Date public let hiddenAt: Date enum CodingKeys: String, CodingKey { case watchedAt = "watched_at" case collectedAt = "collected_at" case ratedAt = "rated_at" case watchlistedAt = "watchlisted_at" case commentedAt = "commented_at" case pausedAt = "paused_at" case hiddenAt = "hidden_at" } } public struct TraktLastActivityEpisodes: Codable, Hashable { public let watchedAt: Date public let collectedAt: Date public let ratedAt: Date public let watchlistedAt: Date public let commentedAt: Date public let pausedAt: Date enum CodingKeys: String, CodingKey { case watchedAt = "watched_at" case collectedAt = "collected_at" case ratedAt = "rated_at" case watchlistedAt = "watchlisted_at" case commentedAt = "commented_at" case pausedAt = "paused_at" } } public struct TraktLastActivityShows: Codable, Hashable { public let ratedAt: Date public let watchlistedAt: Date public let commentedAt: Date public let hiddenAt: Date enum CodingKeys: String, CodingKey { case ratedAt = "rated_at" case watchlistedAt = "watchlisted_at" case commentedAt = "commented_at" case hiddenAt = "hidden_at" } } public struct TraktLastActivitySeasons: Codable, Hashable { public let ratedAt: Date public let watchlistedAt: Date public let commentedAt: Date public let hiddenAt: Date enum CodingKeys: String, CodingKey { case ratedAt = "rated_at" case watchlistedAt = "watchlisted_at" case commentedAt = "commented_at" case hiddenAt = "hidden_at" } } public struct TraktLastActivityComments: Codable, Hashable { public let likedAt: Date enum CodingKeys: String, CodingKey { case likedAt = "liked_at" } } public struct TraktLastActivityLists: Codable, Hashable { public let likedAt: Date public let updatedAt: Date public let commentedAt: Date enum CodingKeys: String, CodingKey { case likedAt = "liked_at" case updatedAt = "updated_at" case commentedAt = "commented_at" } }
mit
dc7009cf78223e1a8be59217ee36682d
24.136126
62
0.651948
4.313567
false
false
false
false
PhillipEnglish/TIY-Assignments
MuttCutts/MuttCutts/MapViewController.swift
1
2575
// // MapViewController.swift // MuttCutts // // Created by Phillip English on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let geocoder = CLGeocoder() geocoder.geocodeAddressString("Lakeland, FL", completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in if let placemark = placemarks?[0] { let annotation = MKPointAnnotation() annotation.coordinate = (placemark.location?.coordinate)! annotation.title = "Lakeland, FL" self.mapView.addAnnotation(annotation) } }) let tiyOrlando = CLLocationCoordinate2DMake(28.540923, -81.38216) let tiyOrlandoAnnotation = MKPointAnnotation() tiyOrlandoAnnotation.coordinate = tiyOrlando tiyOrlandoAnnotation.title = "The Iron Yard" tiyOrlandoAnnotation.subtitle = "Orlando" let tiyTampa = CLLocationCoordinate2DMake(27.770068, -82.63642) let tiyTampaAnnotation = MKPointAnnotation() tiyTampaAnnotation.coordinate = tiyTampa tiyTampaAnnotation.title = "The Iron Yard" tiyTampaAnnotation.subtitle = "Tampa" //mapView.camera.altitude *= 9 ???????????????????? let annotations = [tiyOrlandoAnnotation, tiyTampaAnnotation] mapView.addAnnotations(annotations) mapView.showAnnotations(annotations, animated: true) // let viewRegion = MKCoordinateRegionMakeWithDistance(tiyOrlando, 2000, 2000) // mapView.setRegion(viewRegion, animated: true) let orlandoLocation = CLLocation(coordinate: tiyOrlando, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, timestamp: NSDate()) let tampaLocation = CLLocation(coordinate: tiyTampa, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, timestamp: NSDate()) let lineOfSightDistance = orlandoLocation.distanceFromLocation(tampaLocation) print("distance between \(tiyOrlandoAnnotation.subtitle!) and \(tiyTampaAnnotation.subtitle!): " + String(format: "%.2f", lineOfSightDistance * 0.00062137) + " miles") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc0-1.0
beced617239574bfe3e665259b8a6d66
35.771429
175
0.655012
4.53169
false
false
false
false
mumuda/Swift_Weibo
weibo/weibo/Classes/Home/Popover/PopoverAnimal.swift
1
4854
// // PopoverAnimal.swift // weibo // // Created by ldj on 16/6/3. // Copyright © 2016年 ldj. All rights reserved. // import UIKit // 定义常量,保存通知的名称 let ZDPopoverAnimalWillShow = "ZDPopoverAnimalWillShow" let ZDPopoverAnimalWillDismiss = "ZDPopoverAnimalWillDismiss" class PopoverAnimal: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning { // 记录当前是否展开 var isPresent:Bool = false // 定义属性,保存菜单大小 var presentedFrame = CGRectZero // 实现代理方法,告诉系统谁来负责专场动画 // UIPresentationController iOS8推出专门用来负责转场动画 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let pc = PopPresentationController(presentedViewController: presented, presentingViewController: presenting) pc.presentedFrame = presentedFrame return pc } // MARK: - 只要实现了一下方法,系统默认的动画就没有了,"所有"东西都需要程序员自己实现 /** 告诉系统谁来负责modal 的展现动画 - parameter presented: 被展现实体 - parameter presenting: 发起视图 - returns: 谁来负责 */ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{ isPresent = true // 发送通知,通知控制器即将展开 NSNotificationCenter.defaultCenter().postNotificationName(ZDPopoverAnimalWillShow, object: self) return self } /** 告诉系统谁来负责modal的消失动画 - parameter dismissed: 被关闭的视图 - returns: 谁来负责 */ func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false // 发送通知,通知控制器即将消失 NSNotificationCenter.defaultCenter().postNotificationName(ZDPopoverAnimalWillDismiss, object: self) return self } // MARK: - UIViewControllerAnimatedTransitioning /** 返回动画时长 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 - returns: 动画时长 */ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /** 告诉系统如何动画,无论是动画展示或者消失,都会调用这个动画 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 */ func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 1.拿到展示视图 // let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) // let frameVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) // print(toVC , frameVC) // 通过打印发现要修改的就是toVC上面的view if isPresent { let toView = transitionContext.viewForKey(UITransitionContextToViewKey) toView?.transform = CGAffineTransformMakeScale(1.0, 0.0) transitionContext.containerView()?.addSubview(toView!) // 设置锚点 toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0) // 2..执行动画 // 注意: 一定要将视图添加到容器上 [UIView .animateWithDuration(transitionDuration(transitionContext), animations: { toView?.transform = CGAffineTransformIdentity }, completion: { (_) in // 2.1执行完动画一定要告诉系统 // 如果不写,可能导致一些未知错误 transitionContext.completeTransition(true) })] }else { let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { // 注意: 犹豫cgfloat是不准确的,所以如果写0.0是没有动画的, fromView?.transform = CGAffineTransformMakeScale(1.0, 0.00001) }, completion: { (_) in transitionContext.completeTransition(true) }) } } }
mit
207ea05438874249fbeb61c655be3d15
32.572581
219
0.650012
5.357786
false
false
false
false
mentrena/SyncKit
Example/RealmSwift/SyncKitRealmSwiftExample/SyncKitRealmSwiftExample/Company/Realm/RealmSharedCompanyWireframe.swift
1
2002
// // RealmSharedCompanyWireframe.swift // SyncKitRealmSwiftExample // // Created by Manuel Entrena on 26/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import UIKit import RealmSwift import SyncKit class RealmSharedCompanyWireframe: CompanyWireframe { let navigationController: UINavigationController let synchronizer: CloudKitSynchronizer var interactor: RealmSharedCompanyInteractor! let settingsManager: SettingsManager init(navigationController: UINavigationController, synchronizer: CloudKitSynchronizer, settingsManager: SettingsManager) { self.navigationController = navigationController self.synchronizer = synchronizer self.settingsManager = settingsManager } func show() { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Company") as! CompanyViewController interactor = RealmSharedCompanyInteractor(resultsController: synchronizer.multiRealmResultsController()!) let presenter = DefaultCompanyPresenter(view: viewController, interactor: interactor, wireframe: self, synchronizer: synchronizer, canEdit: false, settingsManager: settingsManager) viewController.presenter = presenter interactor.delegate = presenter navigationController.viewControllers = [viewController] } func show(company: Company, canEdit: Bool) { guard let modelCompany = interactor.modelObject(for: company) as? QSCompany, let realm = modelCompany.realm else { return } let employeeWireframe = RealmEmployeeWireframe(navigationController: navigationController, realm: realm) employeeWireframe.show(company: company, canEdit: canEdit) } }
mit
c81b4a71454ea79c8097cd00dd188105
44.477273
147
0.667166
6.214286
false
false
false
false
material-foundation/cocoapods-catalog-by-convention
src/SwiftUI/SwiftUIExampleWrapper.swift
1
1287
#if canImport(SwiftUI) import SwiftUI import UIKit /// A view controller to host SwiftUI views wrapped by a UIHostingControllers. /// Sample use, where MySwiftUIExample is a SwiftUI View: /// /// class MySwiftUIExampleWrapper: SwiftUIExampleWrapper { /// override func viewDidLoad() { /// super.viewDidLoad() /// addChildHostingController(UIHostingController(rootView: MySwiftUIExample())) /// } /// } open class SwiftUIExampleWrapper: UIViewController { public func addChildHostingController(_ swiftUIHostingController: UIViewController) { swiftUIHostingController.view.translatesAutoresizingMaskIntoConstraints = false addChild(swiftUIHostingController) view.addSubview(swiftUIHostingController.view) swiftUIHostingController.didMove(toParent: self) swiftUIHostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true swiftUIHostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true swiftUIHostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true swiftUIHostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } } #endif
apache-2.0
adc6e06802c3b414f69995bd945456ad
41.9
102
0.747475
5.210526
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/01033-swift-declcontext-lookupqualified.swift
1
459
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a<f : g, g : g where f.f == g> { } protocol g { typealias f } struct c<h : g> : g { typealias e = a<c<h>, f> class d<c>: NSObject { init(b: c) { g) { h } } protocol f { }} struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
apache-2.0
106cc87b8267744d54447b3f0cf15bc8
20.857143
87
0.657952
2.905063
false
true
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/misc/BitSet.swift
6
34676
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// // // BitSet.swift // Antlr.swift // // Created by janyou on 15/9/8. // import Foundation /// /// This class implements a vector of bits that grows as needed. Each /// component of the bit set has a `boolean` value. The /// bits of a `BitSet` are indexed by nonnegative integers. /// Individual indexed bits can be examined, set, or cleared. One /// `BitSet` may be used to modify the contents of another /// `BitSet` through logical AND, logical inclusive OR, and /// logical exclusive OR operations. /// /// By default, all bits in the set initially have the value /// `false`. /// /// Every bit set has a current size, which is the number of bits /// of space currently in use by the bit set. Note that the size is /// related to the implementation of a bit set, so it may change with /// implementation. The length of a bit set relates to logical length /// of a bit set and is defined independently of implementation. /// /// A `BitSet` is not safe for multithreaded use without /// external synchronization. /// /// - note: Arthur van Hoff /// - note: Michael McCloskey /// - note: Martin Buchholz /// - note: JDK1.0 /// public class BitSet: Hashable, CustomStringConvertible { /// /// BitSets are packed into arrays of "words." Currently a word is /// a long, which consists of 64 bits, requiring 6 address bits. /// The choice of word size is determined purely by performance concerns. /// private static let ADDRESS_BITS_PER_WORD: Int = 6 private static let BITS_PER_WORD: Int = 1 << ADDRESS_BITS_PER_WORD private static let BIT_INDEX_MASK: Int = BITS_PER_WORD - 1 /// /// Used to shift left or right for a partial word mask /// private static let WORD_MASK: Int64 = Int64.max //0xfffffffffffffff//-1 // 0xffffffffffffffffL; /// /// - bits long[] /// /// The bits in this BitSet. The ith bit is stored in bits[i/64] at /// bit position i % 64 (where bit position 0 refers to the least /// significant bit and 63 refers to the most significant bit). /// /// /// The internal field corresponding to the serialField "bits". /// fileprivate var words: [Int64] /// /// The number of words in the logical size of this BitSet. /// fileprivate var wordsInUse: Int = 0 //transient /// /// Whether the size of "words" is user-specified. If so, we assume /// the user knows what he's doing and try harder to preserve it. /// private var sizeIsSticky: Bool = false //transient /// /// use serialVersionUID from JDK 1.0.2 for interoperability /// private let serialVersionUID: Int64 = 7997698588986878753 //L; /// /// Given a bit index, return word index containing it. /// private static func wordIndex(_ bitIndex: Int) -> Int { return bitIndex >> ADDRESS_BITS_PER_WORD } /// /// Every public method must preserve these invariants. /// fileprivate func checkInvariants() { assert((wordsInUse == 0 || words[wordsInUse - 1] != 0), "Expected: (wordsInUse==0||words[wordsInUse-1]!=0)") assert((wordsInUse >= 0 && wordsInUse <= words.count), "Expected: (wordsInUse>=0&&wordsInUse<=words.length)") // print("\(wordsInUse),\(words.count),\(words[wordsInUse])") assert((wordsInUse == words.count || words[wordsInUse] == 0), "Expected: (wordsInUse==words.count||words[wordsInUse]==0)") } /// /// Sets the field wordsInUse to the logical size in words of the bit set. /// WARNING:This method assumes that the number of words actually in use is /// less than or equal to the current value of wordsInUse! /// private func recalculateWordsInUse() { // Traverse the bitset until a used word is found var i: Int = wordsInUse - 1 while i >= 0 { if words[i] != 0 { break } i -= 1 } wordsInUse = i + 1 // The new logical size } /// /// Creates a new bit set. All bits are initially `false`. /// public init() { sizeIsSticky = false words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1) //initWords(BitSet.BITS_PER_WORD); } /// /// Creates a bit set whose initial size is large enough to explicitly /// represent bits with indices in the range `0` through /// `nbits-1`. All bits are initially `false`. /// /// - parameter nbits: the initial size of the bit set /// - throws: _ANTLRError.negativeArraySize_ if the specified initial size /// is negative /// public init(_ nbits: Int) throws { // nbits can't be negative; size 0 is OK // words = [BitSet.wordIndex(nbits-1) + 1]; words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1) sizeIsSticky = true if nbits < 0 { throw ANTLRError.negativeArraySize(msg: "nbits < 0:\(nbits) ") } // initWords(nbits); } private func initWords(_ nbits: Int) { // words = [Int64](count: BitSet.wordIndex(BitSet.BITS_PER_WORD-1) + 1, repeatedValue: Int64(0)); // words = [BitSet.wordIndex(nbits-1) + 1]; } /// /// Creates a bit set using words as the internal representation. /// The last word (if there is one) must be non-zero. /// private init(_ words: [Int64]) { self.words = words self.wordsInUse = words.count checkInvariants() } /// /// Returns a new long array containing all the bits in this bit set. /// /// More precisely, if /// `long[] longs = s.toLongArray();` /// then `longs.length == (s.length()+63)/64` and /// `s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)` /// for all `n < 64 * longs.length`. /// /// - returns: a long array containing a little-endian representation /// of all the bits in this bit set /// public func toLongArray() -> [Int64] { return copyOf(words, wordsInUse) } private func copyOf(_ words: [Int64], _ newLength: Int) -> [Int64] { var newWords = [Int64](repeating: Int64(0), count: newLength) let length = min(words.count, newLength) newWords[0 ..< length] = words[0 ..< length] return newWords } /// /// Ensures that the BitSet can hold enough words. /// - parameter wordsRequired: the minimum acceptable number of words. /// private func ensureCapacity(_ wordsRequired: Int) { if words.count < wordsRequired { // Allocate larger of doubled size or required size let request: Int = max(2 * words.count, wordsRequired) words = copyOf(words, request) sizeIsSticky = false } } /// /// Ensures that the BitSet can accommodate a given wordIndex, /// temporarily violating the invariants. The caller must /// restore the invariants before returning to the user, /// possibly using recalculateWordsInUse(). /// - parameter wordIndex: the index to be accommodated. /// private func expandTo(_ wordIndex: Int) { let wordsRequired: Int = wordIndex + 1 if wordsInUse < wordsRequired { ensureCapacity(wordsRequired) wordsInUse = wordsRequired } } /// /// Checks that fromIndex ... toIndex is a valid range of bit indices. /// private static func checkRange(_ fromIndex: Int, _ toIndex: Int) throws { if fromIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)") } if toIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "toIndex < 0: \(toIndex)") } if fromIndex > toIndex { throw ANTLRError.indexOutOfBounds(msg: "fromInde: \(fromIndex) > toIndex: \(toIndex)") } } /// /// Sets the bit at the specified index to the complement of its /// current value. /// /// - parameter bitIndex: the index of the bit to flip /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// public func flip(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") } let index: Int = BitSet.wordIndex(bitIndex) expandTo(index) words[index] ^= (Int64(1) << Int64(bitIndex % 64)) recalculateWordsInUse() checkInvariants() } /// /// Sets each bit from the specified `fromIndex` (inclusive) to the /// specified `toIndex` (exclusive) to the complement of its current /// value. /// /// - parameter fromIndex: index of the first bit to flip /// - parameter toIndex: index after the last bit to flip /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative, /// or `toIndex` is negative, or `fromIndex` is /// larger than `toIndex` /// public func flip(_ fromIndex: Int, _ toIndex: Int) throws { try BitSet.checkRange(fromIndex, toIndex) if fromIndex == toIndex { return } let startWordIndex: Int = BitSet.wordIndex(fromIndex) let endWordIndex: Int = BitSet.wordIndex(toIndex - 1) expandTo(endWordIndex) let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64) let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex) //var lastWordMask : Int64 = WORD_MASK >>> Int64(-toIndex); if startWordIndex == endWordIndex { // Case 1: One word words[startWordIndex] ^= (firstWordMask & lastWordMask) } else { // Case 2: Multiple words // Handle first word words[startWordIndex] ^= firstWordMask // Handle intermediate words, if any let start = startWordIndex + 1 for i in start..<endWordIndex { words[i] ^= BitSet.WORD_MASK } // Handle last word words[endWordIndex] ^= lastWordMask } recalculateWordsInUse() checkInvariants() } /// /// Sets the bit at the specified index to `true`. /// /// - parameter bitIndex: a bit index /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// public func set(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") } let index: Int = BitSet.wordIndex(bitIndex) expandTo(index) // print(words.count) words[index] |= (Int64(1) << Int64(bitIndex % 64)) // Restores invariants checkInvariants() } /// /// Sets the bit at the specified index to the specified value. /// /// - parameter bitIndex: a bit index /// - parameter value: a boolean value to set /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// public func set(_ bitIndex: Int, _ value: Bool) throws { if value { try set(bitIndex) } else { try clear(bitIndex) } } /// /// Sets the bits from the specified `fromIndex` (inclusive) to the /// specified `toIndex` (exclusive) to `true`. /// /// - parameter fromIndex: index of the first bit to be set /// - parameter toIndex: index after the last bit to be set /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative, /// or `toIndex` is negative, or `fromIndex` is /// larger than `toIndex` /// public func set(_ fromIndex: Int, _ toIndex: Int) throws { try BitSet.checkRange(fromIndex, toIndex) if fromIndex == toIndex { return } // Increase capacity if necessary let startWordIndex: Int = BitSet.wordIndex(fromIndex) let endWordIndex: Int = BitSet.wordIndex(toIndex - 1) expandTo(endWordIndex) let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64) let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex) //var lastWordMask : Int64 = WORD_MASK >>>Int64( -toIndex); if startWordIndex == endWordIndex { // Case 1: One word words[startWordIndex] |= (firstWordMask & lastWordMask) } else { // Case 2: Multiple words // Handle first word words[startWordIndex] |= firstWordMask // Handle intermediate words, if any let start = startWordIndex + 1 for i in start..<endWordIndex { words[i] = BitSet.WORD_MASK } // Handle last word (restores invariants) words[endWordIndex] |= lastWordMask } checkInvariants() } /// /// Sets the bits from the specified `fromIndex` (inclusive) to the /// specified `toIndex` (exclusive) to the specified value. /// /// - parameter fromIndex: index of the first bit to be set /// - parameter toIndex: index after the last bit to be set /// - parameter value: value to set the selected bits to /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative, /// or `toIndex` is negative, or `fromIndex` is /// larger than `toIndex` /// public func set(_ fromIndex: Int, _ toIndex: Int, _ value: Bool) throws { if value { try set(fromIndex, toIndex) } else { try clear(fromIndex, toIndex) } } /// /// Sets the bit specified by the index to `false`. /// /// - parameter bitIndex: the index of the bit to be cleared /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// - JDK1.0 /// public func clear(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") } let index: Int = BitSet.wordIndex(bitIndex) if index >= wordsInUse { return } let option = Int64(1) << Int64(bitIndex % 64) words[index] &= ~option recalculateWordsInUse() checkInvariants() } /// /// Sets the bits from the specified `fromIndex` (inclusive) to the /// specified `toIndex` (exclusive) to `false`. /// /// - parameter fromIndex: index of the first bit to be cleared /// - parameter toIndex: index after the last bit to be cleared /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative, /// or `toIndex` is negative, or `fromIndex` is /// larger than `toIndex` /// public func clear(_ fromIndex: Int, _ toIndex: Int) throws { var toIndex = toIndex try BitSet.checkRange(fromIndex, toIndex) if fromIndex == toIndex { return } let startWordIndex: Int = BitSet.wordIndex(fromIndex) if startWordIndex >= wordsInUse { return } var endWordIndex: Int = BitSet.wordIndex(toIndex - 1) if endWordIndex >= wordsInUse { toIndex = length() endWordIndex = wordsInUse - 1 } let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64) // ar lastWordMask : Int64 = WORD_MASK >>> Int64((-toIndex); let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex) if startWordIndex == endWordIndex { // Case 1: One word words[startWordIndex] &= ~(firstWordMask & lastWordMask) } else { // Case 2: Multiple words // Handle first word words[startWordIndex] &= ~firstWordMask // Handle intermediate words, if any let start = startWordIndex + 1 for i in start..<endWordIndex { words[i] = 0 } // Handle last word words[endWordIndex] &= ~lastWordMask } recalculateWordsInUse() checkInvariants() } /// /// Sets all of the bits in this BitSet to `false`. /// public func clear() { while wordsInUse > 0 { wordsInUse -= 1 words[wordsInUse] = 0 } } /// /// Returns the value of the bit with the specified index. The value /// is `true` if the bit with the index `bitIndex` /// is currently set in this `BitSet`; otherwise, the result /// is `false`. /// /// - parameter bitIndex: the bit index /// - returns: the value of the bit with the specified index /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// public func get(_ bitIndex: Int) throws -> Bool { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") } checkInvariants() let index: Int = BitSet.wordIndex(bitIndex) return (index < wordsInUse) && ((words[index] & ((Int64(1) << Int64(bitIndex % 64)))) != 0) } /// /// Returns a new `BitSet` composed of bits from this `BitSet` /// from `fromIndex` (inclusive) to `toIndex` (exclusive). /// /// - parameter fromIndex: index of the first bit to include /// - parameter toIndex: index after the last bit to include /// - returns: a new `BitSet` from a range of this `BitSet` /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative, /// or `toIndex` is negative, or `fromIndex` is /// larger than `toIndex` /// public func get(_ fromIndex: Int, _ toIndex: Int) throws -> BitSet { var toIndex = toIndex try BitSet.checkRange(fromIndex, toIndex) checkInvariants() let len: Int = length() // If no set bits in range return empty bitset if len <= fromIndex || fromIndex == toIndex { return try BitSet(0) } // An optimization if toIndex > len { toIndex = len } let result: BitSet = try BitSet(toIndex - fromIndex) let targetWords: Int = BitSet.wordIndex(toIndex - fromIndex - 1) + 1 var sourceIndex: Int = BitSet.wordIndex(fromIndex) let wordAligned: Bool = (fromIndex & BitSet.BIT_INDEX_MASK) == 0 // Process all words but the last word var i: Int = 0; while i < targetWords - 1 { let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex)) let wordOption2: Int64 = (words[sourceIndex + 1] << Int64(-fromIndex % 64)) let wordOption = wordOption1 | wordOption2 result.words[i] = wordAligned ? words[sourceIndex] : wordOption i += 1 sourceIndex += 1 } // Process the last word // var lastWordMask : Int64 = WORD_MASK >>> Int64(-toIndex); let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex) let toIndexTest = ((toIndex - 1) & BitSet.BIT_INDEX_MASK) let fromIndexTest = (fromIndex & BitSet.BIT_INDEX_MASK) let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex)) let wordOption2: Int64 = (words[sourceIndex + 1] & lastWordMask) let wordOption3: Int64 = (64 + Int64(-fromIndex % 64)) let wordOption = wordOption1 | wordOption2 << wordOption3 let wordOption4 = (words[sourceIndex] & lastWordMask) let wordOption5 = wordOption4 >>> Int64(fromIndex) result.words[targetWords - 1] = toIndexTest < fromIndexTest ? wordOption : wordOption5 // Set wordsInUse correctly result.wordsInUse = targetWords result.recalculateWordsInUse() result.checkInvariants() return result } /// /// Equivalent to nextSetBit(0), but guaranteed not to throw an exception. /// public func firstSetBit() -> Int { return try! nextSetBit(0) } /// /// Returns the index of the first bit that is set to `true` /// that occurs on or after the specified starting index. If no such /// bit exists then `-1` is returned. /// /// To iterate over the `true` bits in a `BitSet`, /// use the following loop: /// /// ` /// for (int i = bs.firstSetBit(); i >= 0; i = bs.nextSetBit(i+1)) { /// // operate on index i here /// `} /// /// - parameter fromIndex: the index to start checking from (inclusive) /// - returns: the index of the next set bit, or `-1` if there /// is no such bit /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative /// public func nextSetBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)") } checkInvariants() var u: Int = BitSet.wordIndex(fromIndex) if u >= wordsInUse { return -1 } var word: Int64 = words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64)) while true { if word != 0 { let bit = (u * BitSet.BITS_PER_WORD) + word.trailingZeroBitCount return bit } u += 1 if u == wordsInUse { return -1 } word = words[u] } } /// /// Returns the index of the first bit that is set to `false` /// that occurs on or after the specified starting index. /// /// - parameter fromIndex: the index to start checking from (inclusive) /// - returns: the index of the next clear bit /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is negative /// public func nextClearBit(_ fromIndex: Int) throws -> Int { // Neither spec nor implementation handle bitsets of maximal length. // See 4816253. if fromIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)") } checkInvariants() var u: Int = BitSet.wordIndex(fromIndex) if u >= wordsInUse { return fromIndex } var word: Int64 = ~words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64)) while true { if word != 0 { return (u * BitSet.BITS_PER_WORD) + word.trailingZeroBitCount } u += 1 if u == wordsInUse { return wordsInUse * BitSet.BITS_PER_WORD } word = ~words[u] } } /// /// Returns the index of the nearest bit that is set to `true` /// that occurs on or before the specified starting index. /// If no such bit exists, or if `-1` is given as the /// starting index, then `-1` is returned. /// /// To iterate over the `true` bits in a `BitSet`, /// use the following loop: /// /// ` /// for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) { /// // operate on index i here /// `} /// /// - parameter fromIndex: the index to start checking from (inclusive) /// - returns: the index of the previous set bit, or `-1` if there /// is no such bit /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less /// than `-1` /// - note: 1.7 /// public func previousSetBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { if fromIndex == -1 { return -1 } throw ANTLRError.indexOutOfBounds(msg: "fromIndex < -1: \(fromIndex)") } checkInvariants() var u: Int = BitSet.wordIndex(fromIndex) if u >= wordsInUse { return length() - 1 } var word: Int64 = words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1))) while true { if word != 0 { return (u + 1) * BitSet.BITS_PER_WORD - 1 - word.leadingZeroBitCount } if u == 0 { return -1 } u -= 1 word = words[u] } } /// /// Returns the index of the nearest bit that is set to `false` /// that occurs on or before the specified starting index. /// If no such bit exists, or if `-1` is given as the /// starting index, then `-1` is returned. /// /// - parameter fromIndex: the index to start checking from (inclusive) /// - returns: the index of the previous clear bit, or `-1` if there /// is no such bit /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less /// than `-1` /// - note: 1.7 /// public func previousClearBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { if fromIndex == -1 { return -1 } throw ANTLRError.indexOutOfBounds(msg: "fromIndex < -1: \(fromIndex)") } checkInvariants() var u: Int = BitSet.wordIndex(fromIndex) if u >= wordsInUse { return fromIndex } var word: Int64 = ~words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1))) // var word : Int64 = ~words[u] & (WORD_MASK >>> -(fromIndex+1)); while true { if word != 0 { return (u + 1) * BitSet.BITS_PER_WORD - 1 - word.leadingZeroBitCount } if u == 0 { return -1 } u -= 1 word = ~words[u] } } /// /// Returns the "logical size" of this `BitSet`: the index of /// the highest set bit in the `BitSet` plus one. Returns zero /// if the `BitSet` contains no set bits. /// /// - returns: the logical size of this `BitSet` /// public func length() -> Int { if wordsInUse == 0 { return 0 } return BitSet.BITS_PER_WORD * (wordsInUse - 1) + (BitSet.BITS_PER_WORD - words[wordsInUse - 1].leadingZeroBitCount) } /// /// Returns true if this `BitSet` contains no bits that are set /// to `true`. /// /// - returns: boolean indicating whether this `BitSet` is empty /// public func isEmpty() -> Bool { return wordsInUse == 0 } /// /// Returns true if the specified `BitSet` has any bits set to /// `true` that are also set to `true` in this `BitSet`. /// /// - parameter set: `BitSet` to intersect with /// - returns: boolean indicating whether this `BitSet` intersects /// the specified `BitSet` /// public func intersects(_ set: BitSet) -> Bool { var i: Int = min(wordsInUse, set.wordsInUse) - 1 while i >= 0 { if (words[i] & set.words[i]) != 0 { return true } i -= 1 } return false } /// /// Returns the number of bits set to `true` in this `BitSet`. /// /// - returns: the number of bits set to `true` in this `BitSet` /// public func cardinality() -> Int { var sum: Int = 0 for i in 0..<wordsInUse { sum += words[i].nonzeroBitCount } return sum } /// /// Performs a logical __AND__ of this target bit set with the /// argument bit set. This bit set is modified so that each bit in it /// has the value `true` if and only if it both initially /// had the value `true` and the corresponding bit in the /// bit set argument also had the value `true`. /// /// - parameter set: a bit set /// public func and(_ set: BitSet) { if self == set { return } while wordsInUse > set.wordsInUse { wordsInUse -= 1 words[wordsInUse] = 0 } // Perform logical AND on words in common for i in 0..<wordsInUse { words[i] &= set.words[i] } recalculateWordsInUse() checkInvariants() } /// /// Performs a logical __OR__ of this bit set with the bit set /// argument. This bit set is modified so that a bit in it has the /// value `true` if and only if it either already had the /// value `true` or the corresponding bit in the bit set /// argument has the value `true`. /// /// - parameter set: a bit set /// public func or(_ set: BitSet) { if self == set { return } let wordsInCommon: Int = min(wordsInUse, set.wordsInUse) if wordsInUse < set.wordsInUse { ensureCapacity(set.wordsInUse) wordsInUse = set.wordsInUse } // Perform logical OR on words in common for i in 0..<wordsInCommon { words[i] |= set.words[i] } // Copy any remaining words if wordsInCommon < set.wordsInUse { words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse] } // recalculateWordsInUse() is unnecessary checkInvariants() } /// /// Performs a logical __XOR__ of this bit set with the bit set /// argument. This bit set is modified so that a bit in it has the /// value `true` if and only if one of the following /// statements holds: /// /// * The bit initially has the value `true`, and the /// corresponding bit in the argument has the value `false`. /// * The bit initially has the value `false`, and the /// corresponding bit in the argument has the value `true`. /// /// - parameter set: a bit set /// public func xor(_ set: BitSet) { let wordsInCommon: Int = min(wordsInUse, set.wordsInUse) if wordsInUse < set.wordsInUse { ensureCapacity(set.wordsInUse) wordsInUse = set.wordsInUse } // Perform logical XOR on words in common for i in 0..<wordsInCommon { words[i] ^= set.words[i] } // Copy any remaining words if wordsInCommon < set.wordsInUse { words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse] } recalculateWordsInUse() checkInvariants() } /// /// Clears all of the bits in this `BitSet` whose corresponding /// bit is set in the specified `BitSet`. /// /// - parameter set: the `BitSet` with which to mask this /// `BitSet` /// public func andNot(_ set: BitSet) { // Perform logical (a & !b) on words in common var i: Int = min(wordsInUse, set.wordsInUse) - 1 while i >= 0 { words[i] &= ~set.words[i] i -= 1 } recalculateWordsInUse() checkInvariants() } /// /// Returns the hash code value for this bit set. The hash code depends /// only on which bits are set within this `BitSet`. /// /// The hash code is defined to be the result of the following /// calculation: /// ` /// public int hashCode() { /// long h = 1234; /// long[] words = toLongArray(); /// for (int i = words.length; --i >= 0; ) /// h ^= words[i] * (i + 1); /// return (int)((h >> 32) ^ h); /// `} /// Note that the hash code changes if the set of bits is altered. /// /// - returns: the hash code value for this bit set /// private var hashCode: Int { var h: Int64 = 1234 var i: Int = wordsInUse i -= 1 while i >= 0 { h ^= words[i] * Int64(i + 1) i -= 1 } return Int(Int32((h >> 32) ^ h)) } public func hash(into hasher: inout Hasher) { hasher.combine(hashCode) } /// /// Returns the number of bits of space actually in use by this /// `BitSet` to represent bit values. /// The maximum element in the set is the size - 1st element. /// /// - returns: the number of bits currently in this bit set /// public func size() -> Int { return words.count * BitSet.BITS_PER_WORD } /// /// Attempts to reduce internal storage used for the bits in this bit set. /// Calling this method may, but is not required to, affect the value /// returned by a subsequent call to the _#size()_ method. /// private func trimToSize() { if wordsInUse != words.count { words = copyOf(words, wordsInUse) checkInvariants() } } /// /// Returns a string representation of this bit set. For every index /// for which this `BitSet` contains a bit in the set /// state, the decimal representation of that index is included in /// the result. Such indices are listed in order from lowest to /// highest, separated by ",&nbsp;" (a comma and a space) and /// surrounded by braces, resulting in the usual mathematical /// notation for a set of integers. /// /// Example: /// /// `BitSet drPepper = new BitSet();` /// Now `drPepper.description` returns `"{}"`. /// /// `drPepper.set(2);` /// Now `drPepper.description` returns `"{2}"`. /// /// `drPepper.set(4);` /// `drPepper.set(10);` /// Now `drPepper.description` returns `"{2, 4, 10}"`. /// /// - returns: a string representation of this bit set /// public var description: String { checkInvariants() //let numBits: Int = (wordsInUse > 128) ? // cardinality() : wordsInUse * BitSet.BITS_PER_WORD var b = "{" var i = firstSetBit() if i != -1 { b += String(i) i = try! nextSetBit(i + 1) while i >= 0 { let endOfRun = try! nextClearBit(i) repeat { b += ", \(i)" i += 1 } while i < endOfRun i = try! nextSetBit(i + 1) } } b += "}" return b } } public func ==(lhs: BitSet, rhs: BitSet) -> Bool { if lhs === rhs { return true } lhs.checkInvariants() rhs.checkInvariants() if lhs.wordsInUse != rhs.wordsInUse { return false } // Check words in use by both BitSets let length = lhs.wordsInUse for i in 0..<length { if lhs.words[i] != rhs.words[i] { return false } } return true }
bsd-3-clause
dec39e81deccc1e8333468bf5c88a505
30.842057
130
0.563617
4.175316
false
false
false
false
khizkhiz/swift
test/IDE/complete_dynamic_lookup.swift
1
30814
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -emit-module -disable-objc-attr-requires-foundation-module -o %t %S/Inputs/AnyObject/foo_swift_module.swift // RUN: %target-swift-frontend -emit-module -disable-objc-attr-requires-foundation-module -o %t %S/Inputs/AnyObject/bar_swift_module.swift // RUN: cp %S/Inputs/AnyObject/baz_clang_module.h %t // RUN: cp %S/Inputs/AnyObject/module.map %t // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_PARAM_NO_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_PARAM_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_VAR_NO_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_VAR_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_RETURN_VAL_NO_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_RETURN_VAL_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CALL_RETURN_VAL_NO_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=TLOC_MEMBERS_NO_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CALL_RETURN_VAL_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=TLOC_MEMBERS_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_FUNC_NAME_1 < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_PAREN_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_FUNC_NAME_PAREN_1 < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_FUNC_NAME_DOT_1 < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_BANG_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_FUNC_NAME_BANG_1 < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CLASS_NO_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_CLASS_NO_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CLASS_DOT_1 > %t.dl.txt // RUN: FileCheck %s -check-prefix=DL_CLASS_DOT < %t.dl.txt // RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // REQUIRES: objc_interop import foo_swift_module import class bar_swift_module.Bar_ImportedObjcClass import baz_clang_module //===--- //===--- Helper types that are used in this test. //===--- @objc class Base {} @objc class Derived : Base {} protocol Foo { func foo() } protocol Bar { func bar() } //===--- //===--- Types that contain members accessible by dynamic lookup. //===--- // GLOBAL_NEGATIVE-NOT: ERROR // DL_INSTANCE_NO_DOT: Begin completions // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc2!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc3!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc4!()[#Base#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .base1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .base1_Property2[#Base?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Class_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Protocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_Nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_Nested2_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .nested2_Property[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG-NOT:.objectAtIndexedSubscript // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .returnsObjcClass!({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[bar_swift_module]: [{#Bar_ImportedObjcClass#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Foo_TopLevelObjcProtocol#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#Int16#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Int32#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Int64#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#Int8#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#TopLevelObjcClass#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#TopLevelObjcProtocol#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[baz_clang_module]: [{#Int32#}][#AnyObject!?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[baz_clang_module]: [{#AnyObject!#}][#AnyObject!?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT: End completions // DL_INSTANCE_DOT: Begin completions // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc2!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc3!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc4!()[#Base#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: base1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: base1_Property2[#Base?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Class_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[baz_clang_module]: baz_Class_Property1[#Baz_Class!?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[baz_clang_module]: baz_Class_Property2[#Baz_Class!?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Protocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_Nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_Nested2_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: nested2_Property[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: returnsObjcClass!({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT: End completions // DL_CLASS_NO_DOT: Begin completions // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_InstanceFunc1({#self: Bar_ImportedObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc1({#self: Base1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc2({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc3({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc4({#self: Base1#})[#() -> Base#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: .baz_Class_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Class_InstanceFunc1({#self: Baz_Class#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: .baz_Protocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Protocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass1.Foo_Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass2.Foo_Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcInstanceFunc1({#self: Foo_TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_InstanceFunc1({#self: Foo_TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested1_ObjcInstanceFunc1({#self: ContainerForNestedClass1.Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested2_ObjcInstanceFunc1({#self: ContainerForNestedClass2.Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .returnsObjcClass({#self: TopLevelObjcClass#})[#(Int) -> TopLevelObjcClass#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcInstanceFunc1({#self: TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_InstanceFunc1({#self: TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT: End completions // DL_CLASS_DOT: Begin completions // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_InstanceFunc1({#self: Bar_ImportedObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc1({#self: Base1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc2({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc3({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc4({#self: Base1#})[#() -> Base#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: baz_Class_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Class_InstanceFunc1({#self: Baz_Class#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: baz_Protocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Protocol_InstanceFunc1({#self: AnyObject.Type#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass1.Foo_Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass2.Foo_Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcInstanceFunc1({#self: Foo_TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_InstanceFunc1({#self: Foo_TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_InstanceFunc1({#self: AnyObject.Type#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested1_ObjcInstanceFunc1({#self: ContainerForNestedClass1.Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested2_ObjcInstanceFunc1({#self: ContainerForNestedClass2.Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: returnsObjcClass({#self: TopLevelObjcClass#})[#(Int) -> TopLevelObjcClass#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcInstanceFunc1({#self: TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_InstanceFunc1({#self: TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_InstanceFunc1({#self: AnyObject.Type#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT: End completions // TLOC_MEMBERS_NO_DOT: Begin completions // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .returnsObjcClass({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .topLevelObjcClass_InstanceFunc1()[#Void#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int8#}][#Int#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .topLevelObjcClass_Property1[#Int#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: End completions // TLOC_MEMBERS_DOT: Begin completions // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: returnsObjcClass({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: topLevelObjcClass_InstanceFunc1()[#Void#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceVar]/CurrNominal: topLevelObjcClass_Property1[#Int#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: End completions // FIXME: Properties in Clang modules. // There's a test already: baz_Protocol_Property1. // Blocked by: rdar://15136550 Properties in protocols not implemented @objc class TopLevelObjcClass { func returnsObjcClass(i: Int) -> TopLevelObjcClass {} func topLevelObjcClass_InstanceFunc1() {} class func topLevelObjcClass_ClassFunc1() {} subscript(i: Int8) -> Int { get { return 0 } } var topLevelObjcClass_Property1: Int } @objc class TopLevelObjcClass_DuplicateMembers { func topLevelObjcClass_InstanceFunc1() {} class func topLevelObjcClass_ClassFunc1() {} subscript(i: Int8) -> Int { get { return 0 } } var topLevelObjcClass_Property1: Int } class TopLevelClass { @objc func topLevelClass_ObjcInstanceFunc1() {} @objc class func topLevelClass_ObjcClassFunc1() {} @objc subscript (i: Int16) -> Int { get { return 0 } } @objc var topLevelClass_ObjcProperty1: Int func ERROR() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } @objc protocol TopLevelObjcProtocol { func topLevelObjcProtocol_InstanceFunc1() class func topLevelObjcProtocol_ClassFunc1() subscript (i: TopLevelObjcClass) -> Int { get set } var topLevelObjcProtocol_Property1: Int { get set } } class ContainerForNestedClass1 { class Nested1 { @objc func nested1_ObjcInstanceFunc1() {} @objc class func nested1_ObjcClassFunc1() {} @objc var nested1_Property1: Int func ERROR() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } struct ContainerForNestedClass2 { class Nested2 { @objc func nested2_ObjcInstanceFunc1() {} @objc class func nested2_ObjcClassFunc1() {} @objc subscript (i: TopLevelObjcProtocol) -> Int { get { return 0 } } @objc var nested2_Property: Int func ERROR() {} var ERROR_Property: Int } func ERROR() {} } class GenericContainerForNestedClass1<T> { class Nested3 { @objc func ERROR1() {} func ERROR2() {} class func ERROR3() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } struct GenericContainerForNestedClass2<T> { class Nested3 { @objc func ERROR1() {} func ERROR2() {} class func ERROR3() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } @objc class Base1 { func base1_InstanceFunc1() {} func base1_InstanceFunc2(a: Derived) {} func base1_InstanceFunc3(a: Derived) {} func base1_InstanceFunc4() -> Base {} var base1_Property1: Int var base1_Property2: Base } @objc class Derived1 : Base1 { func base1_InstanceFunc1() {} func base1_InstanceFunc2(a: Derived) {} func base1_InstanceFunc3(a: Base) {} func base1_InstanceFunc4() -> Derived {} var base1_Property1: Int { get { return 0 } set {} } var base1_Property2: Derived { get { return Derived() } set {} } } func returnsAnyObject() -> AnyObject { return TopLevelClass() } func testAnyObject1(dl: AnyObject) { dl#^DL_FUNC_PARAM_NO_DOT_1^# } func testAnyObject2(dl: AnyObject) { dl.#^DL_FUNC_PARAM_DOT_1^# } func testAnyObject3() { var dl: AnyObject = TopLevelClass() dl#^DL_VAR_NO_DOT_1^# } func testAnyObject4() { var dl: AnyObject = TopLevelClass() dl.#^DL_VAR_DOT_1^# } func testAnyObject5() { returnsAnyObject()#^DL_RETURN_VAL_NO_DOT_1^# } func testAnyObject6() { returnsAnyObject().#^DL_RETURN_VAL_DOT_1^# } func testAnyObject7(dl: AnyObject) { dl.returnsObjcClass!(42)#^DL_CALL_RETURN_VAL_NO_DOT_1^# } func testAnyObject8(dl: AnyObject) { dl.returnsObjcClass!(42).#^DL_CALL_RETURN_VAL_DOT_1^# } func testAnyObject9() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?(42)#^DL_CALL_RETURN_OPTIONAL_NO_DOT_1^# } func testAnyObject10() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?(42).#^DL_CALL_RETURN_OPTIONAL_DOT_1^# } func testAnyObject11(dl: AnyObject) { dl.returnsObjcClass#^DL_FUNC_NAME_1^# } // FIXME: it would be nice if we produced a call pattern here. // DL_FUNC_NAME_1: Begin completions // DL_FUNC_NAME_1-DAG: Decl[InstanceVar]/CurrNominal: .description[#String#]{{; name=.+$}} // DL_FUNC_NAME_1: End completions func testAnyObject11_(dl: AnyObject) { dl.returnsObjcClass!(#^DL_FUNC_NAME_PAREN_1^# } // DL_FUNC_NAME_PAREN_1: Begin completions // DL_FUNC_NAME_PAREN_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_FUNC_NAME_PAREN_1: End completions func testAnyObject12(dl: AnyObject) { dl.returnsObjcClass.#^DL_FUNC_NAME_DOT_1^# } // FIXME: it would be nice if we produced a call pattern here. // DL_FUNC_NAME_DOT_1: Begin completions // DL_FUNC_NAME_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: description[#String#]{{; name=.+$}} // DL_FUNC_NAME_DOT_1: End completions func testAnyObject13(dl: AnyObject) { dl.returnsObjcClass!#^DL_FUNC_NAME_BANG_1^# } // DL_FUNC_NAME_BANG_1: Begin completions // DL_FUNC_NAME_BANG_1-NEXT: Pattern/ExprSpecific: ({#Int#})[#TopLevelObjcClass#] // DL_FUNC_NAME_BANG_1-NEXT: End completions func testAnyObject14() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?#^DL_FUNC_QUESTION_1^# } func testAnyObjectClassMethods1(dl: AnyObject) { dl.dynamicType#^DL_CLASS_NO_DOT_1^# } func testAnyObjectClassMethods2(dl: AnyObject) { dl.dynamicType.#^DL_CLASS_DOT_1^# }
apache-2.0
3c07766523694557dcea856748f8329c
61
186
0.688161
3.38318
false
true
false
false
visualitysoftware/swift-sdk
CloudBoost/CloudFile.swift
1
8288
// // CloudFile.swift // CloudBoost // // Created by Randhir Singh on 31/03/16. // Copyright © 2016 Randhir Singh. All rights reserved. // import Foundation public class CloudFile { var document = NSMutableDictionary() private var data: NSData? private var strEncodedData: String? public init(name: String, data: NSData, contentType: String){ self.data = data self.strEncodedData = data.base64EncodedStringWithOptions([]) document["_id"] = nil document["_type"] = "file" document["ACL"] = ACL().getACL() document["name"] = name document["size"] = data.length document["url"] = nil document["expires"] = nil document["contentType"] = contentType } public init(id: String){ document["_id"] = id } public init(doc: NSMutableDictionary){ self.document = doc self.data = nil } // MARK: Getters public func getId() -> String? { return document["_id"] as? String } public func getContentType() -> String? { return document["contentType"] as? String } public func getFileUrl() -> String? { return document["url"] as? String } public func getFileName() -> String? { return document["name"] as? String } public func getACL() -> ACL? { if let acl = document["ACL"] as? NSMutableDictionary { return ACL(acl: acl) } return nil } public func getData() -> NSData? { return data } public func getExpires() -> NSDate? { if let expires = document["expires"] as? String { return CloudBoostDateFormatter.getISOFormatter().dateFromString(expires) } return nil } public func setExpires(date: NSDate) { document["expires"] = CloudBoostDateFormatter.getISOFormatter().stringFromDate(date) } // MARK: Setters public func setId(id: String){ document["_id"] = id } public func setContentType(contentType: String){ document["contentType"] = contentType } public func setFileUrl(url: String){ document["url"] = url } public func setFileName(name: String){ document["name"] = name } public func setACL(acl: ACL){ document["ACL"] = acl.getACL() } public func setDate(data: NSData) { self.data = data self.strEncodedData = data.base64EncodedStringWithOptions([]) } // Save a CloudFile object public func save(callback: (response: CloudBoostResponse) -> Void){ let params = NSMutableDictionary() params["key"] = CloudApp.getAppKey()! params["fileObj"] = self.document params["data"] = self.strEncodedData let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: { (response: CloudBoostResponse) in if(response.success) { self.document = (response.object as? NSMutableDictionary)! } callback(response: response) }) } // Save an array of CloudFile public static func saveAll(array: [CloudFile], callback: (CloudBoostResponse)->Void) { // Ready the response let resp = CloudBoostResponse() resp.success = true var count = 0 // Iterate through the array for object in array { let url = CloudApp.serverUrl + "/file/" + CloudApp.appID! let params = NSMutableDictionary() params["key"] = CloudApp.appKey! params["fileObj"] = object.document params["data"] = object.strEncodedData CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {(response: CloudBoostResponse) in count += 1 if(response.success){ if let newDocument = response.object { object.document = newDocument as! NSMutableDictionary } }else{ resp.success = false resp.message = "one or more objects were not saved" } if(count == array.count){ resp.object = count callback(resp) } }) } } // delete a CloudFile public func delete(callback: (response: CloudBoostResponse) -> Void) throws { guard let _ = document["url"] else{ throw CloudBoostError.InvalidArgument } let params = NSMutableDictionary() params["fileObj"] = document params["key"] = CloudApp.getAppKey()! let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! + "/" + self.getId()! CloudCommunications._request("DELETE", url: NSURL(string: url)!, params: params, callback: { (response: CloudBoostResponse) in if response.success && (response.status >= 200 || response.status < 300) { self.document = [:] } callback(response: response) }) } public static func getFileFromUrl(url: NSURL, callback: (response: CloudBoostResponse)->Void){ let cbResponse = CloudBoostResponse() cbResponse.success = false let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in guard let httpRes = response as? NSHTTPURLResponse else { cbResponse.message = "Proper response not received" callback(response: cbResponse) return } cbResponse.status = httpRes.statusCode if( httpRes.statusCode == 200){ guard let strEncodedData = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String else { cbResponse.message = "Error in encoding/decoding" callback(response: cbResponse) return } let nsData = NSData(base64EncodedString: strEncodedData, options: []) cbResponse.success = true cbResponse.object = nsData } else { cbResponse.message = "\(httpRes.statusCode) error" } callback(response: cbResponse) }).resume() } public func uploadSave(progressCallback : (response: CloudBoostProgressResponse)->Void){ let params = NSMutableDictionary() params["key"] = CloudApp.getAppKey()! params["fileObj"] = self.document params["data"] = self.strEncodedData let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! CloudCommunications()._requestFile("POST", url: NSURL(string: url)!, params: params, data: data, uploadCallback: { uploadResponse in progressCallback(response: uploadResponse) }) } public func fetch(callback: (CloudBoostResponse)->Void){ let res = CloudBoostResponse() let query = CloudQuery(tableName: "_File") if getId() == nil { res.message = "ID not set in the object" callback(res) }else{ try! query.equalTo("id", obj: getId()!) query.setLimit(1) query.find({ res in if res.success { if let obj = res.object as? [NSMutableDictionary] { self.document = obj[0] callback(res) }else{ res.success = false res.message = "Invalid response received" callback(res) } } }) } } }
mit
5607748f151073f5dddde5d036fa88ac
31.375
122
0.536262
4.998191
false
false
false
false
robertoseidenberg/MixerBox
MixerBox/MetalView+Setup.swift
1
1971
import QuartzCore #if !(SIMULATOR) import Metal #endif extension MetalView { func setup(fragmentFunctionName: String) { setupDevice() setupPipeline(fragmentFunctionName: fragmentFunctionName) setupBuffer() } private func setupDevice() { #if !(SIMULATOR) guard let device = MTLCreateSystemDefaultDevice() else { fatalError("Unexpected nil value") } self.device = device metalLayer.device = device metalLayer.pixelFormat = .bgra8Unorm commandQueue = device.makeCommandQueue() #endif } private func setupPipeline(fragmentFunctionName: String) { #if !(SIMULATOR) guard let path = Bundle(for: MixerBox.MetalView.self).path(forResource: "default", ofType: "metallib") else { fatalError("Resource missing: MixerBox: default.metallib") } guard let library = try? device.makeLibrary(filepath: path) else { fatalError("Unexpeted nil value: MixerBox: library") } let vertexFunc = library.makeFunction(name: "vertex_main") let fragmentFunc = library.makeFunction(name: fragmentFunctionName) let descriptor = MTLRenderPipelineDescriptor() descriptor.vertexFunction = vertexFunc descriptor.fragmentFunction = fragmentFunc descriptor.colorAttachments[0].pixelFormat = metalLayer.pixelFormat do { pipeline = try device.makeRenderPipelineState(descriptor: descriptor) } catch { fatalError(error.localizedDescription) } #endif } private func setupBuffer() { #if !(SIMULATOR) let vertices = [ // Bottom left Vertex(postition: [ -1, -1, 0, 1]), Vertex(postition: [1, -1, 0, 1]), Vertex(postition: [ -1, 1, 0, 1]), // Top right Vertex(postition: [1, 1, 0, 1]), ] vertexBuffer = device.makeBuffer(bytes: vertices, length: MemoryLayout<Vertex>.size * vertices.count, options: []) #endif } }
mit
19c3e1311287bcec5840bf4b5245a058
26.760563
115
0.651446
4.489749
false
false
false
false
sadawi/PrimarySource
Pod/iOS/DateFieldCell.swift
1
1749
// // DateFieldCell.swift // Pods // // Created by Sam Williams on 11/30/15. // // import UIKit open class DateFieldCell: TextFieldInputCell<Date> { open override var stringValue:String? { get { if let date = self.value { return self.dateFormatter.string(from: date) } else { return nil } } set { // Input is through the datePicker. // TODO: Might want to put date string parsing here, for completeness. } } open var dateFormatter:DateFormatter = DateFormatter() open var datePicker:UIDatePicker? override open func buildView() { super.buildView() self.dateFormatter.dateStyle = .medium self.datePicker = UIDatePicker() self.datePicker?.datePickerMode = .date self.datePicker?.addTarget(self, action: #selector(DateFieldCell.datePickerValueChanged), for: UIControlEvents.valueChanged) self.textField?.inputView = self.datePicker self.textField?.tintColor = UIColor.clear } func datePickerValueChanged() { self.value = self.datePicker?.date } override open func setDefaults() { super.setDefaults() self.toolbarShowsClearButton = true } override open func commit() { self.datePickerValueChanged() super.commit() } override open func clear() { self.value = nil super.clear() } override open func update() { super.update() if let date = self.value { self.datePicker?.date = date } else { self.datePicker?.date = Date() } } }
mit
608132cd596afa0d09ac8f891bd3e274
23.985714
132
0.571755
4.858333
false
false
false
false
kyouko-taiga/anzen
Sources/AST/ASTVisitor+Traversal.swift
1
7200
public extension ASTVisitor { // swiftlint:disable cyclomatic_complexity func visit(_ node: Node) throws { switch node { case let n as ModuleDecl: try visit(n) case let n as Block: try visit(n) case let n as PropDecl: try visit(n) case let n as FunDecl: try visit(n) case let n as ParamDecl: try visit(n) case let n as StructDecl: try visit(n) case let n as InterfaceDecl: try visit(n) case let n as QualTypeSign: try visit(n) case let n as TypeIdent: try visit(n) case let n as FunSign: try visit(n) case let n as ParamSign: try visit(n) case let n as Directive: try visit(n) case let n as WhileLoop: try visit(n) case let n as BindingStmt: try visit(n) case let n as ReturnStmt: try visit(n) case let n as NullRef: try visit(n) case let n as IfExpr: try visit(n) case let n as LambdaExpr: try visit(n) case let n as CastExpr: try visit(n) case let n as BinExpr: try visit(n) case let n as UnExpr: try visit(n) case let n as CallExpr: try visit(n) case let n as CallArg: try visit(n) case let n as SubscriptExpr: try visit(n) case let n as SelectExpr: try visit(n) case let n as Ident: try visit(n) case let n as ArrayLiteral: try visit(n) case let n as SetLiteral: try visit(n) case let n as MapLiteral: try visit(n) case let n as Literal<Bool>: try visit(n) case let n as Literal<Int>: try visit(n) case let n as Literal<Double>: try visit(n) case let n as Literal<String>: try visit(n) default: assertionFailure("unexpected node during generic visit") } } // swiftlint:enable cyclomatic_complexity func visit(_ nodes: [Node]) throws { for node in nodes { try visit(node) } } func visit(_ node: ModuleDecl) throws { try traverse(node) } func traverse(_ node: ModuleDecl) throws { try visit(node.statements) } func visit(_ node: Block) throws { try traverse(node) } func traverse(_ node: Block) throws { try visit(node.statements) } // MARK: Declarations func visit(_ node: PropDecl) throws { try traverse(node) } func traverse(_ node: PropDecl) throws { if let typeAnnotation = node.typeAnnotation { try visit(typeAnnotation) } if let (_, value) = node.initialBinding { try visit(value) } } func visit(_ node: FunDecl) throws { try traverse(node) } func traverse(_ node: FunDecl) throws { try visit(node.parameters) if let codomain = node.codomain { try visit(codomain) } if let body = node.body { try visit(body) } } func visit(_ node: ParamDecl) throws { try traverse(node) } func traverse(_ node: ParamDecl) throws { if let annotation = node.typeAnnotation { try visit(annotation) } } func visit(_ node: StructDecl) throws { try traverse(node) } func traverse(_ node: StructDecl) throws { try visit(node.body) } func visit(_ node: InterfaceDecl) throws { try traverse(node) } func traverse(_ node: InterfaceDecl) throws { try visit(node.body) } // MARK: Type signatures func visit(_ node: QualTypeSign) throws { try traverse(node) } func traverse(_ node: QualTypeSign) throws { if let signature = node.signature { try visit(signature) } } func visit(_ node: TypeIdent) throws { try traverse(node) } func traverse(_ node: TypeIdent) throws { try visit(Array(node.specializations.values)) } func visit(_ node: FunSign) throws { try traverse(node) } func traverse(_ node: FunSign) throws { try visit(node.parameters) try visit(node.codomain) } func visit(_ node: ParamSign) throws { try traverse(node) } func traverse(_ node: ParamSign) throws { try visit(node.typeAnnotation) } // MARK: Statements func visit(_ node: Directive) throws { } func visit(_ node: WhileLoop) throws { try traverse(node) } func traverse(_ node: WhileLoop) throws { try visit(node.condition) try visit(node.body) } func visit(_ node: BindingStmt) throws { try traverse(node) } func traverse(_ node: BindingStmt) throws { try visit(node.lvalue) try visit(node.rvalue) } func visit(_ node: ReturnStmt) throws { try traverse(node) } func traverse(_ node: ReturnStmt) throws { if let (_, value) = node.binding { try visit(value) } } // MARK: Expressions func visit(_ node: NullRef) throws { } func visit(_ node: IfExpr) throws { try traverse(node) } func traverse(_ node: IfExpr) throws { try visit(node.condition) try visit(node.thenBlock) if let elseBlock = node.elseBlock { try visit(elseBlock) } } func visit(_ node: LambdaExpr) throws { try traverse(node) } func traverse(_ node: LambdaExpr) throws { try visit(node.parameters) if let codomain = node.codomain { try visit(codomain) } try visit(node.body) } func visit(_ node: CastExpr) throws { try traverse(node) } func traverse(_ node: CastExpr) throws { try visit(node.operand) try visit(node.castType) } func visit(_ node: BinExpr) throws { try traverse(node) } func traverse(_ node: BinExpr) throws { try visit(node.left) try visit(node.right) } func visit(_ node: UnExpr) throws { try traverse(node) } func traverse(_ node: UnExpr) throws { try visit(node.operand) } func visit(_ node: CallExpr) throws { try traverse(node) } func traverse(_ node: CallExpr) throws { try visit(node.callee) try visit(node.arguments) } func visit(_ node: CallArg) throws { try traverse(node) } func traverse(_ node: CallArg) throws { try visit(node.value) } func visit(_ node: SubscriptExpr) throws { try traverse(node) } func traverse(_ node: SubscriptExpr) throws { try visit(node.callee) try visit(node.arguments) } func visit(_ node: SelectExpr) throws { try traverse(node) } func traverse(_ node: SelectExpr) throws { if let owner = node.owner { try visit(owner) } try visit(node.ownee) } func visit(_ node: Ident) throws { try traverse(node) } func traverse(_ node: Ident) throws { try visit(Array(node.specializations.values)) } func visit(_ node: ArrayLiteral) throws { try traverse(node) } func traverse(_ node: ArrayLiteral) throws { try visit(node.elements) } func visit(_ node: SetLiteral) throws { try traverse(node) } func traverse(_ node: SetLiteral) throws { try visit(node.elements) } func visit(_ node: MapLiteral) throws { try traverse(node) } func traverse(_ node: MapLiteral) throws { try visit(Array(node.elements.values)) } func visit(_ node: Literal<Bool>) throws { } func visit(_ node: Literal<Int>) throws { } func visit(_ node: Literal<Double>) throws { } func visit(_ node: Literal<String>) throws { } }
apache-2.0
1191708223809399c5705d42bdcb3654
20.95122
62
0.622778
3.673469
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/bitwise-and-of-numbers-range.swift
2
729
/** * https://leetcode.com/problems/bitwise-and-of-numbers-range/ * * */ // Date: Thu Apr 23 07:34:11 PDT 2020 /// The idea is very simple: /// /// 1. last bit of (odd number & even number) is 0. /// 2. when m != n, There is at least an odd number and an even number, so the last bit position result is 0. /// 3. Move m and n rigth a position. /// /// Keep doing step 1,2,3 until m equal to n, use a factor to record the iteration time. class Solution { func rangeBitwiseAnd(_ m: Int, _ n: Int) -> Int { if m == 0 { return 0 } var m = m var n = n var bit = 0 while m != n { m /= 2 n /= 2 bit += 1 } return m << bit } }
mit
397842b04dc09009bcd9ce19e52a5b48
24.137931
109
0.526749
3.328767
false
false
false
false
scheib/chromium
ios/chrome/browser/widget_kit/widget_metrics_logger.swift
2
3880
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import WidgetKit /// Logs metrics associated with iOS 14 home screen widgets. public final class WidgetsMetricLogger: NSObject { /// The queue onto which time-consuming work is dispatched. private static let queue = DispatchQueue(label: "com.google.chrome.ios.WidgetMetricLogger") // MARK: Public /// A callback to be called when a widget install is detected. This callback is passed the /// information about which widget was installed. /// /// This property must be set before the `logInstalledWidgets` method is called. @objc public static var widgetInstalledCallback: ((String) -> Void)? = nil /// A callback to be called when a widget uninstall is detected. This callback is passed the /// kind about which widget was uninstalled. /// /// This property must be set before the `logInstalledWidgets` method is called. @objc public static var widgetUninstalledCallback: ((String) -> Void)? = nil /// A callback to be called when a widget in use is detected. This callback is passed the /// kind about which widget is in use. /// /// This property must be set before the `logInstalledWidgets` method is called. @objc public static var widgetCurrentCallback: ((String) -> Void)? = nil /// Logs metrics if the user has installed or uninstalled a widget since the last check. /// /// This method should be called once per application foreground, for example in the /// `applicationWillEnterForeground` method. /// /// This method is safe to call from any thread. @objc(logInstalledWidgets) public static func logInstalledWidgets() { if #available(iOS 14, *) { // To avoid blocking startup, perform work on a background queue. queue.async { logInstalledWidgets(fetcher: WidgetCenter.shared, store: UserDefaultsWidgetStore()) } } } // MARK: Private /// Logs metrics if the user has installed or uninstalled a widget since the last app launch. static func logInstalledWidgets(fetcher: WidgetCenter, store: UserDefaultsWidgetStore) { fetcher.getCurrentConfigurations { result in // If fetching either current or previous info fails, avoid logging anything. The next time // this is called, metrics will be logged. guard let currentWidgets = try? result.get().map({ $0.kind }) else { return } // Log current widgets. for widget in currentWidgets { widgetCurrentCallback?(widget) } guard let storedWidgets = try? store.retrieveStoredWidgetInfo().get() else { return } // Attempt to store the new configurations and verify that it is successful to avoid double // logging. If metrics were logged when storage failed, they would be double-logged the next // time this method is called. do { try store.storeWidgetInfo(currentWidgets) } catch { return } // Current widgets minus stored widgets are installations. var installedWidgets = currentWidgets for storedWidget in storedWidgets { if let index = installedWidgets.firstIndex(of: storedWidget) { installedWidgets.remove(at: index) } } for installedWidget in installedWidgets { widgetInstalledCallback?(installedWidget) } // Stored widgets minus current widgets are uninstallations. var uninstalledWidgets = storedWidgets for currentWidget in currentWidgets { if let index = uninstalledWidgets.firstIndex(of: currentWidget) { uninstalledWidgets.remove(at: index) } } for uninstalledWidget in uninstalledWidgets { widgetUninstalledCallback?(uninstalledWidget) } } } }
bsd-3-clause
4635ca7b207de63e369a1f299a7a78d4
37.039216
98
0.698454
4.784217
false
false
false
false
alvaromb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Feed/Chatter/ChatViewController.swift
1
6143
// // ChatViewController.swift // Twitter_test // // Created by Marin Todorov on 6/18/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite import XLPagerTabStrip import Haneke class ChatViewController: TweetListViewController { let chatCtr = ChatController() let userCtr = UserController() override func viewDidLoad() { super.viewDidLoad() observeNotification(kDidPostTweetNotification, selector: "fetchTweets") } deinit { observeNotification(kDidPostTweetNotification, selector: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) observeNotification(kTabItemSelectedNotification, selector: "didTapTabItem:") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) observeNotification(kTabItemSelectedNotification, selector: nil) } func didTapTabItem(notification: NSNotification) { if let index = notification.userInfo?["object"] as? Int where index == EventBlankTabIndex.Feed.rawValue { if self.tweets.count > 0 { mainQueue({ self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) }) } } } //MARK: - table view methods override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell let row = indexPath.row let tweet = self.tweets[indexPath.row] let usersTable = database[UserConfig.tableName] let user = usersTable.filter(User.idColumn == tweet[Chat.idUser]).first cell.message.text = tweet[Chat.message] cell.timeLabel.text = NSDate(timeIntervalSince1970: Double(tweet[Chat.created])).relativeTimeToString() cell.message.selectedRange = NSRange(location: 0, length: 0) if let attachmentUrlString = tweet[Chat.imageUrl], let attachmentUrl = NSURL(string: attachmentUrlString) { cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 0.0, completion: {result in cell.attachmentImage.image = result }) }) cell.didTapAttachment = { PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view) } cell.attachmentHeight.constant = 148.0 } if let user = user { cell.nameLabel.text = user[User.name] if let imageUrlString = user[User.photoUrl], let imageUrl = NSURL(string: imageUrlString) { cell.userImage.hnk_setImageFromURL(imageUrl, placeholder: UIImage(named: "feed-item"), format: nil, failure: nil, success: {image in image.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5.0, completion: {result in cell.userImage.image = result }) }) } } cell.didTapURL = {tappedUrl in if tappedUrl.absoluteString!.hasPrefix("http") { let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = tappedUrl self.navigationController!.pushViewController(webVC, animated: true) } else { UIApplication.sharedApplication().openURL(tappedUrl) } } return cell } //MARK: - fetching data override func loadTweets() { //fetch latest tweets from db let latestText = tweets.first?[Chat.message] tweets = self.chatCtr.allMessages() lastRefresh = NSDate().timeIntervalSince1970 if latestText == tweets.first?[Chat.message] { //latest tweet is the same, bail return; } mainQueue { self.tableView.reloadData() if self.tweets.count == 0 { self.tableView.addSubview(MessageView(text: "No tweets found at this time, try again later")) } else { MessageView.removeViewFrom(self.tableView) } } } override func fetchTweets() { twitter.authorize({success in MessageView.removeViewFrom(self.tableView) if success, var hashTag = Event.event[Event.twitterTag] { self.notification(kTwitterAuthorizationChangedNotification, object: true) if !hashTag.hasPrefix("#") { hashTag = "#\(hashTag)" } self.twitter.getSearchForTerm(hashTag, completion: {tweetList, userList in self.userCtr.persistUsers(userList) self.chatCtr.persistMessages(tweetList) let lastSavedId = self.tweets.first?[Chat.idColumn] let lastFetchedId = tweetList.first?.id if lastSavedId != lastFetchedId { self.loadTweets() } }) } else { self.notification(kTwitterAuthorizationChangedNotification, object: false) delay(seconds: 0.5, { self.tableView.addSubview(MessageView(text: "You don't have Twitter accounts set up. Open Settings app, select Twitter and connect an account. \n\nThen pull this view down to refresh the feed.")) }) } //hide the spinner mainQueue { self.refreshView.endRefreshing() } }) } }
mit
36a1ecbeaab2fbbb918e626a4b3309ed
36.693252
215
0.590265
5.323224
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/BoardView.swift
1
4395
// // GoBoard.swift // Sublime // // Created by Eular on 4/14/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit class GoBoardView: UIView { let padding: CGFloat = 10 var dimension: Int var gridWidth: CGFloat var stoneWidth: CGFloat = 9 var isEnd: Bool = false let board: GoBoardModel init(board: GoBoardModel, gridWidth: CGFloat) { self.gridWidth = gridWidth self.board = board self.dimension = board.dimension let width = gridWidth * (dimension - 1) + 2 * padding super.init(frame: CGRectMake(0, 0, width, width)) self.backgroundColor = UIColor.clearColor() self.layer.borderWidth = 1 self.layer.borderColor = UIColor.grayColor().CGColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let d = dimension for i in 0..<d { drawLine((i, 0), (i, d - 1)) // col drawLine((0, i), (d - 1, i)) // row } for i in 0..<d { for j in 0..<d { let s = board[i,j] if s.type != .Void { drawStone(i, j, CGFloat(s.value - 1)) } } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) if !isEnd { if let touch = touches.first { let location = touch.locationInView(self) let x = Int(round((location.x - padding) / gridWidth)) let y = Int(round((location.y - padding) / gridWidth)) onStoneDropDown(x, y) } } } func onStoneDropDown(x: Int, _ y: Int) { print("Stone: [\(x), \(y)]") } private func drawStone(x: Int, _ y: Int, _ c: CGFloat) { let g = gridWidth let r = stoneWidth let pos = (g * x + padding, g * y + padding) let context = UIGraphicsGetCurrentContext() CGContextAddArc(context, pos.0, pos.1, r - c / 2, 0, 3.1415926*2, 0) CGContextSetRGBFillColor(context, c, c, c, 1) CGContextFillPath(context) } private func drawLine(p1: (Int, Int), _ p2: (Int, Int)) { let g = gridWidth let context = UIGraphicsGetCurrentContext() CGContextMoveToPoint(context, g * p1.0 + padding, g * p1.1 + padding) CGContextAddLineToPoint(context, g * p2.0 + padding, g * p2.1 + padding) CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1) CGContextStrokePath(context) } func reset() { isEnd = false board.reset() setNeedsDisplay() } } class GomokuBoardView: GoBoardView { let depth = 1 // 目前只能用 1 层,2 的计算量太大,耗时太长,有待后续优化 let AI: GomokuAI var onWin: (() -> Void)? var onLose: (() -> Void)? init() { let gomokuBoard = GomokuBoardModel() self.AI = GomokuAI(board: gomokuBoard) super.init(board: gomokuBoard, gridWidth: 20) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func onStoneDropDown(x: Int, _ y: Int) { if board[x,y].type == .Void { // 黑棋落子 board[x,y].type = .Black setNeedsDisplay() // 检查输赢 let r = board.check() if r == .Win { isEnd = true onWin?() } else { let queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0) dispatch_async(queue) { let AIMove = self.AI.search(2, depth: self.depth) self.board[AIMove[1], AIMove[2]].type = .White dispatch_async(dispatch_get_main_queue()) { self.setNeedsDisplay() // 再次检查输赢 if self.board.check() == .Lose { self.isEnd = true self.onLose?() } } } } } } }
gpl-3.0
58c2f3ed15c7460afccdf63481ff00f6
29.401408
82
0.500463
4.098765
false
false
false
false
bigxodus/candlelight
candlelight/screen/main/controller/crawler/TodayHumorArticleCrawler.swift
1
3818
import Foundation import BrightFutures import enum Result.Result import enum Result.NoError import Alamofire import Kanna class TodayHumorArticleCrawler: ArticleCrawler { let url: String init(_ url: String) { self.url = url } func getContent() -> Future<Article?, NoError> { return AlamofireRequest(url).flatMap(getContentWithHtml) } func getContentWithHtml(html: String) -> Future<Article?, NoError> { let commentUrl = parseCommentUrl(html: html) let parseContent = {self.parseHTML(html: html, comments: $0)} return AlamofireRequestAsJson(commentUrl).map(parseComment).map(parseContent) } func parseCommentUrl(html: String) -> String { let parentId = Util.matches(for: "(?<=id = \")[0-9]+(?=.;)", in: html).first! let parentTable = Util.matches(for: "(?<=parent_table = \")[a-zA-Z0-9_]+(?=\")", in: html).first! return "http://www.todayhumor.co.kr/board/ajax_memo_list.php?parent_table=\(parentTable)&parent_id=\(parentId)" } func parseComment(_ response: DataResponse<Any>) -> [Comment] { switch response.result { case .success(let JSON): let response = JSON as! NSDictionary let memos = response["memos"] as! NSArray var comments = [Comment]() for memo in memos { let memoDic = memo as! NSDictionary let content = memoDic["memo"] as! String let author = memoDic["name"] as! String let regDate = memoDic["date"] as! String let depth = memoDic["parent_memo_no"] as? String let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let dd = (formatter.date(from: regDate)) if depth != nil { comments.append(Comment(author: author, content: content, regDate: dd!, depth: 1)) } else { comments.append(Comment(author: author, content: content, regDate: dd!, depth: 0)) } } return comments case .failure(_): return [Comment]() } } func parseHTML(html: String, comments: [Comment]) -> Article? { if let doc = HTML(html: html, encoding: .utf8) { let titleOption = doc.xpath("//div[contains(@class, 'viewSubjectDiv')]").first?.text let authorOption = doc.xpath("//div[contains(@class, 'writerInfoContents')]//div[2]//a").first?.text let readCountOption = doc.xpath("//div[contains(@class, 'writerInfoContents')]//div[4]").first?.text let contentOption = doc.xpath("//div[contains(@class, 'viewContent')]").first?.innerHTML let regDateOption = doc.xpath("//div[contains(@class, 'writerInfoContents')]//div[7]").first?.text guard let title = titleOption, let readCount = readCountOption, let content = contentOption, let regDate = regDateOption else { print("data is invalid") return nil } let matchedDate = Util.matches(for: "\\d+/\\d+/\\d+\\s\\d+:\\d+:\\d+", in: regDate).first! let dd = Util.dateFromString(dateStr: matchedDate, format: "yyyy/MM/dd HH:mm:ss") let author = authorOption ?? "" // TODO: should fix it when name is image. let arr = readCount.components(separatedBy: ":")[1].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return Article(title: title, author: author, readCount: Int(arr)!,content: content, regDate: dd, comments: comments) } return nil } }
apache-2.0
7e0adeab24c2460692efc7968ccbf857
39.617021
128
0.567837
4.323896
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/iPhone/Classes/Animations/LoginCreateUserTransition.swift
1
6891
// // LoginCreateUserTransition.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 24/07/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class LoginCreateUserInteractiveTransition : InteractiveTransition{ var initialScale : CGFloat = 0 @objc func gestureTransitionMethod(_ gesture : UIPinchGestureRecognizer){ var delta = fabs((gesture.scale - initialScale) / 8) if gesture.state == .began { self.interactiveTransition = UIPercentDrivenInteractiveTransition() self.navigationController.popViewController(animated: true) self.initialScale = gesture.scale }else if gesture.state == .changed{ delta = delta > 1.0 ? 1 : delta self.interactiveTransition?.update(delta) }else{ self.interactiveTransition?.finish() self.interactiveTransition = nil } } } class LoginCreateUserTransition: ControllerTransition { override func createInteractiveTransition(navigationController: UINavigationController) -> InteractiveTransition? { let interactiveTransition = LoginCreateUserInteractiveTransition() interactiveTransition.navigationController = navigationController interactiveTransition.gestureTransition = UIPinchGestureRecognizer(target: interactiveTransition, action: #selector(interactiveTransition.gestureTransitionMethod(_:))) interactiveTransition.navigationController.view.addGestureRecognizer(interactiveTransition.gestureTransition!) return interactiveTransition } override func animatePush(toContext context : UIViewControllerContextTransitioning) { let fromVC = self.controllerOrigin as! LoginViewController let toVC = self.controllerDestination as! CreateNewAccountViewController let containerView = context.containerView let fromView = context.view(forKey: .from)! let toView = context.view(forKey: .to)! let duration = self.transitionDuration(using: context) toView.frame = UIScreen.main.bounds containerView.addSubview(toView) fromView.frame = UIScreen.main.bounds containerView.addSubview(fromView) toVC.constraintCenterForm.constant = (UIScreen.main.bounds.size.height + toVC.viewFormUser.bounds.size.height) / 2 toVC.constraintBottomViewLogo.constant = UIScreen.main.bounds.size.height toVC.constraintTopViewLogo.constant = -(UIScreen.main.bounds.size.height + toVC.viewLogo.frame.size.height) containerView.layoutIfNeeded() UIView.animate(withDuration: duration, animations: { fromVC.constraintCenterForm.constant = (UIScreen.main.bounds.size.height + fromVC.viewFormUser.bounds.size.height) / 2 fromVC.constraintBottomViewLogo.constant = UIScreen.main.bounds.size.height fromVC.constraintTopViewLogo.constant = -(UIScreen.main.bounds.size.height + fromVC.viewLogo.frame.size.height) containerView.layoutIfNeeded() }) { (_) in fromView.backgroundColor = .clear UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: { toVC.constraintCenterForm.constant = toVC.initialValueConstraintCenterForm toVC.constraintBottomViewLogo.constant = 0 toVC.constraintTopViewLogo.constant = 0 containerView.layoutIfNeeded() }) { (_) in fromVC.constraintCenterForm.constant = fromVC.initialValueConstraintCenterForm fromVC.constraintBottomViewLogo.constant = 0 fromVC.constraintTopViewLogo.constant = 0 fromView.backgroundColor = .white context.completeTransition(true) } } } override func animatePop(toContext context : UIViewControllerContextTransitioning) { let fromVC = self.controllerOrigin as! CreateNewAccountViewController let toVC = self.controllerDestination as! LoginViewController let containerView = context.containerView let fromView = context.view(forKey: .from)! let toView = context.view(forKey: .to)! let duration = self.transitionDuration(using: context) toView.frame = UIScreen.main.bounds containerView.addSubview(toView) fromView.frame = UIScreen.main.bounds containerView.addSubview(fromView) toVC.constraintCenterForm.constant = (UIScreen.main.bounds.size.height + toVC.viewFormUser.bounds.size.height) / 2 toVC.constraintBottomViewLogo.constant = UIScreen.main.bounds.size.height toVC.constraintTopViewLogo.constant = -(UIScreen.main.bounds.size.height + toVC.viewLogo.frame.size.height) containerView.layoutIfNeeded() UIView.animate(withDuration: duration, animations: { fromVC.constraintCenterForm.constant = (UIScreen.main.bounds.size.height + fromVC.viewFormUser.bounds.size.height) / 2 fromVC.constraintBottomViewLogo.constant = UIScreen.main.bounds.size.height fromVC.constraintTopViewLogo.constant = -(UIScreen.main.bounds.size.height + fromVC.viewLogo.frame.size.height) containerView.layoutIfNeeded() }) { (_) in fromView.backgroundColor = .clear UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: { toVC.constraintCenterForm.constant = toVC.initialValueConstraintCenterForm toVC.constraintBottomViewLogo.constant = 0 toVC.constraintTopViewLogo.constant = 0 containerView.layoutIfNeeded() }) { (_) in fromVC.constraintCenterForm.constant = fromVC.initialValueConstraintCenterForm fromVC.constraintBottomViewLogo.constant = 0 fromVC.constraintTopViewLogo.constant = 0 fromView.backgroundColor = .white context.completeTransition(true) } } } override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } }
apache-2.0
9b5b1cab5a9cbb6f25ddc4117631b9f6
40.506024
175
0.640058
5.722591
false
false
false
false
pedrohperalta/StarWars-iOS-BDD
StarWarsTests/Modules/CharacteresViewControllerTests.swift
1
4979
// // CharactersViewControllerTests.swift // StarWars // // Created by Pedro Henrique Prates Peralta on 5/14/16. // Copyright © 2016 Pedro Henrique Peralta. All rights reserved. // @testable import StarWars import Quick import Nimble class CharactersViewControllerTests: QuickSpec { var sut: CharactersViewController! var charactersViewControllerPresenterMock: CharactersViewControllerPresenterMock! var charactersList: [[String: String]]! override func spec() { beforeSuite { self.sut = CharactersViewController() self.charactersViewControllerPresenterMock = CharactersViewControllerPresenterMock() self.sut.presenter = self.charactersViewControllerPresenterMock } describe("The View being loaded") { beforeEach { self.sut.viewDidLoad() } it("Should notify the Presenter about its life cycle") { expect(self.charactersViewControllerPresenterMock.notifiedWhenViewLoaded).to(beTrue()) } it("Should have an UITableView not null") { expect(self.sut.charactersTableView).toNot(beNil()) } it("Should have an UITableView as a child view") { expect(self.sut.view.subviews.contains(self.sut.charactersTableView)).to(beTrue()) } it("Should conform to UITableViewDataSource protocol") { expect(self.sut.conforms(to: UITableViewDataSource.self)).to(beTrue()) } it("Should have an UITableView with DataSource") { expect(self.sut.charactersTableView.dataSource).toNot(beNil()) } it("Should have an UILabel for empty dataset message as a child view") { expect(self.sut.view.subviews.contains(self.sut.emptyDataSetLabel)).to(beTrue()) } } describe("The View being told to show the characters list") { beforeEach { self.charactersList = [[:]] self.sut.showCharactersList(self.charactersList) } it("Should have the table view set as visible") { expect(self.sut.charactersTableView.isHidden).to(beFalse()) } it("Should have the empty dataset message label set as invisible") { expect(self.sut.emptyDataSetLabel.isHidden).to(beTrue()) } it("Should set the characters' list for the data source") { for (index, character) in self.sut.charactersList.enumerated() { expect(character).to(equal(self.charactersList[index])) } } it("Should have a row for each character in the table view") { let expectedRows = self.charactersList.count expect(self.sut.charactersTableView.numberOfRows(inSection: 0)).to(equal(expectedRows)) } it("Should return a valid cell when it's dequeued from the table view") { let cell = self.sut.charactersTableView.cellForRow(at: IndexPath(row: 0, section: 0)) expect(cell).notTo(beNil()) } } describe("The View being told to show the empty dataset screen") { beforeEach { self.sut.showEmptyDatasetScreen() } it("Should shown the proper message in the empty dataset label") { expect(self.sut.emptyDataSetLabel.text).to(equal("No characters to show =(")) } it("Should have the empty dataset message label set as visible") { expect(self.sut.emptyDataSetLabel.isHidden).to(beFalse()) } it("Should have the table view set as invisible") { expect(self.sut.charactersTableView.isHidden).to(beTrue()) } } describe("The characters list being set") { beforeEach { self.sut.charactersTableView = CharactersTableViewMock() self.sut.charactersList = [] } it("Should reload the characters' table view data") { expect((self.sut.charactersTableView as! CharactersTableViewMock).reloadDataCalled).to(beTrue()) } } afterSuite { self.sut = nil self.charactersViewControllerPresenterMock = nil } } } class CharactersViewControllerPresenterMock: CharactersPresentation { var notifiedWhenViewLoaded = false func viewDidLoad() { notifiedWhenViewLoaded = true } } class CharactersTableViewMock: UITableView { var reloadDataCalled = false override func reloadData() { self.reloadDataCalled = true super.reloadData() } }
mit
6df91bc5b0b522916b11c1f47b8a534e
31.75
112
0.58176
5.284501
false
false
false
false
OpenLocate/openlocate-ios
Source/LocationManager.swift
1
8497
// // LocationManager.swift // // Copyright (c) 2017 OpenLocate // // 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 CoreLocation typealias LocationsHandler = ([(location: CLLocation, context: OpenLocateLocation.Context)]) -> Void // Location Manager protocol LocationManagerType { func subscribe(_ locationHandler: @escaping LocationsHandler) func cancel() var updatingLocation: Bool { get } var lastLocation: CLLocation? { get } func fetchLocation(onCompletion: @escaping ((Bool) -> Void)) } final class LocationManager: NSObject, LocationManagerType, CLLocationManagerDelegate { static let visitRegionIdentifier = "VisitRegion" static let minimumVisitRegionRadius = 25.0 private let manager: CLLocationManager private let requestAuthorizationStatus: CLAuthorizationStatus private var requests: [LocationsHandler] = [] private var fetchLocationCompletionHandler: ((Bool) -> Void)? required init(manager: CLLocationManager = CLLocationManager(), requestAuthorizationStatus: CLAuthorizationStatus) { self.manager = manager self.requestAuthorizationStatus = requestAuthorizationStatus super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters } static func authorizationStatus() -> CLAuthorizationStatus { return CLLocationManager.authorizationStatus() } static func locationServicesEnabled() -> Bool { return CLLocationManager.locationServicesEnabled() } func fetchLocation(onCompletion: @escaping ((Bool) -> Void)) { if #available(iOS 9.0, *) { manager.requestLocation() } else { manager.startUpdatingLocation() } self.fetchLocationCompletionHandler = onCompletion } // MARK: CLLocationManager func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) { var date = Date() var context = OpenLocateLocation.Context.unknown if visit.departureDate != Date.distantFuture { date = visit.departureDate context = .visitExit startMonitoringVisitRegion(with: visit.coordinate, maxRadius: visit.horizontalAccuracy) } else if visit.arrivalDate != Date.distantPast { date = visit.arrivalDate context = .visitEntry stopMonitoringVisitRegion() } let location = CLLocation(coordinate: visit.coordinate, altitude: 0, horizontalAccuracy: visit.horizontalAccuracy, verticalAccuracy: -1.0, timestamp: date) var locations = [(location: location, context: context)] if let currentLocation = manager.location { locations.append((location: currentLocation, context: .passive)) } for request in requests { request(locations) } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for request in requests { request(locations.map({return (location: $0, context: OpenLocateLocation.Context.backgroundFetch)})) } if let fetchLocationCompletionHandler = self.fetchLocationCompletionHandler { fetchLocationCompletionHandler(true) self.fetchLocationCompletionHandler = nil if #available(iOS 9.0, *) { } else { manager.stopUpdatingLocation() } } } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { if let location = manager.location { for request in requests { request([(location: location, context: OpenLocateLocation.Context.geofenceEntry)]) } } } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { if let location = manager.location { for request in requests { request([(location: location, context: OpenLocateLocation.Context.geofenceExit)]) } if manager.monitoredRegions.contains(region) { startMonitoringVisitRegion(with: location.coordinate, maxRadius: location.horizontalAccuracy) } } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { debugPrint(error) if let fetchLocationCompletionHandler = self.fetchLocationCompletionHandler { fetchLocationCompletionHandler(false) self.fetchLocationCompletionHandler = nil } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { updateRunningLocationServicesForAuthorizationStatus(status) } // MARK: LocationManagerType func subscribe(_ locationHandler: @escaping LocationsHandler) { if requests.isEmpty { requests.append(locationHandler) } requestAuthorizationIfNeeded() updateRunningLocationServicesForAuthorizationStatus(LocationManager.authorizationStatus()) } func cancel() { requests.removeAll() manager.stopMonitoringVisits() manager.stopMonitoringSignificantLocationChanges() } var updatingLocation: Bool { return !requests.isEmpty } // MARK: Private private func startMonitoringVisitRegion(with coordinate: CLLocationCoordinate2D, maxRadius: CLLocationDistance) { if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) { let region = CLCircularRegion(center: coordinate, radius: max(LocationManager.minimumVisitRegionRadius, maxRadius), identifier: LocationManager.visitRegionIdentifier) manager.startMonitoring(for: region) } } private func stopMonitoringVisitRegion() { let regions = manager.monitoredRegions.filter({ $0.identifier == LocationManager.visitRegionIdentifier }) regions.forEach { manager.stopMonitoring(for: $0) } } private func updateRunningLocationServicesForAuthorizationStatus(_ status: CLAuthorizationStatus) { if status == .authorizedAlways && requestAuthorizationStatus == .authorizedAlways && updatingLocation { manager.startMonitoringVisits() manager.startMonitoringSignificantLocationChanges() } else { manager.stopMonitoringVisits() manager.stopMonitoringSignificantLocationChanges() } } private func requestAuthorizationIfNeeded() { let status = CLLocationManager.authorizationStatus() switch status { case .notDetermined: if requestAuthorizationStatus == .authorizedWhenInUse { manager.requestWhenInUseAuthorization() } else if requestAuthorizationStatus == .authorizedAlways { manager.requestAlwaysAuthorization() } case .authorizedWhenInUse: if requestAuthorizationStatus == .authorizedAlways { manager.requestAlwaysAuthorization() } default: break } } var lastLocation: CLLocation? { return manager.location } }
mit
461d83711f918753c47e5a427df19677
36.431718
117
0.667647
5.807929
false
false
false
false
sheepy1/SelectionOfZhihu
SelectionOfZhihu/UserMenu.swift
1
1901
// // UserMenu.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/24. // Copyright © 2016年 Sheepy. All rights reserved. // import UIKit enum UserMenuItem: Int { // rawValue 对应相应的 cellHeight case Dynamic = 100 case Answer = 80 case More = 0 } class UserMenu: UITableViewCell { @IBOutlet weak var dynamicButton: UIButton! @IBOutlet weak var answerButton: UIButton! @IBOutlet weak var moreButton: UIButton! @IBOutlet weak var indicator: UIView! @IBOutlet weak var indicatorCenterX: NSLayoutConstraint! lazy var lastSelectedItem: UIButton = { return self.dynamicButton }() lazy var selectedColor: UIColor! = { return self.dynamicButton.titleColorForState(.Normal) }() let deselectedColor = UIColor.lightGrayColor() weak var delegate: UserMenuDelegate? func addMenuItemTarget() { [dynamicButton, answerButton, moreButton].forEach { $0.addTarget(self, action: "selectMenuItem:", forControlEvents: .TouchUpInside) } } func selectMenuItem(item: UIButton) { //将选中的 item 设为选中色,并将上一次选中的 item 恢复为未选中色 item.setTitleColor(selectedColor, forState: .Normal) lastSelectedItem.setTitleColor(deselectedColor, forState: .Normal) lastSelectedItem = item //改变指示条的约束,使其水平中心点与选中 item 的水平中心点相同 let newCenterX = NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: item, attribute: .CenterX, multiplier: 1, constant: 0) indicatorCenterX.active = false indicatorCenterX = newCenterX indicatorCenterX.active = true //通知代理 delegate?.selectMenuItem(UserMenuItem(rawValue: item.tag)!) } }
mit
c6dc90dcdb1f858b71afe57990b5a98d
27.126984
163
0.661964
4.463476
false
false
false
false
giangbvnbgit128/AnViet
AnViet/Class/Models/NewsUpload.swift
1
1410
// // NewsUpload.swift // AnViet // // Created by Bui Giang on 6/27/17. // Copyright © 2017 Bui Giang. All rights reserved. // import UIKit import ObjectMapper class NewsUpload: Mappable { var error:String = "FALSE" var host:String = "" var message:String = "" var data:DataForNewsPost = DataForNewsPost() init() {} required init(map: Map) { } func mapping(map: Map) { error <- map["error"] host <- map["host"] message <- map["mess"] data <- map["data"] } } class DataForNewsPost: Mappable { var id:String = "" var title:String = "" var avatar:String = "" var user_id:String = "" var content:String = "" var image:String = "" var user_like:String = "" var user_view:String = "" var active:String = "" var status:String = "" var created_date:String = "" init() { } required init(map: Map) { } func mapping(map: Map) { id <- map["id"] title <- map["title"] avatar <- map["avatar"] user_id <- map["user_id"] content <- map["content"] image <- map["image"] user_like <- map["user_like"] user_view <- map["user_view"] active <- map["active"] status <- map["status"] created_date <- map["created_date"] } }
apache-2.0
da0f6d7f023f7dfde427982c0f96b0ab
19.128571
52
0.508872
3.797844
false
false
false
false
onevcat/Kingfisher
Sources/Extensions/UIButton+Kingfisher.swift
2
17503
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2019 Wei Wang <[email protected]> // // 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. #if !os(watchOS) #if canImport(UIKit) import UIKit extension KingfisherWrapper where Base: UIButton { // MARK: Setting Image /// Sets an image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setImage( with: source, for: state, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Sets an image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource?.convertToSource(), for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } @discardableResult public func setImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, parsedOptions: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setImage(placeholder, for: state) setTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = parsedOptions if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } var mutatingSelf = self let issuedIdentifier = Source.Identifier.next() setTaskIdentifier(issuedIdentifier, for: state) if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, progressiveImageSetter: { self.base.setImage($0, for: state) }, referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.taskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.setTaskIdentifier(nil, for: state) switch result { case .success(let value): self.base.setImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setImage(image, for: state) } completionHandler?(result) } } } ) mutatingSelf.imageTask = task return task } // MARK: Cancelling Downloading Task /// Cancels the image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelImageDownloadTask() { imageTask?.cancel() } // MARK: Setting Background Image /// Sets a background image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setBackgroundImage( with: source, for: state, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Sets a background image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setBackgroundImage( with: resource?.convertToSource(), for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } func setBackgroundImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, parsedOptions: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setBackgroundImage(placeholder, for: state) setBackgroundTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = parsedOptions if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } var mutatingSelf = self let issuedIdentifier = Source.Identifier.next() setBackgroundTaskIdentifier(issuedIdentifier, for: state) if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 }, progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) }, referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.backgroundImageTask = nil mutatingSelf.setBackgroundTaskIdentifier(nil, for: state) switch result { case .success(let value): self.base.setBackgroundImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setBackgroundImage(image, for: state) } completionHandler?(result) } } } ) mutatingSelf.backgroundImageTask = task return task } // MARK: Cancelling Background Downloading Task /// Cancels the background image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: UIButton { private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]> public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return taskIdentifierInfo.value[state.rawValue] } private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { taskIdentifierInfo.value[state.rawValue] = identifier } private var taskIdentifierInfo: TaskIdentifier { return getAssociatedObject(base, &taskIdentifierKey) ?? { setRetainedAssociatedObject(base, &taskIdentifierKey, $0) return $0 } (TaskIdentifier([:])) } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } private var backgroundTaskIdentifierKey: Void? private var backgroundImageTaskKey: Void? // MARK: Background Properties extension KingfisherWrapper where Base: UIButton { public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return backgroundTaskIdentifierInfo.value[state.rawValue] } private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { backgroundTaskIdentifierInfo.value[state.rawValue] = identifier } private var backgroundTaskIdentifierInfo: TaskIdentifier { return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? { setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0) return $0 } (TaskIdentifier([:])) } private var backgroundImageTask: DownloadTask? { get { return getAssociatedObject(base, &backgroundImageTaskKey) } mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } } } #endif #endif
mit
2be13c79c2cc558c865c2d272f085df6
42.7575
119
0.634977
5.507552
false
false
false
false
GrandCentralBoard/GrandCentralBoard
GrandCentralBoard/Widgets/GitHub/GitHubSource.swift
2
1756
// // GitHubSource.swift // GrandCentralBoard // // Created by Michał Laskowski on 22/05/16. // import RxSwift import GCBCore struct GitHubSourceNoDataError: ErrorType, HavingMessage { let message = "GitHub returned no repositories".localized } private extension CollectionType where Generator.Element == Repository { func filterAndSortByPRCountAndName() -> [Repository] { return filter { $0.pullRequestsCount > 0 }.sort({ (left, right) -> Bool in if left.pullRequestsCount == right.pullRequestsCount { return left.name < right.name } return left.pullRequestsCount > right.pullRequestsCount }) } } final class GitHubSource: Asynchronous { typealias ResultType = Result<[Repository]> let sourceType: SourceType = .Momentary private let disposeBag = DisposeBag() private let dataProvider: GitHubDataProviding let interval: NSTimeInterval init(dataProvider: GitHubDataProviding, refreshInterval: NSTimeInterval) { self.dataProvider = dataProvider interval = refreshInterval } func read(closure: (ResultType) -> Void) { dataProvider.repositoriesWithPRsCount().single().map { (repositories) -> [Repository] in guard repositories.count > 0 else { throw GitHubSourceNoDataError() } return repositories.filterAndSortByPRCountAndName() }.observeOn(MainScheduler.instance).subscribe { (event) in switch event { case .Error(let error): closure(.Failure(error)) case .Next(let repositories): closure(.Success(repositories.filterAndSortByPRCountAndName())) case .Completed: break } }.addDisposableTo(disposeBag) } }
gpl-3.0
f88eabddf0e9b72d518aa099185c57d6
32.113208
105
0.676353
4.848066
false
false
false
false
phatblat/realm-cocoa
examples/ios/swift/GettingStarted.playground/Contents.swift
2
2019
//: To get this Playground running do the following: //: //: 1) In the scheme selector choose RealmSwift > iPhone 6s //: 2) Press Cmd + B //: 3) If the Playground didn't already run press the ▶︎ button at the bottom import Foundation import RealmSwift //: I. Define the data entities class Person: Object { @Persisted var name: String @Persisted var age: Int @Persisted var spouse: Person? @Persisted var cars: List<Car> override var description: String { return "Person {\(name), \(age), \(spouse?.name ?? "nil")}" } } class Car: Object { @Persisted var brand: String @Persisted var name: String? @Persisted var year: Int override var description: String { return "Car {\(brand), \(name), \(year)}" } } //: II. Init the realm file let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "TemporaryRealm")) //: III. Create the objects let car1 = Car(value: ["brand": "BMW", "year": 1980]) let car2 = Car() car2.brand = "DeLorean" car2.name = "Outatime" car2.year = 1981 // people let wife = Person() wife.name = "Jennifer" wife.cars.append(objectsIn: [car1, car2]) wife.age = 47 let husband = Person(value: [ "name": "Marty", "age": 47, "spouse": wife ]) wife.spouse = husband //: IV. Write objects to the realm try! realm.write { realm.add(husband) } //: V. Read objects back from the realm let favorites = ["Jennifer"] let favoritePeopleWithSpousesAndCars = realm.objects(Person.self) .filter("cars.@count > 1 && spouse != nil && name IN %@", favorites) .sorted(byKeyPath: "age") for person in favoritePeopleWithSpousesAndCars { person.name person.age guard let car = person.cars.first else { continue } car.name car.brand //: VI. Update objects try! realm.write { car.year += 1 } car.year } //: VII. Delete objects try! realm.write { realm.deleteAll() } realm.objects(Person.self).count //: Thanks! To learn more about Realm go to https://realm.io
apache-2.0
d8b1a6552f5a7fea0fa96743487460bd
20.210526
100
0.655583
3.358333
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Client/QuoteClientAPI.swift
1
1086
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import MoneyKit public struct QuoteQueryRequest: Encodable { /// Profile for the quote let profile: String /// The trading pair for the quote let pair: String /// The fiat value represented in minor units let inputValue: String /// The payment method payload type used let paymentMethod: String? /// The payment method Id for the quote let paymentMethodId: String? init(from query: QuoteQuery) { profile = query.profile.rawValue pair = "\(query.sourceCurrency.code)-\(query.destinationCurrency.code)" inputValue = query.amount.minorString paymentMethod = query.paymentMethod?.rawValue paymentMethodId = query.paymentMethodId } } protocol QuoteClientAPI: AnyObject { /// Get a quote from a simple-buy order. In the future, it will support all sorts of order (buy, sell, swap) func getQuote( queryRequest: QuoteQueryRequest ) -> AnyPublisher<QuoteResponse, NabuNetworkError> }
lgpl-3.0
8dfd8a41b3944331be7f1c7769ef1e7f
26.820513
112
0.699539
4.779736
false
false
false
false
huonw/swift
test/SILOptimizer/diagnostic_constant_propagation.swift
1
25076
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify // // These are tests for diagnostics produced by constant propagation pass. // Due to the change in the implementation of Integer initializers some of the // tests here that must fail don't currently. Such tests have comments // describing the desirable behavior. They are false negatives now but have // to be addressed in the future. // References: <rdar://problem/29937936>, <rdar://problem/29939484>, // <https://bugs.swift.org/browse/SR-5964>, <rdar://problem/39120081> import StdlibUnittest func testArithmeticOverflow() { let xu8 : UInt8 = 250 let yu8 : UInt8 = 250 var _ /*zu8*/ = xu8 + yu8 // expected-error {{arithmetic operation '250 + 250' (on type 'UInt8') results in an overflow}} var _ /*xpyu8*/ : UInt8 = 250 + 250 // expected-error {{arithmetic operation '250 + 250' (on type 'UInt8') results in an overflow}} var _ /*xpyi8*/ : Int8 = 126 + 126 // expected-error {{arithmetic operation '126 + 126' (on type 'Int8') results in an overflow}} var _ /*xmyu16*/ : UInt16 = 65000 * 2 // expected-error {{arithmetic operation '65000 * 2' (on type 'UInt16') results in an overflow}} var _ /*xmyi16*/ : Int16 = 32000 * 2 // expected-error {{arithmetic operation '32000 * 2' (on type 'Int16') results in an overflow}} var _ /*xmyu32*/ : UInt32 = 4294967295 * 30 // expected-error {{arithmetic operation '4294967295 * 30' (on type 'UInt32') results in an overflow}} var _ /*xpyi32*/ : Int32 = 2147483647 + 30 // expected-error {{arithmetic operation '2147483647 + 30' (on type 'Int32') results in an overflow}} var _ /*xpyu64*/ : UInt64 = 9223372036854775807 * 30 // expected-error {{results in an overflow}} var _ /*xpyi64*/ : Int64 = 9223372036854775807 + 1 // expected-error {{results in an overflow}} var xu8_2 : UInt8 = 240 xu8_2 += 40 // expected-error {{arithmetic operation '240 + 40' (on type 'UInt8') results in an overflow}} var _ : UInt8 = 230 - 240 // expected-error {{arithmetic operation '230 - 240' (on type 'UInt8') results in an overflow}} var xu8_3 : UInt8 = 240 // Global (cross block) analysis. for _ in 0..<10 {} xu8_3 += 40 // expected-error {{arithmetic operation '240 + 40' (on type 'UInt8') results in an overflow}} var _ : UInt8 = 240 + 5 + 15 // expected-error {{arithmetic operation '245 + 15' (on type 'UInt8') results in an overflow}} var _ = Int8(126) + Int8(1+1) // FIXME: false negative: overflow that is not // caught by diagnostics (see also <rdar://problem/39120081>). var _: Int8 = (1 << 7) - 1 // FIXME: false negative: should expect an error // like {{arithmetic operation '-128 - 1' (on type 'Int8') results in an overflow}} // Note: asserts in the shift operators confuse constant propagation var _: Int8 = (-1 & ~(1<<7))+1 // FIXME: false negative: should expect an error // like {{arithmetic operation '127 + 1' (on type 'Int8') results in an overflow}} // The following cases check that overflows in arithmetic over large literals // without explicit types are caught. Note that if a literal overflows even // Int20148 it will be caught by the Sema phases. Also note that the // overflow is detected during implicit conversion to 'Int'. _blackHole( -00016158503035655503650357438344334975980222051334857742016065172713762327569433945446598600705761456731844358980460949009747059779575245460547544076193224141560315438683650498045875098875194826053398028819192033784138396109321309878080919047169238085235290822926018152521443787945770532904303776199561965192760957166694834171210342487393282284747428088017663161029038902829665513096354230157075129296432088558362971801859230928678799175576150822952201848806616643615613562842355410104862578550863465661734839271290328348967522998634176499319107762583194718667771801067716614802322659239302476074096777926805529798115328 - 1) // expected-error@-1 {{integer literal '-16158503035655503650357438344334975980222051334857742016065172713762327569433945446598600705761456731844358980460949009747059779575245460547544076193224141560315438683650498045875098875194826053398028819192033784138396109321309878080919047169238085235290822926018152521443787945770532904303776199561965192760957166694834171210342487393282284747428088017663161029038902829665513096354230157075129296432088558362971801859230928678799175576150822952201848806616643615613562842355410104862578550863465661734839271290328348967522998634176499319107762583194718667771801067716614802322659239302476074096777926805529798115328' overflows when stored into 'Int'}} _blackHole( 00016158503035655503650357438344334975980222051334857742016065172713762327569433945446598600705761456731844358980460949009747059779575245460547544076193224141560315438683650498045875098875194826053398028819192033784138396109321309878080919047169238085235290822926018152521443787945770532904303776199561965192760957166694834171210342487393282284747428088017663161029038902829665513096354230157075129296432088558362971801859230928678799175576150822952201848806616643615613562842355410104862578550863465661734839271290328348967522998634176499319107762583194718667771801067716614802322659239302476074096777926805529798115327 + 1) // expected-error@-1 {{integer literal '16158503035655503650357438344334975980222051334857742016065172713762327569433945446598600705761456731844358980460949009747059779575245460547544076193224141560315438683650498045875098875194826053398028819192033784138396109321309878080919047169238085235290822926018152521443787945770532904303776199561965192760957166694834171210342487393282284747428088017663161029038902829665513096354230157075129296432088558362971801859230928678799175576150822952201848806616643615613562842355410104862578550863465661734839271290328348967522998634176499319107762583194718667771801067716614802322659239302476074096777926805529798115327' overflows when stored into 'Int'}} } @_transparent func myaddSigned(_ x: Int8, _ y: Int8, _ z: Int8) -> Int8 { return x + y } @_transparent func myaddUnsigned(_ x: UInt8, _ y: UInt8, _ z: UInt8) -> UInt8 { return x + y } func testGenericArithmeticOverflowMessage() { _ = myaddSigned(125, 125, 125) // expected-error{{arithmetic operation '125 + 125' (on signed 8-bit integer type) results in an overflow}} _ = myaddUnsigned(250, 250, 250) // expected-error{{arithmetic operation '250 + 250' (on unsigned 8-bit integer type) results in an overflow}} } typealias MyInt = UInt8 func testConvertOverflow() { var _ /*int8_minus_two*/ : Int8 = (-2) var _ /*int8_plus_two*/ : Int8 = (2) var _ /*int16_minus_two*/ : Int16 = (-2) var _ /*int16_plus_two*/ : Int16 = (2) var _ /*int32_minus_two*/ : Int32 = (-2) var _ /*int32_plus_two*/ : Int32 = (2) var _ /*int64_minus_two*/ : Int64 = (-2) var _ /*int64_plus_two*/ : Int64 = (2) let int_minus_two : Int = (-2) let int_plus_two : Int = (2) var _ /*convert_minus_two*/ = Int8(int_minus_two) var _ /*convert_plus_two*/ = Int8(int_plus_two) var _ /*uint8_minus_two*/ : UInt8 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt8'}} var _ /*uint8_plus_two*/ : UInt8 = (2) var _ /*uint16_minus_two*/ : UInt16 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt16'}} var _ /*uint16_plus_two*/ : UInt16 = (2) var _ /*uint32_minus_two*/ : UInt32 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt32'}} let uint32_plus_two : UInt32 = (2) var _ /*uint64_minus_two*/ : UInt64 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt64'}} var _ /*uint64_plus_two*/ : UInt64 = (2) var _ /*convert_s_to_u_minus_two*/ = UInt8(int_minus_two) // FIXME: false negative: // overflow that is not caught by diagnostics. var _ /*convert_s_to_u_plus_two*/ = UInt8(int_plus_two) var _ /*convert_u_to_s_plus_two*/ = Int8(uint32_plus_two) var _ /*int8_min*/ : Int8 = (-128) var _ /*int8_min_m1*/ : Int8 = (-129) // expected-error {{integer literal '-129' overflows when stored into 'Int8'}} var _ /*int16_min*/ : Int16 = (-32768) var _ /*int16_min_m1*/ : Int16 = (-32769) // expected-error {{integer literal '-32769' overflows when stored into 'Int16'}} var _ /*int32_min*/ : Int32 = (-2147483648) var _ /*int32_min_m1*/ : Int32 = (-2147483649) // expected-error {{integer literal '-2147483649' overflows when stored into 'Int32'}} var _ /*int64_min*/ : Int64 = (-9223372036854775808) var _ /*int64_min_m1*/ : Int64 = (-9223372036854775809) // expected-error {{integer literal '-9223372036854775809' overflows when stored into 'Int64'}} let int_minus_128 = -128 var _ /*int8_min_conv*/ = Int8(int_minus_128) let int_minus_129 = -129 var _ /*int8_min_m1_conv*/ = Int8(int_minus_129) // FIXME: false negative: // overflow that is not caught by diagnostics (see also <rdar://problem/39120081>). var _ /*int8_max*/ : Int8 = (127) var _ /*int8_max_p1*/ : Int8 = (128) // expected-error {{integer literal '128' overflows when stored into 'Int8'}} let int16_max : Int16 = (32767) var _ /*int16_max_p1*/ : Int16 = (32768) // expected-error {{integer literal '32768' overflows when stored into 'Int16'}} var _ /*int32_max*/ : Int32 = (2147483647) var _ /*int32_max_p1*/ : Int32 = (2147483648) // expected-error {{integer literal '2147483648' overflows when stored into 'Int32'}} var _ /*int64_max*/ : Int64 = (9223372036854775807) var _ /*int64_max_p1*/ : Int64 = (9223372036854775808) // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int64'}} var _ /*int16_max_conv*/ = Int16(UInt64(int16_max)) let uint64_plus_32768 : UInt64 = 32768 var _ /*int16_max_p1_conv*/ = Int16(uint64_plus_32768) // FIXME: false negative: // overflow that is not caught by diagnostics (see also <rdar://problem/39120081>) var _ /*int8_max_pa*/ : Int8 = -13333; //expected-error{{integer literal '-13333' overflows when stored into 'Int8}} var _ /*int32_max_p_hex*/ : Int32 = 0xFFFF_FFFF; //expected-error{{integer literal '4294967295' overflows when stored into 'Int32'}} var _ /*uint32_max_hex*/ : UInt32 = 0xFFFF_FFFF var _ /*uint32_max_p_hex*/ : UInt32 = 0xFFFF_FFFF_F; //expected-error{{integer literal '68719476735' overflows when stored into 'UInt32'}} var _ /*uint0_typealias*/ : MyInt = 256; //expected-error{{integer literal '256' overflows when stored into 'MyInt'}} var _ /*uint8_min*/ : UInt8 = (0) let uint16_min : UInt16 = (0) var _ /*uint32_min*/ : UInt32 = (0) let uint64_min : UInt64 = (0) var _ /*uint8_min_conv_to_u*/ = UInt8(uint64_min) let int8_zero : Int8 = (0) var _ /*int16_zero*/ : Int16 = (0) var _ /*int32_zero*/ : Int32 = (0) var _ /*int64_zero*/ : Int64 = (0) var _ /*int8_min_conv_to_s*/ = Int8(uint16_min) var _ /*uint8_max*/ : UInt8 = (255) var _ /*uint8_max_p1*/ : UInt8 = (256) // expected-error {{integer literal '256' overflows when stored into 'UInt8'}} var _ /*uint16_max*/ : UInt16 = (65535) var _ /*uint16_max_p1*/ : UInt16 = (65536) // expected-error {{integer literal '65536' overflows when stored into 'UInt16'}} var _ /*uint32_max*/ : UInt32 = (4294967295) var _ /*uint32_max_p1*/ : UInt32 = (4294967296) // expected-error {{integer literal '4294967296' overflows when stored into 'UInt32'}} var _ /*uint64_max*/ : UInt64 = (18446744073709551615) var _ /*uint64_max_p1*/ : UInt64 = (18446744073709551616) // expected-error {{integer literal '18446744073709551616' overflows when stored into 'UInt64'}} let uint16_255 : UInt16 = 255 var _ /*uint8_max_conv*/ = UInt8(uint16_255) let uint16_256 : UInt16 = 256 var _ /*uint8_max_p1_conv*/ = UInt8(uint16_256) // FIXME: false negative: // overflow that is not caught by diagnostics (see also <rdar://problem/39120081>) // Check same size int conversions. let int8_minus_1 : Int8 = -1 let _ /*ssint8_neg*/ = UInt8(int8_minus_1) // FIXME: false negative: // overflow that is not caught by diagnostics (see also <rdar://problem/39120081>) let uint8_128 : UInt8 = 128 let _ /*ssint8_toobig*/ = Int8(uint8_128) // FIXME: false negative: overflow // that is not caught by diagnostics (see also <rdar://problem/39120081>) let uint8_127 : UInt8 = 127 let _ /*ssint8_good*/ = Int8(uint8_127) let int8_127 : Int8 = 127 let _ /*ssint8_good2*/ = UInt8(int8_127) let _ /*ssint8_zero*/ = UInt8(int8_zero) let uint8_zero : UInt8 = 0 let _ /*ssint8_zero2*/ = Int8(uint8_zero) // Check signed to unsigned extending size conversions. var _ = UInt16(Int8(-1)) // FIXME: false negative: overflow that is not caught // (see also <rdar://problem/39120081>) var _ = UInt64(Int16(-200)) // FIXME: false negative: overflow that is not // caught by diagnostics (see also <rdar://problem/39120081>) var _ = UInt64(Int32(-200)) // FIXME: false negative: overflow that is not // caught by diagnostics (see also <rdar://problem/39120081>) Int16(Int8(-1)) // expected-warning{{unused}} Int64(Int16(-200)) // expected-warning{{unused}} Int64(Int32(-200)) // expected-warning{{unused}} Int64(UInt32(200)) // expected-warning{{unused}} UInt64(UInt32(200)) // expected-warning{{unused}} // IEEE binary32 max value = 2^128 * (2^23-1)/2^23 var _ /*float32_max*/ : Float32 = (340282326356119256160033759537265639424) var _ /*float32_max_p1*/ : Float32 = (340282326356119256160033759537265639425) // 2^128 * (2^25-1)/2^25 - 1 var _ /*float32_max_not_yet_overflow*/ : Float32 = (340282356779733661637539395458142568447) // 2^128 * (2^25-1)/2^25 var _ /*float32_max_first_overflow*/ : Float32 = (340282356779733661637539395458142568448) // expected-error {{integer literal '340282356779733661637539395458142568448' overflows when stored into 'Float32'}} // 2^128 var _ /*float32_max_definitely_overflow*/ : Float32 = (340282366920938463463374607431768211456) // expected-error {{integer literal '340282366920938463463374607431768211456' overflows when stored into 'Float32'}} // IEEE binary32 min value = -1 * 2^128 * (2^23-1)/2^23 var _ /*float32_min*/ : Float32 = (-340282326356119256160033759537265639424) var _ /*float32_min_p1*/ : Float32 = (-340282326356119256160033759537265639425) // -1 * 2^128 * (2^25-1)/2^25 - 1 var _ /*float32_min_not_yet_overflow*/ : Float32 = (-340282356779733661637539395458142568447) // -1 * 2^128 * (2^25-1)/2^25 var _ /*float32_min_first_overflow*/ : Float32 = (-340282356779733661637539395458142568448) // expected-error {{integer literal '-340282356779733661637539395458142568448' overflows when stored into 'Float32'}} // -1 * 2^128 var _ /*float32_min_definitely_overflow*/ : Float32 = (-340282366920938463463374607431768211456) // expected-error {{integer literal '-340282366920938463463374607431768211456' overflows when stored into 'Float32'}} // IEEE binary64 max value = 2^1024 * (2^52-1)/2^52 var _ /*float64_max*/ : Float64 = (179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) var _ /*float64_max_p1*/ : Float64 = (179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) // 2^1024 * (2^54-1)/2^54 - 1 var _/*float64_max_not_yet_overflow*/ : Float64 = (179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791) // 2^1024 * (2^54-1)/2^54 var _ /*float64_max_first_overflow*/ : Float64 = (179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792) // expected-error {{integer literal '179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792' overflows when stored into 'Double'}} // 2^1024 var _/*float64_max_definitely_overflow*/ : Float64 = (179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216) // expected-error {{integer literal '179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216' overflows when stored into 'Double'}} // IEEE binary64 min value = -1 * 2^1024 * (2^52-1)/2^52 var _/*float64_min*/ : Float64 = (-179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) var _/*float64_min_p1*/ : Float64 = (-179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) // -1 * 2^1024 * (2^54-1)/2^54 - 1 var _/*float64_min_not_yet_overflow*/ : Float64 = (-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791) // -1 * 2^1024 * (2^54-1)/2^54 var _/*float64_min_first_overflow*/ : Float64 = (-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792) // expected-error {{integer literal '-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792' overflows when stored into 'Double'}} // -1 * 2^1024 var _/*float64_min_definitely_overflow*/ : Float64 = (-179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216) // expected-error {{integer literal '-179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216' overflows when stored into 'Double'}} } @_transparent func intConversionWrapperForUSCheckedConversion(_ x: UInt8, _ unused: UInt8) -> Int8 { return Int8(x) } @_transparent func intConversionWrapperForLiteral() -> Int8 { return 255 // expected-error {{integer literal '255' overflows when stored into 'Int8'}} } func testFallBackDiagnosticMessages() { _ = intConversionWrapperForUSCheckedConversion(255, 30) // FIXME: false negative: // uncaught overflow error. See the function `intConversionWrapperForLiteral` // definition (see also <rdar://problem/39120081>). _ = intConversionWrapperForLiteral() // expected-error {{integer literal '255' overflows when stored into signed 'Builtin.Int8'}} } func testDivision() { var _ : Int = 3 / 3 var _ : Int = 3 / 0 // expected-error{{division by zero}} var _ : Int = 3 % 0 // expected-error{{division by zero}} let uzero : UInt8 = 0 let uone : UInt8 = 1 var _ : UInt8 = uzero / uone var _ : UInt8 = uone / uzero // expected-error{{division by zero}} var _ : UInt8 = uone % uzero // expected-error{{division by zero}} var _ : Float = 3.0 / 0.0 let minusOne : Int32 = -1 var _ : Int32 = -2147483648 / minusOne // expected-error{{division '-2147483648 / -1' results in an overflow}} } func testPostIncOverflow() { var s8_max = Int8.max s8_max += 1 // expected-error {{arithmetic operation '127 + 1' (on type 'Int8') results in an overflow}} var u8_max = UInt8.max u8_max += 1 // expected-error {{arithmetic operation '255 + 1' (on type 'UInt8') results in an overflow}} var s16_max = Int16.max s16_max += 1 // expected-error {{arithmetic operation '32767 + 1' (on type 'Int16') results in an overflow}} var u16_max = UInt16.max u16_max += 1 // expected-error {{arithmetic operation '65535 + 1' (on type 'UInt16') results in an overflow}} var s32_max = Int32.max s32_max += 1 // expected-error {{arithmetic operation '2147483647 + 1' (on type 'Int32') results in an overflow}} var u32_max = UInt32.max u32_max += 1 // expected-error {{arithmetic operation '4294967295 + 1' (on type 'UInt32') results in an overflow}} var s64_max = Int64.max s64_max += 1 // expected-error {{arithmetic operation '9223372036854775807 + 1' (on type 'Int64') results in an overflow}} var u64_max = UInt64.max u64_max += 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt64') results in an overflow}} } func testPostDecOverflow() { var s8_min = Int8.min s8_min -= 1 // expected-error {{arithmetic operation '-128 - 1' (on type 'Int8') results in an overflow}} var u8_min = UInt8.min u8_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt8') results in an overflow}} var s16_min = Int16.min s16_min -= 1 // expected-error {{arithmetic operation '-32768 - 1' (on type 'Int16') results in an overflow}} var u16_min = UInt16.min u16_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt16') results in an overflow}} var s32_min = Int32.min s32_min -= 1 // expected-error {{arithmetic operation '-2147483648 - 1' (on type 'Int32') results in an overflow}} var u32_min = UInt32.min u32_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt32') results in an overflow}} var s64_min = Int64.min s64_min -= 1 // expected-error {{arithmetic operation '-9223372036854775808 - 1' (on type 'Int64') results in an overflow}} var u64_min = UInt64.min u64_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt64') results in an overflow}} } func testAssumeNonNegative() { let input = -3 _ = _assumeNonNegative(input) // expected-error {{assumed non-negative value '-3' is negative}} } protocol Num { func Double() -> Self } extension Int8 : Num { @_transparent func Double() -> Int8 { return self * 2 } } @_transparent func Double<T : Num>(_ x: T) -> T { return x.Double() } func tryDouble() -> Int8 { return Double(Int8.max) // expected-error {{arithmetic operation '127 * 2' (on signed 8-bit integer type) results in an overflow}} } @_transparent func add<T : SignedInteger>(_ left: T, _ right: T) -> T { return left + right } @_transparent func applyBinary<T : SignedInteger>(_ fn: (T, T) -> (T), _ left: T, _ right: T) -> T { return fn(left, right) } func testTransparentApply() -> Int8 { return applyBinary(add, Int8.max, Int8.max) // expected-error {{arithmetic operation '127 + 127' (on signed 8-bit integer type) results in an overflow}} }
apache-2.0
b60f4521870efb1f90b3e5ade45b01c6
70.238636
754
0.746889
3.407065
false
false
false
false
shadowsocks/ShadowsocksX-NG
Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift
2
18821
// // DelegateProxyType.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) import Foundation import RxSwift /** `DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with views that can have only one delegate/datasource registered. `Proxies` store information about observers, subscriptions and delegates for specific views. Type implementing `DelegateProxyType` should never be initialized directly. To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method should be used. This is more or less how it works. +-------------------------------------------+ | | | UIView subclass (UIScrollView) | | | +-----------+-------------------------------+ | | Delegate | | +-----------v-------------------------------+ | | | Delegate proxy : DelegateProxyType +-----+----> Observable<T1> | , UIScrollViewDelegate | | +-----------+-------------------------------+ +----> Observable<T2> | | | +----> Observable<T3> | | | forwards events | | to custom delegate | | v +-----------v-------------------------------+ | | | Custom delegate (UIScrollViewDelegate) | | | +-------------------------------------------+ Since RxCocoa needs to automagically create those Proxys and because views that have delegates can be hierarchical UITableView : UIScrollView : UIView .. and corresponding delegates are also hierarchical UITableViewDelegate : UIScrollViewDelegate : NSObject ... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) } */ public protocol DelegateProxyType: AnyObject { associatedtype ParentObject: AnyObject associatedtype Delegate /// It is require that enumerate call `register` of the extended DelegateProxy subclasses here. static func registerKnownImplementations() /// Unique identifier for delegate static var identifier: UnsafeRawPointer { get } /// Returns designated delegate property for object. /// /// Objects can have multiple delegate properties. /// /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. /// /// It's abstract method. /// /// - parameter object: Object that has delegate property. /// - returns: Value of delegate property. static func currentDelegate(for object: ParentObject) -> Delegate? /// Sets designated delegate property for object. /// /// Objects can have multiple delegate properties. /// /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. /// /// It's abstract method. /// /// - parameter toObject: Object that has delegate property. /// - parameter delegate: Delegate value. static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) /// Returns reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - returns: Value of reference if set or nil. func forwardToDelegate() -> Delegate? /// Sets reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool) } // default implementations extension DelegateProxyType { /// Unique identifier for delegate public static var identifier: UnsafeRawPointer { let delegateIdentifier = ObjectIdentifier(Delegate.self) let integerIdentifier = Int(bitPattern: delegateIdentifier) return UnsafeRawPointer(bitPattern: integerIdentifier)! } } // workaround of Delegate: class extension DelegateProxyType { static func _currentDelegate(for object: ParentObject) -> AnyObject? { currentDelegate(for: object).map { $0 as AnyObject } } static func _setCurrentDelegate(_ delegate: AnyObject?, to object: ParentObject) { setCurrentDelegate(castOptionalOrFatalError(delegate), to: object) } func _forwardToDelegate() -> AnyObject? { self.forwardToDelegate().map { $0 as AnyObject } } func _setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { self.setForwardToDelegate(castOptionalOrFatalError(forwardToDelegate), retainDelegate: retainDelegate) } } extension DelegateProxyType { /// Store DelegateProxy subclass to factory. /// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory /// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type. /// Should call it from concrete DelegateProxy type, not generic. public static func register<Parent>(make: @escaping (Parent) -> Self) { self.factory.extend(make: make) } /// Creates new proxy for target object. /// Should not call this function directory, use 'DelegateProxy.proxy(for:)' public static func createProxy(for object: AnyObject) -> Self { castOrFatalError(factory.createProxy(for: object)) } /// Returns existing proxy for object or installs new instance of delegate proxy. /// /// - parameter object: Target object on which to install delegate proxy. /// - returns: Installed instance of delegate proxy. /// /// /// extension Reactive where Base: UISearchBar { /// /// public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> { /// return RxSearchBarDelegateProxy.proxy(for: base) /// } /// /// public var text: ControlProperty<String> { /// let source: Observable<String> = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) /// ... /// } /// } public static func proxy(for object: ParentObject) -> Self { MainScheduler.ensureRunningOnMainThread() let maybeProxy = self.assignedProxy(for: object) let proxy: AnyObject if let existingProxy = maybeProxy { proxy = existingProxy } else { proxy = castOrFatalError(self.createProxy(for: object)) self.assignProxy(proxy, toObject: object) assert(self.assignedProxy(for: object) === proxy) } let currentDelegate = self._currentDelegate(for: object) let delegateProxy: Self = castOrFatalError(proxy) if currentDelegate !== delegateProxy { delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false) assert(delegateProxy._forwardToDelegate() === currentDelegate) self._setCurrentDelegate(proxy, to: object) assert(self._currentDelegate(for: object) === proxy) assert(delegateProxy._forwardToDelegate() === currentDelegate) } return delegateProxy } /// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate. /// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations. /// /// - parameter forwardDelegate: Delegate object to set. /// - parameter retainDelegate: Retain `forwardDelegate` while it's being set. /// - parameter onProxyForObject: Object that has `delegate` property. /// - returns: Disposable object that can be used to clear forward delegate. public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable { weak var weakForwardDelegate: AnyObject? = forwardDelegate as AnyObject let proxy = self.proxy(for: object) assert(proxy._forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" + "If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" + " This is the source object value: \(object)\n" + " This is the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" + "Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n") proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate) return Disposables.create { MainScheduler.ensureRunningOnMainThread() let delegate: AnyObject? = weakForwardDelegate assert(delegate == nil || proxy._forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)") proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate) } } } // private extensions extension DelegateProxyType { private static var factory: DelegateProxyFactory { DelegateProxyFactory.sharedFactory(for: self) } private static func assignedProxy(for object: ParentObject) -> AnyObject? { let maybeDelegate = objc_getAssociatedObject(object, self.identifier) return castOptionalOrFatalError(maybeDelegate) } private static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) { objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN) } } /// Describes an object that has a delegate. public protocol HasDelegate: AnyObject { /// Delegate type associatedtype Delegate /// Delegate var delegate: Delegate? { get set } } extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate { public static func currentDelegate(for object: ParentObject) -> Delegate? { object.delegate } public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { object.delegate = delegate } } /// Describes an object that has a data source. public protocol HasDataSource: AnyObject { /// Data source type associatedtype DataSource /// Data source var dataSource: DataSource? { get set } } extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource { public static func currentDelegate(for object: ParentObject) -> Delegate? { object.dataSource } public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { object.dataSource = delegate } } /// Describes an object that has a prefetch data source. @available(iOS 10.0, tvOS 10.0, *) public protocol HasPrefetchDataSource: AnyObject { /// Prefetch data source type associatedtype PrefetchDataSource /// Prefetch data source var prefetchDataSource: PrefetchDataSource? { get set } } @available(iOS 10.0, tvOS 10.0, *) extension DelegateProxyType where ParentObject: HasPrefetchDataSource, Self.Delegate == ParentObject.PrefetchDataSource { public static func currentDelegate(for object: ParentObject) -> Delegate? { object.prefetchDataSource } public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { object.prefetchDataSource = delegate } } #if os(iOS) || os(tvOS) import UIKit extension ObservableType { func subscribeProxyDataSource<DelegateProxy: DelegateProxyType>(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event<Element>) -> Void) -> Disposable where DelegateProxy.ParentObject: UIView , DelegateProxy.Delegate: AnyObject { let proxy = DelegateProxy.proxy(for: object) let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) // Do not perform layoutIfNeeded if the object is still not in the view heirarchy if object.window != nil { // this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75) object.layoutIfNeeded() } let subscription = self.asObservable() .observe(on:MainScheduler()) .catch { error in bindingError(error) return Observable.empty() } // source can never end, otherwise it would release the subscriber, and deallocate the data source .concat(Observable.never()) .take(until: object.rx.deallocated) .subscribe { [weak object] (event: Event<Element>) in if let object = object { assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))") } binding(proxy, event) switch event { case .error(let error): bindingError(error) unregisterDelegate.dispose() case .completed: unregisterDelegate.dispose() default: break } } return Disposables.create { [weak object] in subscription.dispose() if object?.window != nil { object?.layoutIfNeeded() } unregisterDelegate.dispose() } } } #endif /** To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). class RxScrollViewDelegateProxy: DelegateProxy { public static func registerKnownImplementations() { self.register { RxTableViewDelegateProxy(parentObject: $0) } } ... */ private class DelegateProxyFactory { private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:] fileprivate static func sharedFactory<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory { MainScheduler.ensureRunningOnMainThread() let identifier = DelegateProxy.identifier if let factory = _sharedFactories[identifier] { return factory } let factory = DelegateProxyFactory(for: proxyType) _sharedFactories[identifier] = factory DelegateProxy.registerKnownImplementations() return factory } private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)] private var _delegateProxyType: Any.Type private var _identifier: UnsafeRawPointer private init<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) { self._factories = [:] self._delegateProxyType = proxyType self._identifier = proxyType.identifier } fileprivate func extend<DelegateProxy: DelegateProxyType, ParentObject>(make: @escaping (ParentObject) -> DelegateProxy) { MainScheduler.ensureRunningOnMainThread() precondition(self._identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier") guard self._factories[ObjectIdentifier(ParentObject.self)] == nil else { rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.") } self._factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) } } fileprivate func createProxy(for object: AnyObject) -> AnyObject { MainScheduler.ensureRunningOnMainThread() var maybeMirror: Mirror? = Mirror(reflecting: object) while let mirror = maybeMirror { if let factory = self._factories[ObjectIdentifier(mirror.subjectType)] { return factory(object) } maybeMirror = mirror.superclassMirror } rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.") } } #endif
gpl-3.0
dcda2e4cadd90b4390d949bfd67301cb
42.264368
359
0.606695
5.948167
false
false
false
false
armadsen/CocoaHeads-SLC-Presentations
IntroToConcurrentProgramming/GCD.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
1
457
//: [Previous](@previous) import Foundation let queue = OperationQueue() queue.name = "MyOperationQueue" queue.maxConcurrentOperationCount = OperationQueue.defaultMaxConcurrentOperationCount let op1 = BlockOperation { print("Do this") } let op2 = BlockOperation { print("Do this at the same time") } let op3 = BlockOperation { print("Do this when both of those are done") } op3.addDependency(op1) op3.addDependency(op2) //: [Next](@next)
mit
b4a03738f7693e29ce067b285695aeee
18.869565
85
0.728665
3.745902
false
false
false
false
tlax/GaussSquad
GaussSquad/Metal/Spatial/MetalSpatialRect.swift
1
1209
import Foundation import MetalKit class MetalSpatialRect { let vertexBuffer:MTLBuffer init(vertexBuffer:MTLBuffer) { self.vertexBuffer = vertexBuffer } init( device:MTLDevice, width:Float, height:Float) { let width_2:Float = width / 2.0 let height_2:Float = height / 2.0 let top:Float = height_2 let bottom:Float = -height_2 let left:Float = -width_2 let right:Float = width_2 let topLeft:MetalVertex = MetalVertex( positionX:left, positionY:top) let topRight:MetalVertex = MetalVertex( positionX:right, positionY:top) let bottomLeft:MetalVertex = MetalVertex( positionX:left, positionY:bottom) let bottomRight:MetalVertex = MetalVertex( positionX:right, positionY:bottom) let vertexFace:MetalVertexFace = MetalVertexFace( topLeft:topLeft, topRight:topRight, bottomLeft:bottomLeft, bottomRight:bottomRight) vertexBuffer = device.generateBuffer(bufferable:vertexFace) } }
mit
8cf4bf6bb9152c45dd8665a9ddaab65a
25.282609
67
0.578164
4.914634
false
false
false
false
mbigatti/ComplicationExample
WatchApp Extension/ComplicationController.swift
1
1934
// // ComplicationController.swift // WatchApp Extension // // Created by Massimiliano Bigatti on 10/10/15. // Copyright © 2015 Massimiliano Bigatti. All rights reserved. // import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { handler([]) } // MARK: - Timeline Population func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) { let template = CLKComplicationTemplateCircularSmallRingText() template.textProvider = CLKSimpleTextProvider(text: "Work day", shortText: "WK") template.fillFraction = workdayCompletion() let entry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: template) handler(entry) } // calculate completion against workday 9.00-18.00 func workdayCompletion() -> Float { let calendar = NSCalendar.currentCalendar() let now = NSDate() let currentHour = Float(calendar.component(NSCalendarUnit.Hour, fromDate: now)) let currentMinutes = Float(calendar.component(NSCalendarUnit.Minute, fromDate: now)) let startHour : Float = 9 let hour = (currentHour + currentMinutes / 60) - startHour return 1.0 / 9 * hour } // MARK: - Placeholder Templates func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { let template = CLKComplicationTemplateCircularSmallRingText() template.textProvider = CLKSimpleTextProvider(text: "Work day", shortText: "WK") handler(template) } }
mit
ae21ae91be8f19a58fd55e14d0101a54
34.145455
157
0.69581
5.586705
false
false
false
false
leios/algorithm-archive
contents/tree_traversal/code/swift/tree.swift
1
2436
class Node { var value: Int var children: [Node]? init(value: Int, children: [Node]) { self.value = value self.children = children } } func createTree(numRows: Int, numChildren: Int) -> Node { let node = Node(value: numRows, children: []) if numRows > 0 { for _ in 1...numChildren { let child = createTree(numRows: numRows-1, numChildren: numChildren) node.children?.append(child) } } return node } func dfsRecursive(node: Node) { print(node.value, terminator:" ") for child in node.children! { dfsRecursive(node: child) } } func dfsRecursivePostOrder(node: Node) { for child in node.children! { dfsRecursivePostOrder(node: child) } print(node.value, terminator:" ") } func dfsRecursiveInOrderBinary(node: Node) { if node.children?.count == 2 { dfsRecursiveInOrderBinary(node: node.children![0]) print(node.value, terminator:" ") dfsRecursiveInOrderBinary(node: node.children![1]) } else if node.children?.count == 1 { dfsRecursiveInOrderBinary(node: node.children![0]) print(node.value, terminator:" ") } else if node.children?.count == 0 { print(node.value, terminator:" ") } else { print("Not a binary tree!") } } func dfsStack(node: Node) { var stack = [node] var temp: Node while stack.count > 0 { temp = stack.popLast()! print(temp.value, terminator:" ") for child in temp.children! { stack.append(child) } } } func bfsQueue(node: Node) { var queue = [node] var temp: Node while queue.count > 0 { temp = queue.remove(at: 0) print(temp.value, terminator:" ") for child in temp.children! { queue.append(child) } } } func main() { let root = createTree(numRows: 2, numChildren: 3) print("[#]\nRecursive DFS:") dfsRecursive(node: root) print() print("[#]\nRecursive Postorder DFS:") dfsRecursivePostOrder(node: root) print() print("[#]\nStack-based DFS:") dfsStack(node: root) print() print("[#]\nQueue-based BFS:") bfsQueue(node: root) print() let rootBinary = createTree(numRows: 3, numChildren: 2) print("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) print() } main()
mit
b6f4a59a6cc4d7b69c57402a9e9cef8e
21.348624
80
0.591544
3.690909
false
false
false
false
ATFinke-Productions/Steppy-2
SwiftSteppy/View Controllers/Modal/STPYModalViewController.swift
1
1633
// // STPYModalViewController.swift // SwiftSteppy // // Created by Andrew Finke on 1/12/15. // Copyright (c) 2015 Andrew Finke. All rights reserved. // import UIKit class STPYModalViewController: UIViewController { var color: UIColor? //MARK: Loading override func viewDidLoad() { super.viewDidLoad() if let color = color { self.navigationController?.navigationBar.barTintColor = color self.view.backgroundColor = color } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Interface /** Configures the buttons for the standard app style */ func configureButtons(buttons : [UIButton]) { for button in buttons { button.layer.borderColor = UIColor.whiteColor().CGColor button.layer.borderWidth = 2 button.layer.cornerRadius = 5 } } //MARK: Menu Button /** Called for view controllers that need a done button */ func loadMenuBarButtonItem() { let barButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "menuButtonPressed:") self.navigationItem.rightBarButtonItem = barButtonItem } /** Called when the user presses the done button */ @IBAction func menuButtonPressed(sender: AnyObject) { self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } }
mit
40ba50c5e5db8ad11039b4bbb0d0b097
25.770492
136
0.647275
5.200637
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardVerify/CardBase.swift
1
1012
// // CardBase.swift // CardScan // // Created by Jaime Park on 1/31/20. // import Foundation class CardBase: NSObject { var last4: String var bin: String? var expMonth: String? var expYear: String? var isNewCard: Bool = false init( last4: String, bin: String?, expMonth: String? = nil, expYear: String? = nil ) { self.last4 = last4 self.bin = bin self.expMonth = expMonth self.expYear = expYear } func expiryForDisplay() -> String? { guard let month = self.expMonth, let year = self.expYear else { return nil } return CreditCardUtils.formatExpirationDate(expMonth: month, expYear: year) } func toOcrJson() -> [String: Any] { var ocrJson: [String: Any] = [:] ocrJson["last4"] = self.last4 ocrJson["bin"] = self.bin ocrJson["exp_month"] = self.expMonth ocrJson["exp_year"] = self.expYear return ocrJson } }
mit
a5c5e1276427ba05ed971b75036d11e8
21
83
0.566206
3.833333
false
false
false
false
duke-compsci408-fall2014/Pawns
BayAreaChess/BayAreaChess/PayPalPortal.swift
1
6072
// // PayPalPortal.swift // BayAreaChess // // Created by Carlos Reyes on 11/18/14. // Copyright (c) 2014 Bay Area Chess. All rights reserved. // import UIKit class PalPalPortal: UIViewController, PayPalPaymentDelegate { var config = PayPalConfiguration(); var request = HTTPTask(); var myTournamentID : String? = ""; var myAmount : Int? = 0; @IBOutlet var username : UITextField!; @IBOutlet var password : UITextField!; override func viewDidLoad() { super.viewDidLoad(); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true); PayPalMobile.preconnectWithEnvironment(PayPalEnvironmentNoNetwork); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } /** * Sends GET request to the API server to verify login * credentials, as well as another GET request that receives * payment information in regards to the tournament specific * costs. * * Also sends user feedback if payment is completed successfully * or not. * * @param sender The sending class */ @IBAction func buyClicked(sender : AnyObject) { var tournament_id : String = String(myTournamentID!); var url = Constants.Base.allTournamentsURL+tournament_id; if (self.myTournamentID == "") { return; } var verify_login_url = Constants.Base.verifyURL + username.text + "/" + password.text; println(verify_login_url); request.GET(verify_login_url, parameters: nil, success: {(response: HTTPResponse) in if let loginData = response.responseObject as? NSData { let loginJSON = NSJSONSerialization.JSONObjectWithData(loginData, options: nil, error: nil) as NSDictionary; if (loginJSON[Constants.JSON.verification] as? String == "success") { self.request.GET(url, parameters: nil, success: {(response: HTTPResponse) in if let data = response.responseObject as? NSData { let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary; let amount = NSDecimalNumber(integer: self.myAmount!); var payment = PayPalPayment(); payment.amount = amount; payment.currencyCode = "USD"; payment.shortDescription = "Registration Payment"; if (!payment.processable) { println("Failed to Enter PayPal"); } else { println("Success"); var paymentViewController = PayPalPaymentViewController(payment: payment, configuration: self.config, delegate: self); dispatch_async(dispatch_get_main_queue(), { self.presentViewController(paymentViewController, animated: true, completion: nil); }); } } },failure: {(error: NSError, response: HTTPResponse?) in println("error: \(error)"); }); } else { return; } } },failure: {(error: NSError, response: HTTPResponse?) in println("error: \(error)"); }); } /** * View controller for the PayPal payment view. * Verifies payments and dismisses view when * Payment is completed. * * @param completedPayment A PayPal payment */ func payPalPaymentViewController(paymentViewController: PayPalPaymentViewController!, didCompletePayment completedPayment: PayPalPayment!) { self.verifyCompletedPayment(completedPayment); dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil); }); } /** * On cancellation of a payment, the view controller is dismissed * * @param completedPayment A PayPal Payment View Controller */ func payPalPaymentDidCancel(paymentViewController: PayPalPaymentViewController!) { dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil); }); } /** * On confirmation of payment, sends details about payment back to the server * to be processed. Data sent includes user, tournament id, and payment amount * * @param completedPayment A PayPal payment */ func verifyCompletedPayment(completedPayment: PayPalPayment) { var confirmation: NSDictionary = completedPayment.confirmation as NSDictionary; println(confirmation); var data : NSData = NSJSONSerialization.dataWithJSONObject(completedPayment.confirmation, options: nil, error: nil)!; var paypalData : Dictionary<String, AnyObject> = confirmation[Constants.Response.response] as Dictionary<String, AnyObject>; paypalData[Constants.JSON.user] = username.text; paypalData[Constants.JSON.tid] = myTournamentID; paypalData[Constants.JSON.netPay] = myAmount!; println(paypalData); request.requestSerializer = JSONRequestSerializer(); request.POST(Constants.Base.registrationRegisterURL, parameters: paypalData, success: {(response: HTTPResponse) in },failure: {(error: NSError, response: HTTPResponse?) in println("There was an error in POSTing the JSON :("); }); } @IBAction func back() { dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil); }); } }
mit
7735867ab37c5f4285416d472950bb22
39.211921
150
0.585968
5.382979
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/Detail/PostDetailGenerator.swift
1
12334
//// /// PostDetailGenerator.swift // protocol PostDetailStreamDestination: StreamDestination { func appendComments(_: [StreamCellItem]) } final class PostDetailGenerator: StreamGenerator { var currentUser: User? var streamKind: StreamKind weak private var postDetailStreamDestination: PostDetailStreamDestination? var destination: StreamDestination? { get { return postDetailStreamDestination } set { if !(newValue is PostDetailStreamDestination) { fatalError( "CategoryGenerator.destination must conform to PostDetailStreamDestination" ) } postDetailStreamDestination = newValue as? PostDetailStreamDestination } } private var post: Post? private let postParam: String private var before: String? private var localToken: String = "" private var loadingToken = LoadingToken() private let queue = OperationQueue() init( currentUser: User?, postParam: String, post: Post?, streamKind: StreamKind, destination: StreamDestination ) { self.currentUser = currentUser self.post = post self.postParam = postParam self.streamKind = streamKind self.destination = destination } func load(reload: Bool = false) { let doneOperation = AsyncOperation() queue.addOperation(doneOperation) localToken = loadingToken.resetInitialPageLoadingToken() if reload { post = nil } else { setPlaceHolders() } setInitialPost(doneOperation, reload: reload) loadPost(doneOperation, reload: reload) displayCommentBar(doneOperation) loadPostComments(doneOperation) loadPostLovers(doneOperation) loadPostReposters(doneOperation) loadRelatedPosts(doneOperation) } func loadMoreComments() { guard let before = before else { return } let loadingComments = [StreamCellItem(type: .streamLoading)] self.destination?.replacePlaceholder(type: .postLoadingComments, items: loadingComments) API().postComments(postToken: .fromParam(postParam), before: before) .execute() .done { pageConfig, comments in self.before = pageConfig.next let commentItems = self.parse(jsonables: comments) self.postDetailStreamDestination?.appendComments(commentItems) let loadMoreComments = self.loadMoreCommentItems( lastComment: comments.last, pageConfig: pageConfig ) self.destination?.replacePlaceholder( type: .postLoadingComments, items: loadMoreComments ) } .catch { _ in self.destination?.replacePlaceholder(type: .postLoadingComments, items: []) } } } extension PostDetailGenerator { static func socialPadding() -> [StreamCellItem] { return [StreamCellItem(type: .spacer(height: 8.0))] } static func userAvatarCellItems( users: [User], postParam: String, type: UserAvatarCellModel.EndpointType ) -> [StreamCellItem] { let model = UserAvatarCellModel( type: type, users: users, postParam: postParam ) return [ StreamCellItem(type: .spacer(height: 4.0)), StreamCellItem(jsonable: model, type: .userAvatars) ] } } private extension PostDetailGenerator { func setPlaceHolders() { destination?.setPlaceholders(items: [ StreamCellItem(type: .placeholder, placeholderType: .postHeader), StreamCellItem(type: .placeholder, placeholderType: .postLovers), StreamCellItem(type: .placeholder, placeholderType: .postReposters), StreamCellItem(type: .placeholder, placeholderType: .postSocialPadding), StreamCellItem(type: .placeholder, placeholderType: .postCommentBar), StreamCellItem(type: .placeholder, placeholderType: .postComments), StreamCellItem(type: .placeholder, placeholderType: .postLoadingComments), StreamCellItem(type: .placeholder, placeholderType: .postRelatedPosts), ]) } func setInitialPost(_ doneOperation: AsyncOperation, reload: Bool) { guard !reload, let post = post else { return } destination?.setPrimary(jsonable: post) if post.content.count > 0 || post.repostContent.count > 0 { let postItems = parse(jsonables: [post]) destination?.replacePlaceholder(type: .postHeader, items: postItems) doneOperation.run() } } func loadPost(_ doneOperation: AsyncOperation, reload: Bool) { guard !doneOperation.isFinished || reload else { return } let username = post?.author?.username API().postDetail(token: .fromParam(postParam), username: username) .execute() .done { post in guard self.loadingToken.isValidInitialPageLoadingToken(self.localToken) else { return } self.post = post self.destination?.setPrimary(jsonable: post) let postItems = self.parse(jsonables: [post]) self.destination?.replacePlaceholder(type: .postHeader, items: postItems) doneOperation.run() } .ignoreErrors() } func displayCommentBar(_ doneOperation: AsyncOperation) { let displayCommentBarOperation = AsyncOperation() displayCommentBarOperation.addDependency(doneOperation) queue.addOperation(displayCommentBarOperation) displayCommentBarOperation.run { guard let post = self.post else { return } let commentingEnabled = post.author?.hasCommentingEnabled ?? true guard let currentUser = self.currentUser, commentingEnabled else { return } let barItems = [ StreamCellItem( jsonable: ElloComment.newCommentForPost(post, currentUser: currentUser), type: .createComment ) ] inForeground { self.destination?.replacePlaceholder(type: .postCommentBar, items: barItems) } } } func displaySocialPadding() { let padding = PostDetailGenerator.socialPadding() destination?.replacePlaceholder(type: .postSocialPadding, items: padding) } func loadMoreCommentItems(lastComment: ElloComment?, pageConfig: PageConfig) -> [StreamCellItem] { if pageConfig.next != nil, let lastComment = lastComment { return [StreamCellItem(jsonable: lastComment, type: .loadMoreComments)] } else { return [] } } func loadPostComments(_ doneOperation: AsyncOperation) { guard loadingToken.isValidInitialPageLoadingToken(localToken) else { return } let displayCommentsOperation = AsyncOperation() displayCommentsOperation.addDependency(doneOperation) queue.addOperation(displayCommentsOperation) API().postComments(postToken: .fromParam(postParam)) .execute() .done { pageConfig, comments in guard self.loadingToken.isValidInitialPageLoadingToken(self.localToken) else { return } self.before = pageConfig.next let commentItems = self.parse(jsonables: comments) displayCommentsOperation.run { inForeground { self.destination?.replacePlaceholder( type: .postComments, items: commentItems ) if let lastComment = comments.last { let loadMoreComments = self.loadMoreCommentItems( lastComment: lastComment, pageConfig: pageConfig ) self.destination?.replacePlaceholder( type: .postLoadingComments, items: loadMoreComments ) } } } } .ignoreErrors() } func loadPostLovers(_ doneOperation: AsyncOperation) { guard loadingToken.isValidInitialPageLoadingToken(localToken) else { return } let displayLoversOperation = AsyncOperation() displayLoversOperation.addDependency(doneOperation) queue.addOperation(displayLoversOperation) PostService().loadPostLovers(postParam) .done { users in guard self.loadingToken.isValidInitialPageLoadingToken(self.localToken) else { return } guard users.count > 0 else { return } let loversItems = PostDetailGenerator.userAvatarCellItems( users: users, postParam: self.postParam, type: .lovers ) displayLoversOperation.run { inForeground { self.displaySocialPadding() self.destination?.replacePlaceholder(type: .postLovers, items: loversItems) } } } .ignoreErrors() } func loadPostReposters(_ doneOperation: AsyncOperation) { guard loadingToken.isValidInitialPageLoadingToken(localToken) else { return } let displayRepostersOperation = AsyncOperation() displayRepostersOperation.addDependency(doneOperation) queue.addOperation(displayRepostersOperation) PostService().loadPostReposters(postParam) .done { users in guard self.loadingToken.isValidInitialPageLoadingToken(self.localToken) else { return } guard users.count > 0 else { return } let repostersItems = PostDetailGenerator.userAvatarCellItems( users: users, postParam: self.postParam, type: .reposters ) displayRepostersOperation.run { inForeground { self.displaySocialPadding() self.destination?.replacePlaceholder( type: .postReposters, items: repostersItems ) } } } .ignoreErrors() } func loadRelatedPosts(_ doneOperation: AsyncOperation) { guard loadingToken.isValidInitialPageLoadingToken(localToken) else { return } let displayRelatedPostsOperation = AsyncOperation() displayRelatedPostsOperation.addDependency(doneOperation) queue.addOperation(displayRelatedPostsOperation) PostService().loadRelatedPosts(postParam) .done { relatedPosts in guard self.loadingToken.isValidInitialPageLoadingToken(self.localToken) else { return } guard relatedPosts.count > 0 else { return } let header = NSAttributedString( label: InterfaceString.Post.RelatedPosts, style: .largeGrayHeader ) let headerCellItem = StreamCellItem(type: .tallHeader(header)) let postItems = self.parse(jsonables: relatedPosts, forceGrid: true) let relatedPostItems = [headerCellItem] + postItems displayRelatedPostsOperation.run { inForeground { self.destination?.replacePlaceholder( type: .postRelatedPosts, items: relatedPostItems ) } } } .ignoreErrors() } }
mit
699d164b46f36da8842addd6c2c4774c
35.383481
100
0.577834
5.491541
false
false
false
false
ello/ello-ios
Sources/Controllers/Notifications/NotificationCell.swift
1
14346
//// /// NotificationCell.swift // import PINRemoteImage import TimeAgoInWords @objc protocol NotificationResponder: class { func userTapped(_ user: User) func userTapped(userId: String) func postTapped(_ post: Post) func commentTapped(_ comment: ElloComment) func artistInviteTapped(_ artistInvite: ArtistInvite) func categoryTapped(_ category: Category) func categoryTapped(slug: String, name: String) func urlTapped(title: String, url: URL) } enum NotificationCellMode { case image case normal var hasImage: Bool { switch self { case .normal: return false default: return true } } } class NotificationCell: UICollectionViewCell, UIWebViewDelegate { static let reuseIdentifier = "NotificationCell" var mode: NotificationCellMode = .normal struct Size { static let BuyButtonSize: CGFloat = 15 static let BuyButtonMargin: CGFloat = 5 static let ButtonHeight: CGFloat = 30 static let ButtonMargin: CGFloat = 15 static let WebHeightCorrection: CGFloat = -10 static let SideMargins: CGFloat = 15 static let ImageWidth: CGFloat = 87 static let InnerMargin: CGFloat = 10 static let MessageMargin: CGFloat = 0 static let CreatedAtHeight: CGFloat = 12 // height of created at and margin from title / notification text static let CreatedAtFixedHeight = CreatedAtHeight + InnerMargin static func messageHtmlWidth(forCellWidth cellWidth: CGFloat, hasImage: Bool) -> CGFloat { let messageLeftMargin: CGFloat = SideMargins + AvatarButton.Size.smallSize.width + InnerMargin var messageRightMargin: CGFloat = SideMargins if hasImage { messageRightMargin += InnerMargin + ImageWidth } return cellWidth - messageLeftMargin - messageRightMargin } static func imageHeight(imageRegion: ImageRegion?) -> CGFloat { if let imageRegion = imageRegion { let aspectRatio = StreamImageCellSizeCalculator.aspectRatioForImageRegion( imageRegion ) return ceil(ImageWidth / aspectRatio) } else { return 0 } } } typealias WebContentReady = (_ webView: UIWebView) -> Void var webContentReady: WebContentReady? var onHeightMismatch: OnHeightMismatch? let avatarButton = AvatarButton() let buyButtonImage = UIImageView() let replyButton = StyledButton(style: .blackPillOutline) let relationshipControl = RelationshipControl() let titleTextView = ElloTextView() let createdAtLabel = UILabel() let messageWebView = ElloWebView() let notificationImageView = PINAnimatedImageView() let separator = UIView() var aspectRatio: CGFloat = 4 / 3 var canReplyToComment: Bool { set { replyButton.isVisible = newValue setNeedsLayout() } get { return !replyButton.isHidden } } var canBackFollow: Bool { set { relationshipControl.isVisible = newValue setNeedsLayout() } get { return !relationshipControl.isHidden } } var buyButtonVisible: Bool { get { return !buyButtonImage.isHidden } set { buyButtonImage.isVisible = newValue } } private var messageVisible = false private var _messageHtml = "" var messageHeight: CGFloat = 0 var messageHtml: String? { get { return _messageHtml } set { if let value = newValue { messageVisible = true if value != _messageHtml { messageWebView.isHidden = true } else { messageWebView.isVisible = true } messageWebView.loadHTMLString( StreamTextCellHTML.postHTML(value), baseURL: URL(string: "/") ) _messageHtml = value } else { messageWebView.isHidden = true messageVisible = false } } } var imageURL: URL? { didSet { guard imageURL != nil else { notificationImageView.isHidden = true return } notificationImageView.isVisible = true self.notificationImageView.pin_setImage(from: imageURL) { [weak self] result in guard let `self` = self, result.hasImage else { return } if let imageSize = result.imageSize { self.aspectRatio = imageSize.width / imageSize.height } let currentRatio = self.notificationImageView.frame.width / self.notificationImageView.frame.height if currentRatio != self.aspectRatio { self.setNeedsLayout() } } self.setNeedsLayout() } } var title: NSAttributedString? { didSet { titleTextView.attributedText = title } } var createdAt: Date? { didSet { if let date = createdAt { createdAtLabel.text = date.timeAgoInWords() } else { createdAtLabel.text = "" } } } var user: User? { didSet { setUser(user) } } var post: Post? var comment: ElloComment? var submission: ArtistInviteSubmission? override init(frame: CGRect) { super.init(frame: frame) avatarButton.addTarget(self, action: #selector(avatarTapped), for: .touchUpInside) titleTextView.textViewDelegate = self buyButtonImage.isHidden = true buyButtonImage.interfaceImage = .buyButton buyButtonImage.frame.size = CGSize(width: Size.BuyButtonSize, height: Size.BuyButtonSize) buyButtonImage.backgroundColor = .greenD1 buyButtonImage.layer.cornerRadius = Size.BuyButtonSize / 2 replyButton.isHidden = true replyButton.title = InterfaceString.Notifications.Reply replyButton.setImage(InterfaceImage.reply.selectedImage, for: .normal) replyButton.contentEdgeInsets.left = 10 replyButton.contentEdgeInsets.right = 10 replyButton.imageEdgeInsets.right = 5 replyButton.addTarget(self, action: #selector(replyTapped), for: .touchUpInside) relationshipControl.isHidden = true notificationImageView.contentMode = .scaleAspectFit messageWebView.scrollView.isScrollEnabled = false messageWebView.delegate = self createdAtLabel.textColor = UIColor.greyA createdAtLabel.font = UIFont.defaultFont(12) createdAtLabel.text = "" separator.backgroundColor = .greyE5 for view in [ avatarButton, titleTextView, messageWebView, notificationImageView, buyButtonImage, createdAtLabel, replyButton, relationshipControl, separator ] { self.contentView.addSubview(view) } } required init?(coder: NSCoder) { super.init(coder: coder) } func onWebContentReady(_ handler: WebContentReady?) { webContentReady = handler } private func setUser(_ user: User?) { avatarButton.setUserAvatarURL(user?.avatarURL()) if let user = user { relationshipControl.userId = user.id relationshipControl.userAtName = user.atName relationshipControl.relationshipPriority = user.relationshipPriority } else { relationshipControl.userId = "" relationshipControl.userAtName = "" relationshipControl.relationshipPriority = .none } } override func layoutSubviews() { super.layoutSubviews() let outerFrame = contentView.bounds.inset(all: Size.SideMargins) let titleWidth = Size.messageHtmlWidth( forCellWidth: self.frame.width, hasImage: mode.hasImage ) separator.frame = contentView.bounds.fromBottom().grow(up: 1) avatarButton.frame = outerFrame.with(size: AvatarButton.Size.smallSize) notificationImageView.frame = outerFrame.fromRight() .grow(left: Size.ImageWidth) .with(height: Size.ImageWidth / aspectRatio) buyButtonImage.frame.origin = CGPoint( x: notificationImageView.frame.maxX - Size.BuyButtonSize - Size.BuyButtonMargin, y: notificationImageView.frame.minY + Size.BuyButtonMargin ) titleTextView.frame = avatarButton.frame.fromRight() .shift(right: Size.InnerMargin) .with(width: titleWidth) let tvSize = titleTextView.sizeThatFits( CGSize(width: titleWidth, height: .greatestFiniteMagnitude) ) titleTextView.frame.size.height = ceil(tvSize.height) var createdAtY = titleTextView.frame.maxY + Size.InnerMargin if messageVisible { createdAtY += messageHeight + Size.MessageMargin messageWebView.frame = titleTextView.frame.fromBottom() .with(width: titleWidth) .shift(down: Size.InnerMargin) .with(height: messageHeight) } createdAtLabel.frame = CGRect( x: avatarButton.frame.maxX + Size.InnerMargin, y: createdAtY, width: titleWidth, height: Size.CreatedAtHeight ) let replyButtonWidth = replyButton.intrinsicContentSize.width replyButton.frame = CGRect( x: createdAtLabel.frame.x, y: createdAtY + Size.CreatedAtHeight + Size.InnerMargin, width: replyButtonWidth, height: Size.ButtonHeight ) let relationshipControlWidth = relationshipControl.intrinsicContentSize.width relationshipControl.frame = replyButton.frame.with(width: relationshipControlWidth) let bottomControl: UIView if !replyButton.isHidden { bottomControl = replyButton } else if !relationshipControl.isHidden { bottomControl = relationshipControl } else { bottomControl = createdAtLabel } let imageMaxY = mode.hasImage ? notificationImageView.frame.maxY : 0 let actualHeight = ceil(max(imageMaxY, bottomControl.frame.maxY)) + Size.SideMargins // don't update the height if // - imageURL is set, but hasn't finished loading, OR // - messageHTML is set, but hasn't finished loading if actualHeight != ceil(frame.size.height) && (imageURL == nil || notificationImageView.image != nil) && (!messageVisible || !messageWebView.isHidden) { self.onHeightMismatch?(actualHeight) } } override func prepareForReuse() { super.prepareForReuse() mode = .normal messageWebView.stopLoading() messageWebView.isHidden = true avatarButton.pin_cancelImageDownload() avatarButton.setImage(nil, for: .normal) notificationImageView.pin_cancelImageDownload() notificationImageView.image = nil aspectRatio = 4 / 3 canReplyToComment = false canBackFollow = false imageURL = nil buyButtonImage.isHidden = true } func webView( _ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType ) -> Bool { if let scheme = request.url?.scheme, scheme == "default" { let responder: StreamCellResponder? = findResponder() responder?.streamCellTapped(cell: self) return false } else { return ElloWebViewHelper.handle(request: request, origin: self) } } func webViewDidFinishLoad(_ webView: UIWebView) { if messageVisible { messageWebView.isVisible = messageVisible } webContentReady?(webView) if let height = webView.windowContentSize()?.height { messageHeight = height } else { messageHeight = 0 } setNeedsLayout() } } extension NotificationCell: ElloTextViewDelegate { func textViewTapped(_ link: String, object: ElloAttributedObject) { guard let responder:NotificationResponder = findResponder() else { return } switch object { case let .attributedUser(user): responder.userTapped(user) case let .attributedUserId(userId): responder.userTapped(userId: userId) case let .attributedPost(post): responder.postTapped(post) case let .attributedComment(comment): responder.commentTapped(comment) case let .attributedArtistInvite(artistInvite): responder.artistInviteTapped(artistInvite) case let .attributedCategory(category): responder.categoryTapped(category) case let .attributedCategoryPartial(partial): responder.categoryTapped(slug: partial.slug, name: partial.name) case let .attributedURL(title, url): responder.urlTapped(title: title, url: url) case .unknown: break } } func textViewTappedDefault() { let responder: StreamCellResponder? = findResponder() responder?.streamCellTapped(cell: self) } } extension NotificationCell { @objc func replyTapped() { guard let responder:NotificationResponder = findResponder() else { return } if let post = post { responder.postTapped(post) } else if let comment = comment { responder.commentTapped(comment) } } @objc func avatarTapped() { if submission != nil { let responder: StreamCellResponder? = findResponder() responder?.streamCellTapped(cell: self) } else { let responder: UserResponder? = findResponder() responder?.userTappedAuthor(cell: self) } } }
mit
cb3ec419d233a7baabdac5e544eb1852
31.90367
98
0.610135
5.224326
false
false
false
false
IMcD23/Proton
Source/Core/View/View.swift
1
3642
// // View.swift // Proton // // Created by McDowell, Ian J [ITACD] on 3/25/16. // Copyright © 2016 Ian McDowell. All rights reserved. // /// Protocol that is implemented by every view in Proton. /// This is used as the return type of the `layout` methods. public protocol ProtonView { func getView() -> UIView } internal struct LayoutPosition { enum LayoutPositionType { case None, Percent, Absolute } init() {} init(type: LayoutPositionType, top: CGFloat?, bottom: CGFloat?, left: CGFloat?, right: CGFloat?) { self.type = type self.top = top self.bottom = bottom self.left = left self.right = right } var type: LayoutPositionType = .None var top: CGFloat? = nil var bottom: CGFloat? = nil var left: CGFloat? = nil var right: CGFloat? = nil var cX = false var cY = false internal mutating func centerX() { cX = true left = nil right = nil } internal mutating func centerY() { cY = true top = nil bottom = nil } } internal struct LayoutSize { enum LayoutSizeType { case None, Percent, Fixed } var type: LayoutSizeType var width: CGFloat? = nil var height: CGFloat? = nil } internal protocol AbsoluteLayoutView { var position: LayoutPosition {get} var size: LayoutSize {get} } /// Base class of View, which is a holder for a `UIView`. All other Proton views /// are subclasses of this. public class View<T: AnyObject>: ProtonView, AbsoluteLayoutView { var view: T! // internal internal var clickHandler = Handler() internal var position = LayoutPosition() internal var size = LayoutSize(type: .None, width: nil, height: nil) // private #if os(iOS) private var tapGestureRecognizer: UITapGestureRecognizer? #endif public init() { // super.init() } internal init(view: T) { // super.init() self.view = view } // MARK: Construct public func construct(fn: (view: T) -> Void) -> Self { fn(view: view) return self } // MARK: tapped #if os(iOS) public func onTap(fn: () -> Void) -> Self { self.clickHandler.action = fn self.tapGestureRecognizer = UITapGestureRecognizer(target: self.clickHandler, action: #selector(self.clickHandler.handleAction)) self.view.addGestureRecognizer(self.tapGestureRecognizer!) self.view.userInteractionEnabled = true return self } #endif // MARK: assign public func assign(inout a: T!) -> Self { a = view return self } public func assign(inout a: T) -> Self { a = view return self } // MARK: Statics public static func construct(fn: (view: T) -> Void) -> View { return View<T>().construct(fn) } public static func assign(inout a: T!) -> View { return View<T>().assign(&a) } public static func assign(inout a: T) -> View { return View<T>().assign(&a) } // MARK: ProtonView public func getView() -> UIView { #if os(OSX) if let v = self.view as? BridgedNSView { return UIView(existingValue: v.getView() as! NSView)! } fatalError() #elseif os(iOS) return self.view as! UIView #endif } } internal class Handler: NSObject { var action: (() -> Void)? @objc func handleAction() { action?() } }
mit
f27361aa3d49ea5ec72951ee1bdfbc8a
22.197452
136
0.570173
4.24359
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/23274-swift-typechecker-typecheckexpression.swift
11
1105
// 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 P{ func a< {Void{ protocol A class b<T where T A { typealias e : Ini: T> ss B<T - B { class a{ }} func b: protocol P{{b< c j> : {class d<T where f: = " func a<H : A }{ func f let i: A:a }protocol c:BooleanType func a< : func a B : (a< = c j:i: = [B<T where j: A protocol e : = " struct c: var b = "" func f: {Void{ var b { }} class a< { class B func < c j: A struct A : {{} struct c<T where j: e protocol B protocol B<T where j: (a<T where h: }}funi: P { ( " " fu{} protocol A { : {{ : A: func f: Int = class b struct A { struct A {func a< = Swift.a< : a { protocol e { func a<T= struct B : a { b {class}{{ init(a<T where j> {{ class B class b:a< { < { func b< < = " struct d { struct d { class B class d<T where T where h:BooleanType struct B { { class B extension NSData {{class}}} if true{ class B : = [B < c j: {init( ) {{ struct A { class B enum S<f { class a<T where j: A.dynamicType){ init( " "" { class a{ struct c<f {
mit
1cc13cb2b4b53b3ebcf7b20219136d56
14.136986
87
0.611765
2.505669
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/DesignMode/DesignMode/Decorate(装饰)/DecorateMode.swift
1
1333
// // DecorateMode.swift // DesignMode // // Created by wuyp on 2017/9/11. // Copyright © 2017年 Raymond. All rights reserved. // import Foundation class Component { //抽象 func operation() { } } class ConcreteComponent: Component { //具体 override func operation() { print("通用操作...") } } class Decorate: Component { //附加修饰 var component: Component? func setComponent(component: Component?) { self.component = component } override func operation() { if let component = self.component { component.operation() } } } class ConcreteComponentA: Decorate { override func operation() { super.operation() print("A对象附加操作....") } } class ConcreteComponentB: Decorate { override func operation() { super.operation() print("B对象附加操作....") } } //MARK: 客户端测试代码 fileprivate class DecorateTest { class func test() { let base: ConcreteComponent = ConcreteComponent() let a: ConcreteComponentA = ConcreteComponentA() let b: ConcreteComponentB = ConcreteComponentB() a.setComponent(component: base) b.setComponent(component: a) b.operation() } }
apache-2.0
ed1b8c37bd550febf37b78043ea66f13
18.212121
57
0.59306
4.090323
false
false
false
false
parkera/swift
test/Generics/unify_nested_types_1.swift
2
725
// RUN: %target-typecheck-verify-swift -requirement-machine=verify -debug-requirement-machine 2>&1 | %FileCheck %s protocol P1 { associatedtype T : P1 } protocol P2 { associatedtype T where T == Int } extension Int : P1 { public typealias T = Int } struct G<T : P1 & P2> {} // Since G.T.T == G.T.T.T == G.T.T.T.T = ... = Int, we tie off the // recursion by introducing a same-type requirement G.T.T => G.T. // CHECK-LABEL: Adding generic signature <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> { // CHECK-LABEL: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:T].[concrete: Int] => τ_0_0.[P1&P2:T] // CHECK: - [P1&P2:T].T => [P1&P2:T].[P1:T] // CHECK: - τ_0_0.[P1&P2:T].[P1:T] => τ_0_0.[P1&P2:T] // CHECK: } // CHECK: }
apache-2.0
a64ebe29b8f834996d4532faa602338b
26.615385
114
0.598886
2.316129
false
false
false
false
S7Vyto/TouchVK
TouchVK/TouchVK/Extensions/UIViewController+Extensions.swift
1
1476
// // UIViewController+Extensions.swift // TouchVK // // Created by Sam on 19/02/2017. // Copyright © 2017 Semyon Vyatkin. All rights reserved. // import Foundation import UIKit extension UIViewController { var indicatorTag: Int { return 100100 } var indicator: UIActivityIndicatorView { let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white) indicator.color = UIColor.rgb(74.0, 137.0, 220.0) indicator.hidesWhenStopped = true indicator.translatesAutoresizingMaskIntoConstraints = false indicator.tag = self.indicatorTag return indicator } var indicatorView: UIActivityIndicatorView { guard let view = self.view.viewWithTag(self.indicatorTag) as? UIActivityIndicatorView else { let view = indicator self.view.addSubview(view) self.view.bringSubview(toFront: view) self.view.addConstraints( [NSLayoutConstraint.centerX(for: view, to: self.view), NSLayoutConstraint.centerY(for: view, to: self.view)] ) return view } return view } var childController: UIViewController? { if self is UINavigationController { return (self as! UINavigationController).visibleViewController } else { return self } } }
apache-2.0
fba0b54bf18f15f8d6aa842f8b16e968
26.830189
100
0.601356
5.344203
false
false
false
false
reproto/reproto
it/structures/swift/default_naming-simple/LowerCamel.swift
1
583
public struct LowerCamel_Value { let foo_bar: String } public extension LowerCamel_Value { static func decode(json: Any) throws -> LowerCamel_Value { let json = try decode_value(json as? [String: Any]) guard let f_foo_bar = json["fooBar"] else { throw SerializationError.missing("fooBar") } let foo_bar = try decode_name(unbox(f_foo_bar, as: String.self), name: "fooBar") return LowerCamel_Value(foo_bar: foo_bar) } func encode() throws -> [String: Any] { var json = [String: Any]() json["fooBar"] = self.foo_bar return json } }
apache-2.0
f3adc8cf4932e857dff2743299b0efa9
23.291667
84
0.646655
3.429412
false
false
false
false
limsangjin12/Hero
Sources/Extensions/CAMediaTimingFunction+Hero.swift
5
2474
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // 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 internal extension CAMediaTimingFunction { // default static let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) static let easeIn = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) static let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) static let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // material static let standard = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0) static let deceleration = CAMediaTimingFunction(controlPoints: 0.0, 0.0, 0.2, 1) static let acceleration = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 1, 1) static let sharp = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.6, 1) // easing.net static let easeOutBack = CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275) static func from(name: String) -> CAMediaTimingFunction? { switch name { case "linear": return .linear case "easeIn": return .easeIn case "easeOut": return .easeOut case "easeInOut": return .easeInOut case "standard": return .standard case "deceleration": return .deceleration case "acceleration": return .acceleration case "sharp": return .sharp default: return nil } } }
mit
bc53170d09d71ab8dd7921cbc04e897b
38.269841
90
0.735247
4.589981
false
false
false
false
omiz/In-Air
In Air/Source/Router.swift
1
1213
// // Router.swift // In Air // // Created by Omar Allaham on 3/30/17. // Copyright © 2017 Bemaxnet. All rights reserved. // import UIKit class Router { static func launch(in window: UIWindow?, with options: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //if an animation needed check window.rootViewController // let firstStart = UserDefaults.standard.isFirstStart // let controller = firstStart ? IntroViewController.instance : MainViewController.instance set(UINavigationController(rootViewController: MainViewController.instance)) PlayerView.shared.prepare() return true } static func set(_ distination: UIViewController, with sourceViewContoller: UIViewController? = nil, in window: UIWindow? = nil) { let window = window ?? AppDelegate.shared.window let sourceViewContoller = sourceViewContoller ?? window?.rootViewController distination.view.alpha = 0 UIView.animate(withDuration: 0.2) { sourceViewContoller?.view.alpha = 0 distination.view.alpha = 1 window?.rootViewController = distination window?.makeKeyAndVisible() } } }
apache-2.0
63cd8ade6c232b688ef763cc0cd5f8ff
25.933333
106
0.670792
4.771654
false
false
false
false
prasanth223344/celapp
Cgrams/Controllers/ProfileImageViewController.swift
1
4302
// // ViewController.swift // SmoothScribble // // Created by Simon Gladman on 04/11/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // import UIKit import KeychainSwift import Alamofire import Photos import SVProgressHUD class ProfileImageViewController: UIViewController { let stackView = UIStackView() var image: UIImage? let keychain = KeychainSwift() @IBOutlet var topHomePrev: UIView! @IBOutlet weak var topView: UIView! @IBOutlet weak var bottomView: UIView! @IBOutlet var viewContainer: UIView! var screenSize: CGRect = UIScreen.main.bounds @IBOutlet var scrollView: UIScrollView! @IBOutlet var imgView: UIImageView! @IBOutlet var viewSubmit: UIView! @IBOutlet weak var btnClose: UIButton! @IBOutlet weak var viewFilter: UIView! @IBAction func saveAs(_ sender: AnyObject) { UIGraphicsBeginImageContextWithOptions(viewContainer.bounds.size, viewContainer.isOpaque, 0.0) viewContainer!.drawHierarchy(in: viewContainer.bounds, afterScreenUpdates: false) let snapshotImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // define parameters let parameters = [ "token": Constants.Server.TOKEN ] SVProgressHUD.show(withStatus: "Please wait...") let keychain = KeychainSwift() let url = Constants.Server.PROFILE_URL + "/" + keychain.get(Constants.KeyChain.CID)! CGWebService.sharedInstance().uploadProfilePicture(url: url, Image: snapshotImage!, Params: parameters, onProgress: { (progress) in SVProgressHUD.showProgress(Float(progress!), status: "Uploading profile...") }) { (error) in if let error = error { SVProgressHUD.showError(withStatus: error) } else { SVProgressHUD.dismiss() self.onClickBtnClose(self.btnClose) } } } override func viewDidLoad() { super.viewDidLoad() navigationController?.interactivePopGestureRecognizer?.isEnabled = false // update back button color let imgClose = btnClose.image(for: .normal) btnClose.setImage(imgClose?.withRenderingMode(.alwaysTemplate), for: .normal) btnClose.tintColor = UIColor.white scrollView.isScrollEnabled = false imgView.image = image viewContainer.addSubview(stackView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.setStatusBarHidden(true, with: .none) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imgView } @IBAction func onClickBtnClose(_ sender: Any) { navigationController!.popToRootViewController(animated: true) } override var prefersStatusBarHidden: Bool { return true } func mergedImageWith(frontImage:UIImage?, backgroundImage: UIImage?) -> UIImage{ if (backgroundImage == nil) { return frontImage! } let size = CGSize(width: (backgroundImage?.size.width)!, height: (backgroundImage?.size.height)!) // let fsize = CGSize(width: (screenSize.height), height: (screenSize.width)) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) backgroundImage?.draw(in: CGRect.init(x: 0, y: 0, width: size.width , height: size.height )) frontImage?.draw(in: CGRect.init(x: 0, y: 0, width: size.width , height: size.height ).insetBy(dx: 0, dy: 0)) let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } }
mit
09bc936653a48bd98cedc4e444eac982
28.258503
128
0.592653
5.636959
false
false
false
false
dilizarov/realm-cocoa
RealmSwift-swift2.0/Object.swift
13
10030
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** In Realm you define your model classes by subclassing `Object` and adding properties to be persisted. You then instantiate and use your custom subclasses instead of using the Object class directly. ```swift class Dog: Object { dynamic var name: String = "" dynamic var adopted: Bool = false let siblings = List<Dog> } ``` ### Supported property types - `String` - `Int` - `Float` - `Double` - `Bool` - `NSDate` - `NSData` - `Object` subclasses for to-one relationships - `List<T: Object>` for to-many relationships ### Querying You can gets `Results` of an Object subclass via tha `objects(_:)` free function or the `objects(_:)` instance method on `Realm`. ### Relationships See our [Cocoa guide](http://realm.io/docs/cocoa) for more details. */ public class Object: RLMObjectBase { // MARK: Initializers /** Initialize a standalone (unpersisted) Object. Call `add(_:)` on a `Realm` to add standalone objects to a realm. - see: Realm().add(_:) */ public required override init() { super.init() } /** Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`. Call `add(_:)` on a `Realm` to add standalone objects to a realm. - parameter value: The value used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. */ public init(value: AnyObject) { self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema super.init(value: value, schema: RLMSchema.partialSharedSchema()) } // MARK: Properties /// The `Realm` this object belongs to, or `nil` if the object /// does not belong to a realm (the object is standalone). public var realm: Realm? { if let rlmReam = RLMObjectBaseRealm(self) { return Realm(rlmReam) } return nil } /// The `ObjectSchema` which lists the persisted properties for this object. public var objectSchema: ObjectSchema { return ObjectSchema(RLMObjectBaseObjectSchema(self)) } /// Indicates if an object can no longer be accessed. public override var invalidated: Bool { return super.invalidated } /// Returns a human-readable description of this object. public override var description: String { return super.description } #if os(OSX) /// Helper to return the class name for an Object subclass. public final override var className: String { return "" } #else /// Helper to return the class name for an Object subclass. public final var className: String { return "" } #endif // MARK: Object Customization /** Override to designate a property as the primary key for an `Object` subclass. Only properties of type String and Int can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set which incurs some overhead. Indexes are created automatically for primary key properties. - returns: Name of the property designated as the primary key, or `nil` if the model has no primary key. */ public class func primaryKey() -> String? { return nil } /** Override to return an array of property names to ignore. These properties will not be persisted and are treated as transient. - returns: `Array` of property names to ignore. */ public class func ignoredProperties() -> [String] { return [] } /** Return an array of property names for properties which should be indexed. Only supported for string and int properties. - returns: `Array` of property names to index. */ public class func indexedProperties() -> [String] { return [] } // MARK: Inverse Relationships /** Get an `Array` of objects of type `className` which have this object as the given property value. This can be used to get the inverse relationship value for `Object` and `List` properties. - parameter className: The type of object on which the relationship to query is defined. - parameter property: The name of the property which defines the relationship. - returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property. */ public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] { // FIXME: use T.className() return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T] } // MARK: Key-Value Coding & Subscripting /// Returns or sets the value of the property with the given name. public subscript(key: String) -> AnyObject? { get { if realm == nil { return self.valueForKey(key) } let property = RLMValidatedGetProperty(self, key) if property.type == .Array { return self.listForProperty(property) } return RLMDynamicGet(self, property) } set(value) { if realm == nil { self.setValue(value, forKey: key) } else { RLMDynamicValidatedSet(self, key, value) } } } // MARK: Equatable /// Returns whether both objects are equal. /// Objects are considered equal when they are both from the same Realm /// and point to the same underlying object in the database. public override func isEqual(object: AnyObject?) -> Bool { return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase); } // MARK: Private functions // FIXME: None of these functions should be exposed in the public interface. /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) } // Helper for getting the list object for a property internal func listForProperty(prop: RLMProperty) -> RLMListBase { return object_getIvar(self, prop.swiftListIvar) as! RLMListBase } } /// Object interface which allows untyped getters and setters for Objects. /// :nodoc: public final class DynamicObject : Object { private var listProperties = [String: List<DynamicObject>]() // Override to create List<DynamicObject> on access internal override func listForProperty(prop: RLMProperty) -> RLMListBase { if let list = listProperties[prop.name] { return list } let list = List<DynamicObject>() listProperties[prop.name] = list return list } /// :nodoc: public override func valueForUndefinedKey(key: String) -> AnyObject? { return self[key] } /// :nodoc: public override func setValue(value: AnyObject?, forUndefinedKey key: String) { self[key] = value } /// :nodoc: public override class func shouldIncludeInDefaultSchema() -> Bool { return false; } } /// :nodoc: /// Internal class. Do not use directly. public class ObjectUtil: NSObject { @objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.ignoredProperties() as NSArray? } return nil } @objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.indexedProperties() as NSArray? } return nil } // Get the names of all properties in the object which are of type List<>. @objc private class func getGenericListPropertyNames(object: AnyObject) -> NSArray { return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in return prop.value.dynamicType is RLMListBase.Type }.flatMap { (prop: Mirror.Child) in return prop.label } } @objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) { (object as! Object).listForProperty(property)._rlmArray = array } @objc private class func getOptionalPropertyNames(object: AnyObject) -> NSArray { return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in return Mirror(reflecting: prop.value).displayStyle == .Optional }.flatMap { (prop: Mirror.Child) in return prop.label } } @objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? { return nil } }
apache-2.0
8bff8a4ba8d02c6477f5638ede623230
33.232082
127
0.652542
4.726673
false
false
false
false
viviancrs/fanboy
FanBoy/Source/Business/Group/GroupBusiness.swift
1
1400
// // ItemBusiness.swift // FanBoy // // Created by Vivian Cristhine da Rosa Soares on 16/07/17. // Copyright © 2017 CI&T. All rights reserved. // import Foundation struct GroupBusiness { var provider: GroupServiceSessionProtocol = GroupServiceSession() /** Get list of Item objects - parameter completion: person list or an error */ func getGroup(completion: @escaping GroupResultCallback) { let results = DatabaseProvider.sharedProvider.fetchAll(Group.self) if results.count > 0 { completion { Array(results) } return } provider.getGroup { (result) in do { guard let groupResult = try result() else { return } var groups = [Group]() for key in groupResult.keys { if let value = groupResult[key] as? String { let group = Group() group.name = key.normalize() group.url = value groups.append(group) } } try DatabaseProvider.sharedProvider.save(objects: groups, update: true) completion { groups } } catch let error { completion { throw error } } } } }
gpl-3.0
8525a4b45751258fa7518ac935693992
28.145833
87
0.503931
5.124542
false
false
false
false
sergdort/CleanArchitectureRxSwift
CoreDataPlatform/Repository/Repository.swift
1
1470
import Foundation import CoreData import RxSwift import QueryKit protocol AbstractRepository { associatedtype T func query(with predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?) -> Observable<[T]> func save(entity: T) -> Observable<Void> func delete(entity: T) -> Observable<Void> } final class Repository<T: CoreDataRepresentable>: AbstractRepository where T == T.CoreDataType.DomainType { private let context: NSManagedObjectContext private let scheduler: ContextScheduler init(context: NSManagedObjectContext) { self.context = context self.scheduler = ContextScheduler(context: context) } func query(with predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> Observable<[T]> { let request = T.CoreDataType.fetchRequest() request.predicate = predicate request.sortDescriptors = sortDescriptors return context.rx.entities(fetchRequest: request) .mapToDomain() .subscribe(on: scheduler) } func save(entity: T) -> Observable<Void> { return entity.sync(in: context) .mapToVoid() .flatMapLatest(context.rx.save) .subscribe(on: scheduler) } func delete(entity: T) -> Observable<Void> { return entity.sync(in: context) .map({$0 as! NSManagedObject}) .flatMapLatest(context.rx.delete) } }
mit
458186bdddb5da7962603ec66c8385a3
30.956522
107
0.64966
4.772727
false
false
false
false
edx/edx-app-ios
Source/CourseUnknownBlockViewController.swift
1
10533
// // CourseUnknownBlockViewController.swift // edX // // Created by Ehmad Zubair Chughtai on 20/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class CourseUnknownBlockViewController: UIViewController, CourseBlockViewController { typealias Environment = DataManagerProvider & OEXInterfaceProvider & OEXAnalyticsProvider & OEXConfigProvider & OEXStylesProvider & OEXRouterProvider & DataManagerProvider & RemoteConfigProvider & ReachabilityProvider & NetworkManagerProvider private let environment: Environment let blockID: CourseBlockID? let courseID: String var block: CourseBlock? { didSet { navigationItem.title = block?.displayName } } private var messageView: IconMessageView? private lazy var valuePropView: ValuePropComponentView = { let view = ValuePropComponentView(environment: environment, courseID: courseID, blockID: blockID) view.delegate = self return view }() private var loader: OEXStream<URL?>? init(blockID: CourseBlockID?, courseID: String, environment: Environment) { self.blockID = blockID self.courseID = courseID self.environment = environment super.init(nibName: nil, bundle: nil) let courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: self.courseID, environment: environment) courseQuerier.blockWithID(id: blockID).extendLifetimeUntilFirstResult ( success: { [weak self] block in self?.block = block if let video = block.type.asVideo, video.isYoutubeVideo { self?.showYoutubeMessage(buttonTitle: Strings.Video.viewOnYoutube, message: Strings.Video.onlyOnYoutube, icon: Icon.CourseVideos, videoUrl: video.videoURL) } else { self?.showError() } }, failure: { [weak self] _ in self?.showError() } ) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = environment.styles.standardBackgroundColor() } override func updateViewConstraints() { if isVerticallyCompact() { applyLandscapeConstraints() } else { applyPortraitConstraints() } super.updateViewConstraints() } private func showYoutubeMessage(buttonTitle: String, message: String, icon: Icon, videoUrl: String?) { messageView = IconMessageView(icon: icon, message: message) messageView?.buttonInfo = MessageButtonInfo(title : buttonTitle) { guard let videoURL = videoUrl, let url = URL(string: videoURL), UIApplication.shared.canOpenURL(url) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } if let messageView = messageView { view.addSubview(messageView) } } private func showError() { guard let block = block else { showCourseContentUnknownView() return } if block.specialExamInfo != nil { showSpecialExamMessageView(blockID: block.blockID) } else if (block.type == .Section && block.children.isEmpty) { showEmptySubsectionMessageView(blockID: block.blockID) } else if block.isGated { if environment.remoteConfig.valuePropEnabled { environment.analytics.trackLockedContentClicked(courseID: courseID, screenName: .CourseUnit, assignmentID: block.blockID) showValuePropMessageView() } else { showGatedContentMessageView() } } else { showCourseContentUnknownView() } } private func showSpecialExamMessageView(blockID: CourseBlockID) { let info = [ AnalyticsEventDataKey.SubsectionID.rawValue: blockID ] environment.analytics.trackScreen(withName: AnalyticsScreenName.SpecialExamBlockedScreen.rawValue, courseID: courseID, value: nil, additionalInfo: info) configureIconMessage(with: IconMessageView(icon: Icon.CourseUnknownContent, message: Strings.courseContentNotAvailable)) } private func showEmptySubsectionMessageView(blockID: CourseBlockID) { let info = [ AnalyticsEventDataKey.SubsectionID.rawValue: blockID ] environment.analytics.trackScreen(withName: AnalyticsScreenName.EmptySectionOutline.rawValue, courseID: courseID, value: nil, additionalInfo: info) configureIconMessage(with: IconMessageView(icon: Icon.CourseUnknownContent, message: Strings.courseContentNotAvailable)) } private func showGatedContentMessageView() { configureIconMessage(with: IconMessageView(icon: Icon.Closed, message: Strings.courseContentGated)) } private func showCourseContentUnknownView() { configureIconMessage(with: IconMessageView(icon: Icon.CourseUnknownContent, message: Strings.courseContentUnknown)) } private func configureIconMessage(with iconView: IconMessageView) { messageView = iconView messageView?.buttonInfo = MessageButtonInfo(title : Strings.openInBrowser) { [weak self] in guard let weakSelf = self else { return } weakSelf.loader?.listen(weakSelf, success : { url in guard let url = url, UIApplication.shared.canOpenURL(url) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) weakSelf.trackBroswerEvent() }, failure : { _ in }) } if let messageView = messageView { view.addSubview(messageView) } } private func showValuePropMessageView() { view.addSubview(valuePropView) view.backgroundColor = OEXStyles.shared().neutralWhiteT() valuePropView.snp.makeConstraints { make in make.top.equalTo(view).offset(StandardVerticalMargin * 2) make.leading.equalTo(view) make.trailing.equalTo(view) make.bottom.equalTo(view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func applyPortraitConstraints() { messageView?.snp.remakeConstraints { make in make.edges.equalTo(safeEdges) } } private func applyLandscapeConstraints() { messageView?.snp.remakeConstraints { make in make.edges.equalTo(safeEdges) let barHeight = navigationController?.toolbar.frame.size.height ?? 0.0 make.bottom.equalTo(safeBottom).offset(-barHeight) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loader = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment).blockWithID(id: blockID).map { $0.webURL as URL? }.firstSuccess() } private func trackBroswerEvent() { guard let block = block else { return } if block.specialExamInfo != nil { environment.analytics.trackSubsectionViewOnWebTapped(isSpecialExam: true, courseID: courseID, subsectionID: block.blockID) } else if (block.type == .Section && block.children.isEmpty) { environment.analytics.trackSubsectionViewOnWebTapped(isSpecialExam: false, courseID: courseID, subsectionID: block.blockID) } else { environment.analytics.trackOpenInBrowser(withURL: block.blockURL?.absoluteString ?? "", courseID: courseID, blockID: block.blockID, minifiedBlockID: block.minifiedBlockID ?? "", supported: block.multiDevice) } } } extension CourseUnknownBlockViewController: ValuePropMessageViewDelegate { func didTapUpgradeCourse(upgradeView: ValuePropComponentView) { guard let course = environment.interface?.enrollmentForCourse(withID: courseID)?.course else { return } disableAppTouchs() let pacing = course.isSelfPaced ? "self" : "instructor" environment.analytics.trackUpgradeNow(with: course.course_id ?? "", blockID: self.blockID ?? "", pacing: pacing) CourseUpgradeHandler.shared.upgradeCourse(course, environment: environment) { [weak self] status in switch status { case .payment: upgradeView.stopAnimating() break case .complete: self?.enableAppTouches() upgradeView.updateUpgradeButtonVisibility(visible: false) self?.dismiss(animated: true) { CourseUpgradeCompletion.shared.handleCompletion(state: .success(course.course_id ?? "", self?.blockID)) } break case .error: self?.enableAppTouches() upgradeView.stopAnimating() self?.dismiss(animated: true) { CourseUpgradeCompletion.shared.handleCompletion(state: .error) } break default: break } } } private func disableAppTouchs() { DispatchQueue.main.async { if !UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.beginIgnoringInteractionEvents() } } } private func enableAppTouches() { DispatchQueue.main.async { if UIApplication.shared.isIgnoringInteractionEvents { UIApplication.shared.endIgnoringInteractionEvents() } } } func showValuePropDetailView() { guard let course = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.course else { return } environment.analytics.trackValuePropLearnMore(courseID: courseID, screenName: .CourseUnit, assignmentID: blockID) environment.router?.showValuePropDetailView(from: self, type: .courseUnit, course: course) { [weak self] in if let weakSelf = self { weakSelf.environment.analytics.trackValuePropModal(with: .CourseUnit, courseId: weakSelf.courseID, assignmentID: weakSelf.blockID) } } } }
apache-2.0
e632d6283a6b213dcd4938efe3eb2e83
39.667954
246
0.639609
5.300956
false
false
false
false
darkzero/DZ_UIKit
DZ_UIKit/Classes/CustomController/CheckBox/DZCheckBox.swift
1
12318
// // DZCheckBox.swift // DZ_UIKit // // Created by Dora.Yuan on 2014/10/08. // Copyright (c) 2014 Dora.Yuan All rights reserved. // import UIKit //let VALUE_KEY_CHECKED = "_checked"; let DEFAULT_CHECKED_COLOR // RGB(184, 208, 98); = RGBA(184, 208, 98, 1.0); let DEFAULT_UNCHECKED_COLOR // RGB(230, 230, 230); = RGBA(230, 230, 230, 1.0); public enum DZCheckBoxType: Int { case circular = 1; case square case rounded } @IBDesignable public class DZCheckBox : UIControl { // MARK: - properties private var uncheckedLayer: CALayer!; private var checkedLayer: CALayer!; private var borderLayer: CALayer!; private var imageView: UIImageView!; private var titleLabel: UILabel!; // for DZCheckBoxType.circular private var expansionRect:CGRect!; private var contractRect:CGRect!; // for DZCheckBox.rounded private var cornerRadius:CGFloat = 8.0; // Border @IBInspectable public var hasBorder: Bool = false; @IBInspectable public var borderColor: UIColor = UIColor.white; // Type public var type:DZCheckBoxType = .circular; // Size @IBInspectable public var checkBoxSize:CGSize = CGSize(width: 48, height: 48) { didSet { self.frame.size.height = checkBoxSize.height; } }; // Title @IBInspectable public var title: String? { didSet { if ( title != nil ) { //self.titleLabel?.text = title; titleLabel.isHidden = false; titleLabel.text = self.title; let attributes = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: frame.size.height-4)]; let rect = NSString(string: self.title!).boundingRect(with: CGSize(width: 0, height: self.bounds.size.height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil); titleLabel.frame.size = rect.size; self.frame.size = CGSize(width: self.frame.size.width + 4 + rect.size.width, height: self.frame.height); } } } // Checked @IBInspectable public var checked: Bool = false { didSet { self.playAnimation(checked); } } // Color @IBInspectable public var uncheckedColor: UIColor = DEFAULT_UNCHECKED_COLOR { didSet { uncheckedLayer.backgroundColor = uncheckedColor.cgColor; } }; @IBInspectable public var checkedColor: UIColor = DEFAULT_CHECKED_COLOR { didSet { checkedLayer.backgroundColor = checkedColor.cgColor; } }; // Image @IBInspectable public var image: UIImage? { didSet { self.imageView.image = image; } }; // Group public var group: DZCheckBoxGroup? { didSet { // } } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder); self.createControllers(); } override init(frame: CGRect) { super.init(frame:frame); self.createControllers(); } public init(frame: CGRect, type: DZCheckBoxType, title: String? = nil, image: UIImage? = nil, borderColor: UIColor? = nil, uncheckedColor: UIColor? = nil, checkedColor: UIColor? = nil) { super.init(frame:frame); if ( borderColor != nil ) { self.hasBorder = true; self.borderColor = borderColor!; } if ( uncheckedColor != nil ) { self.uncheckedColor = uncheckedColor!; } if ( checkedColor != nil ) { self.checkedColor = checkedColor!; } self.title = title; self.image = image; self.type = type; self.createControllers(); } fileprivate func createControllers() { // Initialization code self.backgroundColor = UIColor.clear; self.checkBoxSize = frame.size; self.expansionRect = CGRect(x: 0, y: 0, width: checkBoxSize.width, height: checkBoxSize.height); self.contractRect = CGRect(x: checkBoxSize.width/2, y: checkBoxSize.height/2, width: 0, height: 0); uncheckedLayer = CALayer(); uncheckedLayer.frame = self.bounds; uncheckedLayer.backgroundColor = self.uncheckedColor.cgColor; uncheckedLayer.opacity = 1.0; self.layer.addSublayer(uncheckedLayer); checkedLayer = CALayer(); checkedLayer.frame = contractRect; checkedLayer.backgroundColor = self.checkedColor.cgColor; checkedLayer.opacity = 0.0; self.layer.addSublayer(checkedLayer); // set title self.titleLabel = UILabel(); self.titleLabel.frame = CGRect(x: self.expansionRect.width+4, y: 0, width: 0, height: frame.size.height); self.titleLabel.isHidden = true; self.addSubview(self.titleLabel); if ( self.title != nil ) { self.setTitle(); } // set border layer self.borderLayer = CALayer(); self.borderLayer.frame = self.expansionRect.insetBy(dx: 2, dy: 2)// (by: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)); self.borderLayer.borderColor = UIColor.white.cgColor;//self.borderColor!.cgColor; self.borderLayer.borderWidth = 1; self.borderLayer.opacity = 1.0; self.borderLayer.isHidden = true; self.layer.addSublayer(borderLayer); // set default image imageView = UIImageView(frame: self.bounds); let imageStr = Bundle(for: DZCheckBox.self).path(forResource: "checked", ofType: "png"); self.image = UIImage(data: try! Data(contentsOf: URL(fileURLWithPath: imageStr!))); imageView.frame = CGRect(x: 0, y: 0, width: self.expansionRect.size.width, height: self.expansionRect.size.height); self.addSubview(imageView); self.addTarget(self, action: #selector(DZCheckBox.onCheckBoxTouched(_:)), for: .touchUpInside); } private func setTitle() { titleLabel.isHidden = false; titleLabel.text = self.title; let font = UIFont.boldSystemFont(ofSize: frame.size.height/2) titleLabel.font = font let attributes = [NSAttributedString.Key.font : font]; let rect = NSString(string: self.title!).boundingRect(with: CGSize(width: CGFloat.infinity, height: self.bounds.size.height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil); DebugLog(rect) titleLabel.frame.size = rect.size self.frame.size = CGSize(width: self.frame.size.width + rect.size.width + 10, height: self.frame.height); } // MARK: - touch handler @objc internal func onCheckBoxTouched(_ sender:AnyObject) { let oldValue:Bool = self.checked; self.checked = !oldValue; if ( self.group == nil ) { self.sendActions(for: .valueChanged); } else { self.group?.onCheckBoxCheckedChanged(self); } } fileprivate func playAnimation(_ checked:Bool) { if ( checked ) { UIView.animate(withDuration: 0.1, delay: 0.1, options: .allowUserInteraction, animations: { self.checkedLayer.opacity = 1.0; self.checkedLayer.frame = self.expansionRect; self.titleLabel.textColor = self.checkedColor; switch self.type { case .rounded : self.checkedLayer.cornerRadius = self.cornerRadius; break; case .square : self.checkedLayer.cornerRadius = 0; break; case .circular : self.checkedLayer.cornerRadius = self.expansionRect.size.width / 2; break; } }, completion: { (result) in // if ( self.group == nil ) { // self.sendActions(for: UIControlEvents.valueChanged); // } // else { // self.group?.onCheckBoxCheckedChanged(self); // } }); } else { UIView.animate(withDuration: 0.3, delay: 0.1, options: .allowUserInteraction, animations: { self.checkedLayer.opacity = 0.0; self.checkedLayer.frame = self.contractRect; self.titleLabel.textColor = self.uncheckedColor; }, completion: { (result) in }); } } // MARK: - draw override open func draw(_ rect: CGRect) { super.draw(rect); self.expansionRect = CGRect(x: 0, y: 0, width: checkBoxSize.width, height: checkBoxSize.height); self.titleLabel.frame = CGRect(x: self.expansionRect.width+4, y: 0, width: 100, height: frame.size.height); self.uncheckedLayer.frame = self.expansionRect; self.checkedLayer.frame = self.expansionRect; if self.checked { self.checkedLayer.opacity = 1.0; self.checkedLayer.frame = self.expansionRect; self.titleLabel.textColor = self.checkedColor; } else { self.checkedLayer.opacity = 0.0; self.checkedLayer.frame = self.contractRect; self.titleLabel.textColor = self.uncheckedColor; } uncheckedLayer.backgroundColor = self.uncheckedColor.cgColor; checkedLayer.backgroundColor = self.checkedColor.cgColor; self.borderLayer.frame = self.expansionRect.insetBy(dx: 2, dy: 2) //inset(by: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)); self.borderLayer.borderColor = self.borderColor.cgColor; self.borderLayer.borderWidth = 1; if ( self.hasBorder ) { self.borderLayer.isHidden = false; imageView.frame = CGRect(x: 4, y: 4, width: self.expansionRect.size.width-8, height: self.expansionRect.size.height-8); } else { self.borderLayer.isHidden = true; imageView.frame = CGRect(x: 0, y: 0, width: self.expansionRect.size.width, height: self.expansionRect.size.height); } // Drawing code switch self.type { case .rounded : self.uncheckedLayer.cornerRadius = self.cornerRadius; self.checkedLayer.cornerRadius = self.cornerRadius; self.borderLayer?.cornerRadius = self.cornerRadius - 2; break; case .square : break; case .circular : self.uncheckedLayer.cornerRadius = self.expansionRect.size.width / 2; self.borderLayer?.cornerRadius = (self.expansionRect.size.width - 4) / 2; if self.checked { self.checkedLayer.cornerRadius = self.expansionRect.size.width / 2; } else { self.checkedLayer.cornerRadius = self.cornerRadius; } break; } } }
mit
a04602530f25982f0866c5cc9430222e
35.336283
138
0.529875
4.794862
false
false
false
false
wowiwj/WDayDayCook
WDayDayCook/WDayDayCook/Views/Cell/ArticleCell.swift
1
2525
// // ArticleCell.swift // WDayDayCook // // Created by wangju on 16/7/26. // Copyright © 2016年 wangju. All rights reserved. // import UIKit import Kingfisher class ArticleCell: UICollectionViewCell { @IBOutlet weak var bgView: UIImageView! @IBOutlet weak var foodImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var foodDescription: UILabel! @IBOutlet weak var clickCountButton: UIButton! @IBOutlet weak var favoriteButton: UIButton! fileprivate lazy var placeholderImage: UIImage = { let image = UIImage(named: "default~iphone")! return image }() var newFood: NewFood? { didSet{ guard let _ = newFood else { return } titleLabel.text = newFood?.title foodDescription.text = newFood?.foodDescription clickCountButton.setTitle("\(newFood!.clickCount)", for: UIControlState()) foodImageView.kf.setImage(with: URL(string: (newFood?.imageUrl)!)) } } var recipe: FoodRecmmand? { didSet{ guard let _ = recipe else { return } titleLabel.text = recipe!.title foodDescription.text = recipe!.foodDescription clickCountButton.setTitle("\(recipe!.click_count)", for: UIControlState()) foodImageView.kf.setImage(with: URL(string: recipe!.image_url)) } } var recipeData:Recipe?{ didSet{ guard let recipeData = recipeData else{ return } titleLabel.text = recipeData.title foodDescription.text = recipeData.description clickCountButton.setTitle("\(recipeData.clickCount ?? 0)", for: UIControlState()) foodImageView.kf.setImage(with: URL(string: recipeData.imageUrl!)) } } override func prepareForReuse() { super.prepareForReuse() foodImageView.image = nil titleLabel.text = nil foodDescription.text = nil } override func awakeFromNib() { super.awakeFromNib() // Initialization code bgView.layer.borderWidth = 0.5 bgView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor bgView.layer.cornerRadius = 5 bgView.layer.masksToBounds = true } }
mit
3dcc5e861499c35560e8e739954388b8
24.22
93
0.575734
5.074447
false
false
false
false
gscalzo/FlappySwift
FlappySwift/ParallaxNode.swift
1
1774
// // ParallaxNode.swift // FlappySwift // // Created by Giordano Scalzo on 26/08/2014. // Copyright (c) 2014 Effective Code. All rights reserved. // import SpriteKit class ParallaxNode { private let node: SKSpriteNode! init(textureNamed: String) { let leftHalf = createHalfNodeTexture(textureNamed, offsetX: 0) let rightHalf = createHalfNodeTexture(textureNamed, offsetX: leftHalf.size.width) let size = CGSize(width: leftHalf.size.width + rightHalf.size.width, height: leftHalf.size.height) node = SKSpriteNode(color: UIColor.clearColor(), size: size) node.anchorPoint = CGPointZero node.position = CGPointZero node.addChild(leftHalf) node.addChild(rightHalf) } func zPosition(zPosition: CGFloat) -> ParallaxNode { node.zPosition = zPosition return self } func addTo(parentNode: SKSpriteNode, zPosition: CGFloat) -> ParallaxNode { parentNode.addChild(node) node.zPosition = zPosition return self } } // Mark: Startable extension ParallaxNode { func start(duration duration: NSTimeInterval) { node.runAction(SKAction.repeatActionForever(SKAction.sequence( [ SKAction.moveToX(-node.size.width/2.0, duration: duration), SKAction.moveToX(0, duration: 0) ] ))) } func stop() { node.removeAllActions() } } // Mark: Private private func createHalfNodeTexture(textureNamed: String, offsetX: CGFloat) -> SKSpriteNode { let node = SKSpriteNode(imageNamed: textureNamed, normalMapped: true) node.anchorPoint = CGPointZero node.position = CGPoint(x: offsetX, y: 0) return node }
mit
f03e5f169d2ed4bf5bfe41be28f3d25a
27.629032
92
0.643743
4.479798
false
false
false
false
Chriskuei/Bon-for-Mac
Bon/BonConfig.swift
1
640
// // BonConfig.swift // Bon // // Created by Chris on 16/4/19. // Copyright © 2016年 Chris. All rights reserved. // import Cocoa import Foundation class BonConfig { static let appGroupID: String = "group.chriskuei.Bon" static let BonFont: String = "Avenir Book" //static let ScreenWidth: CGFloat = UIScreen.mainScreen().bounds.width //static let ScreenHeight: CGFloat = UIScreen.mainScreen().bounds.height struct BonNotification { static let GetOnlineInfo = "GetOnlineInfo" static let ShowLoginView = "ShowLoginView" static let HideLoginView = "ShowLoginView" } }
mit
bdafa166f33eb47866d5325b1fb0ea6e
23.538462
76
0.673469
4.083333
false
true
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/CocoaChina/BBS/CCPBBSViewController.swift
1
4439
// // CCPBBSViewController.swift // CocoaChinaPlus // // Created by zixun on 15/8/12. // Copyright © 2015年 zixun. All rights reserved. // import UIKit import MBProgressHUD // MARK: CCPBBSViewController class CCPBBSViewController: ZXBaseViewController { //UI fileprivate lazy var tableView: UITableView = { let newTableView = UITableView() newTableView.backgroundColor = UIColor(hex: 0x000000, alpha: 0.8) newTableView.delegate = self newTableView.dataSource = self newTableView.separatorStyle = .none //tableview 下拉動作 newTableView.addPullToRefresh(actionHandler: { [weak self] () -> Void in guard let sself = self else { return } sself.reloadTableView() }) newTableView.register(CCPBBSTableViewCell.self, forCellReuseIdentifier: "CCPBBSTableViewCell") return newTableView }() fileprivate var dataSource = CCPBBSModel(options: [CCPBBSOptionModel]()) required init(navigatorURL URL: URL?, query: Dictionary<String, String>) { super.init(navigatorURL: URL, query: query) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override func viewDidLoad() { super.viewDidLoad() self.reloadTableView() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tableView.fillSuperview() } } // Private Instance Method extension CCPBBSViewController { //初始化參數 fileprivate func setup() { //設置 tableview self.view.addSubview(self.tableView) } //tableview 重新加載 fileprivate func reloadTableView() { MBProgressHUD.showAdded(to: self.tableView, animated: true) CCPBBSParser.parserBBS { [weak self] (model) -> Void in guard let sself = self else { return } sself.dataSource = model sself.tableView.reloadData() sself.tableView.pullToRefreshView.stopAnimating() MBProgressHUD.hide(for: sself.tableView, animated: true) } } } // MARK: UITableViewDataSource extension CCPBBSViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CCPBBSTableViewCell", for: indexPath) as! CCPBBSTableViewCell let option = self.dataSource.options[indexPath.row] cell.configure(option) return cell } } // MARK: UITableViewDelegate extension CCPBBSViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let link = self.dataSource.options[indexPath.row].urlString ZXOpenURL("go/ccp/edition", param: ["link": link]) } } // MARK: CCPBBSTableViewCell class CCPBBSTableViewCell: CCPTableViewCell { //UI fileprivate lazy var titleLabel: UILabel = { let newTitleLabel = UILabel() newTitleLabel.font = UIFont.systemFont(ofSize: 14) newTitleLabel.textColor = UIColor.white newTitleLabel.textAlignment = .left newTitleLabel.numberOfLines = 2 newTitleLabel.lineBreakMode = .byTruncatingTail return newTitleLabel }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 設置 titlelabel self.containerView.addSubview(self.titleLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() self.titleLabel.fillSuperview(left: 4, right: 0, top: 4, bottom: 0) } func configure(_ model: CCPBBSOptionModel) { self.titleLabel.text = model.title } }
mit
a84e00bcf5a9fa03ae23a5bf7dae30fe
28.346667
127
0.645161
4.946067
false
false
false
false
jaredsinclair/sodes-audio-example
Sodes/SodesFoundation/HTTPOperation.swift
1
2153
// // HTTPOperation.swift // SodesFoundation // // Created by Jared Sinclair on 7/9/16. // // import Foundation public class HTTPOperation: WorkOperation { public enum Result { case data(Data, HTTPURLResponse) case error(HTTPURLResponse?, Error?) } private let internals: HTTPOperationInternals public init(url: URL, session: URLSession, completion: @escaping (Result) -> Void) { let internals = HTTPOperationInternals( request: URLRequest(url: url), session: session ) self.internals = internals super.init { completion(internals.result) } } public init(request: URLRequest, session: URLSession, completion: @escaping (Result) -> Void) { let internals = HTTPOperationInternals( request: request, session: session ) self.internals = internals super.init { completion(internals.result) } } override public func work(_ finish: @escaping () -> Void) { internals.task = internals.session.dataTask(with: internals.request) { (data, response, error) in guard !self.isCancelled else {return} // TODO: [MEDIUM] Consider how to handle redirects (POST vs GET e.g.) guard let r = response as? HTTPURLResponse, let data = data, 200 <= r.statusCode, r.statusCode <= 299 else { self.internals.result = .error((response as? HTTPURLResponse), error) finish() return } self.internals.result = .data(data, r) finish() } internals.task?.resume() } override public func cancel() { internals.task?.cancel() super.cancel() } } private class HTTPOperationInternals { let request: URLRequest let session: URLSession var task: URLSessionDataTask? var result: HTTPOperation.Result = .error(nil, nil) init(request: URLRequest, session: URLSession) { self.request = request self.session = session } }
mit
bfaeb8e357ae056ddfda7b829c2191d0
26.961039
118
0.586159
4.690632
false
false
false
false
bingoogolapple/SwiftNote-PartOne
TableView2/TableView2/ViewController.swift
2
2251
// // ViewController.swift // TableView2 // // Created by bingoogol on 14-6-15. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var _cities:NSDictionary! var _provinces:NSArray! override func viewDidLoad() { super.viewDidLoad() let bundle = NSBundle.mainBundle() let provincesPath = bundle.pathForResource("provinces", ofType: "plist") let citiesPath = bundle.pathForResource("cities", ofType: "plist") _provinces = NSArray(contentsOfFile: provincesPath) _cities = NSDictionary(contentsOfFile: citiesPath) } // 省份的数量 func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return _provinces.count } // 每个省对应的城市的数量 func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { let provinceName = _provinces[section] as String let cities = _cities[provinceName] as NSArray return cities.count } // 表格单元显示的内容 func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) let provinceName = _provinces[indexPath.section] as String let cities = _cities[provinceName] as NSArray cell.textLabel.text = cities[indexPath.row] as String return cell } // 设置组标题 func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! { return _provinces[section] as String } // 选择某一行 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { let provinceName = _provinces[indexPath.section] as String let cities = _cities[provinceName] as NSArray let cityName = cities[indexPath.row] as String println("\(provinceName),\(cityName)") } // 右侧的索引 func sectionIndexTitlesForTableView(tableView: UITableView!) -> AnyObject[]! { return _provinces } }
apache-2.0
cb8ebe13a1e3cc2ab10611abf2494f6d
31.863636
112
0.670816
4.841518
false
false
false
false
ioriwellings/BluetoothKit
Source/BKScanner.swift
13
4467
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // 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 CoreBluetooth internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { // MARK: Type Aliases internal typealias ScanCompletionHandler = ((result: [BKDiscovery]?, error: Error?) -> Void) // MARK: Enums internal enum Error: ErrorType { case NoCentralManagerSet case Busy case Interrupted } // MARK: Properties internal var configuration: BKConfiguration! internal var centralManager: CBCentralManager! private var busy = false private var scanHandlers: ( progressHandler: BKCentral.ScanProgressHandler?, completionHandler: ScanCompletionHandler )? private var discoveries = [BKDiscovery]() private var durationTimer: NSTimer? // MARK: Internal Functions internal func scanWithDuration(duration: NSTimeInterval, progressHandler: BKCentral.ScanProgressHandler? = nil, completionHandler: ScanCompletionHandler) throws { do { try validateForActivity() busy = true scanHandlers = (progressHandler: progressHandler, completionHandler: completionHandler) centralManager.scanForPeripheralsWithServices(configuration.serviceUUIDs, options: nil) durationTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: "durationTimerElapsed", userInfo: nil, repeats: false) } catch let error { throw error } } internal func interruptScan() { guard busy else { return } endScan(.Interrupted) } // MARK: Private Functions private func validateForActivity() throws { guard !busy else { throw Error.Busy } guard centralManager != nil else { throw Error.NoCentralManagerSet } } @objc private func durationTimerElapsed() { endScan(nil) } private func endScan(error: Error?) { invalidateTimer() centralManager.stopScan() let completionHandler = scanHandlers?.completionHandler let discoveries = self.discoveries scanHandlers = nil self.discoveries.removeAll() busy = false completionHandler?(result: discoveries, error: error) } private func invalidateTimer() { if let durationTimer = self.durationTimer { durationTimer.invalidate() self.durationTimer = nil } } // MARK: BKCBCentralManagerDiscoveryDelegate internal func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String: AnyObject], RSSI: NSNumber) { guard busy else { return } let RSSI = Int(RSSI) let remotePeripheral = BKRemotePeripheral(identifier: peripheral.identifier, peripheral: peripheral) remotePeripheral.configuration = configuration let discovery = BKDiscovery(advertisementData: advertisementData, remotePeripheral: remotePeripheral, RSSI: RSSI) if !discoveries.contains(discovery) { discoveries.append(discovery) scanHandlers?.progressHandler?(newDiscoveries: [ discovery ]) } } }
mit
cf86ccae49d3b3fbb093b857dff84c16
35.917355
166
0.682113
5.267689
false
false
false
false
dymx101/Gamers
Gamers/Dao/LiveDao.swift
1
2562
// // LiveDao.swift // Gamers // // Created by 虚空之翼 on 15/8/12. // Copyright (c) 2015年 Freedom. All rights reserved. // import Foundation import Alamofire import Bolts import SwiftyJSON import RealmSwift struct LiveDao {} extension LiveDao { /** 获取在线直播列表 :param: page 页码 :param: limit 每页总数 :returns: 直播列表 */ static func getLive(#page: Int, limit: Int) -> BFTask { var URLRequest = Router.LiveVideo(page: page, limit: limit) return fetchLive(URLRequest: URLRequest) } /** 获取Twitch直播令牌 :param: channelId 玩家频道 :returns: 返回令牌 */ static func getStreamsToken(#channelId: String) -> BFTask { var URLRequest = TwitchRouter.StreamsToken(channelId: channelId) return fetchTwitchTokenResponse(URLRequest: URLRequest) } // MARK: - 解析 //解析twitchtoken数据 private static func fetchTwitchTokenResponse(#URLRequest: URLRequestConvertible) -> BFTask { var source = BFTaskCompletionSource() Alamofire.request(URLRequest).responseJSON { (_, _, JSONDictionary, error) in if error == nil { if let JSONDictionary: AnyObject = JSONDictionary { let token = TwitchToken.collection(json: JSON(JSONDictionary)) source.setResult(token) } } else { source.setError(error) } } return source.task } //解析游戏视频列表的JSON数据 private static func fetchLive(#URLRequest: URLRequestConvertible) -> BFTask { var source = BFTaskCompletionSource() Alamofire.request(URLRequest).responseJSON { (_, _, JSONDictionary, error) in if error == nil { if let JSONDictionary: AnyObject = JSONDictionary { if JSON(JSONDictionary)["errCode"] == nil { let lives = Live.collection(json: JSON(JSONDictionary)) source.setResult(lives) } else { let response = Response.collection(json: JSON(JSONDictionary)) source.setResult(response) } } else { source.setResult(Response()) } } else { source.setError(error) } } return source.task } }
apache-2.0
e32385941ac8d18827b4abd6c64251d6
25.978022
96
0.547677
4.967611
false
false
false
false
PJayRushton/StarvingStudentGuide
StarvingStudentGuide/JSON.swift
1
1458
// // M A R S H A L // // () // /\ // ()--' '--() // `. .' // / .. \ // ()' '() // // import Foundation // MARK: - Types public typealias JSONObject = MarshaledObject // MARK: - Parser public struct JSONParser { private init() { } public static func JSONObjectWithData(data: NSData) throws -> JSONObject { let obj: Any = try NSJSONSerialization.JSONObjectWithData(data, options: []) return try JSONObject.value(obj) } public static func JSONArrayWithData(data: NSData) throws -> [JSONObject] { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) guard let array = object as? [JSONObject] else { throw Error.TypeMismatch(expected: [JSONObject].self, actual: object.dynamicType) } return array } } // MARK: - Collections public protocol JSONCollectionType { func jsonData() throws -> NSData } extension JSONCollectionType { public func jsonData() throws -> NSData { guard let jsonCollection = self as? AnyObject else { throw Error.TypeMismatchWithKey(key:"", expected: AnyObject.self, actual: self.dynamicType) // shouldn't happen } return try NSJSONSerialization.dataWithJSONObject(jsonCollection, options: []) } } extension Dictionary : JSONCollectionType {} extension Array : JSONCollectionType {} extension Set : JSONCollectionType {}
mit
ac936fbaedc6d18afe990a1811677c11
22.516129
123
0.635117
4.486154
false
false
false
false
camflan/SalesforceMobileSDK-iOS
native/SampleApps/FileExplorer/FileExplorer/Classes/AppDelegate.swift
4
8387
/* Copyright (c) 2014, salesforce.com, inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of salesforce.com, inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. */ import Foundation import UIKit // Fill these in when creating a new Connected Application on Force.com let RemoteAccessConsumerKey = "3MVG9Iu66FKeHhINkB1l7xt7kR8czFcCTUhgoA8Ol2Ltf1eYHOU4SqQRSEitYFDUpqRWcoQ2.dBv_a1Dyu5xa"; let OAuthRedirectURI = "testsfdc:///mobilesdk/detect/oauth/done"; let scopes = ["api"]; @UIApplicationMain class AppDelegate : UIResponder, UIApplicationDelegate { var window: UIWindow? override init() { super.init() SFLogger.setLogLevel(SFLogLevelDebug) SalesforceSDKManager.sharedManager().connectedAppId = RemoteAccessConsumerKey SalesforceSDKManager.sharedManager().connectedAppCallbackUri = OAuthRedirectURI SalesforceSDKManager.sharedManager().authScopes = scopes SalesforceSDKManager.sharedManager().postLaunchAction = { [unowned self] (launchActionList: SFSDKLaunchAction) in let launchActionString = SalesforceSDKManager.launchActionsStringRepresentation(launchActionList) self.log(SFLogLevelInfo, msg:"Post-launch: launch actions taken: \(launchActionString)"); self.setupRootViewController(); } SalesforceSDKManager.sharedManager().launchErrorAction = { [unowned self] (error: NSError?, launchActionList: SFSDKLaunchAction) in if let actualError = error { self.log(SFLogLevelError, msg:"Error during SDK launch: \(actualError.localizedDescription)") } else { self.log(SFLogLevelError, msg:"Unknown error during SDK launch.") } self.initializeAppViewState() SalesforceSDKManager.sharedManager().launch() } SalesforceSDKManager.sharedManager().postLogoutAction = { [unowned self] in self.handleSdkManagerLogout() } SalesforceSDKManager.sharedManager().switchUserAction = { [unowned self] (fromUser: SFUserAccount?, toUser: SFUserAccount?) -> () in self.handleUserSwitch(fromUser, toUser: toUser) } } // MARK: - App delegate lifecycle func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.initializeAppViewState(); // // If you wish to register for push notifications, uncomment the line below. Note that, // if you want to receive push notifications from Salesforce, you will also need to // implement the application:didRegisterForRemoteNotificationsWithDeviceToken: method (below). // // SFPushNotificationManager.sharedInstance().registerForRemoteNotifications() SalesforceSDKManager.sharedManager().launch() return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // // Uncomment the code below to register your device token with the push notification manager // // // SFPushNotificationManager.sharedInstance().didRegisterForRemoteNotificationsWithDeviceToken(deviceToken) // if (SFAccountManager.sharedInstance().credentials.accessToken != nil) // { // SFPushNotificationManager.sharedInstance().registerForSalesforceNotifications() // } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError ) { // Respond to any push notification registration errors here. } // MARK: - Private methods func initializeAppViewState() { self.window!.rootViewController = InitialViewController(nibName: nil, bundle: nil) self.window!.makeKeyAndVisible() } func setupRootViewController() { let rootVC = RootViewController(nibName: nil, bundle: nil) let navVC = UINavigationController(rootViewController: rootVC) self.window!.rootViewController = navVC } func resetViewState(postResetBlock: () -> ()) { if let rootViewController = self.window!.rootViewController { if let presentedViewController = rootViewController.presentedViewController { rootViewController.dismissViewControllerAnimated(false, completion: postResetBlock) return } } postResetBlock() } func handleSdkManagerLogout() { self.log(SFLogLevelDebug, msg: "SFAuthenticationManager logged out. Resetting app.") self.resetViewState { () -> () in self.initializeAppViewState() // Multi-user pattern: // - If there are two or more existing accounts after logout, let the user choose the account // to switch to. // - If there is one existing account, automatically switch to that account. // - If there are no further authenticated accounts, present the login screen. // // Alternatively, you could just go straight to re-initializing your app state, if you know // your app does not support multiple accounts. The logic below will work either way. var numberOfAccounts : Int; let allAccounts = SFUserAccountManager.sharedInstance().allUserAccounts as! [SFUserAccount]? if allAccounts != nil { numberOfAccounts = allAccounts!.count; } else { numberOfAccounts = 0; } if numberOfAccounts > 1 { let userSwitchVc = SFDefaultUserManagementViewController(completionBlock: { action in self.window!.rootViewController!.dismissViewControllerAnimated(true, completion: nil) }) self.window!.rootViewController!.presentViewController(userSwitchVc, animated: true, completion: nil) } else { if (numberOfAccounts == 1) { SFUserAccountManager.sharedInstance().currentUser = allAccounts![0] } SalesforceSDKManager.sharedManager().launch() } } } func handleUserSwitch(fromUser: SFUserAccount?, toUser: SFUserAccount?) { let fromUserName = (fromUser != nil) ? fromUser?.userName : "<none>" let toUserName = (toUser != nil) ? toUser?.userName : "<none>" self.log(SFLogLevelDebug, msg:"SFUserAccountManager changed from user \(fromUserName) to \(toUserName). Resetting app.") self.resetViewState { () -> () in self.initializeAppViewState() SalesforceSDKManager.sharedManager().launch() } } }
apache-2.0
f2d275774a11cbdc23f1d8812b846d65
44.340541
129
0.675927
5.33185
false
false
false
false
dflax/Anagrams
Anagrams/Config.swift
1
1158
// // Config.swift // Anagrams // // Created by Caroline on 1/08/2014. // Copyright (c) 2013 Underplot ltd. All rights reserved. // import Foundation import UIKit // Device type - true if iPad or iPad Simulator let isPad: Bool = { if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) { return true } else { return false } }() //UI constants - will work for any sized screen let ScreenWidth = UIScreen.mainScreen().bounds.size.width let ScreenHeight = UIScreen.mainScreen().bounds.size.height let TileMargin: CGFloat = 20.0 let TileYOffset: UInt32 = 10 // Display HUD details let FontHUD: UIFont = { if (isPad) { return UIFont(name:"comic andy", size: 62.0)! } else { return UIFont(name:"comic andy", size: 25.0)! } }() let FontHUDBig: UIFont = { if (isPad) { return UIFont(name:"comic andy", size:120.0)! } else { return UIFont(name:"comic andy", size: 45.0)! } }() let MarginTop: CGFloat = { if (isPad) { return 100.0 } else { return 40.0 } }() //Random integer generator func randomNumber(#minX:UInt32, #maxX:UInt32) -> Int { let result = (arc4random() % (maxX - minX + 1)) + minX return Int(result) }
mit
8b1b96e5e4f2f852f8371c50a2455e14
19.315789
59
0.663212
3.031414
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILESetEventMask.swift
1
7912
// // HCILESetEventMask.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - BluetoothHostControllerInterface public extension BluetoothHostControllerInterface { /// LE Set Event Mask Command /// /// The command is used to control which LE events are generated by the HCI for the Host. func setLowEnergyEventMask(_ eventMask: HCILESetEventMask.EventMask, timeout: HCICommandTimeout = .default) async throws { let parameter = HCILESetEventMask(eventMask: eventMask) try await deviceRequest(parameter, timeout: timeout) } } // MARK: - HCI Command /// LE Set Event Mask Command /// /// The command is used to control which LE events are generated by the HCI for the Host. /// /// If the bit in the LE Event Mask is set to a one, then the event associated with that bit will be enabled. /// The Host has to deal with each event that is generated by an LE Controller. /// The event mask allows the Host to control which events will interrupt it. /// /// For LE events to be generated, the LE Meta Event bit in the Event Mask shall also be set. /// If that bit is not set, then LE events shall not be generated, regardless of how the LE Event Mask is set. @frozen public struct HCILESetEventMask: HCICommandParameter { public typealias EventMask = BitMaskOptionSet<Event> public static let command = HCILowEnergyCommand.setEventMask // 0x0001 /// The mask of LE events allowed to be generated by the HCI. public var eventMask: EventMask /// The value with all bits set to 0 indicates that no events are specified. /// The default is for bits 0 to 4 inclusive (the value 0x0000 0000 0000 001F) to be set. public init(eventMask: EventMask = 0x0000_0000_0000_001F) { self.eventMask = eventMask } public var data: Data { let eventMaskBytes = eventMask.rawValue.littleEndian.bytes return Data([ eventMaskBytes.0, eventMaskBytes.1, eventMaskBytes.2, eventMaskBytes.3, eventMaskBytes.4, eventMaskBytes.5, eventMaskBytes.6, eventMaskBytes.7 ]) } } // MARK: - Supporting Types public extension HCILESetEventMask { /// The value with all bits set to 0 indicates that no events are specified. /// The default is for bits 0 to 4 inclusive (the value `0x0000 0000 0000 001F`) to be set. /// /// All bits not listed in this table are reserved for future use. enum Event: UInt64, BitMaskOption, CustomStringConvertible { /// LE Connection Complete Event case connectionComplete = 0b00 /// LE Advertising Report Event case advertisingReport = 0b01 /// LE Connection Update Complete Event case connectionUpdateComplete = 0b10 /// LE Read Remote Features Complete Event case readRemoteFeaturesComplete = 0b100 /// LE Long Term Key Request Event case longTermKeyRequest = 0b1000 /// LE Remote Connection Parameter Request Event case remoteConnectionParameterRequest = 0b10000 /// LE Data Length Change Event case dataLengthChange = 0b100000 /// LE Read Local P-256 Public Key Complete Event case readLocalP256PublicKeyComplete = 0b1000000 /// LE Generate DHKey Complete Event case generateDHKeyComplete = 0b10000000 /// LE Enhanced Connection Complete Event case enhancedConnectionComplete = 0b100000000 /// LE Directed Advertising Report Event case directedAdvertisingReport = 0b1000000000 /// LE PHY Update Complete Event case phyUpdateComplete = 0b10000000000 /// LE Extended Advertising Report Event case extendedAdvertisingReport = 0b100000000000 /// LE Periodic Advertising Sync Established Event case periodicAdvertisingSyncEstablished = 0b1000000000000 /// LE Periodic Advertising Report Event case periodicAdvertisingReport = 0b10000000000000 /// LE Periodic Advertising Sync Lost Event case periodicAdvertisingSyncLost = 0b100000000000000 /// LE Extended Scan Timeout Event case extendedScanTimeout = 0b1000000000000000 /// LE Extended Advertising Set Terminated Event case extendedAdvertisingSetTerminated = 0b10000000000000000 /// LE Scan Request Received Event case scanRequestReceived = 0b100000000000000000 /// LE Channel Selection Algorithm Event case channelSelectionAlgorithm = 0b1000000000000000000 public static let allCases: [Event] = [ .connectionComplete, .advertisingReport, .connectionUpdateComplete, .readRemoteFeaturesComplete, .longTermKeyRequest, .remoteConnectionParameterRequest, .dataLengthChange, .readLocalP256PublicKeyComplete, .generateDHKeyComplete, .enhancedConnectionComplete, .directedAdvertisingReport, .phyUpdateComplete, .extendedAdvertisingReport, .periodicAdvertisingSyncEstablished, .periodicAdvertisingReport, .periodicAdvertisingSyncLost, .extendedScanTimeout, .extendedAdvertisingSetTerminated, .scanRequestReceived, .channelSelectionAlgorithm ] public var event: LowEnergyEvent { switch self { case .connectionComplete: return .connectionComplete case .advertisingReport: return .advertisingReport case .connectionUpdateComplete: return .connectionUpdateComplete case .readRemoteFeaturesComplete: return .readRemoteUsedFeaturesComplete case .longTermKeyRequest: return .longTermKeyRequest case .remoteConnectionParameterRequest: return .remoteConnectionParameterRequest case .dataLengthChange: return .dataLengthChange case .readLocalP256PublicKeyComplete: return .readLocalP256PublicKeyComplete case .generateDHKeyComplete: return .generateDHKeyComplete case .enhancedConnectionComplete: return .enhancedConnectionComplete case .directedAdvertisingReport: return .directedAdvertisingReport case .phyUpdateComplete: return .phyUpdateComplete case .extendedAdvertisingReport: return .extendedAdvertisingReport case .periodicAdvertisingSyncEstablished: return .periodicAdvertisingSyncEstablished case .periodicAdvertisingReport: return .periodicAdvertisingReport case .periodicAdvertisingSyncLost: return .periodicAdvertisingSyncLost case .extendedScanTimeout: return .scanTimeout case .extendedAdvertisingSetTerminated: return .advertisingSetTerminated case .scanRequestReceived: return .scanRequestReceived case .channelSelectionAlgorithm: return .channelSelectionAlgorithm } } public var description: String { return event.description } } }
mit
118f0a2048682580d1e724c996f79510
38.954545
110
0.628113
5.524441
false
false
false
false
orta/RxSwift
RxSwift/RxSwift/Rx.swift
1
2076
// // Rx.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if DEBUG // counts resources // used to detect resource leaks during unit tests // it's not perfect, but works well public var resourceCount: Int32 = 0 #endif // This is the pipe operator (left associative function application operator) // a >- b >- c == c(b(a)) // The reason this one is chosen for now is because // * It's subtle, doesn't add a lot of visual noise // * It's short // * It kind of looks like ASCII art horizontal sink to the right // infix operator >- { associativity left precedence 91 } public func >- <In, Out>(lhs: In, @noescape rhs: In -> Out) -> Out { return rhs(lhs) } func contract(@autoclosure condition: () -> Bool) { if !condition() { let exception = NSException(name: "ContractError", reason: "Contract failed", userInfo: nil) exception.raise() } } // Because ... Swift // Because ... Crash // Because ... compiler bugs // Wrapper for any value type public class Box<T> : Printable { public let value : T public init (_ value: T) { self.value = value } public var description: String { get { return "Box(\(self.value))" } } } // Wrapper for any value type that can be mutated public class MutatingBox<T> : Printable { public var value : T public init (_ value: T) { self.value = value } public var description: String { get { return "MutatingBox(\(self.value))" } } } // Swift doesn't have a concept of abstract metods. // This function is being used as a runtime check that abstract methods aren't being called. func abstractMethod<T>() -> T { rxFatalError("Abstract method") let dummyValue: T? = nil return dummyValue! } func rxFatalError(lastMessage: String) { // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. fatalError(lastMessage) }
mit
8f909fdd60a78701aa95aa7f7051698c
24.62963
115
0.637765
3.880374
false
false
false
false