repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tecgirl/firefox-ios
Client/Frontend/Widgets/SiteTableViewController.swift
1
8097
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage struct SiteTableViewControllerUX { static let HeaderHeight = CGFloat(32) static let RowHeight = CGFloat(44) static let HeaderFont = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium) static let HeaderTextMargin = CGFloat(16) } class SiteTableViewHeader: UITableViewHeaderFooterView, Themeable { // I can't get drawRect to play nicely with the glass background. As a fallback // we just use views for the top and bottom borders. let topBorder = UIView() let bottomBorder = UIView() let titleLabel = UILabel() override var textLabel: UILabel? { return titleLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBold addSubview(topBorder) addSubview(bottomBorder) contentView.addSubview(titleLabel) topBorder.snp.makeConstraints { make in make.left.right.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } // A table view will initialize the header with CGSizeZero before applying the actual size. Hence, the label's constraints // must not impose a minimum width on the content view. titleLabel.snp.makeConstraints { make in make.left.equalTo(contentView).offset(SiteTableViewControllerUX.HeaderTextMargin).priority(1000) make.right.equalTo(contentView).offset(-SiteTableViewControllerUX.HeaderTextMargin).priority(1000) make.left.greaterThanOrEqualTo(contentView) // Fallback for when the left space constraint breaks make.right.lessThanOrEqualTo(contentView) // Fallback for when the right space constraint breaks make.centerY.equalTo(contentView) } applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() applyTheme() } func applyTheme() { titleLabel.textColor = UIColor.theme.tableView.headerTextDark topBorder.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder bottomBorder.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } /** * Provides base shared functionality for site rows and headers. */ class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { fileprivate let CellIdentifier = "CellIdentifier" fileprivate let HeaderIdentifier = "HeaderIdentifier" let profile: Profile var data: Cursor<Site> = Cursor<Site>(status: .success, msg: "No data set") var tableView = UITableView() private override init(nibName: String?, bundle: Bundle?) { fatalError("init(coder:) has not been implemented") } init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) return } tableView.delegate = self tableView.dataSource = self tableView.register(SiteTableViewCell.self, forCellReuseIdentifier: CellIdentifier) tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier) tableView.layoutMargins = .zero tableView.keyboardDismissMode = .onDrag tableView.accessibilityIdentifier = "SiteTable" tableView.cellLayoutMarginsFollowReadableWidth = false // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() if #available(iOS 11.0, *), let _ = self as? HomePanelContextMenu { tableView.dragDelegate = self } } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { context in //The AS context menu does not behave correctly. Dismiss it when rotating. if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } }, completion: nil) } func reloadData() { if data.status != .success { print("Err: \(data.statusMessage)", terminator: "\n") } else { self.tableView.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) if self.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath) { cell.separatorInset = .zero } cell.textLabel?.textColor = UIColor.theme.tableView.rowText return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderIdentifier) } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel?.textColor = UIColor.theme.tableView.headerTextDark header.contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return SiteTableViewControllerUX.HeaderHeight } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return SiteTableViewControllerUX.RowHeight } func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool { return false } func applyTheme() { tableView.backgroundColor = UIColor.theme.tableView.rowBackground tableView.separatorColor = UIColor.theme.tableView.separator reloadData() } } @available(iOS 11.0, *) extension SiteTableViewController: UITableViewDragDelegate { func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let homePanelVC = self as? HomePanelContextMenu, let site = homePanelVC.getSiteDetails(for: indexPath), let url = URL(string: site.url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .url, value: .homePanel) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = site return [dragItem] } func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { presentedViewController?.dismiss(animated: true) } }
mpl-2.0
8be68fc75d6b70edf521e0cce01d3f44
37.374408
208
0.690009
5.268055
false
false
false
false
A752575700/HOMEWORK
Day5_1/Day5_1.playground/Contents.swift
1
3267
//: Playground - noun: a place where people can play import UIKit //<T:..>用的时候再声明类型 public class Node <T:Equatable>{ //变量有赋值时可以不用initializer var value: T var next: Node? = nil /* public func addValue(x: Int){ self.value = x }*/ //类里面有value就需要下划线 init (_ value: T){ self.value = value } } var str = "Hello, playground" public class List<T:Equatable>{ var head: Node<T>? = nil var newhead1: Node<T>? = nil var newhead2: Node<T>? = nil public func addTail(newvalue: T){ if head == nil{ head = Node(newvalue) } else { var lastnode = head while lastnode?.next != nil { lastnode = lastnode?.next } lastnode?.next = Node(newvalue) } } public func addHead(newvalue: T){ if head == nil{ head = Node(newvalue) } else{ let newhead = Node(newvalue) newhead.next = head head = newhead } } public func description() -> String{ if head?.value != nil{ var outcome: String = "\(head!.value)" var item = head while item?.next != nil{ item = item!.next outcome = outcome + " \(item!.value)" } return outcome } return "nil" } public func removeFirstValue(value: T){ var item = head var isFound = false if item!.value == value { if item!.next == nil{ head = nil } else if item!.next != nil{ head = item?.next } } else { //while item!.next != nil{ var item2 = item while item2!.next != nil{ item = item2 item2 = item2!.next //println(item2!.value) if(item2!.value == value){ isFound = true break } } if isFound == true { item!.next = item2!.next }else{ print("\(value) not found") } } } //同时用remove和insert 每个反转 public func reverse(){ if head?.next != nil{ //newhead1?.value = 5 newhead1 = Node(head!.value) head = head!.next while head?.next != nil{ //newhead2?.value = head!.value newhead2 = Node(head!.value) newhead2?.next = newhead1 newhead1 = newhead2 head = head!.next } head?.next = newhead1 } } } var newList = List<Int>() newList.addTail(5) newList.addTail(6) newList.addTail(7) newList.addTail(8) print(newList.description()) newList.reverse() print(newList.description()) var newList2 = List<String>() newList2.addTail("a") newList2.addTail("b") //newList2.addTail("c") //newList2.addTail("d") print(newList2.description()) newList2.reverse() print(newList2.description())
mit
8d3cf634309c0aa99b5d31539a36c1b0
22.659259
53
0.465706
4.190289
false
false
false
false
almazrafi/Metatron
Sources/ID3v2/FrameStuffs/ID3v2NumberValue.swift
1
2300
// // ID3v2NumberValue.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 public extension ID3v2TextInformation { // MARK: Instance Properties public var numberValue: TagNumber { get { guard let field = self.fields.first else { return TagNumber() } let parts = field.components(separatedBy: "/") guard parts.count < 3 else { return TagNumber() } guard let value = Int(parts[0]) else { return TagNumber() } if parts.count == 1 { return TagNumber(value) } guard let total = Int(parts[1]) else { return TagNumber() } return TagNumber(value, total: total) } set { if newValue.isValid { if newValue.total > 0 { self.fields = [String(format: "%d/%d", newValue.value, newValue.total)] } else { self.fields = [String(format: "%d", newValue.value)] } } else { self.fields.removeAll() } } } }
mit
2b1543d2d16eadf96fc6706558423c58
31.394366
91
0.607826
4.518664
false
false
false
false
OscarSwanros/swift
test/ClangImporter/objc_missing_designated_init.swift
16
4125
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules %s -swift-version 4 -verify // REQUIRES: objc_interop import UnimportableMembers class IncompleteInitSubclassImplicit : IncompleteDesignatedInitializers { var myOneNewMember = 1 } class IncompleteInitSubclass : IncompleteDesignatedInitializers { override init(first: Int) {} override init(second: Int) {} } class IncompleteConvenienceInitSubclass : IncompleteConvenienceInitializers {} class IncompleteUnknownInitSubclass : IncompleteUnknownInitializers {} func testBaseClassesBehaveAsExpected() { _ = IncompleteDesignatedInitializers(first: 0) // okay _ = IncompleteDesignatedInitializers(second: 0) // okay _ = IncompleteDesignatedInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteDesignatedInitializers(conveniently: 0) // okay _ = IncompleteDesignatedInitializers(category: 0) // okay _ = IncompleteConvenienceInitializers(first: 0) // okay _ = IncompleteConvenienceInitializers(second: 0) // okay _ = IncompleteConvenienceInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteConvenienceInitializers(conveniently: 0) // okay _ = IncompleteConvenienceInitializers(category: 0) // okay _ = IncompleteUnknownInitializers(first: 0) // okay _ = IncompleteUnknownInitializers(second: 0) // okay _ = IncompleteUnknownInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteUnknownInitializers(conveniently: 0) // okay _ = IncompleteUnknownInitializers(category: 0) // okay } func testSubclasses() { _ = IncompleteInitSubclass(first: 0) // okay _ = IncompleteInitSubclass(second: 0) // okay _ = IncompleteInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteInitSubclass(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteInitSubclass(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteInitSubclassImplicit(first: 0) // okay _ = IncompleteInitSubclassImplicit(second: 0) // okay _ = IncompleteInitSubclassImplicit(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteInitSubclassImplicit(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteInitSubclassImplicit(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteConvenienceInitSubclass(first: 0) // okay _ = IncompleteConvenienceInitSubclass(second: 0) // okay _ = IncompleteConvenienceInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteConvenienceInitSubclass(conveniently: 0) // okay _ = IncompleteConvenienceInitSubclass(category: 0) // okay _ = IncompleteUnknownInitSubclass(first: 0) // okay _ = IncompleteUnknownInitSubclass(second: 0) // okay _ = IncompleteUnknownInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}} _ = IncompleteUnknownInitSubclass(conveniently: 0) // okay // FIXME: This initializer isn't being inherited for some reason, unrelated // to the non-importable -initMissing:. // https://bugs.swift.org/browse/SR-4566 _ = IncompleteUnknownInitSubclass(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}} }
apache-2.0
0d4a9e27b3d9e1c223c59ee90d8ee8f5
59.661765
174
0.753212
5.042787
false
false
false
false
mirchow/HungerFreeCity
ios/Hunger Free City/Controllers/CentersViewController.swift
1
3078
// // FirstViewController.swift // HungerFreeCity // // Created by Mirek Chowaniok on 6/6/15. // Copyright (c) 2015 Jacksonville Community. All rights reserved. // import UIKit import Firebase import GeoFire class CentersViewController: UIViewController { //}, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate { // class CitiesViewController: UITableViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate { @IBOutlet weak var mapContainerView: UIView! @IBOutlet weak var listContainerView: UIView! override func viewDidLoad() { super.viewDidLoad() print("entered CentersViewController") // let provider: HFCDataProvider() // provider.getDistributionCentersNearby() // HFCDataProvider provider = HFCDataProvider() // let tracker = GAI.sharedInstance().defaultTracker // tracker.set(kGAIScreenName, value: "/index") // tracker.send(GAIDictionaryBuilder.createScreenView().build()) // UA-64518089-1 let geofireRef = Firebase(url: "https://amber-torch-2255.firebaseio.com/") let geoFire = GeoFire(firebaseRef: geofireRef) let center = CLLocation(latitude: 37.7832889, longitude: -122.4056973) // Query locations at [37.7832889, -122.4056973] with a radius of 20000 meters var circleQuery = geoFire.queryAtLocation(center, withRadius: 20.0) print("circleQuery \(circleQuery)") circleQuery.observeReadyWithBlock({ print("All initial data has been loaded and events have been fired!") // println("\(snapshot.key) -> \(snapshot.value)") }) // myRootRef.observeEventType(.Value, withBlock: { // snapshot in // println("\(snapshot.key) -> \(snapshot.value)") // }) // // Query location by region // let span = MKCoordinateSpanMake(0.001, 0.001) // let region = MKCoordinateRegionMake(center.coordinate, span) // var regionQuery = geoFire.queryWithRegion(region) // geoFire.setLocation(CLLocation(latitude: 37.7853889, longitude: -122.4056973), forKey: "firebase-hq") { (error) in // if (error != nil) { // println("An error occured: \(error)") // } else { // println("Saved location successfully!") // } // } } override func awakeFromNib() { self.navigationController?.navigationBar.titleTextAttributes = Constants.Color.TitleDict as! [String : AnyObject] } @IBAction func viewTypeSegmentPressed(sender: UISegmentedControl) { print("entered viewTypeSegmentPressed \(sender)") switch sender.selectedSegmentIndex { case 0: listContainerView.hidden = true mapContainerView.hidden = false case 1: mapContainerView.hidden = true listContainerView.hidden = false default: break } } }
mit
bf19158e5b3ecf8c14bc3d694ec65e5b
36.084337
149
0.641001
4.757342
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI/TimeParser.swift
1
1287
// // TimeParser.swift // VBVMI // // Created by Thomas Carey on 11/07/16. // Copyright © 2016 Tom Carey. All rights reserved. // import Foundation import Regex enum TimeParser { //Typical Title = "Galatians - Lesson 16B" fileprivate static let title = Regex("^(\\d*\\.?\\d*)") static func match(_ string: String) -> [String?]? { return title.firstMatch(in: string)?.captures } static func getTime(_ string: String) -> (DateComponents?) { guard let matches = match(string) else { return nil } //logger.warning("Matches: \(matches)") if matches.count == 1 { if let time = Double(matches[0]!) { let totalSeconds = time * 60 let hours = floor(totalSeconds / 3600) let minutes = floor((totalSeconds - (hours * 3600)) / 60) let seconds = totalSeconds - (hours * 3600) - (minutes * 60) var dateComponents = DateComponents() dateComponents.hour = Int(hours) dateComponents.minute = Int(minutes) dateComponents.second = Int(seconds) return dateComponents } } return nil } }
mit
6e48b4d83ab4a096b9638bb18ae4cb99
28.227273
76
0.528771
4.642599
false
false
false
false
gongmingqm10/DriftBook
DriftReading/DriftReading/MyDropBookViewController.swift
1
3674
// // MyDropBookViewController.swift // DriftReading // // Created by Ming Gong on 7/27/15. // Copyright © 2015 gongmingqm10. All rights reserved. // import UIKit class MyDropBookViewController: UITableViewController { @IBOutlet var dropTableView: UITableView! let driftAPI = DriftAPI() var books: [Book] = [] var selectedBook: Book? override func viewDidLoad() { let user = DataUtils.sharedInstance.currentUser() driftAPI.getOweBooks(user.userId, success: { (books) -> Void in self.books = books self.dropTableView.reloadData() }) { (error) -> Void in print(error.description) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "MyDropBookDetail" { let bookDetailController = segue.destinationViewController as! BookDetailViewController bookDetailController.bookId = selectedBook!.id } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedBook = books[indexPath.row] self.performSegueWithIdentifier("MyDropBookDetail", sender: self) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return books.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 158 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = dropTableView.dequeueReusableCellWithIdentifier("MyBookCell", forIndexPath: indexPath) as! MyBookCell let book = books[indexPath.row] cell.populate(book) cell.onButtonTapped = {(book) -> Void in let message = book.status == Book.STATUS_STOP ? Constants.MESSAGE_REDROP_BOOK : Constants.MESSAGE_RECEIVE_BOOK let status = book.status == Book.STATUS_STOP ? Book.STATUS_DRIFTING : Book.STATUS_STOP let alertController = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in let currentUser = DataUtils.sharedInstance.currentUser() self.driftAPI.updateBookStatus(currentUser.userId, bookId: (book.id)!, status: status, success: {(book) -> Void in cell.populate(book) self.updateBook(book) }, failure: {(error) -> Void in self.showErrorMessage(error) }) })) alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } return cell } private func updateBook(book: Book) { for var index = 0; index < books.count; ++index { if books[index].id == book.id { books[index] = book } } } private func showErrorMessage(error: APIError) { let alertController = UIAlertController(title: "错误", message: error.message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
085363c14ee79a80fa60ddc475e47fdd
40.511364
136
0.652341
4.956581
false
false
false
false
arthurschiller/ARKit-LeapMotion
Mac App/LeapMotion Visualization/ViewController/LeapVisualizationViewController.swift
1
6720
// // LeapMotionVisualizationViewController.swift // Mac App // // Created by Arthur Schiller on 12.08.17. // import Cocoa import SceneKit import MultipeerConnectivity class LeapVisualizationViewController: NSViewController { fileprivate var sceneManager: LeapVisualizationSceneManager? fileprivate let scene = LeapVisualizationScene() fileprivate lazy var sceneView: SCNView = { let view = SCNView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false return view }() // setup some properties for using multipeer connectivity fileprivate var peerID: MCPeerID! fileprivate var mcSession: MCSession! fileprivate var mcAdvertiserAssistant: MCAdvertiserAssistant! fileprivate var streamTargetPeer: MCPeerID? fileprivate var outputStream: OutputStream? fileprivate let leapService = LeapService() override func viewDidLoad() { super.viewDidLoad() commonInit() } override func viewDidAppear() { super.viewDidAppear() // as soon as the view appears, start advertising the service startHostingMCSession() } fileprivate func commonInit() { leapService.delegate = self leapService.run() sceneManager = LeapVisualizationSceneManager( sceneView: self.sceneView, scene: self.scene ) view.addSubview(sceneView) NSLayoutConstraint.activate([ sceneView.topAnchor.constraint(equalTo: view.topAnchor), sceneView.rightAnchor.constraint(equalTo: view.rightAnchor), sceneView.bottomAnchor.constraint(equalTo: view.bottomAnchor), sceneView.leftAnchor.constraint(equalTo: view.leftAnchor) ]) setupMultipeerConnectivity() scene.toggleNodes(show: false) } fileprivate func setupMultipeerConnectivity() { setupPeerId() mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .none) mcSession.delegate = self } fileprivate func startHostingMCSession() { print("Start advertising.") mcAdvertiserAssistant = MCAdvertiserAssistant( serviceType: LMMCService.type, discoveryInfo: nil, session: mcSession ) mcAdvertiserAssistant?.start() } fileprivate func setupPeerId() { /* If we have already have set a peerID, load it from the UserDefaults so we avoid creating a new one. Otherwise complications could arise. See: https://developer.apple.com/documentation/multipeerconnectivity/mcpeerid */ let kDisplayNameKey = "kDisplayNameKey" let kPeerIDKey = "kPeerIDKey" let displayName: String = "LMDSupply" let defaults = UserDefaults.standard let oldDisplayName = defaults.string(forKey: kDisplayNameKey) if oldDisplayName == displayName { guard let peerIDData = defaults.data(forKey: kPeerIDKey) else { return } guard let id = NSKeyedUnarchiver.unarchiveObject(with: peerIDData) as? MCPeerID else { return } self.peerID = id return } let peerID = MCPeerID(displayName: displayName) let peerIDData = NSKeyedArchiver.archivedData(withRootObject: peerID) defaults.set(peerIDData, forKey: kPeerIDKey) defaults.set(displayName, forKey: kDisplayNameKey) defaults.synchronize() self.peerID = peerID } fileprivate func stream(data: LMHData) { guard let outputStream = outputStream else { print("No Stream available") return } outputStream.write(data.toBytes(), maxLength: 24) } fileprivate func startStream() { guard let streamTargetPeer = streamTargetPeer, let stream = try? mcSession.startStream(withName: "LMDataStream", toPeer: streamTargetPeer) else { return } stream.schedule(in: .main, forMode: .defaultRunLoopMode) stream.delegate = self stream.open() self.outputStream = stream } } extension LeapVisualizationViewController: MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { switch state { case MCSessionState.connected: print("Connected: \(peerID.displayName)") streamTargetPeer = peerID startStream() case MCSessionState.connecting: print("Connecting: \(peerID.displayName)") case MCSessionState.notConnected: print("Not Connected: \(peerID.displayName)") } } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { print("did receive stream") } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { print("did start receiving resource") } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { print("did finish receiving resource") } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { print("did receive data") } } extension LeapVisualizationViewController: StreamDelegate { func stream(_ aStream: Stream, handle eventCode: Stream.Event) { // handle stream } } extension LeapVisualizationViewController: LeapServiceDelegate { func willUpdateData() { scene.toggleNodes(show: true) } func didStopUpdatingData() { scene.toggleNodes(show: false) } func didUpdate(handRepresentation: LeapHandRepresentation) { sceneManager?.leapHandRepresentation = handRepresentation serializeAndStream(handData: handRepresentation) } private func serializeAndStream(handData: LeapHandRepresentation) { guard let translation = handData.translation else { return } let serializedData = LMHData( x: translation.x, y: translation.y, z: translation.z, pitch: handData.eulerAngles.x, yaw: handData.eulerAngles.y, roll: handData.eulerAngles.z ) stream(data: serializedData) } }
mit
4047c834a53772d0a7f76fe26eda8f01
31.941176
168
0.64003
5.308057
false
false
false
false
zyuanming/YMStretchableHeaderTabViewController
Demo/YMStretchableHeaderTabViewController/SampleDataViewController.swift
1
2497
// // SampleDataViewController.swift // YMStretchableHeaderTabViewController // // Created by Zhang Yuanming on 4/30/17. // Copyright © 2017 None. All rights reserved. // import UIKit class SampleDataViewController: UITableViewController { var datas: [String] = [] { didSet { self.tableView.reloadData() } } var tag: String = "" override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") tableView.rowHeight = 44 tableView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("appear: \(tag)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("disappear: \(tag)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) if 0 <= indexPath.row, indexPath.row < datas.count { let text = datas[indexPath.row] cell.textLabel?.text = text } return cell } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let numberOfRows = CGFloat(tableView.dataSource?.tableView(tableView, numberOfRowsInSection: section) ?? 0) if numberOfRows == 0 { return tableView.frame.height } else { let extralHeight = tableView.frame.height - numberOfRows * tableView.rowHeight - tableView.contentInset.bottom return max(0.01, extralHeight) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.1 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UIView() } }
mit
a0c9694f6c07ddc75c59431698ebf464
27.689655
122
0.655048
5.157025
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXResult/New UI/PixCode/InstructionView.swift
1
4527
import UIKit final class InstructionView: UIView { // MARK: - Private properties private weak var delegate: ActionViewDelegate? private let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.ml_semiboldSystemFont(ofSize: 20) return label }() private let stepsStack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.alignment = .leading stack.spacing = 16 return stack }() private let watchIcon: UIImageView = { let image = UIImageView() image.image = ResourceManager.shared.getImage("iconTime") return image }() private let footerLabel: UILabel = { let label = UILabel() label.font = UIFont.ml_regularSystemFont(ofSize: 12) label.numberOfLines = 0 return label }() // MARK: - Initialization init(instruction: PXInstruction, delegate: ActionViewDelegate?) { self.delegate = delegate super.init(frame: .zero) setupViewConfiguration() setupInfos(with: instruction) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private methods private func setupInfos(with instruction: PXInstruction) { titleLabel.isHidden = instruction.subtitle == "" || instruction.subtitle == nil titleLabel.attributedText = instruction.subtitle?.htmlToAttributedString?.with(font: titleLabel.font) instruction.info.forEach { info in addLabel(info: info) } instruction.interactions?.forEach { interaction in addVariableComponents(interaction: interaction) } instruction.references?.forEach { reference in stepsStack.addArrangedSubviews(views: [InstructionReferenceView(reference: reference)]) } instruction.actions?.forEach { action in stepsStack.addArrangedSubviews(views: [ActionView(action: action, delegate: self)]) } instruction.secondaryInfo?.forEach { info in addLabel(info: info) } instruction.tertiaryInfo?.forEach { info in addLabel(info: info) } instruction.accreditationComments.forEach { info in addLabel(info: info) } footerLabel.attributedText = instruction.accreditationMessage?.htmlToAttributedString?.with(font: footerLabel.font) } private func addVariableComponents(interaction: PXInstructionInteraction) { stepsStack.addArrangedSubviews(views: [InstructionActionView(instruction: interaction, delegate: self)]) } private func addLabel(info: String) { let instructionLabel: UILabel = { let label = UILabel() label.attributedText = info.htmlToAttributedString?.with(font: UIFont.ml_lightSystemFont(ofSize: 16)) label.numberOfLines = 0 return label }() stepsStack.addArrangedSubviews(views: [instructionLabel]) } } extension InstructionView: ViewConfiguration { func buildHierarchy() { addSubviews(views: [titleLabel, stepsStack, watchIcon, footerLabel]) stepsStack.addArrangedSubviews(views: [titleLabel]) } func setupConstraints() { NSLayoutConstraint.activate([ stepsStack.topAnchor.constraint(equalTo: topAnchor, constant: 24), stepsStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 32), stepsStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -32), watchIcon.centerYAnchor.constraint(equalTo: footerLabel.centerYAnchor), watchIcon.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor), watchIcon.heightAnchor.constraint(equalToConstant: 16), watchIcon.widthAnchor.constraint(equalToConstant: 16), footerLabel.topAnchor.constraint(equalTo: stepsStack.bottomAnchor, constant: 24), footerLabel.leadingAnchor.constraint(equalTo: watchIcon.trailingAnchor, constant: 8), footerLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor), footerLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4) ]) } func viewConfigure() { backgroundColor = .white } } extension InstructionView: ActionViewDelegate { func didTapOnActionButton(action: PXInstructionAction?) { delegate?.didTapOnActionButton(action: action) } }
mit
fc5f3c7978ffa8eb03e88b16387baaaa
33.823077
123
0.666225
5.115254
false
false
false
false
JohnEstropia/Animo
Animo/Internal/Transition+AnimoInternals.swift
2
2407
// // Transition+AnimoInternals.swift // Animo // // Copyright © 2016 eureka, Inc. // // 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 QuartzCore // MARK: - Transition internal extension Transition { // MARK: Internal internal func applyTo(_ object: CATransition) { func subtypeForCATransition(_ direction: Direction) -> String { switch direction { case .leftToRight: return kCATransitionFromLeft case .rightToLeft: return kCATransitionFromRight case .topToBottom: return kCATransitionFromTop case .bottomToTop: return kCATransitionFromBottom } } switch self { case .fade: object.type = kCATransitionFade object.subtype = nil case .moveIn(let direction): object.type = kCATransitionMoveIn object.subtype = subtypeForCATransition(direction) case .push(let direction): object.type = kCATransitionPush object.subtype = subtypeForCATransition(direction) case .reveal(let direction): object.type = kCATransitionReveal object.subtype = subtypeForCATransition(direction) } } }
mit
0d43269788bbcb402783940b4fbb85ca
33.869565
82
0.657107
5.033473
false
false
false
false
mkaply/firefox-ios
Client/Frontend/Browser/MailProviders.swift
7
4748
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared // mailto headers: subject, body, cc, bcc protocol MailProvider { var beginningScheme: String {get set} var supportedHeaders: [String] {get set} func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? } private func constructEmailURLString(_ beginningURLString: String, metadata: MailToMetadata, supportedHeaders: [String], bodyHName: String = "body", toHName: String = "to") -> String { var lowercasedHeaders = [String: String]() metadata.headers.forEach { (hname, hvalue) in lowercasedHeaders[hname.lowercased()] = hvalue } var toParam: String if let toHValue = lowercasedHeaders["to"] { let value = metadata.to.isEmpty ? toHValue : [metadata.to, toHValue].joined(separator: "%2C%20") lowercasedHeaders.removeValue(forKey: "to") toParam = "\(toHName)=\(value)" } else { toParam = "\(toHName)=\(metadata.to)" } var queryParams: [String] = [] lowercasedHeaders.forEach({ (hname, hvalue) in if supportedHeaders.contains(hname) { queryParams.append("\(hname)=\(hvalue)") } else if hname == "body" { queryParams.append("\(bodyHName)=\(hvalue)") } }) let stringParams = queryParams.joined(separator: "&") let finalURLString = beginningURLString + (stringParams.isEmpty ? toParam : [toParam, stringParams].joined(separator: "&")) return finalURLString } class ReaddleSparkIntegration: MailProvider { var beginningScheme = "readdle-spark://compose?" var supportedHeaders = [ "subject", "recipient", "textbody", "html", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "textbody", toHName: "recipient").asURL } } class AirmailIntegration: MailProvider { var beginningScheme = "airmail://compose?" var supportedHeaders = [ "subject", "from", "to", "cc", "bcc", "plainBody", "htmlBody" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "htmlBody").asURL } } class MyMailIntegration: MailProvider { var beginningScheme = "mymail-mailto://?" var supportedHeaders = [ "to", "subject", "body", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class MailRuIntegration: MyMailIntegration { override init() { super.init() self.beginningScheme = "mailru-mailto://?" } } class MSOutlookIntegration: MailProvider { var beginningScheme = "ms-outlook://emails/new?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class YMailIntegration: MailProvider { var beginningScheme = "ymail://mail/any/compose?" var supportedHeaders = [ "to", "cc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class GoogleGmailIntegration: MailProvider { var beginningScheme = "googlegmail:///co?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class FastmailIntegration: MailProvider { var beginningScheme = "fastmail://mail/compose?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } }
mpl-2.0
fb4c42a4a399eb21c517b8ddf3a06a6a
29.435897
184
0.646167
4.168569
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine/dTextureManager.swift
1
3293
// // DKRTextureManager.swift // DrakkenEngine // // Created by Allison Lindner on 19/05/16. // Copyright © 2016 Allison Lindner. All rights reserved. // import Metal import MetalKit internal class dTextureManager { private var _mtkTextureLoaderInternal: MTKTextureLoader! private var _mtkTextureLoader: MTKTextureLoader { get { if _mtkTextureLoaderInternal == nil { _mtkTextureLoaderInternal = MTKTextureLoader(device: dCore.instance.device) } return self._mtkTextureLoaderInternal } } private var _textures: [Int : MTLTexture] = [:] private var _renderTargetTextures: [Int : MTLTexture] = [:] private var _namedTextures: [String : Int] = [:] private var _namedRenderTargetTextures: [String : Int] = [:] private var _nextTextureIndex: Int = 0 private var _nextRenderTargetIndex: Int = 0 internal var screenTexture: MTLTexture? internal func create(_ file: String) -> Int { let texture = self.loadImage(file)! guard let indexed = _namedTextures[file] else { let _index = _nextTextureIndex _textures[_index] = texture _nextTextureIndex += 1 _namedTextures[file] = _index return _index } _textures[indexed] = texture return indexed } internal func createRenderTarget(_ name: String, width: Int, height: Int) -> Int { let textureDesc = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false ) textureDesc.usage.insert(.renderTarget) let texture = dCore.instance.device.makeTexture(descriptor: textureDesc) guard let indexed = _namedRenderTargetTextures[name] else { let _index = _nextRenderTargetIndex _renderTargetTextures[_index] = texture _nextRenderTargetIndex += 1 _namedRenderTargetTextures[name] = _index return _index } _renderTargetTextures[indexed] = texture return indexed } internal func getTexture(_ id: Int) -> MTLTexture { return _textures[id]! } internal func getRenderTargetTexture(_ id: Int) -> MTLTexture { return _renderTargetTextures[id]! } internal func getTexture(_ file: String) -> MTLTexture { return getTexture(_namedTextures[file]!) } internal func getRenderTargetTexture(_ name: String) -> MTLTexture { return getRenderTargetTexture(_namedRenderTargetTextures[name]!) } internal func getID(_ name: String) -> Int? { return _namedTextures[name] } internal func getRenderTargetID(_ name: String) -> Int{ return _namedRenderTargetTextures[name]! } private func loadImage(_ name: String) -> MTLTexture? { var _textureURL: URL? do { if let textureURL = Bundle(identifier: "drakkenstudio.DrakkenEngine")!.url(forResource: name, withExtension: nil, subdirectory: "Assets") { _textureURL = textureURL } else if let textureURL = dCore.instance.IMAGES_PATH?.appendingPathComponent(name) { _textureURL = textureURL } if _textureURL != nil { let texture = try _mtkTextureLoader.newTexture(withContentsOf: _textureURL!, options: nil) return texture } else { fatalError("Fail load image with name: \(name)") } } catch { fatalError("Fail load image with name: \(name)") } return nil } internal func deleteAll() { _textures.removeAll() } }
gpl-3.0
bd164d78c25045dfbaebe2890be1621f
24.323077
142
0.696841
3.703037
false
false
false
false
hirohisa/RxSwift
RxSwift/RxSwift/Observables/Implementations/Catch.swift
11
5913
// // Catch.swift // RxSwift // // Created by Krunoslav Zaher on 4/19/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // catch with callback class CatchSinkProxy<O: ObserverType> : ObserverType { typealias Element = O.Element typealias Parent = CatchSink<O> let parent: Parent init(parent: Parent) { self.parent = parent } func on(event: Event<Element>) { trySend(parent.observer, event) switch event { case .Next: break case .Error: parent.dispose() case .Completed: parent.dispose() } } } class CatchSink<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.Element typealias Parent = Catch<Element> let parent: Parent let subscription = SerialDisposable() init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let disposableSubscription = parent.source.subscribeSafe(self) subscription.disposable = disposableSubscription return subscription } func on(event: Event<Element>) { switch event { case .Next: trySend(observer, event) case .Completed: trySend(observer, event) self.dispose() case .Error(let error): parent.handler(error).recoverWith { error2 in trySendError(observer, error2) self.dispose() return failure(error2) }.flatMap { catchObservable -> RxResult<Void> in let d = SingleAssignmentDisposable() subscription.disposable = d let observer = CatchSinkProxy(parent: self) let subscription2 = catchObservable.subscribeSafe(observer) d.disposable = subscription2 return SuccessResult } } } } class Catch<Element> : Producer<Element> { typealias Handler = (ErrorType) -> RxResult<Observable<Element>> let source: Observable<Element> let handler: Handler init(source: Observable<Element>, handler: Handler) { self.source = source self.handler = handler } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = CatchSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } } // catch to result // O: ObserverType caused compiler crashes, so let's leave that for now class CatchToResultSink<ElementType> : Sink<Observer<RxResult<ElementType>>>, ObserverType { typealias Element = ElementType typealias Parent = CatchToResult<Element> let parent: Parent init(parent: Parent, observer: Observer<RxResult<Element>>, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return parent.source.subscribeSafe(self) } func on(event: Event<Element>) { switch event { case .Next(let boxedValue): let value = boxedValue.value trySendNext(observer, success(value)) case .Completed: trySendCompleted(observer) self.dispose() case .Error(let error): trySendNext(observer, failure(error)) trySendCompleted(observer) self.dispose() } } } class CatchToResult<Element> : Producer <RxResult<Element>> { let source: Observable<Element> init(source: Observable<Element>) { self.source = source } override func run<O: ObserverType where O.Element == RxResult<Element>>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = CatchToResultSink(parent: self, observer: Observer<RxResult<Element>>.normalize(observer), cancel: cancel) setSink(sink) return sink.run() } } // catch enumerable class CatchSequenceSink<O: ObserverType> : TailRecursiveSink<O> { typealias Element = O.Element typealias Parent = CatchSequence<Element> var lastError: ErrorType? override init(observer: O, cancel: Disposable) { super.init(observer: observer, cancel: cancel) } override func on(event: Event<Element>) { switch event { case .Next: trySend(observer, event) case .Error(let error): self.lastError = error self.scheduleMoveNext() case .Completed: trySend(self.observer, event) self.dispose() } } override func done() { if let lastError = self.lastError { trySendError(observer, lastError) } else { trySendCompleted(observer) } self.dispose() } override func extract(observable: Observable<Element>) -> GeneratorOf<Observable<O.Element>>? { if let catch = observable as? CatchSequence<Element> { return catch.sources.generate() } else { return nil } } } class CatchSequence<Element> : Producer<Element> { let sources: SequenceOf<Observable<Element>> init(sources: SequenceOf<Observable<Element>>) { self.sources = sources } override func run<O : ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = CatchSequenceSink(observer: observer, cancel: cancel) setSink(sink) return sink.run(self.sources.generate()) } }
mit
f3f0ef9059dab6bcff05e11a1ff81226
27.708738
155
0.59885
4.696585
false
false
false
false
dreamsxin/swift
test/IDE/print_omit_needless_words.swift
2
15445
// RUN: rm -rf %t // RUN: mkdir -p %t // REQUIRES: objc_interop // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/AppKit.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ObjectiveC -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix > %t.ObjectiveC.txt // RUN: FileCheck %s -check-prefix=CHECK-OBJECTIVEC -strict-whitespace < %t.ObjectiveC.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.Foundation.txt // RUN: FileCheck %s -check-prefix=CHECK-FOUNDATION -strict-whitespace < %t.Foundation.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=AppKit -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.AppKit.txt // RUN: FileCheck %s -check-prefix=CHECK-APPKIT -strict-whitespace < %t.AppKit.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/../ClangModules/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=CoreCooling -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.CoreCooling.txt // RUN: FileCheck %s -check-prefix=CHECK-CORECOOLING -strict-whitespace < %t.CoreCooling.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=OmitNeedlessWords -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.OmitNeedlessWords.txt 2> %t.OmitNeedlessWords.diagnostics.txt // RUN: FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS -strict-whitespace < %t.OmitNeedlessWords.txt // RUN: FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS-DIAGS -strict-whitespace < %t.OmitNeedlessWords.diagnostics.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=errors -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.errors.txt // RUN: FileCheck %s -check-prefix=CHECK-ERRORS -strict-whitespace < %t.errors.txt // Note: SEL -> "Selector" // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector) // Note: "with" parameters. // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: AnyObject?) // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: AnyObject?, with: AnyObject?) // Note: don't prefix-strip swift_bridged classes or their subclasses. // CHECK-FOUNDATION: func mutableCopy() -> NSMutableArray // Note: id -> "Object". // CHECK-FOUNDATION: func index(of: AnyObject) -> Int // Note: Class -> "Class" // CHECK-OBJECTIVEC: func isKind(of aClass: AnyClass) -> Bool // Note: Pointer-to-struct name matching; preposition splitting. // // CHECK-FOUNDATION: func copy(with: Zone? = nil) -> AnyObject! // Note: Objective-C type parameter names. // CHECK-FOUNDATION: func object(forKey: Copying) -> AnyObject? // CHECK-FOUNDATION: func removeObject(forKey: Copying) // Note: Don't drop the name of the first parameter in an initializer entirely. // CHECK-FOUNDATION: init(array: [AnyObject]) // Note: struct name matching; don't drop "With". // CHECK-FOUNDATION: class func withRange(_: NSRange) -> Value // Note: built-in types. // CHECK-FOUNDATION: func add(_: Double) -> Number // Note: built-in types. // CHECK-FOUNDATION: func add(_: Bool) -> Number // Note: builtin-types. // CHECK-FOUNDATION: func add(_: UInt16) -> Number // Note: builtin-types. // CHECK-FOUNDATION: func add(_: Int32) -> Number // Note: Typedefs with a "_t" suffix". // CHECK-FOUNDATION: func subtract(_: Int32) -> Number // Note: Respect the getter name for BOOL properties. // CHECK-FOUNDATION: var isMakingHoney: Bool // Note: multi-word enum name matching; "with" splits the first piece. // CHECK-FOUNDATION: func someMethod(_: DeprecatedOptions = []) // Note: class name matching; don't drop "With". // CHECK-FOUNDATION: class func withString(_: String!) -> Self! // Note: lowercasing enum constants. // CHECK-FOUNDATION: enum ByteCountFormatterCountStyle : Int { // CHECK-FOUNDATION: case file // CHECK-FOUNDATION-NEXT: case memory // CHECK-FOUNDATION-NEXT: case decimal // CHECK-FOUNDATION-NEXT: case binary // Note: Make sure NSURL works in various places // CHECK-FOUNDATION: open(_: URL!, completionHandler: ((Bool) -> Void)!) // Note: property name stripping property type. // CHECK-FOUNDATION: var uppercased: String // Note: ok to map base name down to a keyword. // CHECK-FOUNDATION: func `do`(_: Selector!) // Note: Strip names preceded by a gerund. // CHECK-FOUNDATION: func startSquashing(_: Bee) // CHECK-FOUNDATION: func startSoothing(_: Bee) // CHECK-FOUNDATION: func startShopping(_: Bee) // Note: Removing plural forms when working with collections // CHECK-FOUNDATION: func add(_: [AnyObject]) // Note: Int and Index match. // CHECK-FOUNDATION: func slice(from: Int, to: Int) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func appending(_: String) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func withString(_: String) -> String // Note: Noun phrase puts preposition inside. // CHECK-FOUNDATION: func url(withAddedString: String) -> URL? // Note: CalendarUnits is not a set of "Options". // CHECK-FOUNDATION: class func forCalendarUnits(_: CalendarUnit) -> String! // Note: <property type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: var deletingLastPathComponent: URL? { get } // Note: <property type><preposition> --> <preposition>. // CHECK-FOUNDATION: var withHTTPS: URL { get } // Note: lowercasing option set values // CHECK-FOUNDATION: struct EnumerationOptions // CHECK-FOUNDATION: static var concurrent: EnumerationOptions // CHECK-FOUNDATION: static var reverse: EnumerationOptions // Note: usingBlock -> body // CHECK-FOUNDATION: func enumerateObjects(_: ((AnyObject?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // CHECK-FOUNDATION: func enumerateObjects(_: EnumerationOptions = [], using: ((AnyObject?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // Note: WithBlock -> body, nullable closures default to nil. // CHECK-FOUNDATION: func enumerateObjectsRandomly(_: ((AnyObject?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)? = nil) // Note: id<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomething(with: Copying) // Note: NSObject<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomethingElse(with: protocol<Copying, ObjectProtocol>) // Note: Function type -> "Function". // CHECK-FOUNDATION: func sort(_: @convention(c) (AnyObject, AnyObject) -> Int) // Note: Plural: NSArray without type arguments -> "Objects". // CHECK-FOUNDATION: func remove(_: [AnyObject]) // Note: Skipping "Type" suffix. // CHECK-FOUNDATION: func doSomething(with: UnderlyingType) // Don't introduce default arguments for lone parameters to setters. // CHECK-FOUNDATION: func setDefaultEnumerationOptions(_: EnumerationOptions) // CHECK-FOUNDATION: func normalizingXMLPreservingComments(_: Bool) // Collection element types. // CHECK-FOUNDATION: func adding(_: AnyObject) -> Set<Object> // Boolean properties follow the getter. // CHECK-FOUNDATION: var empty: Bool { get } // CHECK-FOUNDATION: func nonEmpty() -> Bool // CHECK-FOUNDATION: var isStringSet: Bool { get } // CHECK-FOUNDATION: var wantsAUnion: Bool { get } // CHECK-FOUNDATION: var watchesItsLanguage: Bool { get } // CHECK-FOUNDATION: var appliesForAJob: Bool { get } // CHECK-FOUNDATION: var setShouldBeInfinite: Bool { get } // "UTF8" initialisms. // CHECK-FOUNDATION: init?(utf8String: UnsafePointer<Int8>!) // Don't strip prefixes from globals. // CHECK-FOUNDATION: let NSGlobalConstant: String // CHECK-FOUNDATION: func NSGlobalFunction() // Cannot strip because we end up with something that isn't an identifier // CHECK-FOUNDATION: func NS123() // CHECK-FOUNDATION: func NSYELLING() // CHECK-FOUNDATION: func NS_SCREAMING() // CHECK-FOUNDATION: func NS_() // CHECK-FOUNDATION: let NSHTTPRequestKey: String // Lowercasing initialisms with plurals. // CHECK-FOUNDATION: var urlsInText: [URL] { get } // Don't strip prefixes from macro names. // CHECK-FOUNDATION: var NSTimeIntervalSince1970: Double { get } // CHECK-FOUNDATION: var NS_DO_SOMETHING: Int // Note: class method name stripping context type. // CHECK-APPKIT: class func red() -> NSColor // Note: instance method name stripping context type. // CHECK-APPKIT: func same() -> Self // Note: Unsafe(Mutable)Pointers don't get defaulted to 'nil' // CHECK-APPKIT: func getRGBAComponents(_: UnsafeMutablePointer<Int8>?) // Note: Skipping over "3D" // CHECK-APPKIT: func drawInAir(at: Point3D) // Note: with<something> -> <something> // CHECK-APPKIT: func draw(at: Point3D, withAttributes: [String : AnyObject]? = [:]) // Note: Don't strip names that aren't preceded by a verb or preposition. // CHECK-APPKIT: func setTextColor(_: NSColor?) // Note: Splitting with default arguments. // CHECK-APPKIT: func draw(in: NSView?) // Note: NSDictionary default arguments for "options" // CHECK-APPKIT: func drawAnywhere(in: NSView?, options: [Object : AnyObject] = [:]) // CHECK-APPKIT: func drawAnywhere(options: [Object : AnyObject] = [:]) // Note: no lowercasing of initialisms when there might be a prefix. // CHECK-CORECOOLING: func CFBottom() -> // Note: Skipping over "Ref" // CHECK-CORECOOLING: func replace(_: CCPowerSupply!) // Make sure we're removing redundant context type info at both the // beginning and the end. // CHECK-APPKIT: func reversing() -> NSBezierPath // Make sure we're dealing with 'instancetype' properly. // CHECK-APPKIT: func inventing() -> Self // Make sure we're removing redundant context type info at both the // beginning and the end of a property. // CHECK-APPKIT: var flattening: NSBezierPath { get } // CHECK-APPKIT: func dismiss(animated: Bool) // CHECK-APPKIT: func shouldCollapseAutoExpandedItems(forDeposited: Bool) -> Bool // Introducing argument labels and pruning the base name. // CHECK-APPKIT: func rectForCancelButton(whenCentered: Bool) // CHECK-APPKIT: func openUntitledDocumentAndDisplay(_: Bool) // Don't strip due to weak type information. // CHECK-APPKIT: func setContentHuggingPriority(_: NSLayoutPriority) // Look through typedefs of pointers. // CHECK-APPKIT: func layout(at: NSPointPointer!) // The presence of a property prevents us from stripping redundant // type information from the base name. // CHECK-APPKIT: func addGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func removeGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func favoriteView(for: NSGestureRecognizer) -> NSView? // CHECK-APPKIT: func addLayoutConstraints(_: Set<NSLayoutConstraint>) // CHECK-APPKIT: func add(_: Rect) // CHECK-APPKIT: class func conjureRect(_: Rect) // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: URL) // CHECK-OMIT-NEEDLESS-WORDS: func objectIs(compatibleWith: AnyObject) -> Bool // CHECK-OMIT-NEEDLESS-WORDS: func insetBy(x: Int, y: Int) // CHECK-OMIT-NEEDLESS-WORDS: func setIndirectlyToValue(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func jumpToTop(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func removeWithNoRemorse(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func bookmark(with: [URL]) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: URL, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func index(withItemNamed: String) // CHECK-OMIT-NEEDLESS-WORDS: func methodAndReturnError(_: AutoreleasingUnsafeMutablePointer<Error?>!) // CHECK-OMIT-NEEDLESS-WORDS: func type(of: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofNamedString: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofTypeNamed: String) // Look for preposition prior to "of". // CHECK-OMIT-NEEDLESS-WORDS: func append(withContentsOf: String) // Leave subscripts alone // CHECK-OMIT-NEEDLESS-WORDS: subscript(_: UInt) -> AnyObject { get } // CHECK-OMIT-NEEDLESS-WORDS: func objectAtIndexedSubscript(_: UInt) -> AnyObject // CHECK-OMIT-NEEDLESS-WORDS: func exportPresets(bestMatching: String) // CHECK-OMIT-NEEDLESS-WORDS: func `is`(compatibleWith: String) // CHECK-OMIT-NEEDLESS-WORDS: func add(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func slobbering(_: String) -> OmitNeedlessWords // Elements of C array types // CHECK-OMIT-NEEDLESS-WORDS: func drawPolygon(with: UnsafePointer<Point>!, count: Int) // Typedef ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func drawFilledPolygon(with: PointArray!, count: Int) // Non-parameterized Objective-C class ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func draw(_: SEGreebieArray) // "bound by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(boundBy: Int) // "separated by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(separatedBy: Int) // "Property"-like stripping for "set" methods. // CHECK-OMIT-NEEDLESS-WORDS: class func current() -> OmitNeedlessWords // CHECK-OMIT-NEEDLESS-WORDS: class func setCurrent(_: OmitNeedlessWords) // Property-name sensitivity in the base name "Self" stripping. // CHECK-OMIT-NEEDLESS-WORDS: func addDoodle(_: ABCDoodle) // Protocols as contexts // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWLanding { // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func flip() // Verify that we get the Swift name from the original declaration. // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWWiggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func wiggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWWaggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func waggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var waggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: class OMWSuper // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: class OMWSub // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C method 'conflicting1' in 'OMWSub' ('waggle1()' in 'OMWWaggle' vs. 'wiggle1()' in 'OMWWiggle') // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C property 'conflictingProp1' in 'OMWSub' ('waggleProp1' in 'OMWWaggle' vs. 'wiggleProp1' in 'OMWSuper') // Don't drop the 'error'. // CHECK-ERRORS: func tryAndReturnError(_: ()) throws
apache-2.0
83a4e450a44e291f04e0ad442c8665c4
44.426471
346
0.73383
3.387804
false
false
false
false
idapgroup/IDPDesign
Tests/iOS/Pods/Nimble/Sources/Nimble/Matchers/BeLessThanOrEqual.swift
18
1696
import Foundation /// A Nimble matcher that succeeds when the actual value is less than /// or equal to the expected value. public func beLessThanOrEqualTo<T: Comparable>(_ expectedValue: T?) -> Predicate<T> { return Predicate.simple("be less than or equal to <\(stringify(expectedValue))>") { actualExpression in if let actual = try actualExpression.evaluate(), let expected = expectedValue { return PredicateStatus(bool: actual <= expected) } return .fail } } /// A Nimble matcher that succeeds when the actual value is less than /// or equal to the expected value. public func beLessThanOrEqualTo<T: NMBComparable>(_ expectedValue: T?) -> Predicate<T> { return Predicate.simple("be less than or equal to <\(stringify(expectedValue))>") { actualExpression in let actualValue = try actualExpression.evaluate() let matches = actualValue.map { $0.NMB_compare(expectedValue) != .orderedDescending } ?? false return PredicateStatus(bool: matches) } } public func <=<T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beLessThanOrEqualTo(rhs)) } public func <=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beLessThanOrEqualTo(rhs)) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func beLessThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let expr = actualExpression.cast { $0 as? NMBComparable } return try beLessThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage) } } } #endif
bsd-3-clause
c12d929ae2de819fda09974431ecbb79
40.365854
107
0.695165
4.583784
false
false
false
false
zzxuxu/TestKitchen
TestKitchen/TestKitchen/Classes/Ingredient/main/model/IngreRecommend.swift
1
3762
// // IngreRecommend.swift // TestKitchen // // Created by 王健旭 on 2016/10/24. // Copyright © 2016年 王健旭. All rights reserved. // import UIKit import SwiftyJSON class IngreRecommend: NSObject { var code: NSNumber? var data:IngreRecommendData? var msg:NSNumber? var timestamp:NSNumber? var version:String? //解析 class func parseData(data:NSData) ->IngreRecommend { let json = JSON(data: data) let model = IngreRecommend() model.code = json["code"].number model.data = IngreRecommendData.parseModel(json["data"]) model.msg = json["msg"].number model.timestamp = json["timestamp"].number model.version = json["version"].string return model } } class IngreRecommendData: NSObject { var bannerArray: Array<IngreRecommendBanner>? var widgetList:Array<IngreRecommendwidgetList>? //解析 class func parseModel(json:JSON) -> IngreRecommendData { let model = IngreRecommendData() //广告数据 var tmpBannerArray = Array<IngreRecommendBanner>() for (_, subjson):(String, JSON) in json["banner"] { let bannerModel = IngreRecommendBanner.parseModel(subjson) tmpBannerArray.append(bannerModel) } model.bannerArray = tmpBannerArray //列表数据 var tmpList = Array<IngreRecommendwidgetList>() for (_, subjson): (String, JSON) in json["widgetList"] { let wModel = IngreRecommendwidgetList.parseModel(subjson) tmpList.append(wModel) } model.widgetList = tmpList return model } } class IngreRecommendBanner: NSObject { var banner_id: NSNumber? var banner_link: String? var banner_picture: String? var banner_title: String? var is_link: NSNumber? var refer_key:NSNumber? var type_id:NSNumber? class func parseModel(json:JSON) -> IngreRecommendBanner { let model = IngreRecommendBanner() model.banner_id = json["banner_id"].number model.banner_link = json["banner_link"].string model.banner_picture = json["banner_picture"].string model.banner_title = json["banner_title"].string model.is_link = json["is_link"].number model.refer_key = json["refer_key"].number model.type_id = json["type_id"].number return model } } class IngreRecommendwidgetList:NSObject { var desc:String? var title:String? var title_link:String? var widget_data:Array<IngreRecommendwidgetData>? var widget_id:NSNumber? var widget_type:NSNumber? class func parseModel(json:JSON) -> IngreRecommendwidgetList { let model = IngreRecommendwidgetList() model.desc = json["desc"].string model.title = json["title"].string model.title_link = json["title_link"].string var dataArray = Array<IngreRecommendwidgetData>() for (_,subjson):(String,JSON) in json["widget_data"] { let subModel = IngreRecommendwidgetData.parseModel(subjson) dataArray.append(subModel) } model.widget_data = dataArray model.widget_id = json["widget_id"].number model.widget_type = json["widget_type"].number return model } } class IngreRecommendwidgetData:NSObject { var content:String? var id:NSNumber? var link:String? var type:String? class func parseModel(json:JSON) -> IngreRecommendwidgetData { let model = IngreRecommendwidgetData() model.content = json["content"].string model.id = json["id"].number model.link = json["link"].string model.type = json["type"].string return model } }
mit
d507202fc2b4abb55502f3226d142bab
23.655629
71
0.637926
4.127494
false
false
false
false
velvetroom/columbus
Source/Model/CreateSave/MCreateSave+MapFactory.swift
1
1298
import MapKit extension MCreateSave { //MARK: private private class func factoryMapPoints(stops:[DPlanStop]) -> [MKMapPoint] { var points:[MKMapPoint] = [] for stop:DPlanStop in stops { let mapPoint:MKMapPoint = MKMapPointForCoordinate(stop.coordinate) points.append(mapPoint) } return points } private class func factoryMapRange(mapPoints:[MKMapPoint]) -> MCreateSaveMapRange? { var mapRange:MCreateSaveMapRange? for mapPoint:MKMapPoint in mapPoints { guard mapRange == nil else { mapRange = mapRange?.comparingMapPoint(mapPoint:mapPoint) continue } mapRange = MCreateSaveMapRange.fromMapPoint(mapPoint:mapPoint) } return mapRange } //MARK: internal class func factoryMapRange(stops:[DPlanStop]) -> MCreateSaveMapRange? { let mapPoints:[MKMapPoint] = factoryMapPoints(stops:stops) let mapRange:MCreateSaveMapRange? = factoryMapRange(mapPoints:mapPoints) return mapRange } }
mit
36aac62c69d84de45819e0a181b10809
23.490566
86
0.540832
5.150794
false
false
false
false
emilstahl/swift
stdlib/public/core/SliceBuffer.swift
9
10847
//===--- SliceBuffer.swift - Backing storage for ArraySlice<Element> ------===// // // 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 // //===----------------------------------------------------------------------===// /// Buffer type for `ArraySlice<Element>`. public // @testable struct _SliceBuffer<Element> : _ArrayBufferType { internal typealias NativeStorage = _ContiguousArrayStorage<Element> public typealias NativeBuffer = _ContiguousArrayBuffer<Element> init( owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>, indices: Range<Int>, hasNativeBuffer: Bool ) { self.owner = owner self.subscriptBaseAddress = subscriptBaseAddress self.startIndex = indices.startIndex let bufferFlag = UInt(hasNativeBuffer ? 1 : 0) self.endIndexAndFlags = (UInt(indices.endIndex) << 1) | bufferFlag _invariantCheck() } public init() { let empty = _ContiguousArrayBuffer<Element>() self.owner = empty.owner self.subscriptBaseAddress = empty.firstElementAddress self.startIndex = empty.startIndex self.endIndexAndFlags = 1 _invariantCheck() } public init(_ buffer: NativeBuffer, shiftedToStartIndex: Int) { let shift = buffer.startIndex - shiftedToStartIndex self.init( owner: buffer.owner, subscriptBaseAddress: buffer.subscriptBaseAddress + shift, indices: shiftedToStartIndex..<shiftedToStartIndex + buffer.count, hasNativeBuffer: true) } func _invariantCheck() { let isNative = _hasNativeBuffer let isNativeStorage: Bool = (owner as? _ContiguousArrayStorageBase) != nil _sanityCheck(isNativeStorage == isNative) if isNative { _sanityCheck(count <= nativeBuffer.count) } } var _hasNativeBuffer: Bool { return (endIndexAndFlags & 1) != 0 } var nativeBuffer: NativeBuffer { _sanityCheck(_hasNativeBuffer) return NativeBuffer( owner as? _ContiguousArrayStorageBase ?? _emptyArrayStorage) } public var nativeOwner: AnyObject { _sanityCheck(_hasNativeBuffer, "Expect a native array") return owner } /// Replace the given subRange with the first newCount elements of /// the given collection. /// /// - Requires: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer` and /// `insertCount <= numericCast(newValues.count)`. public mutating func replace< C : CollectionType where C.Generator.Element == Element >( subRange subRange: Range<Int>, with insertCount: Int, elementsOf newValues: C ) { _invariantCheck() _sanityCheck(insertCount <= numericCast(newValues.count)) _sanityCheck(_hasNativeBuffer && isUniquelyReferenced()) let eraseCount = subRange.count let growth = insertCount - eraseCount let oldCount = count var native = nativeBuffer let hiddenElementCount = firstElementAddress - native.firstElementAddress _sanityCheck(native.count + growth <= native.capacity) let start = subRange.startIndex - startIndex + hiddenElementCount let end = subRange.endIndex - startIndex + hiddenElementCount native.replace( subRange: start..<end, with: insertCount, elementsOf: newValues) self.endIndex = self.startIndex + oldCount + growth _invariantCheck() } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. public var identity: UnsafePointer<Void> { return UnsafePointer(firstElementAddress) } /// An object that keeps the elements stored in this buffer alive. public var owner: AnyObject public let subscriptBaseAddress: UnsafeMutablePointer<Element> public var firstElementAddress: UnsafeMutablePointer<Element> { return subscriptBaseAddress + startIndex } /// [63:1: 63-bit index][0: has a native buffer] var endIndexAndFlags: UInt //===--- Non-essential bits ---------------------------------------------===// @warn_unused_result public mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { _invariantCheck() if _fastPath(_hasNativeBuffer && isUniquelyReferenced()) { if capacity >= minimumCapacity { // Since we have the last reference, drop any inaccessible // trailing elements in the underlying storage. That will // tend to reduce shuffling of later elements. Since this // function isn't called for subscripting, this won't slow // down that case. var native = nativeBuffer let offset = self.firstElementAddress - native.firstElementAddress let backingCount = native.count let myCount = count if _slowPath(backingCount > myCount + offset) { native.replace( subRange: (myCount+offset)..<backingCount, with: 0, elementsOf: EmptyCollection()) } _invariantCheck() return native } } return nil } @warn_unused_result public mutating func isMutableAndUniquelyReferenced() -> Bool { return _hasNativeBuffer && isUniquelyReferenced() } @warn_unused_result public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return _hasNativeBuffer && isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @warn_unused_result public func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { _invariantCheck() if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) { return nativeBuffer } return nil } public func _uninitializedCopy( subRange: Range<Int>, target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _invariantCheck() _sanityCheck(subRange.startIndex >= startIndex) _sanityCheck(subRange.endIndex >= subRange.startIndex) _sanityCheck(subRange.endIndex <= endIndex) let c = subRange.count target.initializeFrom(subscriptBaseAddress + subRange.startIndex, count: c) return target + c } var arrayPropertyIsNative : Bool { return _hasNativeBuffer } /// True, if the array is native and does not need a deferred type check. var arrayPropertyIsNativeTypeChecked : Bool { return _hasNativeBuffer } public var count: Int { get { return endIndex - startIndex } set { let growth = newValue - count if growth != 0 { nativeBuffer.count += growth self.endIndex += growth } _invariantCheck() } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `startIndex ≤ index < endIndex` internal func _checkValidSubscript(index : Int) { _precondition( index >= startIndex && index < endIndex, "Index out of bounds") } public var capacity: Int { let count = self.count if _slowPath(!_hasNativeBuffer) { return count } let n = nativeBuffer let nativeEnd = n.firstElementAddress + n.count if (firstElementAddress + count) == nativeEnd { return count + (n.capacity - n.count) } return count } @warn_unused_result mutating func isUniquelyReferenced() -> Bool { return isUniquelyReferencedNonObjC(&owner) } @warn_unused_result mutating func isUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinnedNonObjC(&owner) } @warn_unused_result func getElement(i: Int) -> Element { _sanityCheck(i >= startIndex, "negative slice index is out of range") _sanityCheck(i < endIndex, "slice index out of range") return subscriptBaseAddress[i] } /// Access the element at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Int) -> Element { get { return getElement(position) } nonmutating set { _sanityCheck(position >= startIndex, "negative slice index is out of range") _sanityCheck(position < endIndex, "slice index out of range") subscriptBaseAddress[position] = newValue } } public subscript(subRange: Range<Int>) -> _SliceBuffer { get { _sanityCheck(subRange.startIndex >= startIndex) _sanityCheck(subRange.endIndex >= subRange.startIndex) _sanityCheck(subRange.endIndex <= endIndex) return _SliceBuffer( owner: owner, subscriptBaseAddress: subscriptBaseAddress, indices: subRange, hasNativeBuffer: _hasNativeBuffer) } set { fatalError("not implemented") } } //===--- CollectionType conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Int /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Int { get { return Int(endIndexAndFlags >> 1) } set { endIndexAndFlags = (UInt(newValue) << 1) | (_hasNativeBuffer ? 1 : 0) } } //===--- misc -----------------------------------------------------------===// /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. public func withUnsafeBufferPointer<R>( @noescape body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. public mutating func withUnsafeMutableBufferPointer<R>( @noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } } extension _SliceBuffer { public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Element> { if _hasNativeBuffer { let n = nativeBuffer if count == n.count { return n } } let result = _ContiguousArrayBuffer<Element>( count: count, minimumCapacity: 0) result.firstElementAddress.initializeFrom(firstElementAddress, count: count) return result } }
apache-2.0
246c910eda7232959d22d3e6ae474b44
29.985714
82
0.666667
4.891746
false
false
false
false
rtsbtx/EasyIOS-Swift
Pod/Classes/Easy/Lib/EZKit.swift
4
6028
// // CEMKit.swift // CEMKit-Swift // // Created by Cem Olcay on 05/11/14. // Copyright (c) 2014 Cem Olcay. All rights reserved. // import UIKit // MARK: - UIBarButtonItem public func barButtonItem (imageName: String, action: (AnyObject)->()) -> UIBarButtonItem { let button = BlockButton (frame: CGRect(x: 0, y: 0, width: 20, height: 20)) button.setImage(UIImage(named: imageName), forState: .Normal) button.actionBlock = action return UIBarButtonItem (customView: button) } public func barButtonItem (title: String, color: UIColor, action: (AnyObject)->()) -> UIBarButtonItem { let button = BlockButton (frame: CGRect(x: 0, y: 0, width: 20, height: 20)) button.setTitle(title, forState: .Normal) button.setTitleColor(color, forState: .Normal) button.actionBlock = action button.sizeToFit() return UIBarButtonItem (customView: button) } // MARK: - CGSize public func + (left: CGSize, right: CGSize) -> CGSize { return CGSize (width: left.width + right.width, height: left.height + right.height) } public func - (left: CGSize, right: CGSize) -> CGSize { return CGSize (width: left.width - right.width, height: left.width - right.width) } // MARK: - CGPoint public func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint (x: left.x + right.x, y: left.y + right.y) } public func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint (x: left.x - right.x, y: left.y - right.y) } public enum AnchorPosition: CGPoint { case TopLeft = "{0, 0}" case TopCenter = "{0.5, 0}" case TopRight = "{1, 0}" case MidLeft = "{0, 0.5}" case MidCenter = "{0.5, 0.5}" case MidRight = "{1, 0.5}" case BottomLeft = "{0, 1}" case BottomCenter = "{0.5, 1}" case BottomRight = "{1, 1}" } extension CGPoint: StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self = CGPointFromString(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self = CGPointFromString(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self = CGPointFromString(value) } } // MARK: - CGFloat public func degreesToRadians (angle: CGFloat) -> CGFloat { return (CGFloat (M_PI) * angle) / 180.0 } public func normalizeValue (value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { return (max - min) / value } public func convertNormalizedValue (value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { return ((max - min) * value) + min } // MARK: - Block Classes // MARK: - BlockButton public class BlockButton: UIButton { override init (frame: CGRect) { super.init(frame: frame) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var actionBlock: ((sender: BlockButton) -> ())? { didSet { self.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside) } } func action (sender: BlockButton) { actionBlock! (sender: sender) } } // MARK: - BlockWebView public class BlockWebView: UIWebView, UIWebViewDelegate { var didStartLoad: ((NSURLRequest) -> ())? var didFinishLoad: ((NSURLRequest) -> ())? var didFailLoad: ((NSURLRequest, NSError) -> ())? var shouldStartLoadingRequest: ((NSURLRequest) -> (Bool))? override init(frame: CGRect) { super.init(frame: frame) delegate = self } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func webViewDidStartLoad(webView: UIWebView) { didStartLoad? (webView.request!) } private func webViewDidFinishLoad(webView: UIWebView) { didFinishLoad? (webView.request!) } private func webView(webView: UIWebView, didFailLoadWithError error: NSError) { didFailLoad? (webView.request!, error) } private func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let should = shouldStartLoadingRequest { return should (request) } else { return true } } } public func nsValueForAny(anyValue:Any) -> NSObject? { switch(anyValue) { case let intValue as Int: return NSNumber(int: CInt(intValue)) case let doubleValue as Double: return NSNumber(double: CDouble(doubleValue)) case let stringValue as String: return stringValue as NSString case let boolValue as Bool: return NSNumber(bool: boolValue) default: return nil } } extension NSObject{ public class var nameOfClass: String{ return NSStringFromClass(self).componentsSeparatedByString(".").last! } public var nameOfClass: String{ return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last! } public func listProperties() -> Dictionary<String,AnyObject>{ var mirror=reflect(self) var modelDictionary = Dictionary<String,AnyObject>() for (var i=0;i<mirror.count;i++) { if (mirror[i].0 != "super") { if let nsValue = nsValueForAny(mirror[i].1.value) { modelDictionary.updateValue(nsValue, forKey: mirror[i].0) } } } return modelDictionary } } public func isEmpty<C : NSObject>(x: C) -> Bool { if x.isKindOfClass(NSNull) { return true }else if x.respondsToSelector(Selector("length")) && NSData().self.length == 0 { return true }else if x.respondsToSelector(Selector("count")) && NSArray().self.count == 0 { return true } return false }
mit
8a024128ea87cfe7340f67712b589cbc
23.909091
145
0.614134
4.242083
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/PreviewingViewController.swift
2
1586
import UIKit class PreviewingViewController: ThemeableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) registerForPreviewingIfAvailable() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) unregisterForPreviewing() } // MARK - 3D Touch var previewingContext: UIViewControllerPreviewing? func unregisterForPreviewing() { guard let context = previewingContext else { return } unregisterForPreviewing(withContext: context) } func registerForPreviewingIfAvailable() { unregisterForPreviewing() guard traitCollection.forceTouchCapability == .available, let sourceView = viewIfLoaded else { return } previewingContext = registerForPreviewing(with: self, sourceView: sourceView) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) registerForPreviewingIfAvailable() } } // MARK: - UIViewControllerPreviewingDelegate extension PreviewingViewController: UIViewControllerPreviewingDelegate { open func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { return nil } open func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { } }
mit
88d31ea9416cc1eea98a69de6ad78a0c
32.744681
148
0.717528
7.080357
false
false
false
false
raphaelhanneken/iconizer
Iconizer/Controller/AppIconViewController.swift
1
3919
// // AppIconViewController.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // import Cocoa /// Controller for the AppIconView class AppIconViewController: NSViewController, IconizerViewControllerProtocol { /// Create an App Icon for Apple Car Play. @IBOutlet weak var carPlay: NSButton! /// Create an App Icon for the iPad. @IBOutlet weak var iPad: NSButton! /// Create an App Icon for the iPhone. @IBOutlet weak var iPhone: NSButton! /// Crete an App Icon for macOS. @IBOutlet weak var osx: NSButton! /// Create an App Icon for the Apple Watch. @IBOutlet weak var watch: NSButton! /// Create an Icon for the iMessage. @IBOutlet weak var iMessage: NSButton! /// Holds the ImageView for the image to generate the App Icon from. @IBOutlet weak var imageView: NSImageView! /// Manage the user's preferences. let prefManager = PreferenceManager() /// Check which platforms are selected. var appPlatforms: [Platform] { // String array of selected platforms. var platform = [Platform]() if carPlay.state == .on { platform.append(Platform.car) } if iPad.state == .on { platform.append(Platform.iPad) } if iPhone.state == .on { platform.append(Platform.iPhone) } if osx.state == .on { platform.append(Platform.macOS) } if watch.state == .on { platform.append(Platform.watch) } if iPad.state == .on || iPhone.state == .on { platform.append(Platform.iOS) } if iMessage.state == .on { platform.append(Platform.iMessage) } return platform } /// The name of the corresponding nib file. override var nibName: NSNib.Name { return "AppIconView" } // MARK: View Controller override func viewDidLoad() { super.viewDidLoad() watch.state = .init(rawValue: prefManager.generateAppIconForAppleWatch) iPhone.state = .init(rawValue: prefManager.generateAppIconForIPhone) iPad.state = .init(rawValue: prefManager.generateAppIconForIPad) osx.state = .init(rawValue: prefManager.generateAppIconForMac) carPlay.state = .init(rawValue: prefManager.generateAppIconForCar) iMessage.state = .init(rawValue: prefManager.generateMessagesIcon) } override func viewWillDisappear() { prefManager.generateAppIconForAppleWatch = watch.state.rawValue prefManager.generateAppIconForIPad = iPad.state.rawValue prefManager.generateAppIconForIPhone = iPhone.state.rawValue prefManager.generateAppIconForMac = osx.state.rawValue prefManager.generateAppIconForCar = carPlay.state.rawValue prefManager.generateMessagesIcon = iMessage.state.rawValue } // MARK: Iconizer View Controller func saveAssetCatalog(named name: String, toURL url: URL) throws { guard let image = imageView.image else { throw IconizerViewControllerError.missingImage } guard appPlatforms.count > 0 else { throw IconizerViewControllerError.missingPlatform } let catalog = AssetCatalog<AppIcon>() try appPlatforms.forEach { platform in if platform == .iMessage { let iMessageCatalog = AssetCatalog<MessagesIcon>() try iMessageCatalog.add(.iMessage) try iMessageCatalog.save([.all: image], named: name, toURL: url) } else { try catalog.add(platform) } } try catalog.save([.all: image], named: name, toURL: url) } func openSelectedImage(_ image: NSImage?) throws { guard let img = image else { throw IconizerViewControllerError.selectedImageNotFound } imageView.image = img } }
mit
ce846f0aee5645dbf27de8b113e75902
32.495726
80
0.638428
4.738815
false
false
false
false
liqk2014/actor-platform
actor-apps/app-ios/Actor/Controllers/Dialogs/Cells/DialogCell.swift
55
6206
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit; class DialogCell: UITableViewCell { let avatarView = AvatarView(frameSize: 48, type: .Rounded) let titleView: UILabel = UILabel() let messageView: UILabel = UILabel() let dateView: UILabel = UILabel() let statusView: UIImageView = UIImageView() let separatorView = TableViewSeparator(color: MainAppTheme.list.separatorColor) let unreadView: UILabel = UILabel() let unreadViewBg: UIImageView = UIImageView() var bindedFile: jlong? = nil; var avatarCallback: CocoaDownloadCallback? = nil; init(reuseIdentifier:String) { super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) backgroundColor = MainAppTheme.list.bgColor titleView.font = UIFont(name: "Roboto-Medium", size: 19); titleView.textColor = MainAppTheme.list.dialogTitle messageView.font = UIFont(name: "HelveticaNeue", size: 16); messageView.textColor = MainAppTheme.list.dialogText dateView.font = UIFont(name: "HelveticaNeue", size: 14); dateView.textColor = MainAppTheme.list.dialogDate dateView.textAlignment = NSTextAlignment.Right; statusView.contentMode = UIViewContentMode.Center; unreadView.font = UIFont(name: "HelveticaNeue", size: 14); unreadView.textColor = MainAppTheme.list.unreadText unreadView.textAlignment = .Center unreadViewBg.image = Imaging.imageWithColor(MainAppTheme.list.unreadBg, size: CGSizeMake(18, 18)) .roundImage(18).resizableImageWithCapInsets(UIEdgeInsetsMake(9, 9, 9, 9)) self.contentView.addSubview(avatarView) self.contentView.addSubview(titleView) self.contentView.addSubview(messageView) self.contentView.addSubview(dateView) self.contentView.addSubview(statusView) self.contentView.addSubview(separatorView) self.contentView.addSubview(unreadViewBg) self.contentView.addSubview(unreadView) var selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindDialog(dialog: AMDialog, isLast:Bool) { self.avatarView.bind(dialog.getDialogTitle(), id: dialog.getPeer().getPeerId(), avatar: dialog.getDialogAvatar()); self.titleView.text = dialog.getDialogTitle(); self.messageView.text = MSG.getFormatter().formatDialogText(dialog) if (dialog.getDate() > 0) { self.dateView.text = MSG.getFormatter().formatShortDate(dialog.getDate()); self.dateView.hidden = false; } else { self.dateView.hidden = true; } if (dialog.getUnreadCount() != 0) { self.unreadView.text = "\(dialog.getUnreadCount())" self.unreadView.hidden = false self.unreadViewBg.hidden = false } else { self.unreadView.hidden = true self.unreadViewBg.hidden = true } var messageState = UInt(dialog.getStatus().ordinal()); if (messageState == AMMessageState.PENDING.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSending self.statusView.image = Resources.iconClock; self.statusView.hidden = false; } else if (messageState == AMMessageState.READ.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogRead self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == AMMessageState.RECEIVED.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogReceived self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == AMMessageState.SENT.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSent self.statusView.image = Resources.iconCheck1; self.statusView.hidden = false; } else if (messageState == AMMessageState.ERROR.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogError self.statusView.image = Resources.iconError; self.statusView.hidden = false; } else { self.statusView.hidden = true; } self.separatorView.hidden = isLast; setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews(); // We expect height == 76; let width = self.contentView.frame.width; let leftPadding = CGFloat(76); let padding = CGFloat(14); avatarView.frame = CGRectMake(padding, padding, 48, 48); titleView.frame = CGRectMake(leftPadding, 18, width - leftPadding - /*paddingRight*/(padding + 50), 18); var messagePadding:CGFloat = 0; if (!self.statusView.hidden) { messagePadding = 22; statusView.frame = CGRectMake(leftPadding, 44, 20, 18); } var unreadPadding = CGFloat(0) if (!self.unreadView.hidden) { unreadView.frame = CGRectMake(0, 0, 1000, 1000) unreadView.sizeToFit() let unreadW = max(unreadView.frame.width + 8, 18) unreadView.frame = CGRectMake(width - padding - unreadW, 44, unreadW, 18) unreadViewBg.frame = unreadView.frame unreadPadding = unreadW } messageView.frame = CGRectMake(leftPadding+messagePadding, 44, width - leftPadding - /*paddingRight*/padding - messagePadding - unreadPadding, 18); dateView.frame = CGRectMake(width - /*width*/60 - /*paddingRight*/padding , 18, 60, 18); separatorView.frame = CGRectMake(leftPadding, 75.5, width, 0.5); } }
mit
5b81aa764c7e4440698fcb9cfa025bb3
39.835526
155
0.631486
4.810853
false
false
false
false
adrfer/swift
test/decl/func/trailing_closures.swift
11
1017
// RUN: %target-parse-verify-swift // Warn about non-trailing closures followed by parameters with // default arguments. func f1(f: () -> (), bar: Int = 10) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} func f2(f: (() -> ())!, bar: Int = 10, wibble: Int = 17) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} func f3(f: (() -> ())?, bar: Int = 10) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} func f4(f: (() -> ())?, bar: Int = 10) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} // An extra set of parentheses suppresses the warning. func g1(f: (() -> ()), bar: Int = 10) { } // no-warning // Stop at the first closure. func g2(f: () -> (), g: (() -> ())? = nil) { } // no-warning
apache-2.0
74a1203efd0a56eca0f447db28b4f457
71.642857
186
0.668633
3.852273
false
false
false
false
nathantannar4/NTComponents
NTComponents/Extensions/Date.swift
1
12330
// // Date.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 2/12/17. // public extension Date { func addMonth(_ n: Int) -> Date { let cal = NSCalendar.current return cal.date(byAdding: .month, value: n, to: self)! } func addDay(_ n: Int) -> Date { let cal = NSCalendar.current return cal.date(byAdding: .day, value: n, to: self)! } func addSec(_ n: Int) -> Date { let cal = NSCalendar.current return cal.date(byAdding: .second, value: n, to: self)! } func startOfMonth() -> Date { return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))! } func endOfMonth() -> Date { return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())! } func string(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String { let dateFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.timeStyle = timeStyle dateFormatter.dateStyle = dateStyle return dateFormatter.string(from: self) } func timeElapsedDescription() -> String { let seconds = Date().timeIntervalSince(self) var elapsed: String if seconds < 60 { elapsed = "Just now" } else if seconds < 60 * 60 { let minutes = Int(seconds / 60) let suffix = (minutes > 1) ? "mins" : "min" elapsed = "\(minutes) \(suffix) ago" } else if seconds < 24 * 60 * 60 { let hours = Int(seconds / (60 * 60)) let suffix = (hours > 1) ? "hours" : "hour" elapsed = "\(hours) \(suffix) ago" } else { let days = Int(seconds / (24 * 60 * 60)) let suffix = (days > 1) ? "days" : "day" elapsed = "\(days) \(suffix) ago" } return elapsed } // MARK:- APP SPECIFIC FORMATS func dateFromString(strDate: String, format: String) -> Date? { let dateFormatter:DateFormatter = DateFormatter() dateFormatter.dateFormat = format if let dtDate = dateFormatter.date(from: strDate){ return dtDate as Date? } return nil } func stringify() -> String { let dateFormatter:DateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let strdt = dateFormatter.string(from: self as Date) if let dtDate = dateFormatter.date(from: strdt){ return dateFormatter.string(from: dtDate) } return "--" } func stringifyTimestamp() -> String { return "\(self.hourTwoDigit):\(self.minuteTwoDigit) \(self.AM_PM) \(self.monthNameShort) \(self.dayTwoDigit)" } func getUTCFormateDate(localDate: NSDate) -> String { let dateFormatter:DateFormatter = DateFormatter() let timeZone: NSTimeZone = NSTimeZone(name: "UTC")! dateFormatter.timeZone = timeZone as TimeZone! dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm" let dateString: String = dateFormatter.string(from: localDate as Date) return dateString } func combineDateWithTime(date: NSDate, time: NSDate) -> NSDate? { let calendar = NSCalendar.current let dateComponents = calendar.dateComponents([.year, .month, .day], from: date as Date) let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time as Date) let mergedComponments = NSDateComponents() mergedComponments.year = dateComponents.year! mergedComponments.month = dateComponents.month! mergedComponments.day = dateComponents.day! mergedComponments.hour = timeComponents.hour! mergedComponments.minute = timeComponents.minute! mergedComponments.second = timeComponents.second! return calendar.date(from: mergedComponments as DateComponents) as NSDate? } func getDatesBetweenDates(startDate: Date, andEndDate endDate: Date) -> [Date] { let gregorian: NSCalendar = NSCalendar.current as NSCalendar; let components = gregorian.components(NSCalendar.Unit.day, from: startDate, to: endDate, options: []) var arrDates = [Date]() for i in 0...components.day!{ arrDates.append(startDate.addingTimeInterval(60*60*24*Double(i))) } return arrDates } func isGreaterThanDate(_ dateToCompare: NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(_ dateToCompare: Date) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending { isLess = true } //Return Result return isLess } func isEqualToDate(_ dateToCompare: NSDate) -> Bool { //Declare Variables var isEqualTo = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame { isEqualTo = true } //Return Result return isEqualTo } // MARK:- TIME var timeWithAMPM: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mma" dateFormatter.amSymbol = "am" dateFormatter.pmSymbol = "pm" return dateFormatter.string(from: self as Date) } // MARK:- YEAR var yearFourDigit_Int: Int { return Int(self.yearFourDigit)! } var yearOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "y" return dateFormatter.string(from: self as Date) } var yearTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yy" return dateFormatter.string(from: self as Date) } var yearFourDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy" return dateFormatter.string(from: self as Date) } // MARK:- MONTH var monthOneDigit_Int: Int { return Int(self.monthOneDigit)! } var monthTwoDigit_Int: Int { return Int(self.monthTwoDigit)! } var monthOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "M" return dateFormatter.string(from: self as Date) } var monthTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM" return dateFormatter.string(from: self as Date) } var monthNameShort: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM" return dateFormatter.string(from: self as Date) } var monthNameFull: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM" return dateFormatter.string(from: self as Date) } var monthNameFirstLetter: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMMM" return dateFormatter.string(from: self as Date) } // MARK:- DAY var dayOneDigit_Int: Int { return Int(self.dayOneDigit)! } var dayTwoDigit_Int: Int { return Int(self.dayTwoDigit)! } var dayOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "d" return dateFormatter.string(from: self as Date) } var dayTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd" return dateFormatter.string(from: self as Date) } var dayNameShort: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "E" return dateFormatter.string(from: self as Date) } var dayNameFull: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self as Date) } var dayNameFirstLetter: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEEE" return dateFormatter.string(from: self as Date) } // MARK:- AM PM var AM_PM: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "a" return dateFormatter.string(from: self as Date) } // MARK:- HOUR var hourOneDigit_Int: Int { return Int(self.hourOneDigit)! } var hourTwoDigit_Int: Int { return Int(self.hourTwoDigit)! } var hourOneDigit24Hours_Int: Int { return Int(self.hourOneDigit24Hours)! } var hourTwoDigit24Hours_Int: Int { return Int(self.hourTwoDigit24Hours)! } var hourOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h" return dateFormatter.string(from: self as Date) } var hourTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh" return dateFormatter.string(from: self as Date) } var hourOneDigit24Hours: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "H" return dateFormatter.string(from: self as Date) } var hourTwoDigit24Hours: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH" return dateFormatter.string(from: self as Date) } // MARK:- MINUTE var minuteOneDigit_Int: Int { return Int(self.minuteOneDigit)! } var minuteTwoDigit_Int: Int { return Int(self.minuteTwoDigit)! } var minuteOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "m" return dateFormatter.string(from: self as Date) } var minuteTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "mm" return dateFormatter.string(from: self as Date) } // MARK:- SECOND var secondOneDigit_Int: Int { return Int(self.secondOneDigit)! } var secondTwoDigit_Int: Int { return Int(self.secondTwoDigit)! } var secondOneDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "s" return dateFormatter.string(from: self as Date) } var secondTwoDigit: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "ss" return dateFormatter.string(from: self as Date) } }
mit
34bbfbf446210e7910fafbc4f5065529
30.857881
139
0.615135
4.693186
false
false
false
false
guoc/excerptor
Excerptor/SelectionLink.swift
1
8595
// // SelectionLink.swift // Excerptor // // Created by Chen Guo on 5/05/2015. // Copyright (c) 2015 guoc. All rights reserved. // import Foundation import ScriptingBridge import Quartz class SelectionLink: Link { fileprivate let selectionLocation: SelectionLocation! init(fileID: FileID, selectionLocation: SelectionLocation) { self.selectionLocation = selectionLocation super.init(fileID: fileID) } required convenience init?(location: Location, text: String?) { if let location = location as? SelectionLocation { self.init(selectionLocation: location) } else { exitWithError("SelectionLink init failed") } } convenience init(filePath: String, selectionLocation: SelectionLocation) { self.init(fileID: FileID.filePath(filePath), selectionLocation: selectionLocation) } convenience init(dntpUuid: String, selectionLocation: SelectionLocation) { self.init(fileID: FileID.dNtpUuid(dntpUuid), selectionLocation: selectionLocation) } convenience init(filePathOrDNtpUuid: String, selectionLocation: SelectionLocation) { self.init(fileID: FileID(filePathOrDNtpUuid: filePathOrDNtpUuid), selectionLocation: selectionLocation) } convenience init(selectionLocation: SelectionLocation) { self.init(fileID: FileID.filePath(selectionLocation.pdfFilePath), selectionLocation: selectionLocation) } required convenience init?(linkString: String) { guard linkString.hasPrefix(SelectionLink.head) else { exitWithError("The link string has incorrect head: " + linkString) } let linkStringWithoutHead = linkString.stringByRemovingPrefix(SelectionLink.head) let arr = linkStringWithoutHead.components(separatedBy: ":") guard arr.count == 3 else { exitWithError("The link string has incorrect number of components: " + linkString) } guard let fileIDString = arr[0].removingPercentEncoding else { exitWithError("The link string contains an invalid file ID: " + linkString) } let fileID = FileID(filePathOrDNtpUuid: fileIDString) guard let selectionLocation = SelectionLocation(string: linkStringWithoutHead) else { exitWithError("Could not parse the link string to selection location: " + linkString) } self.init(fileID: fileID, selectionLocation: selectionLocation) } override var string: String { let fileIDString = fileID.percentEncodedString return "\(SelectionLink.head)\(fileIDString):\(selectionLocation.stringWithoutPDFFilePath)" } override var location: Location { return selectionLocation } var pageIndices: [Int] { return selectionLocation.pageIndices } var firstPageIndex: Int { return pageIndices.reduce(Int.max) { min($0, $1) } } var selectionTextArrayInOneLine: String { return selectionLocation.selectionTextInOneLine } fileprivate struct Constants { static let SelectionTextDelimiter = "-" } override func getDNtpUuidTypeLink() -> Link? { if isDNtpUuidLinkType { return self } if let dntpUuid = getDNtpUuid() { return SelectionLink(dntpUuid: dntpUuid, selectionLocation: selectionLocation) } else { return nil } } override func getFilePathTypeLink() -> Link? { if isFilePathLinkType { return self } let filePath = getFilePath() return SelectionLink(filePath: filePath, selectionLocation: selectionLocation) } } extension SelectionLocation { var stringWithoutPDFFilePath: String { let selectionString = selectionLineLocations.map { ($0 as AnyObject).string }.map { (string: String) -> String in let replacedString = string.components(separatedBy: CharacterSet.whitespacesAndNewlines).filter({!$0.isEmpty}).joined(separator: "+") let allowedCharaterSet = NSMutableCharacterSet(charactersIn: "+") allowedCharaterSet.formUnion(with: URIUnreservedCharacterSet as CharacterSet) let encodedString = replacedString.addingPercentEncoding(withAllowedCharacters: allowedCharaterSet as CharacterSet)! return encodedString }.joined(separator: SelectionLink.Constants.SelectionTextDelimiter) guard let unwrappedSelectionLineLocations = selectionLineLocations as? [SelectionLineLocation] else { exitWithError("selectionLineLocations contain non-SelectionLineLocation object. selectionLineLocations: \(selectionLineLocations)") } let locationStrings = unwrappedSelectionLineLocations.map { (lineLocation: SelectionLineLocation) -> String in var lineLocationString = "p\(lineLocation.pageIndex + 1)_\(lineLocation.range.location)_\(lineLocation.range.length)" if Preferences.sharedPreferences.boolForSelectionLinkIncludesBoundsInfo { lineLocationString += "_\(lineLocation.bound.origin.x)_\(lineLocation.bound.origin.y)_\(lineLocation.bound.size.width)_\(lineLocation.bound.size.height)" } return lineLocationString } return selectionString + ":" + locationStrings.joined(separator: "-") } var pageIndices: [Int] { guard let unwrappedSelectionLineLocations = selectionLineLocations as? [SelectionLineLocation] else { exitWithError("selectionLineLocations contain non-SelectionLineLocation object. selectionLineLocations: \(selectionLineLocations)") } return unwrappedSelectionLineLocations.map { Int($0.pageIndex) } } var selectionTextInOneLine: String { return selectionLineLocations.map { ($0 as AnyObject).string }.joined(separator: " ") } convenience init?(string: String) { let arr = string.components(separatedBy: ":") if arr.count != 3 { exitWithError("Incorrect selection link format") } let pdfFilePath = FileID(filePathOrDNtpUuid: arr[0].removingPercentEncoding!).getFilePath() let stringArray = arr[1].components(separatedBy: SelectionLink.Constants.SelectionTextDelimiter) let selectionArray = arr[2].components(separatedBy: "-") let zippedArray = Array(zip(stringArray, selectionArray)) let selectionLineLocations = zippedArray.map { (stringAndSelection: (annotationString: String, selection: String)) -> SelectionLineLocation in let annotationString = stringAndSelection.annotationString.removingPercentEncoding! let selectionString = stringAndSelection.selection if selectionString.hasPrefix("p") { let arr = String(selectionString.dropFirst()).components(separatedBy: "_") if arr.count == 3 || arr.count == 7 { if let pageNumber = Int(arr[0]), let location = Int(arr[1]), let length = Int(arr[2]) // swiftlint:disable opening_brace { let pageIndex = UInt(pageNumber - 1) let range = NSRange(location: location, length: length) var bound: NSRect = CGRect.zero if Preferences.sharedPreferences.boolForSelectionLinkIncludesBoundsInfo && arr.count == 7 { if let x = NumberFormatter().number(from: arr[3])?.floatValue, let y = NumberFormatter().number(from: arr[4])?.floatValue, let width = NumberFormatter().number(from: arr[5])?.floatValue, let height = NumberFormatter().number(from: arr[6])?.floatValue { bound = NSRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height)) } else { exitWithError("Incorrect selection link format") } } return SelectionLineLocation(string: annotationString, pageIndex: pageIndex, range: range, bound: bound) } // swiftlint:enable opening_brace } } exitWithError("Incorrect selection link format") } self.init(pdfFilePath: pdfFilePath, selectionLineLocations: selectionLineLocations) } // swiftlint:enable function_body_length }
mit
c20a95297d6c2e41ebcb28d2986c5ac6
43.533679
169
0.64968
5.067807
false
false
false
false
Enziferum/iosBoss
iosBoss/NotificationManager.swift
1
4325
// // RequestCenter.swift // iosBoss // // Created by AlexRaag on 30/08/2017. // Copyright © 2017 AlexRaag. All rights reserved. // import Foundation import UIKit import UserNotifications //Allows work with Manager,throw protocol protocol NotificationManagerDelegate { func prepateNotifications(application: UIApplication) func didReceiveRemoteNotification (userInfo: [AnyHashable: Any]) func didReceiveRemoteNotification (userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) func didFailToRegisterForRemoteNotificationsWithError (error: Error) } //MARK:Custom Manager for working with push notification, as Singleton class NotificationManager:NSObject{ static let shared = NotificationManager() override init(){ gcmMessageIDKey = "gcm.message_id" } func prepareNotifications(application: UIApplication){ if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() print("prepareNotifications") } func registerNotifications(){ UIApplication.shared.registerForRemoteNotifications() } fileprivate var gcmMessageIDKey:String open var isProxy:Bool! //var authOptions: UNAuthorizationOptions! } //Implements Delegate methods (base Features),allows,create Custom extension NotificationManager:NotificationManagerDelegate{ func prepateNotifications(application: UIApplication) { } func printMessageID(userInfo: [AnyHashable: Any]){ guard let messageID = userInfo[gcmMessageIDKey] else { return } print("Message:\(messageID)") print(userInfo) } //TODO add some code // func didFailToRegisterForRemoteNotificationsWithError (error: Error){ print("Unable to register for remote notifications: \(error.localizedDescription)") } func didReceiveRemoteNotification (userInfo: [AnyHashable: Any]){ if !isProxy { // FirebaseWrapper.shared.appDidReceiveMessage(userInfo: userInfo) } // printMessageID(userInfo: userInfo) print("didReceiveRemoteNotification") } func didReceiveRemoteNotification (userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ){ if !isProxy { // FirebaseWrapper.shared.appDidReceiveMessage(userInfo: userInfo) } printMessageID(userInfo: userInfo) print("didReceiveRemoteNotification + Handler") completionHandler(UIBackgroundFetchResult.newData) } func didRegisterForRemoteNotificationsWithDeviceToken (deviceToken: Data) { print("APNs token retrieved: \(deviceToken)") print("didRegisterForRemoteNotificationsWithDeviceToken") } } //MARK: IOS 10+ Delegate Realisation @available(iOS 10, *) extension NotificationManager: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo if !isProxy { //FirebaseWrapper.shared.appDidReceiveMessage(userInfo: userInfo) } //printMessageID(userInfo: userInfo) print("userNotificationCenter") completionHandler([]) } }
mit
1dd312c08617bf29e5d9291b70193e5e
31.511278
129
0.663043
6.133333
false
false
false
false
tkremenek/swift
test/decl/class/actor/conformance.swift
1
2298
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking // REQUIRES: concurrency protocol AsyncProtocol { func asyncMethod() async -> Int } actor MyActor { } // Actors conforming to asynchronous program. extension MyActor: AsyncProtocol { func asyncMethod() async -> Int { return 0 } } protocol SyncProtocol { var propertyA: Int { get } var propertyB: Int { get set } func syncMethodA() func syncMethodC() -> Int subscript (index: Int) -> String { get } static func staticMethod() static var staticProperty: Int { get } } actor OtherActor: SyncProtocol { var propertyB: Int = 17 // expected-error@-1{{actor-isolated property 'propertyB' cannot be used to satisfy a protocol requirement}} var propertyA: Int { 17 } // expected-error@-1{{actor-isolated property 'propertyA' cannot be used to satisfy a protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'propertyA' to make this property not isolated to the actor}}{{3-3=nonisolated }} func syncMethodA() { } // expected-error@-1{{actor-isolated instance method 'syncMethodA()' cannot be used to satisfy a protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'syncMethodA()' to make this instance method not isolated to the actor}}{{3-3=nonisolated }} // nonisolated methods are okay. // FIXME: Consider suggesting nonisolated if this didn't match. nonisolated func syncMethodC() -> Int { 5 } subscript (index: Int) -> String { "\(index)" } // expected-error@-1{{actor-isolated subscript 'subscript(_:)' cannot be used to satisfy a protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'subscript(_:)' to make this subscript not isolated to the actor}}{{3-3=nonisolated }} // Static methods and properties are okay. static func staticMethod() { } static var staticProperty: Int = 17 } protocol Initializers { init() init(string: String) init(int: Int) async } protocol SelfReqs { func withBells() async -> Self } actor A1: Initializers, SelfReqs { init() { } init(string: String) { } init(int: Int) async { } func withBells() async -> A1 { self } } actor A2: Initializers { init() { } init(string: String) { } init(int: Int) { } func withBells() async -> A2 { self } }
apache-2.0
45af365a26b1b3d1577c6873bf085d29
27.37037
136
0.694952
3.855705
false
false
false
false
jingkecn/WatchWorker
src/ios/JSCore/Events/EventInit.swift
1
2238
// // EventInit.swift // WTVJavaScriptCore // // Created by Jing KE on 29/06/16. // Copyright © 2016 WizTiVi. All rights reserved. // import Foundation import JavaScriptCore @objc protocol EventInitJSExport: JSExport { var bubbles: Bool { get } var cancelable: Bool { get } var composed: Bool { get } } class EventInit: JSClassDelegate, EventInitJSExport { let bubbles: Bool let cancelable: Bool let composed: Bool init(context: ScriptContext, bubbles: Bool? = nil, cancelable: Bool? = nil, composed: Bool? = nil) { self.bubbles = bubbles ?? false self.cancelable = cancelable ?? false self.composed = composed ?? false super.init(context: context) } convenience init(context: ScriptContext, initValue: JSValue) { guard !initValue.isUndefined else { self.init(context: context, bubbles: false, cancelable: false, composed: false) return } let bubblesValue = initValue.objectForKeyedSubscript("bubbles") let bubbles = bubblesValue.isBoolean ? bubblesValue.toBool() : false let cancelableValue = initValue.objectForKeyedSubscript("cancelable") let cancelable = cancelableValue.isBoolean ? cancelableValue.toBool() : false let composedValue = initValue.objectForKeyedSubscript("composed") let composed = composedValue.isBoolean ? composedValue.toBool() : false self.init(context: context, bubbles: bubbles, cancelable: cancelable, composed: composed) } convenience init(context: ScriptContext, initDict: Dictionary<String, AnyObject>) { self.init( context: context, bubbles: initDict["bubbles"] as? Bool, cancelable: initDict["cancelable"] as? Bool, composed: initDict["composed"] as? Bool ) } } extension EventInit { class func create(context: ScriptContext, initValue: JSValue) -> EventInit { return EventInit(context: context, initValue: initValue) } class func create(context: ScriptContext, initDict: Dictionary<String, AnyObject>) -> EventInit { return EventInit(context: context, initDict: initDict) } }
mit
4be2a90678f371ec3171fdbe4fdf4a19
31.911765
104
0.658918
4.510081
false
false
false
false
ericmarkmartin/Nightscouter2
Common/Extensions/Double-Extension.swift
1
4025
// // ApplicationExtensions.swift // Nightscout // // Created by Peter Ina on 5/18/15. // Copyright (c) 2015 Peter Ina. All rights reserved. // import Foundation public extension Range { public var randomInt: Int { get { var offset = 0 if (startIndex as! Int) < 0 // allow negative ranges { offset = abs(startIndex as! Int) } let mini = UInt32(startIndex as! Int + offset) let maxi = UInt32(endIndex as! Int + offset) return Int(mini + arc4random_uniform(maxi - mini)) - offset } } } public extension MgdlValue { public var toMmol: Double { get{ return (self / 18) } } public var toMgdl: Double { get{ return floor(self * 18) } } internal var mgdlFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .NoStyle return numberFormat } public var formattedForMgdl: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mgdlFormatter.stringFromNumber(self)! } internal var mmolFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .DecimalStyle numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 return numberFormat } public var formattedForMmol: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mmolFormatter.stringFromNumber(self.toMmol)! } } public extension MgdlValue { internal var bgDeltaFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .DecimalStyle numberFormat.positivePrefix = numberFormat.plusSign numberFormat.negativePrefix = numberFormat.minusSign return numberFormat } public func formattedBGDelta(forUnits units: Units, appendString: String? = nil) -> String { var formattedNumber: String = "" switch units { case .Mmol: let numberFormat = bgDeltaFormatter numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 formattedNumber = numberFormat.stringFromNumber(self) ?? "?" case .Mgdl: formattedNumber = self.bgDeltaFormatter.stringFromNumber(self) ?? "?" } var unitMarker: String = units.description if let appendString = appendString { unitMarker = appendString } return formattedNumber + " " + unitMarker } public var formattedForBGDelta: String { return self.bgDeltaFormatter.stringFromNumber(self)! } } public extension Double { var isInteger: Bool { return rint(self) == self } } public extension Double { public func millisecondsToSecondsTimeInterval() -> NSTimeInterval { return round(self/1000) } public var inThePast: NSTimeInterval { return -self } public func toDateUsingMilliseconds() -> NSDate { let date = NSDate(timeIntervalSince1970:millisecondsToSecondsTimeInterval()) return date } } extension NSTimeInterval { var minuteSecondMS: String { return String(format:"%d:%02d.%03d", minute , second, millisecond ) } var minute: Double { return (self/60.0)%60 } var second: Double { return self % 60 } var millisecond: Double { return self*1000 } } extension Int { var msToSeconds: Double { return Double(self) / 1000 } }
mit
db2af920be2fe62471f001e75ee34311
24.643312
96
0.599006
5.082071
false
false
false
false
rsrbk/SRCountdownTimer
SRCountdownTimerExample/SRCountdownTimerExample/ViewController.swift
1
911
// // ViewController.swift // SRCountdownTimerExample // // Created by Ruslan Serebriakov on 5/13/17. // Copyright © 2017 Ruslan Serebriakov. All rights reserved. // import UIKit import SRCountdownTimer class ViewController: UIViewController { @IBOutlet weak var countdownTimer: SRCountdownTimer! override func viewDidLoad() { super.viewDidLoad() // uncomment this line if would like to see a minute and second representation of the remaining time // (rather than just a second representation //countdownTimer.useMinutesAndSecondsRepresentation = true countdownTimer.labelFont = UIFont(name: "HelveticaNeue-Light", size: 50.0) countdownTimer.labelTextColor = UIColor.red countdownTimer.timerFinishingText = "End" countdownTimer.lineWidth = 4 countdownTimer.start(beginingValue: 15, interval: 1) } }
mit
24cd89a539e6332d5aa59738439df07d
29.333333
108
0.703297
4.482759
false
false
false
false
shorlander/firefox-ios
Client/Frontend/Widgets/Menu/MenuView.swift
6
15184
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class MenuView: UIView { lazy var toolbar: RoundedToolbar = { let toolbar = RoundedToolbar() toolbar.setContentHuggingPriority(UILayoutPriorityRequired, for: UILayoutConstraintAxis.vertical) toolbar.contentMode = .redraw return toolbar }() lazy var openMenuImage: UIImageView = { let openMenuImage = UIImageView() openMenuImage.contentMode = UIViewContentMode.scaleAspectFit openMenuImage.isUserInteractionEnabled = true openMenuImage.isAccessibilityElement = true openMenuImage.accessibilityTraits = UIAccessibilityTraitButton openMenuImage.accessibilityLabel = NSLocalizedString("Menu.CloseMenu.AccessibilityLabel", tableName: "Menu", value: "Close Menu", comment: "Accessibility label describing the button that closes the menu when open") return openMenuImage }() lazy var menuFooterView: UIView = UIView() fileprivate lazy var pageControl: UIPageControl = { let pageControl = UIPageControl() pageControl.currentPage = 0 pageControl.hidesForSinglePage = true pageControl.addTarget(self, action: #selector(self.pageControlDidPage(_:)), for: UIControlEvents.valueChanged) return pageControl }() weak var toolbarDelegate: MenuToolbarItemDelegate? weak var toolbarDataSource: MenuToolbarDataSource? weak var menuItemDelegate: MenuItemDelegate? weak var menuItemDataSource: MenuItemDataSource? fileprivate let pagingCellReuseIdentifier = "PagingCellReuseIdentifier" fileprivate lazy var menuPagingLayout: PagingMenuItemCollectionViewLayout = { let layout = PagingMenuItemCollectionViewLayout() layout.interitemSpacing = self.itemPadding layout.lineSpacing = self.itemPadding return layout }() fileprivate lazy var menuPagingView: UICollectionView = { let pagingView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.menuPagingLayout) pagingView.register(MenuItemCollectionViewCell.self, forCellWithReuseIdentifier: self.pagingCellReuseIdentifier) pagingView.dataSource = self pagingView.delegate = self pagingView.showsHorizontalScrollIndicator = false pagingView.isPagingEnabled = true pagingView.backgroundColor = UIColor.clear return pagingView }() fileprivate var menuContainerView = UIView() fileprivate var presentationStyle: MenuViewPresentationStyle var cornersToRound: UIRectCorner? var cornerRadius: CGSize? var menuColor: UIColor = UIColor.clear { didSet { menuContainerView.backgroundColor = menuColor menuFooterView.backgroundColor = menuColor } } var toolbarColor: UIColor = UIColor.white { didSet { toolbar.backgroundColor = toolbarColor } } override var backgroundColor: UIColor! { didSet { menuColor = backgroundColor } } override var tintColor: UIColor! { didSet { menuPagingView.tintColor = tintColor pageControl.currentPageIndicatorTintColor = tintColor pageControl.pageIndicatorTintColor = tintColor.withAlphaComponent(0.25) } } var toolbarHeight: Float = 40.0 { didSet { self.setNeedsLayout() } } var menuRowHeight: Float = 0 { didSet { self.setNeedsLayout() } } var itemPadding: CGFloat = 10.0 { didSet { self.setNeedsLayout() } } var currentPageIndex: Int = 0 { didSet { needsReload = true self.setNeedsLayout() } } var menuFooterHeight: CGFloat = 44 { didSet { self.setNeedsLayout() } } var nextPageIndex: Int? fileprivate var needsReload: Bool = true fileprivate var toolbarItems = [UIBarButtonItem]() init(presentationStyle: MenuViewPresentationStyle) { self.presentationStyle = presentationStyle super.init(frame: CGRect.zero) self.addSubview(menuContainerView) let longPress = UILongPressGestureRecognizer(target: self, action: #selector(menuLongPressed)) menuPagingView.addGestureRecognizer(longPress) menuContainerView.addSubview(menuPagingView) menuContainerView.addSubview(pageControl) self.addSubview(toolbar) switch presentationStyle { case .modal: addFooter() toolbar.snp.makeConstraints { make in make.height.equalTo(toolbarHeight) make.top.left.right.equalTo(self) } menuContainerView.snp.makeConstraints { make in make.top.equalTo(toolbar.snp.bottom) make.left.right.equalTo(self) make.bottom.equalTo(menuFooterView.snp.top) } menuPagingView.snp.makeConstraints { make in make.top.left.right.equalTo(menuContainerView) make.bottom.equalTo(pageControl.snp.top) make.height.equalTo(0) } pageControl.snp.makeConstraints { make in make.bottom.equalTo(menuContainerView) make.centerX.equalTo(self) } case .popover: menuContainerView.snp.makeConstraints { make in make.bottom.equalTo(toolbar.snp.top) make.left.right.top.equalTo(self) } menuPagingView.snp.makeConstraints { make in make.top.left.right.equalTo(menuContainerView) make.bottom.equalTo(pageControl.snp.top).offset(-itemPadding) make.height.equalTo(0) } pageControl.snp.makeConstraints { make in make.bottom.equalTo(menuContainerView) make.centerX.equalTo(self) } toolbar.snp.makeConstraints { make in make.height.equalTo(toolbarHeight) make.bottom.left.right.equalTo(self) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func addFooter() { self.addSubview(menuFooterView) // so it always displays the colour of the background menuFooterView.backgroundColor = UIColor.clear menuFooterView.snp.makeConstraints { make in make.height.equalTo(menuFooterHeight) make.left.right.equalTo(self) make.bottom.equalTo(self) } menuFooterView.addSubview(openMenuImage) openMenuImage.snp.makeConstraints { make in make.center.equalTo(menuFooterView) } } @objc func pageControlDidPage(_ sender: AnyObject) { let pageSize = menuPagingView.bounds.size let xOffset = pageSize.width * CGFloat(pageControl.currentPage) menuPagingView.setContentOffset(CGPoint(x: xOffset, y: 0), animated: true) } @objc fileprivate func toolbarButtonSelected(_ sender: UIView) { guard let selectedItemIndex = toolbarItems.index(where: { $0.customView == sender }) else { return } toolbarDelegate?.menuView(self, didSelectItemAtIndex: selectedItemIndex) } @objc fileprivate func toolbarButtonTapped(_ gesture: UIGestureRecognizer) { guard let view = gesture.view else { return } toolbarButtonSelected(view) } @objc fileprivate func toolbarLongPressed(_ recognizer: UILongPressGestureRecognizer) { guard recognizer.state == .began else { return } let view = recognizer.view guard let index = toolbarItems.index(where: { $0.customView == view }) else { return } toolbarDelegate?.menuView(self, didLongPressItemAtIndex: index) } @objc fileprivate func menuLongPressed(_ recognizer: UILongPressGestureRecognizer) { guard recognizer.state == .began else { return } let point = recognizer.location(in: menuPagingView) guard let indexPath = menuPagingView.indexPathForItem(at: point) else { return } menuItemDelegate?.menuView(self, didLongPressItemAtIndexPath: indexPath) } // MARK : Menu Cell Management and Recycling func reloadData() { toolbarItems.removeAll() toolbar.items?.removeAll() loadToolbar() loadMenu() needsReload = false } fileprivate func loadToolbar() { guard let toolbarDataSource = toolbarDataSource else { return } let numberOfToolbarItems = toolbarDataSource.numberOfToolbarItemsInMenuView(self) for index in 0..<numberOfToolbarItems { let toolbarItemView = toolbarDataSource.menuView(self, buttonForItemAtIndex: index) if let buttonView = toolbarItemView as? UIButton { buttonView.addTarget(self, action: #selector(self.toolbarButtonSelected(_:)), for: .touchUpInside) } else { toolbarItemView.isUserInteractionEnabled = true toolbarItemView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.toolbarButtonTapped(_:)))) } toolbarItemView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(toolbarLongPressed))) let toolbarButton = UIBarButtonItem(customView: toolbarItemView) toolbarButton.accessibilityLabel = toolbarItemView.accessibilityLabel toolbarButton.isAccessibilityElement = true toolbarButton.accessibilityTraits = UIAccessibilityTraitButton toolbarButton.accessibilityIdentifier = toolbarItemView.accessibilityIdentifier toolbarItems.append(toolbarButton) } } fileprivate func loadMenu() { let numberOfPages = menuItemDataSource?.numberOfPagesInMenuView(self) ?? 0 pageControl.numberOfPages = numberOfPages pageControl.currentPage = currentPageIndex menuPagingView.reloadData() } func setNeedsReload() { if !needsReload { needsReload = true setNeedsLayout() } } fileprivate func reloadDataIfNeeded() { if needsReload { reloadData() } } // MARK : Layout override func layoutSubviews() { super.layoutSubviews() reloadDataIfNeeded() layoutToolbar() layoutMenu() layoutFooter() roundCorners() } func roundCorners() { guard let cornersToRound = cornersToRound, let cornerRadius = cornerRadius else { return } // if we have no toolbar items, we won't display a toolbar so we should round the corners of the menuContainerView if toolbarItems.count == 0 { menuContainerView.addRoundedCorners(cornersToRound, cornerRadius: cornerRadius, color: menuColor) } else { toolbar.cornerRadius = cornerRadius toolbar.cornersToRound = cornersToRound } } fileprivate func layoutToolbar() { var displayToolbarItems = [UIBarButtonItem]() for (index, item) in toolbarItems.enumerated() { displayToolbarItems.append(item) if index < toolbarItems.count-1 { displayToolbarItems.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)) } } if displayToolbarItems.count == 0 { toolbar.snp.updateConstraints { make in make.height.equalTo(0) } } else { toolbar.snp.updateConstraints { make in make.height.equalTo(toolbarHeight) } toolbar.setItems(displayToolbarItems, animated: false) } toolbar.backgroundColor = toolbarColor } fileprivate func layoutMenu() { menuContainerView.backgroundColor = menuColor let numberOfItemsInRow = CGFloat(menuItemDataSource?.numberOfItemsPerRowInMenuView(self) ?? 0) menuPagingLayout.maxNumberOfItemsPerPageRow = Int(numberOfItemsInRow) menuPagingLayout.menuRowHeight = CGFloat(menuItemDelegate?.heightForRowsInMenuView(self) ?? 0) menuRowHeight = Float(menuPagingLayout.menuRowHeight) menuPagingView.snp.updateConstraints { make in let numberOfRows: CGFloat if let maxNumberOfItemsForPage = self.menuItemDataSource?.menuView(self, numberOfItemsForPage: 0) { numberOfRows = ceil(CGFloat(maxNumberOfItemsForPage) / numberOfItemsInRow) } else { numberOfRows = 0 } let menuHeight = itemPadding + (numberOfRows * (CGFloat(self.menuRowHeight) + itemPadding)) make.height.equalTo(menuHeight) } } fileprivate func layoutFooter() { menuFooterView.snp.updateConstraints { make in make.height.equalTo(menuFooterHeight) } } } extension MenuView: UICollectionViewDataSource { func dequeueReusableCellForIndexPath(_ indexPath: IndexPath) -> MenuItemCollectionViewCell { return self.menuPagingView.dequeueReusableCell(withReuseIdentifier: pagingCellReuseIdentifier, for: indexPath) as! MenuItemCollectionViewCell } func numberOfSections(in collectionView: UICollectionView) -> Int { return menuItemDataSource?.numberOfPagesInMenuView(self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return menuItemDataSource?.menuView(self, numberOfItemsForPage: section) ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let dataSource = menuItemDataSource else { return collectionView.dequeueReusableCell(withReuseIdentifier: pagingCellReuseIdentifier, for: indexPath) } return dataSource.menuView(self, menuItemCellForIndexPath: indexPath) } } extension MenuView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { menuItemDelegate?.menuView(self, didSelectItemAtIndexPath: indexPath) } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return menuItemDelegate?.menuView(self, shouldSelectItemAtIndexPath: indexPath) ?? false } } extension MenuView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageSize = menuPagingView.bounds.size let selectedPageIndex = Int(floor((scrollView.contentOffset.x-pageSize.width/2)/pageSize.width))+1 pageControl.currentPage = Int(selectedPageIndex) } }
mpl-2.0
ff7dd9c6f3ab340b60543d7306c82881
35.41247
223
0.662342
5.545654
false
false
false
false
WSUCSClub/upac-ios
UPAC/EventsViewController.swift
1
5332
// // EventsViewController.swift // UPAC // // Created by Marquez, Richard A on 10/9/14. // Copyright (c) 2014 wsu-cs-club. All rights reserved. // import UIKit var __eventsTableView: UITableView? = nil class EventsViewController: UITableViewController { @IBOutlet var eventsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() __eventsTableView = eventsTableView refreshControl = UIRefreshControl() refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl!.addTarget(self, action: "refresh", forControlEvents: .ValueChanged) eventsTableView.addSubview(refreshControl!) onboarding() } func onboarding() { // Onboarding //NSUserDefaults.standardUserDefaults().removeObjectForKey("firstRun") if NSUserDefaults.standardUserDefaults().objectForKey("firstRun") == nil { var onboardingTitle = "How Raffles Work" var onboardingMessage = "\nJust tap the \"Enter Raffle\" button to enter the event's raffle for a chance to win a prize, then during the event UPAC will announce the winners that are chosen at random.\n\nRULES\n* Free to enter\n* No sign-up required\n* Drawings are held at their respective event's location\n* Must be present at event to win\n* Must show raffle ticket # on device to UPAC host to receive prize\n* Must be current Winona State University student to be eligible\n\nNOTE\nApple is not a sponsor of these raffles, nor are they involved in any way." var alert = UIAlertController(title: onboardingTitle, message: onboardingMessage, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) alert.view.tintColor = UIColor.blueColor() self.presentViewController(alert, animated: true, completion: nil) NSUserDefaults.standardUserDefaults().setObject(false, forKey: "firstRun") } } func refresh() { raffleMgr.getRaffles() eventMgr.getFBEvents { void in self.refreshControl!.endRefreshing() } } // Tell user to refresh if unable to load events override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if eventMgr.list.count < 1 { var loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) loadingIndicator.color = UIColor.grayColor() loadingIndicator.startAnimating() eventsTableView.backgroundView = loadingIndicator eventsTableView.separatorStyle = .None return 0 } else { eventsTableView.backgroundView = nil eventsTableView.separatorStyle = .SingleLine return 1 } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return eventMgr.list.count } // Set cell content override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if !eventMgr.list.isEmpty { let e = eventMgr.list[indexPath.row] as Event // Use different layout if event has a raffle var cellIdentifier: String if e.hasRaffle() { cellIdentifier = "TableViewEventRaffleCell" } else { cellIdentifier = "TableViewEventCell" } let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell (cell.contentView.viewWithTag(1) as! UILabel).text = e.name (cell.contentView.viewWithTag(2) as! UILabel).text = "\(e.date.monthStr()) \(e.date.dayNumStr()) @ \(e.location)" (cell.contentView.viewWithTag(3) as! UIImageView).image = UIImage(data: e.imageData) cell.contentView.viewWithTag(3)!.layer.borderColor = UIColor(rgb: 0x888888).CGColor return cell } else { return tableView.dequeueReusableCellWithIdentifier("TableViewEventCell", forIndexPath: indexPath) as! UITableViewCell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // On selection functionality } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EventDetailView" || segue.identifier == "EventDetailRaffleView" { let destinationView:EventDetailViewController = segue.destinationViewController as! EventDetailViewController let indexPath:NSIndexPath = self.eventsTableView.indexPathForCell(sender as! UITableViewCell)! destinationView.delegate = self destinationView.event = eventMgr.list[indexPath.row] as Event destinationView.index = indexPath.row } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
c94aa7ccd6ebee9f25dc480a61ac996c
42.349593
574
0.653413
5.332
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Media/Tenor/TenorAPI/TenorReponseParser.swift
2
460
// Parse a Tenor API response import Foundation class TenorResponseParser<T> where T: Decodable { private(set) var results: [T]? private(set) var next: String? func parse(_ data: Data) throws { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let response = try decoder.decode(TenorResponse<[T]>.self, from: data) results = response.results ?? [] next = response.next } }
gpl-2.0
4f1c25df51fc9c8075544519b3b16e41
26.058824
78
0.652174
4.220183
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationDetailsViewController.swift
1
56397
import Foundation import CoreData import Gridicons import SVProgressHUD import WordPressShared /// /// protocol NotificationsNavigationDataSource: AnyObject { func notification(succeeding note: Notification) -> Notification? func notification(preceding note: Notification) -> Notification? } // MARK: - Renders a given Notification entity, onscreen // class NotificationDetailsViewController: UIViewController, NoResultsViewHost { // MARK: - Properties let formatter = FormattableContentFormatter() /// StackView: Top-Level Entity /// @IBOutlet var stackView: UIStackView! /// TableView /// @IBOutlet var tableView: UITableView! /// Pins the StackView to the top of the view (Relationship: = 0) /// @IBOutlet var topLayoutConstraint: NSLayoutConstraint! /// Pins the StackView to the bottom of the view (Relationship: = 0) /// @IBOutlet var bottomLayoutConstraint: NSLayoutConstraint! /// Pins the StackView to the top of the view (Relationship: >= 0) /// @IBOutlet var badgeTopLayoutConstraint: NSLayoutConstraint! /// Pins the StackView to the bottom of the view (Relationship: >= 0) /// @IBOutlet var badgeBottomLayoutConstraint: NSLayoutConstraint! /// Pins the StackView at the center of the view /// @IBOutlet var badgeCenterLayoutConstraint: NSLayoutConstraint! /// RelpyTextView /// @IBOutlet var replyTextView: ReplyTextView! /// Reply Suggestions /// @IBOutlet var suggestionsTableView: SuggestionsTableView? /// Embedded Media Downloader /// fileprivate var mediaDownloader = NotificationMediaDownloader() /// Keyboard Manager: Aids in the Interactive Dismiss Gesture /// fileprivate var keyboardManager: KeyboardDismissHelper? /// Cached values used for returning the estimated row heights of autosizing cells. /// fileprivate let estimatedRowHeightsCache = NSCache<AnyObject, AnyObject>() /// A Reader Detail VC to display post content if needed /// private var readerDetailViewController: ReaderDetailViewController? /// Previous NavBar Navigation Button /// var previousNavigationButton: UIButton! /// Next NavBar Navigation Button /// var nextNavigationButton: UIButton! /// Arrows Navigation Datasource /// weak var dataSource: NotificationsNavigationDataSource? /// Used to present CommentDetailViewController when previous/next notification is a Comment. /// weak var notificationCommentDetailCoordinator: NotificationCommentDetailCoordinator? /// Notification being displayed /// var note: Notification! { didSet { guard oldValue != note && isViewLoaded else { return } confettiWasShown = false router = makeRouter() setupTableDelegates() refreshInterface() markAsReadIfNeeded() } } /// Whether a confetti animation was presented on this notification or not /// private var confettiWasShown = false lazy var coordinator: ContentCoordinator = { return DefaultContentCoordinator(controller: self, context: mainContext) }() /// Service to access the currently authenticated user /// lazy var accountService: AccountService = { return AccountService(managedObjectContext: mainContext) }() lazy var router: NotificationContentRouter = { return makeRouter() }() /// Whenever the user performs a destructive action, the Deletion Request Callback will be called, /// and a closure that will effectively perform the deletion action will be passed over. /// In turn, the Deletion Action block also expects (yet another) callback as a parameter, to be called /// in the eventuallity of a failure. /// var onDeletionRequestCallback: ((NotificationDeletionRequest) -> Void)? /// Closure to be executed whenever the notification that's being currently displayed, changes. /// This happens due to Navigation Events (Next / Previous) /// var onSelectedNoteChange: ((Notification) -> Void)? var likesListController: LikesListController? deinit { // Failsafe: Manually nuke the tableView dataSource and delegate. Make sure not to force a loadView event! guard isViewLoaded else { return } tableView.delegate = nil tableView.dataSource = nil } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) restorationClass = type(of: self) } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupMainView() setupTableView() setupTableViewCells() setupTableDelegates() setupReplyTextView() setupSuggestionsView() setupKeyboardManager() Environment.current.appRatingUtility.incrementSignificantEvent(section: "notifications") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRowWithAnimation(true) keyboardManager?.startListeningToKeyboardNotifications() refreshInterface() markAsReadIfNeeded() setupNotificationListeners() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showConfettiIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardManager?.stopListeningToKeyboardNotifications() tearDownNotificationListeners() storeNotificationReplyIfNeeded() dismissNotice() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { context in self.refreshInterfaceIfNeeded() }) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() refreshNavigationBar() adjustLayoutConstraintsIfNeeded() } private func makeRouter() -> NotificationContentRouter { return NotificationContentRouter(activity: note, coordinator: coordinator) } fileprivate func markAsReadIfNeeded() { guard !note.read else { return } NotificationSyncMediator()?.markAsRead(note) } fileprivate func refreshInterfaceIfNeeded() { guard isViewLoaded else { return } refreshInterface() } fileprivate func refreshInterface() { formatter.resetCache() tableView.reloadData() attachReplyViewIfNeeded() attachSuggestionsViewIfNeeded() adjustLayoutConstraintsIfNeeded() refreshNavigationBar() } fileprivate func refreshNavigationBar() { title = note.title if splitViewControllerIsHorizontallyCompact { enableNavigationRightBarButtonItems() } else { navigationItem.rightBarButtonItems = nil } } fileprivate func enableNavigationRightBarButtonItems() { // https://github.com/wordpress-mobile/WordPress-iOS/issues/6662#issue-207316186 let buttonSize = CGFloat(24) let buttonSpacing = CGFloat(12) let width = buttonSize + buttonSpacing + buttonSize let height = buttonSize let buttons = UIStackView(arrangedSubviews: [nextNavigationButton, previousNavigationButton]) buttons.axis = .horizontal buttons.spacing = buttonSpacing buttons.frame = CGRect(x: 0, y: 0, width: width, height: height) UIView.performWithoutAnimation { navigationItem.rightBarButtonItem = UIBarButtonItem(customView: buttons) } previousNavigationButton.isEnabled = shouldEnablePreviousButton nextNavigationButton.isEnabled = shouldEnableNextButton previousNavigationButton.accessibilityLabel = NSLocalizedString("Previous notification", comment: "Accessibility label for the previous notification button") nextNavigationButton.accessibilityLabel = NSLocalizedString("Next notification", comment: "Accessibility label for the next notification button") } } // MARK: - State Restoration // extension NotificationDetailsViewController: UIViewControllerRestoration { class func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { let context = Environment.current.mainContext guard let noteURI = coder.decodeObject(forKey: Restoration.noteIdKey) as? URL, let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: noteURI) else { return nil } let notification = try? context.existingObject(with: objectID) guard let restoredNotification = notification as? Notification else { return nil } let storyboard = coder.decodeObject(forKey: UIApplication.stateRestorationViewControllerStoryboardKey) as? UIStoryboard guard let vc = storyboard?.instantiateViewController(withIdentifier: Restoration.restorationIdentifier) as? NotificationDetailsViewController else { return nil } vc.note = restoredNotification return vc } override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(note.objectID.uriRepresentation(), forKey: Restoration.noteIdKey) } } // MARK: - UITableView Methods // extension NotificationDetailsViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Settings.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return note.headerAndBodyContentGroups.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let group = contentGroup(for: indexPath) let reuseIdentifier = reuseIdentifierForGroup(group) guard let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? NoteBlockTableViewCell else { DDLogError("Failed dequeueing NoteBlockTableViewCell.") return UITableViewCell() } setup(cell, withContentGroupAt: indexPath) return cell } func setup(_ cell: NoteBlockTableViewCell, withContentGroupAt indexPath: IndexPath) { let group = contentGroup(for: indexPath) setup(cell, with: group, at: indexPath) downloadAndResizeMedia(at: indexPath, from: group) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { estimatedRowHeightsCache.setObject(cell.frame.height as AnyObject, forKey: indexPath as AnyObject) guard let cell = cell as? NoteBlockTableViewCell else { return } setupSeparators(cell, indexPath: indexPath) } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if let height = estimatedRowHeightsCache.object(forKey: indexPath as AnyObject) as? CGFloat { return height } return Settings.estimatedRowHeight } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let group = contentGroup(for: indexPath) displayContent(group) } func displayContent(_ contentGroup: FormattableContentGroup) { switch contentGroup.kind { case .header: displayNotificationSource() case .user: let content: FormattableUserContent? = contentGroup.blockOfKind(.user) let url = content?.metaLinksHome displayURL(url) case .footer: let content: FormattableTextContent? = contentGroup.blockOfKind(.text) let lastRange = content?.ranges.last as? LinkContentRange let url = lastRange?.url displayURL(url) default: tableView.deselectSelectedRowWithAnimation(true) } } } // MARK: - Setup Helpers // extension NotificationDetailsViewController { func setupNavigationBar() { // Don't show the notification title in the next-view's back button let backButton = UIBarButtonItem(title: String(), style: .plain, target: nil, action: nil) navigationItem.backBarButtonItem = backButton let next = UIButton(type: .custom) next.setImage(.gridicon(.arrowUp), for: .normal) next.addTarget(self, action: #selector(nextNotificationWasPressed), for: .touchUpInside) let previous = UIButton(type: .custom) previous.setImage(.gridicon(.arrowDown), for: .normal) previous.addTarget(self, action: #selector(previousNotificationWasPressed), for: .touchUpInside) previousNavigationButton = previous nextNavigationButton = next enableNavigationRightBarButtonItems() } func setupMainView() { view.backgroundColor = note.isBadge ? .ungroupedListBackground : .listBackground } func setupTableView() { tableView.separatorStyle = .none tableView.keyboardDismissMode = .interactive tableView.accessibilityIdentifier = NSLocalizedString("Notification Details Table", comment: "Notifications Details Accessibility Identifier") tableView.backgroundColor = note.isBadge ? .ungroupedListBackground : .listBackground } func setupTableViewCells() { let cellClassNames: [NoteBlockTableViewCell.Type] = [ NoteBlockHeaderTableViewCell.self, NoteBlockTextTableViewCell.self, NoteBlockActionsTableViewCell.self, NoteBlockCommentTableViewCell.self, NoteBlockImageTableViewCell.self, NoteBlockUserTableViewCell.self, NoteBlockButtonTableViewCell.self ] for cellClass in cellClassNames { let classname = cellClass.classNameWithoutNamespaces() let nib = UINib(nibName: classname, bundle: Bundle.main) tableView.register(nib, forCellReuseIdentifier: cellClass.reuseIdentifier()) } tableView.register(LikeUserTableViewCell.defaultNib, forCellReuseIdentifier: LikeUserTableViewCell.defaultReuseID) } /// Configure the delegate and data source for the table view based on notification type. /// This method may be called several times, especially upon previous/next button click /// since notification kind may change. func setupTableDelegates() { if note.kind == .like || note.kind == .commentLike, let likesListController = LikesListController(tableView: tableView, notification: note, delegate: self) { tableView.delegate = likesListController tableView.dataSource = likesListController self.likesListController = likesListController // always call refresh to ensure that the controller fetches the data. likesListController.refresh() } else { tableView.delegate = self tableView.dataSource = self } } func setupReplyTextView() { let previousReply = NotificationReplyStore.shared.loadReply(for: note.notificationId) let replyTextView = ReplyTextView(width: view.frame.width) replyTextView.placeholder = NSLocalizedString("Write a reply", comment: "Placeholder text for inline compose view") replyTextView.text = previousReply replyTextView.accessibilityIdentifier = NSLocalizedString("Reply Text", comment: "Notifications Reply Accessibility Identifier") replyTextView.delegate = self replyTextView.onReply = { [weak self] content in let group = self?.note.contentGroup(ofKind: .comment) guard let block: FormattableCommentContent = group?.blockOfKind(.comment) else { return } self?.replyCommentWithBlock(block, content: content) } replyTextView.setContentCompressionResistancePriority(.required, for: .vertical) self.replyTextView = replyTextView } func setupSuggestionsView() { guard let siteID = note.metaSiteID else { return } suggestionsTableView = SuggestionsTableView(siteID: siteID, suggestionType: .mention, delegate: self) suggestionsTableView?.prominentSuggestionsIds = SuggestionsTableView.prominentSuggestions( fromPostAuthorId: nil, commentAuthorId: note.metaCommentAuthorID, defaultAccountId: try? WPAccount.lookupDefaultWordPressComAccount(in: self.mainContext)?.userID ) suggestionsTableView?.translatesAutoresizingMaskIntoConstraints = false } func setupKeyboardManager() { precondition(replyTextView != nil) precondition(bottomLayoutConstraint != nil) keyboardManager = KeyboardDismissHelper(parentView: view, scrollView: tableView, dismissableControl: replyTextView, bottomLayoutConstraint: bottomLayoutConstraint) } func setupNotificationListeners() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(notificationWasUpdated), name: .NSManagedObjectContextObjectsDidChange, object: note.managedObjectContext) } func tearDownNotificationListeners() { let nc = NotificationCenter.default nc.removeObserver(self, name: .NSManagedObjectContextObjectsDidChange, object: note.managedObjectContext) } } // MARK: - Reply View Helpers // extension NotificationDetailsViewController { func attachReplyViewIfNeeded() { guard shouldAttachReplyView else { replyTextView.removeFromSuperview() return } stackView.addArrangedSubview(replyTextView) } var shouldAttachReplyView: Bool { // Attach the Reply component only if the notification has a comment, and it can be replied to. // guard let block: FormattableCommentContent = note.contentGroup(ofKind: .comment)?.blockOfKind(.comment) else { return false } return block.action(id: ReplyToCommentAction.actionIdentifier())?.on ?? false } func storeNotificationReplyIfNeeded() { guard let reply = replyTextView?.text, let notificationId = note?.notificationId, !reply.isEmpty else { return } NotificationReplyStore.shared.store(reply: reply, for: notificationId) } } // MARK: - Reader Helpers // private extension NotificationDetailsViewController { func attachReaderViewIfNeeded() { guard shouldAttachReaderView, let postID = note.metaPostID, let siteID = note.metaSiteID else { readerDetailViewController?.remove() return } readerDetailViewController?.remove() let readerDetailViewController = ReaderDetailViewController.controllerWithPostID(postID, siteID: siteID) add(readerDetailViewController) readerDetailViewController.view.translatesAutoresizingMaskIntoConstraints = false view.pinSubviewToSafeArea(readerDetailViewController.view) self.readerDetailViewController = readerDetailViewController } var shouldAttachReaderView: Bool { return note.kind == .newPost } } // MARK: - Suggestions View Helpers // private extension NotificationDetailsViewController { func attachSuggestionsViewIfNeeded() { guard shouldAttachSuggestionsView, let suggestionsTableView = self.suggestionsTableView else { self.suggestionsTableView?.removeFromSuperview() return } view.addSubview(suggestionsTableView) NSLayoutConstraint.activate([ suggestionsTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), suggestionsTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), suggestionsTableView.topAnchor.constraint(equalTo: view.topAnchor), suggestionsTableView.bottomAnchor.constraint(equalTo: replyTextView.topAnchor) ]) } var shouldAttachSuggestionsView: Bool { guard let siteID = note.metaSiteID, let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else { return false } return shouldAttachReplyView && SuggestionService.shared.shouldShowSuggestions(for: blog) } } // MARK: - Layout Helpers // private extension NotificationDetailsViewController { func adjustLayoutConstraintsIfNeeded() { // Badge Notifications: // - Should be vertically centered // - Don't need cell separators // - Should have Vertical Scroll enabled only if the Table Content falls off the screen. // let requiresVerticalAlignment = note.isBadge topLayoutConstraint.isActive = !requiresVerticalAlignment bottomLayoutConstraint.isActive = !requiresVerticalAlignment badgeTopLayoutConstraint.isActive = requiresVerticalAlignment badgeBottomLayoutConstraint.isActive = requiresVerticalAlignment badgeCenterLayoutConstraint.isActive = requiresVerticalAlignment if requiresVerticalAlignment { tableView.isScrollEnabled = tableView.intrinsicContentSize.height > view.bounds.height } else { tableView.isScrollEnabled = true } } func reuseIdentifierForGroup(_ blockGroup: FormattableContentGroup) -> String { switch blockGroup.kind { case .header: return NoteBlockHeaderTableViewCell.reuseIdentifier() case .footer: return NoteBlockTextTableViewCell.reuseIdentifier() case .subject: fallthrough case .text: return NoteBlockTextTableViewCell.reuseIdentifier() case .comment: return NoteBlockCommentTableViewCell.reuseIdentifier() case .actions: return NoteBlockActionsTableViewCell.reuseIdentifier() case .image: return NoteBlockImageTableViewCell.reuseIdentifier() case .user: return NoteBlockUserTableViewCell.reuseIdentifier() case .button: return NoteBlockButtonTableViewCell.reuseIdentifier() default: assertionFailure("Unmanaged group kind: \(blockGroup.kind)") return NoteBlockTextTableViewCell.reuseIdentifier() } } func setupSeparators(_ cell: NoteBlockTableViewCell, indexPath: IndexPath) { cell.isBadge = note.isBadge cell.isLastRow = (indexPath.row >= note.headerAndBodyContentGroups.count - 1) cell.refreshSeparators() } } // MARK: - UITableViewCell Subclass Setup // private extension NotificationDetailsViewController { func setup(_ cell: NoteBlockTableViewCell, with blockGroup: FormattableContentGroup, at indexPath: IndexPath) { switch cell { case let cell as NoteBlockHeaderTableViewCell: setupHeaderCell(cell, blockGroup: blockGroup) case let cell as NoteBlockTextTableViewCell where blockGroup is FooterContentGroup: setupFooterCell(cell, blockGroup: blockGroup) case let cell as NoteBlockUserTableViewCell: setupUserCell(cell, blockGroup: blockGroup) case let cell as NoteBlockCommentTableViewCell: setupCommentCell(cell, blockGroup: blockGroup, at: indexPath) case let cell as NoteBlockActionsTableViewCell: setupActionsCell(cell, blockGroup: blockGroup) case let cell as NoteBlockImageTableViewCell: setupImageCell(cell, blockGroup: blockGroup) case let cell as NoteBlockTextTableViewCell: setupTextCell(cell, blockGroup: blockGroup, at: indexPath) case let cell as NoteBlockButtonTableViewCell: setupButtonCell(cell, blockGroup: blockGroup) default: assertionFailure("NotificationDetails: Please, add support for \(cell)") } } func setupHeaderCell(_ cell: NoteBlockHeaderTableViewCell, blockGroup: FormattableContentGroup) { // Note: // We're using a UITableViewCell as a Header, instead of UITableViewHeaderFooterView, because: // - UITableViewCell automatically handles highlight / unhighlight for us // - UITableViewCell's taps don't require a Gestures Recognizer. No big deal, but less code! // cell.attributedHeaderTitle = nil cell.attributedHeaderDetails = nil guard let gravatarBlock: NotificationTextContent = blockGroup.blockOfKind(.image), let snippetBlock: NotificationTextContent = blockGroup.blockOfKind(.text) else { return } cell.attributedHeaderTitle = formatter.render(content: gravatarBlock, with: HeaderContentStyles()) cell.attributedHeaderDetails = formatter.render(content: snippetBlock, with: HeaderDetailsContentStyles()) // Download the Gravatar let mediaURL = gravatarBlock.media.first?.mediaURL cell.downloadAuthorAvatar(with: mediaURL) } func setupFooterCell(_ cell: NoteBlockTextTableViewCell, blockGroup: FormattableContentGroup) { guard let textBlock = blockGroup.blocks.first else { assertionFailure("Missing Text Block for Notification [\(note.notificationId)") return } cell.attributedText = formatter.render(content: textBlock, with: FooterContentStyles()) cell.isTextViewSelectable = false cell.isTextViewClickable = false } func setupUserCell(_ cell: NoteBlockUserTableViewCell, blockGroup: FormattableContentGroup) { guard let userBlock = blockGroup.blocks.first as? FormattableUserContent else { assertionFailure("Missing User Block for Notification [\(note.notificationId)]") return } let hasHomeURL = userBlock.metaLinksHome != nil let hasHomeTitle = userBlock.metaTitlesHome?.isEmpty == false cell.accessoryType = hasHomeURL ? .disclosureIndicator : .none cell.name = userBlock.text cell.blogTitle = hasHomeTitle ? userBlock.metaTitlesHome : userBlock.metaLinksHome?.host cell.isFollowEnabled = userBlock.isActionEnabled(id: FollowAction.actionIdentifier()) cell.isFollowOn = userBlock.isActionOn(id: FollowAction.actionIdentifier()) cell.onFollowClick = { [weak self] in self?.followSiteWithBlock(userBlock) } cell.onUnfollowClick = { [weak self] in self?.unfollowSiteWithBlock(userBlock) } // Download the Gravatar let mediaURL = userBlock.media.first?.mediaURL cell.downloadGravatarWithURL(mediaURL) } func setupCommentCell(_ cell: NoteBlockCommentTableViewCell, blockGroup: FormattableContentGroup, at indexPath: IndexPath) { // Note: // The main reason why it's a very good idea *not* to reuse NoteBlockHeaderTableViewCell, just to display the // gravatar, is because we're implementing a custom behavior whenever the user approves/ unapproves the comment. // // - Font colors are updated. // - A left separator is displayed. // guard let commentBlock: FormattableCommentContent = blockGroup.blockOfKind(.comment) else { assertionFailure("Missing Comment Block for Notification [\(note.notificationId)]") return } guard let userBlock: FormattableUserContent = blockGroup.blockOfKind(.user) else { assertionFailure("Missing User Block for Notification [\(note.notificationId)]") return } // Merge the Attachments with their ranges: [NSRange: UIImage] let mediaMap = mediaDownloader.imagesForUrls(commentBlock.imageUrls) let mediaRanges = commentBlock.buildRangesToImagesMap(mediaMap) let styles = RichTextContentStyles(key: "RichText-\(indexPath)") let text = formatter.render(content: commentBlock, with: styles).stringByEmbeddingImageAttachments(mediaRanges) // Setup: Properties cell.name = userBlock.text cell.timestamp = (note.timestampAsDate as NSDate).mediumString() cell.site = userBlock.metaTitlesHome ?? userBlock.metaLinksHome?.host cell.attributedCommentText = text.trimNewlines() cell.isApproved = commentBlock.isCommentApproved // Add comment author's name to Reply placeholder. let placeholderFormat = NSLocalizedString("Reply to %1$@", comment: "Placeholder text for replying to a comment. %1$@ is a placeholder for the comment author's name.") replyTextView.placeholder = String(format: placeholderFormat, cell.name ?? String()) // Setup: Callbacks cell.onUserClick = { [weak self] in guard let homeURL = userBlock.metaLinksHome else { return } self?.displayURL(homeURL) } cell.onUrlClick = { [weak self] url in self?.displayURL(url as URL) } cell.onAttachmentClick = { [weak self] attachment in guard let image = attachment.image else { return } self?.router.routeTo(image) } cell.onTimeStampLongPress = { [weak self] in guard let urlString = self?.note.url, let url = URL(string: urlString) else { return } UIAlertController.presentAlertAndCopyCommentURLToClipboard(url: url) } // Download the Gravatar let mediaURL = userBlock.media.first?.mediaURL cell.downloadGravatarWithURL(mediaURL) } func setupActionsCell(_ cell: NoteBlockActionsTableViewCell, blockGroup: FormattableContentGroup) { guard let commentBlock: FormattableCommentContent = blockGroup.blockOfKind(.comment) else { assertionFailure("Missing Comment Block for Notification \(note.notificationId)") return } // Setup: Properties // Note: Approve Action is actually a synonym for 'Edit' (Based on Calypso's basecode) // cell.isReplyEnabled = UIDevice.isPad() && commentBlock.isActionOn(id: ReplyToCommentAction.actionIdentifier()) cell.isLikeEnabled = commentBlock.isActionEnabled(id: LikeCommentAction.actionIdentifier()) cell.isApproveEnabled = commentBlock.isActionEnabled(id: ApproveCommentAction.actionIdentifier()) cell.isTrashEnabled = commentBlock.isActionEnabled(id: TrashCommentAction.actionIdentifier()) cell.isSpamEnabled = commentBlock.isActionEnabled(id: MarkAsSpamAction.actionIdentifier()) cell.isEditEnabled = commentBlock.isActionOn(id: ApproveCommentAction.actionIdentifier()) cell.isLikeOn = commentBlock.isActionOn(id: LikeCommentAction.actionIdentifier()) cell.isApproveOn = commentBlock.isActionOn(id: ApproveCommentAction.actionIdentifier()) // Setup: Callbacks cell.onReplyClick = { [weak self] _ in self?.focusOnReplyTextViewWithBlock(commentBlock) } cell.onLikeClick = { [weak self] _ in self?.likeCommentWithBlock(commentBlock) } cell.onUnlikeClick = { [weak self] _ in self?.unlikeCommentWithBlock(commentBlock) } cell.onApproveClick = { [weak self] _ in self?.approveCommentWithBlock(commentBlock) } cell.onUnapproveClick = { [weak self] _ in self?.unapproveCommentWithBlock(commentBlock) } cell.onTrashClick = { [weak self] _ in self?.trashCommentWithBlock(commentBlock) } cell.onSpamClick = { [weak self] _ in self?.spamCommentWithBlock(commentBlock) } cell.onEditClick = { [weak self] _ in self?.displayCommentEditorWithBlock(commentBlock) } } func setupImageCell(_ cell: NoteBlockImageTableViewCell, blockGroup: FormattableContentGroup) { guard let imageBlock = blockGroup.blocks.first as? NotificationTextContent else { assertionFailure("Missing Image Block for Notification [\(note.notificationId)") return } let mediaURL = imageBlock.media.first?.mediaURL cell.downloadImage(mediaURL) if note.isViewMilestone { cell.backgroundImage = UIImage(named: Assets.confettiBackground) } } func setupTextCell(_ cell: NoteBlockTextTableViewCell, blockGroup: FormattableContentGroup, at indexPath: IndexPath) { guard let textBlock = blockGroup.blocks.first as? NotificationTextContent else { assertionFailure("Missing Text Block for Notification \(note.notificationId)") return } // Merge the Attachments with their ranges: [NSRange: UIImage] let mediaMap = mediaDownloader.imagesForUrls(textBlock.imageUrls) let mediaRanges = textBlock.buildRangesToImagesMap(mediaMap) // Load the attributedText let text: NSAttributedString if note.isBadge { let isFirstTextGroup = indexPath.row == indexOfFirstContentGroup(ofKind: .text) text = formatter.render(content: textBlock, with: BadgeContentStyles(cachingKey: "Badge-\(indexPath)", isTitle: isFirstTextGroup)) cell.isTitle = isFirstTextGroup } else { text = formatter.render(content: textBlock, with: RichTextContentStyles(key: "Rich-Text-\(indexPath)")) } // Setup: Properties cell.attributedText = text.stringByEmbeddingImageAttachments(mediaRanges) // Setup: Callbacks cell.onUrlClick = { [weak self] url in guard let `self` = self, self.isViewOnScreen() else { return } self.displayURL(url) } } func setupButtonCell(_ cell: NoteBlockButtonTableViewCell, blockGroup: FormattableContentGroup) { guard let textBlock = blockGroup.blocks.first as? NotificationTextContent else { assertionFailure("Missing Text Block for Notification \(note.notificationId)") return } cell.title = textBlock.text if let linkRange = textBlock.ranges.map({ $0 as? LinkContentRange }).first, let url = linkRange?.url { cell.action = { [weak self] in guard let `self` = self, self.isViewOnScreen() else { return } self.displayURL(url) } } } } // MARK: - Notification Helpers // extension NotificationDetailsViewController { @objc func notificationWasUpdated(_ notification: Foundation.Notification) { let updated = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> ?? Set() let refreshed = notification.userInfo?[NSRefreshedObjectsKey] as? Set<NSManagedObject> ?? Set() let deleted = notification.userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject> ?? Set() // Reload the table, if *our* notification got updated + Mark as Read since it's already onscreen! if updated.contains(note) || refreshed.contains(note) { refreshInterface() // We're being called when the managed context is saved // Let's defer any data changes or we will try to save within a save // and crash 💥 DispatchQueue.main.async { [weak self] in self?.markAsReadIfNeeded() } } else { // Otherwise, refresh the navigation bar as the notes list might have changed refreshNavigationBar() } // Dismiss this ViewController if *our* notification... just got deleted if deleted.contains(note) { _ = navigationController?.popToRootViewController(animated: true) } } } // MARK: - Resources // private extension NotificationDetailsViewController { func displayURL(_ url: URL?) { guard let url = url else { tableView.deselectSelectedRowWithAnimation(true) return } router.routeTo(url) } func displayNotificationSource() { do { try router.routeToNotificationSource() } catch { tableView.deselectSelectedRowWithAnimation(true) } } func displayUserProfile(_ user: LikeUser, from indexPath: IndexPath) { let userProfileVC = UserProfileSheetViewController(user: user) userProfileVC.blogUrlPreviewedSource = "notif_like_list_user_profile" let bottomSheet = BottomSheetViewController(childViewController: userProfileVC) let sourceView = tableView.cellForRow(at: indexPath) ?? view bottomSheet.show(from: self, sourceView: sourceView) WPAnalytics.track(.userProfileSheetShown, properties: ["source": "like_notification_list"]) } } // MARK: - Helpers // private extension NotificationDetailsViewController { func contentGroup(for indexPath: IndexPath) -> FormattableContentGroup { return note.headerAndBodyContentGroups[indexPath.row] } func indexOfFirstContentGroup(ofKind kind: FormattableContentGroup.Kind) -> Int? { return note.headerAndBodyContentGroups.firstIndex(where: { $0.kind == kind }) } } // MARK: - Media Download Helpers // private extension NotificationDetailsViewController { /// Extracts all of the imageUrl's for the blocks of the specified kinds /// func imageUrls(from content: [FormattableContent], inKindSet kindSet: Set<FormattableContentKind>) -> Set<URL> { let filtered = content.filter { kindSet.contains($0.kind) } let imageUrls = filtered.compactMap { ($0 as? NotificationTextContent)?.imageUrls }.flatMap { $0 } return Set(imageUrls) } func downloadAndResizeMedia(at indexPath: IndexPath, from contentGroup: FormattableContentGroup) { // Notes: // - We'll *only* download Media for Text and Comment Blocks // - Plus, we'll also resize the downloaded media cache *if needed*. This is meant to adjust images to // better fit onscreen, whenever the device orientation changes (and in turn, the maxMediaEmbedWidth changes too). // let urls = imageUrls(from: contentGroup.blocks, inKindSet: ContentMedia.richBlockTypes) let completion = { // Workaround: Performing the reload call, multiple times, without the .BeginFromCurrentState might // lead to a state in which the cell remains not visible. // UIView.animate(withDuration: ContentMedia.duration, delay: ContentMedia.delay, options: ContentMedia.options, animations: { [weak self] in self?.tableView.reloadRows(at: [indexPath], with: .fade) }) } mediaDownloader.downloadMedia(urls: urls, maximumWidth: maxMediaEmbedWidth, completion: completion) mediaDownloader.resizeMediaWithIncorrectSize(maxMediaEmbedWidth, completion: completion) } var maxMediaEmbedWidth: CGFloat { let readableWidth = ceil(tableView.readableContentGuide.layoutFrame.size.width) return readableWidth > 0 ? readableWidth : view.frame.size.width } } // MARK: - Action Handlers // private extension NotificationDetailsViewController { func followSiteWithBlock(_ block: FormattableUserContent) { UINotificationFeedbackGenerator().notificationOccurred(.success) actionsService.followSiteWithBlock(block) WPAppAnalytics.track(.notificationsSiteFollowAction, withBlogID: block.metaSiteID) } func unfollowSiteWithBlock(_ block: FormattableUserContent) { actionsService.unfollowSiteWithBlock(block) WPAppAnalytics.track(.notificationsSiteUnfollowAction, withBlogID: block.metaSiteID) } func likeCommentWithBlock(_ block: FormattableCommentContent) { guard let likeAction = block.action(id: LikeCommentAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block) likeAction.execute(context: actionContext) WPAppAnalytics.track(.notificationsCommentLiked, withBlogID: block.metaSiteID) } func unlikeCommentWithBlock(_ block: FormattableCommentContent) { guard let likeAction = block.action(id: LikeCommentAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block) likeAction.execute(context: actionContext) WPAppAnalytics.track(.notificationsCommentUnliked, withBlogID: block.metaSiteID) } func approveCommentWithBlock(_ block: FormattableCommentContent) { guard let approveAction = block.action(id: ApproveCommentAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block) approveAction.execute(context: actionContext) WPAppAnalytics.track(.notificationsCommentApproved, withBlogID: block.metaSiteID) } func unapproveCommentWithBlock(_ block: FormattableCommentContent) { guard let approveAction = block.action(id: ApproveCommentAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block) approveAction.execute(context: actionContext) WPAppAnalytics.track(.notificationsCommentUnapproved, withBlogID: block.metaSiteID) } func spamCommentWithBlock(_ block: FormattableCommentContent) { guard onDeletionRequestCallback != nil else { // callback probably missing due to state restoration. at least by // not crashing the user can tap the back button and try again return } guard let spamAction = block.action(id: MarkAsSpamAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block, completion: { [weak self] (request, success) in WPAppAnalytics.track(.notificationsCommentFlaggedAsSpam, withBlogID: block.metaSiteID) guard let request = request else { return } self?.onDeletionRequestCallback?(request) }) spamAction.execute(context: actionContext) // We're thru _ = navigationController?.popToRootViewController(animated: true) } func trashCommentWithBlock(_ block: FormattableCommentContent) { guard onDeletionRequestCallback != nil else { // callback probably missing due to state restoration. at least by // not crashing the user can tap the back button and try again return } guard let trashAction = block.action(id: TrashCommentAction.actionIdentifier()) else { return } let actionContext = ActionContext(block: block, completion: { [weak self] (request, success) in WPAppAnalytics.track(.notificationsCommentTrashed, withBlogID: block.metaSiteID) guard let request = request else { return } self?.onDeletionRequestCallback?(request) }) trashAction.execute(context: actionContext) // We're thru _ = navigationController?.popToRootViewController(animated: true) } func replyCommentWithBlock(_ block: FormattableCommentContent, content: String) { guard let replyAction = block.action(id: ReplyToCommentAction.actionIdentifier()) else { return } let generator = UINotificationFeedbackGenerator() generator.prepare() generator.notificationOccurred(.success) let actionContext = ActionContext(block: block, content: content) { [weak self] (request, success) in if success { WPAppAnalytics.track(.notificationsCommentRepliedTo) let message = NSLocalizedString("Reply Sent!", comment: "The app successfully sent a comment") self?.displayNotice(title: message) } else { generator.notificationOccurred(.error) self?.displayReplyError(with: block, content: content) } } replyAction.execute(context: actionContext) } func updateCommentWithBlock(_ block: FormattableCommentContent, content: String) { guard let editCommentAction = block.action(id: EditCommentAction.actionIdentifier()) else { return } let generator = UINotificationFeedbackGenerator() generator.prepare() generator.notificationOccurred(.success) let actionContext = ActionContext(block: block, content: content) { [weak self] (request, success) in guard success == false else { CommentAnalytics.trackCommentEdited(block: block) return } generator.notificationOccurred(.error) self?.displayCommentUpdateErrorWithBlock(block, content: content) } editCommentAction.execute(context: actionContext) } } // MARK: - Replying Comments // private extension NotificationDetailsViewController { func focusOnReplyTextViewWithBlock(_ content: FormattableContent) { let _ = replyTextView.becomeFirstResponder() } func displayReplyError(with block: FormattableCommentContent, content: String) { let message = NSLocalizedString("There has been an unexpected error while sending your reply", comment: "Reply Failure Message") displayNotice(title: message) } } // MARK: - Editing Comments // private extension NotificationDetailsViewController { func updateComment(with commentContent: FormattableCommentContent, content: String) { self.updateCommentWithBlock(commentContent, content: content) } func displayCommentEditorWithBlock(_ block: FormattableCommentContent) { let editViewController = EditCommentViewController.newEdit() editViewController?.content = block.text editViewController?.onCompletion = { (hasNewContent, newContent) in self.dismiss(animated: true, completion: { guard hasNewContent else { return } let newContent = newContent ?? "" self.updateComment(with: block, content: newContent) }) } let navController = UINavigationController(rootViewController: editViewController!) navController.modalPresentationStyle = .formSheet navController.modalTransitionStyle = .coverVertical navController.navigationBar.isTranslucent = false CommentAnalytics.trackCommentEditorOpened(block: block) present(navController, animated: true) } func displayCommentUpdateErrorWithBlock(_ block: FormattableCommentContent, content: String) { let message = NSLocalizedString("There has been an unexpected error while updating your comment", comment: "Displayed whenever a Comment Update Fails") let cancelTitle = NSLocalizedString("Give Up", comment: "Cancel") let retryTitle = NSLocalizedString("Try Again", comment: "Retry") let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(cancelTitle) { action in block.textOverride = nil self.refreshInterface() } alertController.addDefaultActionWithTitle(retryTitle) { action in self.updateComment(with: block, content: content) } // Note: This viewController might not be visible anymore alertController.presentFromRootViewController() } } // MARK: - UITextViewDelegate // extension NotificationDetailsViewController: ReplyTextViewDelegate { func textView(_ textView: UITextView, didTypeWord word: String) { suggestionsTableView?.showSuggestions(forWord: word) } func replyTextView(_ replyTextView: ReplyTextView, willEnterFullScreen controller: FullScreenCommentReplyViewController) { guard let siteID = note.metaSiteID, let suggestionsTableView = self.suggestionsTableView else { return } let lastSearchText = suggestionsTableView.viewModel.searchText suggestionsTableView.hideSuggestions() controller.enableSuggestions(with: siteID, prominentSuggestionsIds: suggestionsTableView.prominentSuggestionsIds, searchText: lastSearchText) } func replyTextView(_ replyTextView: ReplyTextView, didExitFullScreen lastSearchText: String?) { guard let lastSearchText = lastSearchText, !lastSearchText.isEmpty else { return } suggestionsTableView?.showSuggestions(forWord: lastSearchText) } } // MARK: - UIScrollViewDelegate // extension NotificationDetailsViewController: UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { keyboardManager?.scrollViewWillBeginDragging(scrollView) } func scrollViewDidScroll(_ scrollView: UIScrollView) { keyboardManager?.scrollViewDidScroll(scrollView) } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { keyboardManager?.scrollViewWillEndDragging(scrollView, withVelocity: velocity) } } // MARK: - SuggestionsTableViewDelegate // extension NotificationDetailsViewController: SuggestionsTableViewDelegate { func suggestionsTableView(_ suggestionsTableView: SuggestionsTableView, didSelectSuggestion suggestion: String?, forSearchText text: String) { replyTextView.replaceTextAtCaret(text as NSString?, withText: suggestion) suggestionsTableView.showSuggestions(forWord: String()) } } // MARK: - Milestone notifications // private extension NotificationDetailsViewController { func showConfettiIfNeeded() { guard FeatureFlag.milestoneNotifications.enabled, note.isViewMilestone, !confettiWasShown, let view = UIApplication.shared.mainWindow, let frame = navigationController?.view.frame else { return } // This method will remove any existing `ConfettiView` before adding a new one // This ensures that when we navigate through notifications, if there is an // ongoging animation, it will be removed and replaced by a new one ConfettiView.cleanupAndAnimate(on: view, frame: frame) { confettiView in // removing this instance when the animation completes, will prevent // the animation to suddenly stop if users navigate away from the note confettiView.removeFromSuperview() } confettiWasShown = true } } // MARK: - Navigation Helpers // extension NotificationDetailsViewController { @IBAction func previousNotificationWasPressed() { guard let previous = dataSource?.notification(preceding: note) else { return } WPAnalytics.track(.notificationsPreviousTapped) refreshView(with: previous) } @IBAction func nextNotificationWasPressed() { guard let next = dataSource?.notification(succeeding: note) else { return } WPAnalytics.track(.notificationsNextTapped) refreshView(with: next) } private func refreshView(with note: Notification) { onSelectedNoteChange?(note) trackDetailsOpened(for: note) if FeatureFlag.notificationCommentDetails.enabled, note.kind == .comment { showCommentDetails(with: note) return } hideNoResults() self.note = note showConfettiIfNeeded() } private func showCommentDetails(with note: Notification) { guard let commentDetailViewController = notificationCommentDetailCoordinator?.createViewController(with: note) else { DDLogError("Notification Details: failed creating Comment Detail view.") return } notificationCommentDetailCoordinator?.onSelectedNoteChange = self.onSelectedNoteChange weak var navigationController = navigationController dismiss(animated: true, completion: { commentDetailViewController.navigationItem.largeTitleDisplayMode = .never navigationController?.popViewController(animated: false) navigationController?.pushViewController(commentDetailViewController, animated: false) }) } var shouldEnablePreviousButton: Bool { return dataSource?.notification(preceding: note) != nil } var shouldEnableNextButton: Bool { return dataSource?.notification(succeeding: note) != nil } } // MARK: - LikesListController Delegate // extension NotificationDetailsViewController: LikesListControllerDelegate { func didSelectHeader() { displayNotificationSource() } func didSelectUser(_ user: LikeUser, at indexPath: IndexPath) { displayUserProfile(user, from: indexPath) } func showErrorView(title: String, subtitle: String?) { hideNoResults() configureAndDisplayNoResults(on: tableView, title: title, subtitle: subtitle, image: "wp-illustration-notifications") } } // MARK: - Private Properties // private extension NotificationDetailsViewController { var mainContext: NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } var actionsService: NotificationActionsService { return NotificationActionsService(managedObjectContext: mainContext) } enum DisplayError: Error { case missingParameter case unsupportedFeature case unsupportedType } enum ContentMedia { static let richBlockTypes = Set(arrayLiteral: FormattableContentKind.text, FormattableContentKind.comment) static let duration = TimeInterval(0.25) static let delay = TimeInterval(0) static let options: UIView.AnimationOptions = [.overrideInheritedDuration, .beginFromCurrentState] } enum Restoration { static let noteIdKey = Notification.classNameWithoutNamespaces() static let restorationIdentifier = NotificationDetailsViewController.classNameWithoutNamespaces() } enum Settings { static let numberOfSections = 1 static let estimatedRowHeight = CGFloat(44) static let expirationFiveMinutes = TimeInterval(60 * 5) } enum Assets { static let confettiBackground = "notifications-confetti-background" } } // MARK: - Tracks extension NotificationDetailsViewController { /// Tracks notification details opened private func trackDetailsOpened(for note: Notification) { let properties = ["notification_type": note.type ?? "unknown"] WPAnalytics.track(.openedNotificationDetails, withProperties: properties) } }
gpl-2.0
522ad205080e079db1e68901adae6a94
36.570953
165
0.67337
5.574733
false
false
false
false
google-books/swift-api-client
GoogleBooksApiClient/GoogleApiToken.swift
1
989
import Foundation public struct GoogleApiToken { public let accessToken: String public let expiresIn: Int public let refreshToken: String public let tokenType: String public let updatedAt: Date = Date() public func isExpired(at: NSDate = NSDate()) -> Bool { return at.timeIntervalSince(updatedAt) > Double(expiresIn) } } extension GoogleApiToken: Deserializable { public static func create(_ dict: [AnyHashable : Any]) -> GoogleApiToken? { guard let accessToken = dict["access_token"] as? String, let expiresIn = dict["expires_in"] as? Int, let refreshToken = dict["refresh_token"] as? String, let tokenType = dict["token_type"] as? String else { return nil } return GoogleApiToken( accessToken: accessToken, expiresIn: expiresIn, refreshToken: refreshToken, tokenType: tokenType ) } }
mit
c86dd77192806ee9a63682010df8d3ec
28.088235
79
0.608696
4.945
false
false
false
false
HarveyHu/PoolScoreboard
Pool Scoreboard/Pool Scoreboard/ClockViewModel.swift
1
3990
// // ClockViewModel.swift // Pool Scoreboard // // Created by HarveyHu on 16/01/2017. // Copyright © 2017 HarveyHu. All rights reserved. // import Foundation import RxSwift import RxCocoa import AVFoundation class ClockViewModel { let disposeBag = DisposeBag() var countdownTimer: Timer? var countdownSeconds = 30 { didSet { count = countdownSeconds self.seconds = configureSeconds(count).asDriver(onErrorJustReturn: -1) } } var audioPlayer: AVAudioPlayer? var count = 0 var seconds: Driver<Int> = Driver.never() enum Sound: String { case extensionCall = "extension_call.mp3" case foul = "foul.mp3" case tenSeconds = "ten_seconds.mp3" case tick = "tick.mp3" case alarm = "alarm.mp3" } init() { //self.seconds = configureSeconds(count).asDriver(onErrorJustReturn: -1) count = countdownSeconds } func startTimer() { self.countdownTimer?.invalidate() self.count = self.countdownSeconds self.seconds = configureSeconds(count).asDriver(onErrorJustReturn: -1) } func stopTimer() { self.countdownTimer?.invalidate() self.count = 0 self.seconds = Driver.just(0) audioPlayer?.stop() } func resumeTimer() { self.seconds = configureSeconds(count).asDriver(onErrorJustReturn: -1) } func extentionCall() { self.countdownTimer?.invalidate() self.count = self.count + self.countdownSeconds self.seconds = configureSeconds(count).asDriver(onErrorJustReturn: -1) playSound(.extensionCall) } func playSound(_ sound: Sound) { audioPlayer?.stop() let mainPath = Bundle.main.bundlePath let pathUrl = URL(fileURLWithPath: mainPath + "/" + sound.rawValue) do { self.audioPlayer = try AVAudioPlayer(contentsOf: pathUrl) } catch let e { print("audioPlayer error! \(e.localizedDescription)") } audioPlayer?.play() } @objc func countdown(timer: Timer) { if let observer = timer.userInfo as? AnyObserver<Int> { self.count -= 1 self.playCountDownSound(count: self.count) if self.count < 0 { self.countdownTimer?.invalidate() observer.onCompleted() return } observer.on(.next(self.count)) } } func configureSeconds(_ second: Int) -> Observable<Int> { return Observable.create({ (observer) -> Disposable in observer.on(.next(self.count)) if #available(iOS 10.0, *) { self.countdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in self.count -= 1 self.playCountDownSound(count: self.count) if self.count < 0 { self.countdownTimer?.invalidate() observer.onCompleted() } observer.on(.next(self.count)) }) } else { // Fallback on earlier versions self.countdownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.countdown), userInfo: observer, repeats: true) } return Disposables.create() }) } private func playCountDownSound(count: Int) { switch count { case 10: self.playSound(.tenSeconds) case 1..<10: self.playSound(.tick) case 0: self.playSound(.alarm) default: break } } }
mit
89d2e4ca051a1b4b7661d0f4049dd62d
27.492857
163
0.532464
4.936881
false
false
false
false
oisinlavery/HackingWithSwift
project14-oisin/project14-oisin/WhackSlot.swift
1
2045
// // WhackSlot.swift // project14-oisin // // Created by Oisín Lavery on 12/2/15. // Copyright © 2015 Google. All rights reserved. // import SpriteKit import UIKit class WhackSlot: SKNode { var charNode: SKSpriteNode! var visible = false var isHit = false func configureAtPosition(pos: CGPoint) { position = pos let sprite = SKSpriteNode(imageNamed: "whackHole") addChild(sprite) let cropNode = SKCropNode() cropNode.position = CGPoint(x: 0, y: 15) cropNode.zPosition = 1 cropNode.maskNode = SKSpriteNode(imageNamed: "whackMask") charNode = SKSpriteNode(imageNamed: "penguinGood") charNode.position = CGPoint(x: 0, y: -90) charNode.name = "character" cropNode.addChild(charNode) addChild(cropNode) } func show(hideTime hideTime: Double) { if visible { return } charNode.xScale = 1.0 charNode.yScale = 1.0 charNode.runAction(SKAction.moveByX(0, y: 80, duration: 0.05)) visible = true isHit = false if RandomInt(min: 0, max: 2) == 0 { charNode.texture = SKTexture(imageNamed: "penguinGood") charNode.name = "charFriend" } else { charNode.texture = SKTexture(imageNamed: "penguinEvil") charNode.name = "charEnemy" } RunAfterDelay(hideTime * 3.5) { [unowned self] in self.hide() } } func hide() { if !visible { return } charNode.runAction(SKAction.moveByX(0, y:-80, duration:0.05)) visible = false } func hit() { isHit = true let delay = SKAction.waitForDuration(0.25) let hide = SKAction.moveByX(0, y:-80, duration:0.5) let notVisible = SKAction.runBlock { [unowned self] in self.visible = false } charNode.runAction(SKAction.sequence([delay, hide, notVisible])) } }
unlicense
c33784eb57ec15c5c6f45f029d9d48b4
25.192308
72
0.564856
4.144016
false
false
false
false
AlexeyTyurenkov/NBUStats
NBUStatProject/NBUStat/Modules/BaseClasses/BaseTableViewController.swift
1
3215
// // BaseTableViewController.swift // FinStat Ukraine // // Created by Aleksey Tyurenkov on 2/20/18. // Copyright © 2018 Oleksii Tiurenkov. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { private var customRefreshControl: RefreshController! var searchViewController: UISearchController? override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 88 tableView.tableFooterView = UIView() tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func configureRefreshControl() { customRefreshControl = RefreshController.defaultRefresh(frame:self.refreshControl?.bounds ?? CGRect.zero) self.refreshControl?.addTarget(self, action: #selector(self.handleRefresh(_:)), for: UIControlEvents.valueChanged) self.refreshControl?.addSubview(customRefreshControl) self.refreshControl?.backgroundColor = UIColor.clear self.refreshControl?.tintColor = UIColor.clear } func configureSearch(searchUpdater: UISearchResultsUpdating & UISearchBarDelegate) { self.searchViewController = UISearchController(searchResultsController: nil) definesPresentationContext = true self.searchViewController?.hidesNavigationBarDuringPresentation = false self.searchViewController?.dimsBackgroundDuringPresentation = false self.searchViewController?.searchResultsUpdater = searchUpdater self.searchViewController?.searchBar.delegate = searchUpdater self.searchViewController?.searchBar.placeholder = NSLocalizedString("Шукати за кодом або назвою", comment: "Search") self.searchViewController?.searchBar.sizeToFit() self.searchViewController?.searchBar.tintColor = UIColor.white tableView.tableHeaderView = searchViewController!.searchBar } func register(cellType: BaseTableCellProtocol.Type) { tableView.register(cellType.Nib(), forCellReuseIdentifier: cellType.CellIdentifier()) } @objc func handleRefresh(_ refreshControl: UIRefreshControl) { //Do nothing } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if refreshControl?.isRefreshing ?? false { if customRefreshControl.isAnimating { customRefreshControl.animation { () -> (Bool) in return self.refreshControl?.isRefreshing ?? false } } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
ff19e4f4925337880519ea563fdba8cd
34.466667
125
0.696115
5.867647
false
false
false
false
TechnologySpeaks/smile-for-life
smile-for-life/SQLiteDB.swift
1
15242
// // SQLiteDB.swift // smile-for-life // // Created by Lisa Swanson on 8/15/16. // Copyright © 2016 Technology Speaks. All rights reserved. // // // SQLiteDB.swift // TasksGalore // // Created by Fahim Farook on 12/6/14. // Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved. // /* import Foundation #if os(iOS) import UIKit #else import AppKit #endif let SQLITE_DATE = SQLITE_NULL + 1 private let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self) private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self) // MARK:- SQLiteDB Class - Does all the work @objc(SQLiteDB) class SQLiteDB:NSObject { let DB_NAME = "data.db" let QUEUE_LABEL = "SQLiteDB" static let sharedInstance = SQLiteDB() private var db:OpaquePointer = nil private var queue:dispatch_queue_t! private let fmt = DateFormatter() private var path:String! private override init() { super.init() // Set up for file operations let fm = FileManager.defaultManager() let dbName = String.fromCString(DB_NAME)! // Get path to DB in Documents directory var docDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] // If macOS, add app name to path since otherwise, DB could possibly interfere with another app using SQLiteDB #if os(OSX) let info = NSBundle.mainBundle().infoDictionary! let appName = info["CFBundleName"] as! String docDir = (docDir as NSString).stringByAppendingPathComponent(appName) // Create folder if it does not exist if !fm.fileExistsAtPath(docDir) { do { try fm.createDirectoryAtPath(docDir, withIntermediateDirectories:true, attributes:nil) } catch { NSLog("Error creating DB directory: \(docDir) on macOS") } } #endif let path = (docDir as NSString).stringByAppendingPathComponent(dbName) // NSLog("Database path: \(path)") // Check if copy of DB is there in Documents directory if !(fm.fileExistsAtPath(path)) { // The database does not exist, so copy to Documents directory guard let rp = Bundle.mainBundle().resourcePath else { return } let from = (rp as NSString).stringByAppendingPathComponent(dbName) do { try fm.copyItemAtPath(from, toPath:path) } catch let error as NSError { NSLog("SQLiteDB - failed to copy writable version of DB!") NSLog("Error - \(error.localizedDescription)") return } } openDB(path) } private init(path:String) { super.init() openDB(path: path) } deinit { closeDB() } override var description:String { return "SQLiteDB: \(path)" } // MARK:- Class Methods class func openRO(path:String) -> SQLiteDB { let db = SQLiteDB(path:path) return db } // MARK:- Public Methods func dbDate(dt:NSDate) -> String { return fmt.stringFromDate(dt) } func dbDateFromString(str:String, format:String="") -> NSDate? { let dtFormat = fmt.dateFormat if !format.isEmpty { fmt.dateFormat = format } let dt = fmt.dateFromString(str) if !format.isEmpty { fmt.dateFormat = dtFormat } return dt } // Execute SQL with parameters and return result code func execute(sql:String, parameters:[AnyObject]?=nil)->CInt { var result:CInt = 0 dispatch_sync(queue) { if let stmt = self.prepare(sql, params:parameters) { result = self.execute(stmt, sql:sql) } } return result } // Run SQL query with parameters func query(sql:String, parameters:[AnyObject]?=nil)->[[String:AnyObject]] { var rows = [[String:AnyObject]]() dispatch_sync(queue) { if let stmt = self.prepare(sql, params:parameters) { rows = self.query(stmt, sql:sql) } } print("I am in query and going to return row") for row in rows { print("%%%%#####################") print("\(row["id"]) \(row["stringifiedDate"])") } return rows } // Show alert with either supplied message or last error func alert(msg:String) { dispatch_async(DispatchQueue.main) { #if os(iOS) // let alert = UIAlertView(title: "SQLiteDB", message:msg, delegate: nil, cancelButtonTitle: "OK") let alert = UIAlertController(title: "SQLiteDB", message: msg, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) alert.present(alert, animated: true, completion: nil) #else let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "SQLiteDB" alert.informativeText = msg alert.alertStyle = NSAlertStyle.WarningAlertStyle alert.runModal() #endif } } // Versioning func getDBVersion() -> Int { var version = 0 let arr = query("PRAGMA user_version") if arr.count == 1 { version = arr[0]["user_version"] as! Int } return version } // Sets the 'user_version' value, a user-defined version number for the database. This is useful for managing migrations. func setDBVersion(version:Int) { execute("PRAGMA user_version=\(version)") } // MARK:- Private Methods private func openDB(path:String) { // Set up essentials queue = dispatch_queue_create(QUEUE_LABEL, nil) // You need to set the locale in order for the 24-hour date format to work correctly on devices where 24-hour format is turned off fmt.locale = NSLocale(localeIdentifier:"en_US_POSIX") fmt.timeZone = NSTimeZone(forSecondsFromGMT:0) fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" // Open the DB let cpath = path.cStringUsingEncoding(String.Encoding.utf8) let error = sqlite3_open(cpath!, &db) if error != SQLITE_OK { // Open failed, close DB and fail NSLog("SQLiteDB - failed to open DB!") sqlite3_close(db) return } NSLog("SQLiteDB opened!") } private func closeDB() { if db != nil { // Get launch count value let ud = UserDefaults.standardUserDefaults() var launchCount = ud.integerForKey("LaunchCount") launchCount -= 1 NSLog("SQLiteDB - Launch count \(launchCount)") var clean = false if launchCount < 0 { clean = true launchCount = 500 } ud.setInteger(launchCount, forKey:"LaunchCount") ud.synchronize() // Do we clean DB? if !clean { sqlite3_close(db) return } // Clean DB NSLog("SQLiteDB - Optimize DB") let sql = "VACUUM; ANALYZE" if execute(sql) != SQLITE_OK { NSLog("SQLiteDB - Error cleaning DB") } sqlite3_close(db) } } // Private method which prepares the SQL private func prepare(sql:String, params:[AnyObject]?) -> OpaquePointer? { var stmt:OpaquePointer = nil let cSql = sql.cStringUsingEncoding(NSUTF8StringEncoding) // Prepare let result = sqlite3_prepare_v2(self.db, cSql!, -1, &stmt, nil) if result != SQLITE_OK { sqlite3_finalize(stmt) if let error = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to prepare SQL: \(sql), Error: \(error)" NSLog(msg) } return nil } // Bind parameters, if any if params != nil { // Validate parameters let cntParams = sqlite3_bind_parameter_count(stmt) let cnt = CInt(params!.count) if cntParams != cnt { let msg = "SQLiteDB - failed to bind parameters, counts did not match. SQL: \(sql), Parameters: \(params)" NSLog(msg) return nil } var flag:CInt = 0 // Text & BLOB values passed to a C-API do not work correctly if they are not marked as transient. for ndx in 1...cnt { // NSLog("Binding: \(params![ndx-1]) at Index: \(ndx)") // Check for data types if let txt = params![ndx-1] as? String { flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT) } else if let data = params![ndx-1] as? NSData { flag = sqlite3_bind_blob(stmt, CInt(ndx), data.bytes, CInt(data.length), SQLITE_TRANSIENT) } else if let date = params![ndx-1] as? NSDate { let txt = fmt.stringFromDate(date) flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT) } else if let val = params![ndx-1] as? Double { flag = sqlite3_bind_double(stmt, CInt(ndx), CDouble(val)) } else if let val = params![ndx-1] as? Int { flag = sqlite3_bind_int(stmt, CInt(ndx), CInt(val)) } else { flag = sqlite3_bind_null(stmt, CInt(ndx)) } // Check for errors if flag != SQLITE_OK { sqlite3_finalize(stmt) if let error = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to bind for SQL: \(sql), Parameters: \(params), Index: \(ndx) Error: \(error)" NSLog(msg) } return nil } } } return stmt } // Private method which handles the actual execution of an SQL statement private func execute(stmt:OpaquePointer, sql:String)->CInt { // Step var result = sqlite3_step(stmt) if result != SQLITE_OK && result != SQLITE_DONE { sqlite3_finalize(stmt) if let err = String.fromCString(sqlite3_errmsg(self.db)) { let msg = "SQLiteDB - failed to execute SQL: \(sql), Error: \(err)" NSLog(msg) } return 0 } // Is this an insert let upp = sql.uppercased if upp.hasPrefix("INSERT ") { // Known limitations: http://www.sqlite.org/c3ref/last_insert_rowid.html let rid = sqlite3_last_insert_rowid(self.db) result = CInt(rid) } else if upp.hasPrefix("DELETE") || upp.hasPrefix("UPDATE") { var cnt = sqlite3_changes(self.db) if cnt == 0 { cnt += 1 } result = CInt(cnt) } else { result = 1 } // Finalize sqlite3_finalize(stmt) return result } // Private method which handles the actual execution of an SQL query private func query(stmt:OpaquePointer, sql:String)->[[String:AnyObject]] { var rows = [[String:AnyObject]]() var fetchColumnInfo = true var columnCount:CInt = 0 var columnNames = [String]() var columnTypes = [CInt]() var result = sqlite3_step(stmt) while result == SQLITE_ROW { // Should we get column info? if fetchColumnInfo { columnCount = sqlite3_column_count(stmt) for index in 0..<columnCount { // Get column name let name = sqlite3_column_name(stmt, index) columnNames.append(String.fromCString(name)!) // Get column type columnTypes.append(self.getColumnType(index, stmt:stmt)) } fetchColumnInfo = false } // Get row data for each column var row = [String:AnyObject]() for index in 0..<columnCount { let key = columnNames[Int(index)] let type = columnTypes[Int(index)] if let val = getColumnValue(index, type:type, stmt:stmt) { // NSLog("Column type:\(type) with value:\(val)") row[key] = val } } rows.append(row) // Next row result = sqlite3_step(stmt) } sqlite3_finalize(stmt) return rows } // Get column type private func getColumnType(index:CInt, stmt:OpaquePointer)->CInt { var type:CInt = 0 // Column types - http://www.sqlite.org/datatype3.html (section 2.2 table column 1) let blobTypes = ["BINARY", "BLOB", "VARBINARY"] let charTypes = ["CHAR", "CHARACTER", "CLOB", "NATIONAL VARYING CHARACTER", "NATIVE CHARACTER", "NCHAR", "NVARCHAR", "TEXT", "VARCHAR", "VARIANT", "VARYING CHARACTER"] let dateTypes = ["DATE", "DATETIME", "TIME", "TIMESTAMP"] let intTypes = ["BIGINT", "BIT", "BOOL", "BOOLEAN", "INT", "INT2", "INT8", "INTEGER", "MEDIUMINT", "SMALLINT", "TINYINT"] let nullTypes = ["NULL"] let realTypes = ["DECIMAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "REAL"] // Determine type of column - http://www.sqlite.org/c3ref/c_blob.html let buf = sqlite3_column_decltype(stmt, index) // NSLog("SQLiteDB - Got column type: \(buf)") if buf != nil { var tmp = String.fromCString(buf)!.uppercaseString // Remove brackets let pos = tmp.positionOf("(") if pos > 0 { tmp = tmp.subString(0, length:pos) } // Remove unsigned? // Remove spaces // Is the data type in any of the pre-set values? // NSLog("SQLiteDB - Cleaned up column type: \(tmp)") if intTypes.contains(tmp) { return SQLITE_INTEGER } if realTypes.contains(tmp) { return SQLITE_FLOAT } if charTypes.contains(tmp) { return SQLITE_TEXT } if blobTypes.contains(tmp) { return SQLITE_BLOB } if nullTypes.contains(tmp) { return SQLITE_NULL } if dateTypes.contains(tmp) { return SQLITE_DATE } return SQLITE_TEXT } else { // For expressions and sub-queries type = sqlite3_column_type(stmt, index) } return type } // Get column value private func getColumnValue(index:CInt, type:CInt, stmt:OpaquePointer)->AnyObject? { // Integer if type == SQLITE_INTEGER { let val = sqlite3_column_int(stmt, index) return Int(val) } // Float if type == SQLITE_FLOAT { let val = sqlite3_column_double(stmt, index) return Double(val) } // Text - handled by default handler at end // Blob if type == SQLITE_BLOB { let data = sqlite3_column_blob(stmt, index) let size = sqlite3_column_bytes(stmt, index) let val = NSData(bytes:data, length:Int(size)) return val } // Null if type == SQLITE_NULL { return nil } // Date if type == SQLITE_DATE { // Is this a text date let txt = UnsafePointer<Int8>(sqlite3_column_text(stmt, index)) if txt != nil { if let buf = NSString(CString:txt, encoding:NSUTF8StringEncoding) { let set = NSCharacterSet(charactersIn: "-:") let range = buf.rangeOfCharacterFromSet(set) if range.location != NSNotFound { // Convert to time var time:tm = tm(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_gmtoff: 0, tm_zone:nil) strptime(txt, "%Y-%m-%d %H:%M:%S", &time) time.tm_isdst = -1 let diff = NSTimeZone.localTimeZone.secondsFromGMT let t = mktime(&time) + diff let ti = TimeInterval(t) let val = NSDate(timeIntervalSince1970:ti) return val } } } // If not a text date, then it's a time interval let val = sqlite3_column_double(stmt, index) let dt = NSDate(timeIntervalSince1970: val) return dt } // If nothing works, return a string representation let buf = UnsafePointer<Int8>(sqlite3_column_text(stmt, index)) let val = String.fromCString(buf) return val } } */
mit
cb432b264d9d6fb6a8a705fd6d37c382
31.989177
171
0.61164
3.882068
false
false
false
false
MurLuck/ISImageViewer
ISImageViewer/ISImageViewer/ISImageViewer.swift
1
24243
// // ISImageViewer.swift // ISImageViewer // // Created by VSquare on 17/12/2015. // Copyright © 2015 IgorSokolovsky. All rights reserved. // import Foundation import UIKit import MobileCoreServices class ISImageViewer:UIViewController,UIScrollViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ //------------------------------------------------------------ Class Variabls --------------------------------------------------------------// private var backGroundColor:UIColor? //the image view that was tapped to call this class. private let parentImageView:UIImageView //the image view inside scrollView that holds the image. private var imageView:UIImageView! //the scroll view that allows us to zoom on the imageView. private var scrollView:UIScrollView! //imageViewer toolbar for share ,print and so one default is nil. private var toolBar:UIToolbar? //imageViewer navigationBar , default have only X as dismiss view. private var navBar:UINavigationBar? //the background color after tap (navigationBar Hidden), default is black. private var backGroundColorDimmMode:UIColor? //the background color when navigation bar visible ,default is white. private var backGroundColorLightMode:UIColor? //the panGesture(moving the image ) private var panGestureRecognizer:UIPanGestureRecognizer! //delegate for handling new image from imagePicker var imageViewerDelegate:ISImageViewerDelegate? //------------------------------------------------------ UIViewController Functions --------------------------------------------------------// init(imageView:UIImageView){ self.parentImageView = imageView super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = .All } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.view.superview?.bringSubviewToFront(self.view) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //------------------------------------------------------------ Class Functions -------------------------------------------------------------// /*! prepares the view to be loaded sets up all the necessary subViews */ func prepareViewToBeLoaded(parentView:UIViewController){ parentView.navigationController?.navigationBar.hidden = true parentView.tabBarController?.tabBar.hidden = true self.view.alpha = 1 self.view.frame = parentView.view.bounds self.view.backgroundColor = UIColor.whiteColor() parentView.view.addSubview(self.view) parentView.addChildViewController(self) self.view.addSubview(setScrollView()) if navBar == nil{ setNavigationBar(nil, navBarTitle: nil, rightNavBarItemTitle: nil) } setToolBar(setToolBar: false, toolBarItems: nil) self.view.bringSubviewToFront(navBar!) if toolBar != nil{ self.view.bringSubviewToFront(toolBar!) } centerImageViewAnimationOnload() } /** sets up the navigation bar at the top of the imageViewer view - Parameter leftNavBarItemTitle:your custom left toolBar button Image. dismis the imageViewer. if nil , the image will be shown is X. - parameter navBarTitle:the title of the navigationBar, if nil , no title will be shown. - parameter rightNavBarItemTitle:the right toolBar button Title. Open ActionSheet. if nil , there wont be right button! */ func setNavigationBar(leftNavBarItemImage:UIImage?,navBarTitle:String?,rightNavBarItemTitle:String?){ if navBar == nil{ self.navBar = UINavigationBar(frame: CGRectMake(0,0, self.view.frame.size.width, 64)) self.view.addSubview(navBar!) } let navBarItems = UINavigationItem() if leftNavBarItemImage != nil { let leftNavBarButton = UIBarButtonItem(image: leftNavBarItemImage!, style: UIBarButtonItemStyle.Plain, target: self, action: "dismissImageViewer") navBarItems.leftBarButtonItem = leftNavBarButton }else{ let leftNavBarButtonImage = UIImage(named: "X.png") let leftNavBarButton = UIBarButtonItem(image: leftNavBarButtonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "dismissImageViewer") navBarItems.leftBarButtonItem = leftNavBarButton } if navBarTitle != nil{ navBarItems.title = navBarTitle } if rightNavBarItemTitle != nil { let rightNavBarButton = UIBarButtonItem(title: "\(rightNavBarItemTitle!)", style: UIBarButtonItemStyle.Plain, target: self, action: "openActionSheet") navBarItems.rightBarButtonItem = rightNavBarButton } navBar!.items = [navBarItems] } /** sets up the toolbar , default is false. - parameter setToolBar: set true if you want toolBar else toolBar Wont be shown . - parameter toolBarItems: array of all the UIBarButtonItem that you want in the toolbar . */ func setToolBar(setToolBar setToolBar:Bool,toolBarItems:[UIBarButtonItem]?){ guard setToolBar else{ return } let toolBarYPos = self.view.frame.size.height - 44 toolBar = UIToolbar(frame: CGRectMake(0,toolBarYPos,self.view.frame.size.width,44)) self.view.addSubview(toolBar!) } /** set scroll view min and max zoom for the image, if function dont get called it will be default (min = 1.0, max = 3.0). - parameter scrollViewMinimumZoom: the min zoom out for the image. - parameter scrollviewMaximumZoom: the max zoom in for the image. */ func setScrollViewZoomBounds(scrollViewMinimumZoom:CGFloat,scrollViewMaximumZoom:CGFloat){ self.scrollView.minimumZoomScale = scrollViewMinimumZoom self.scrollView.maximumZoomScale = scrollViewMaximumZoom } /** sets the background color of the view after one tap that hide navigation bar and toolBar if they exist and change the background color - Parameter color: the background color you desire,default is black */ func setBackgroundColorDimmMode(color:UIColor){ self.backGroundColorDimmMode = color } /** sets the background color of the view before tap that hide navigation bar and toolBar if they exist and change the background color - Parameter color: the background color you desire, default is white. */ func setBackgroundColorLightMode(color:UIColor){ self.backGroundColorLightMode = color } /*! handle the rotation call from your view controller - parameter size:the new view size after rotation */ func rotationHandling(size:CGSize){ let parent = self.parentViewController self.view.removeFromSuperview() self.view.frame = CGRectMake(0, 0, size.width, size.height) UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView.frame = self.view.frame self.navBar?.frame = CGRectMake(0, 0, self.view.frame.width, 64) self.imageView.frame = self.scrollView.frame self.toolBar?.frame = CGRectMake(0,size.height - 44,self.view.frame.size.width,44) self.centerScrollViewContents() }) parent?.view.addSubview(self.view) if UIDevice.currentDevice().orientation.isLandscape && !self.navBar!.hidden{ UIApplication.sharedApplication().statusBarHidden = true UIApplication.sharedApplication().statusBarHidden = false } } //------------------------------------------------------------ Private Functions ------------------------------------------------------------// //sets the scroll view as the parent of image view that will handle the zoom,pinch and pan gesture private func setScrollView() -> UIScrollView{ self.scrollView = UIScrollView(frame: self.view.bounds) self.scrollView.delegate = self self.scrollView.maximumZoomScale = 3.0 self.scrollView.minimumZoomScale = 1.0 self.scrollView.zoomScale = 1.0 setTapGestureForScrollView() return self.scrollView } //sets the one and two tap gestureRecognize for the scrollView private func setTapGestureForScrollView(){ let oneTapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:") oneTapGesture.numberOfTapsRequired = 1 let twoTapGesture = UITapGestureRecognizer(target: self, action: "doubleTapGesture:") twoTapGesture.numberOfTapsRequired = 2 oneTapGesture.requireGestureRecognizerToFail(twoTapGesture) self.scrollView.addGestureRecognizer(oneTapGesture) self.scrollView.addGestureRecognizer(twoTapGesture) } //centers the views and animate them private func centerImageViewAnimationOnload(){ imageView = UIImageView(frame: CGRectMake(parentImageView.frame.origin.x, parentImageView.frame.origin.y, parentImageView.frame.size.width, parentImageView.frame.size.height)) imageView.layer.cornerRadius = parentImageView.layer.cornerRadius imageView.clipsToBounds = true imageView.image = parentImageView.image imageView.contentMode = .ScaleAspectFit scrollView.addSubview(self.imageView) UIView.animateWithDuration(0.3, animations: { () -> Void in let imageWidth = self.parentImageView.image?.size.width let imageHeight = self.parentImageView.image?.size.height let imageRatio = imageWidth! / imageHeight! let viewRatio = self.view.frame.size.width/self.view.frame.size.height var ratio:CGFloat! if imageRatio >= viewRatio{ ratio = imageWidth! / self.view.frame.size.width }else{ ratio = imageHeight! / self.view.frame.size.height } let newWidth = imageWidth! / ratio let newHeight = imageHeight! / ratio self.imageView.frame = CGRectMake(self.scrollView.frame.origin.x, self.scrollView.frame.origin.y, newWidth, newHeight) self.imageView.center = CGPointMake(self.scrollView.center.x, self.scrollView.center.y) self.imageView.layer.cornerRadius = 0.0 self.view.backgroundColor = UIColor.whiteColor() }, completion: { (finished) -> Void in self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "onImageMovement:") self.scrollView.addGestureRecognizer(self.panGestureRecognizer) }) } //handle image reposition to center private func centerScrollViewContents(){ let boundSize = self.scrollView.bounds.size var contentsFrame = self.imageView.frame UIView.animateWithDuration(0.1) { () -> Void in if contentsFrame.size.width < boundSize.width{ contentsFrame.origin.x = (boundSize.width - contentsFrame.size.width) / 2.0 }else{ contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundSize.height{ contentsFrame.origin.y = (boundSize.height - contentsFrame.size.height ) / 2.0 }else{ contentsFrame.origin.y = 0.0 } self.imageView.frame = contentsFrame } } //if right naviigationBar button is enabled show action sheet @objc private func openActionSheet(){ let alertControler:UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let deleteAction:UIAlertAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Default) { (action) -> Void in self.imageView.image = self.parentImageView.image } let takePicAction:UIAlertAction = UIAlertAction(title: "Take A Picture", style: UIAlertActionStyle.Default) { (action) -> Void in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let imagePicker:UIImagePickerController = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.allowsEditing = false imagePicker.mediaTypes = [kUTTypeImage as String] self.presentViewController(imagePicker, animated: true, completion: nil) }else{ let alert = UIAlertController(title: "Error", message: "Thers no camera available", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: { (action) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) })) } } let choosePicAction:UIAlertAction = UIAlertAction(title: "Choose Picture From Gallary", style: UIAlertActionStyle.Default) { (action) -> Void in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) }else{ let alert = UIAlertController(title: "Error", message: "Thers no camera available", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: { (action) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) })) } } let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel" ,style: UIAlertActionStyle.Cancel, handler: nil) alertControler.addAction(takePicAction) alertControler.addAction(choosePicAction) alertControler.addAction(deleteAction) alertControler.addAction(cancelAction) self.presentViewController(alertControler, animated: true, completion: nil) } //dsimiss the view and animate the image to the size and center of the tapped image @objc private func dismissImageViewer(){ self.view.backgroundColor = UIColor.clearColor() self.navBar?.hidden = true let cornerRatio = parentImageView.frame.width / parentImageView.layer.cornerRadius let cornerRadius = imageView.frame.width / cornerRatio let heightRatio = parentImageView.frame.width / parentImageView.frame.height let newHeight = imageView.frame.width / heightRatio imageView.frame = CGRectMake(0 , 0, self.imageView.frame.width, newHeight) imageView.layer.cornerRadius = cornerRadius let center = self.view.center self.view.frame = CGRectMake(self.imageView.frame.origin.x , self.imageView.frame.origin.y, self.imageView.frame.width, self.imageView.frame.height) self.view.center = center self.view.layer.cornerRadius = cornerRadius UIView.animateWithDuration(0.3, animations: { () -> Void in self.parentViewController?.navigationController?.navigationBar.hidden = false self.parentViewController?.tabBarController?.tabBar.hidden = false let sx = self.parentImageView.frame.width/self.imageView.frame.width let sy = self.parentImageView.frame.height/self.imageView.frame.height self.imageView.transform = CGAffineTransformMakeScale(sx, sy) self.imageView.frame.origin = CGPointMake(0, 0) self.view.frame.origin = self.parentImageView.frame.origin }) { (finished) -> Void in self.onDismissView() } } //hides the navigation and toolBar and change backGroundColor @objc private func tapGesture(sender:UITapGestureRecognizer){ if let hidden = navBar?.hidden{ if hidden{ self.navBar?.hidden = false self.toolBar?.hidden = false UIApplication.sharedApplication().statusBarHidden = false if backGroundColorLightMode != nil{ self.view.backgroundColor = backGroundColorLightMode }else{ self.view.backgroundColor = UIColor.whiteColor() } }else{ self.navBar?.hidden = true self.toolBar?.hidden = true UIApplication.sharedApplication().statusBarHidden = true if backGroundColorLightMode != nil{ self.view.backgroundColor = backGroundColorDimmMode }else{ self.view.backgroundColor = UIColor.blackColor() } } } } //zoomin and zoomout based on the tap location on the scrollView @objc private func doubleTapGesture(sender:UITapGestureRecognizer){ if self.scrollView.zoomScale == self.scrollView.minimumZoomScale{ let zoomRect = self.zoomRectForScale(self.scrollView.maximumZoomScale, withCenter: sender.locationInView(sender.view)) self.scrollView.zoomToRect(zoomRect, animated: true) }else{ self.scrollView.setZoomScale(self.scrollView.minimumZoomScale, animated: true) } } //handles the zoom on double tap location private func zoomRectForScale(scale:CGFloat,var withCenter center:CGPoint) -> CGRect{ var zoomRect:CGRect = CGRect() zoomRect.size.height = self.imageView.frame.size.height / scale zoomRect.size.width = self.imageView.frame.size.width / scale center = self.imageView.convertPoint(center, fromView: self.view) zoomRect.origin.x = center.x - zoomRect.size.width / 2.0 zoomRect.origin.y = center.y - zoomRect.size.height / 2.0 return zoomRect } //handle image movment and in specific position dismisses the view @objc private func onImageMovement(sender:UIPanGestureRecognizer){ let deltaY = sender.translationInView(self.scrollView).y let translatedPoint = CGPointMake(self.view.center.x, self.view.center.y + deltaY) self.scrollView.center = translatedPoint if sender.state == UIGestureRecognizerState.Ended{ let velocityY = sender.velocityInView(self.scrollView).y let maxDeltaY = (self.view.frame.size.height - imageView.frame.size.height)/2 if velocityY > 700 || (abs(deltaY) > maxDeltaY && deltaY > 0){ UIView.animateWithDuration(0.3, animations: { () -> Void in self.imageView.frame = CGRectMake(self.imageView.frame.origin.x, self.view.frame.size.height, self.imageView.frame.size.width, self.imageView.frame.size.height) self.view.alpha = 0.0 UIApplication.sharedApplication().statusBarHidden = false self.parentViewController?.navigationController?.navigationBar.hidden = false self.parentViewController?.tabBarController?.tabBar.hidden = false }, completion: { (finished) -> Void in self.onDismissView() }) }else if velocityY < -700 || (abs(deltaY) > maxDeltaY && deltaY < 0){ UIView.animateWithDuration(0.3, animations: { () -> Void in self.imageView.frame = CGRectMake(self.imageView.frame.origin.x, -self.view.frame.size.height, self.imageView.frame.size.width, self.imageView.frame.size.height) self.view.alpha = 0.0 UIApplication.sharedApplication().statusBarHidden = false self.parentViewController?.navigationController?.navigationBar.hidden = false self.parentViewController?.tabBarController?.tabBar.hidden = false }, completion: { (finished) -> Void in self.onDismissView() }) }else{ UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView.center = self.view.center }, completion: nil) } } } private func onDismissView(){ self.imageView.removeFromSuperview() self.scrollView.removeFromSuperview() self.navBar?.removeFromSuperview() self.toolBar?.removeFromSuperview() self.navBar = nil self.toolBar = nil self.scrollView = nil self.imageView = nil self.view.removeFromSuperview() self.removeFromParentViewController() self.dismissViewControllerAnimated(false, completion: nil) } //----------------------------------------------------------- ScrollView Delegate -----------------------------------------------------------// func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { self.centerScrollViewContents() if self.scrollView.zoomScale == self.scrollView.minimumZoomScale{ self.scrollView.addGestureRecognizer(panGestureRecognizer) }else{ self.scrollView.removeGestureRecognizer(panGestureRecognizer) } } //----------------------------------------------------------- ImagePicker Delegate ----------------------------------------------------------// func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { var pickedImage:UIImage! let mediaType = info[UIImagePickerControllerMediaType] as! NSString if mediaType.isEqualToString(kUTTypeImage as String) { // Media is an image } else if mediaType.isEqualToString(kUTTypeMovie as String) { return } if picker.allowsEditing{ pickedImage = info[UIImagePickerControllerEditedImage] as! UIImage }else{ pickedImage = info[UIImagePickerControllerOriginalImage] as! UIImage } self.imageView.image = pickedImage self.imageViewerDelegate?.didPickNewImage(pickedImage) picker.dismissViewControllerAnimated(true) { () -> Void in picker.view.removeFromSuperview() picker.removeFromParentViewController() pickedImage = nil } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } }
mit
5eacb2105970e813b95c2de567dc9ed0
42.446237
183
0.619008
5.561367
false
false
false
false
milseman/swift
test/Sema/immutability.swift
4
21890
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} let bad_property_1: Int { // expected-error {{'let' declarations cannot be computed properties}} get { return 42 } } let bad_property_2: Int = 0 { // expected-error {{'let' declarations cannot be computed properties}} expected-error {{variable with getter/setter cannot have an initial value}} get { return 42 } } let no_initializer : Int func foreach_variable() { for i in 0..<42 { i = 11 // expected-error {{cannot assign to value: 'i' is a 'let' constant}} } } func takeClosure(_ fn : (Int) -> Int) {} func passClosure() { takeClosure { a in a = 42 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} return a } takeClosure { $0 = 42 // expected-error{{cannot assign to value: '$0' is immutable}} return 42 } takeClosure { (a : Int) -> Int in a = 42 // expected-error{{cannot assign to value: 'a' is a 'let' constant}} return 42 } } class FooClass { class let type_let = 5 // expected-error {{class stored properties not supported in classes}} init() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } func bar() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}} mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func baz() {} nonmutating // expected-error {{'nonmutating' isn't valid on methods in classes or class-bound protocols}} {{3-15=}} func bay() {} mutating nonmutating // expected-error {{method may not be declared both mutating and nonmutating}} expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} expected-error {{'nonmutating' isn't valid on methods in classes or class-bound protocols}} func bax() {} var x : Int { get { return 32 } set(value) { value = 42 // expected-error {{cannot assign to value: 'value' is a 'let' constant}} } } subscript(i : Int) -> Int { get { i = 42 // expected-error {{cannot assign to value: 'i' is immutable}} return 1 } } } func let_decls() { // <rdar://problem/16927246> provide a fixit to change "let" to "var" if needing to mutate a variable let a = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a = 17 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} let (b,c) = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(b); markUsed(c) b = 17 // expected-error {{cannot assign to value: 'b' is a 'let' constant}} let d = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(d.0); markUsed(d.1) d.0 = 17 // expected-error {{cannot assign to property: 'd' is a 'let' constant}} let e = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} ++e // expected-error {{cannot pass immutable value to mutating operator: 'e' is a 'let' constant}} // <rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic let f = 96 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} var v = 1 swap(&f, &v) // expected-error {{cannot pass immutable value as inout argument: 'f' is a 'let' constant}} // <rdar://problem/19711233> QoI: poor diagnostic for operator-assignment involving immutable operand let g = 14 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} g /= 2 // expected-error {{left side of mutating operator isn't mutable: 'g' is a 'let' constant}} } struct SomeStruct { var iv = 32 static let type_let = 5 // expected-note {{change 'let' to 'var' to make it mutable}} {{10-13=var}} mutating static func f() { // expected-error {{static functions may not be declared mutating}} {{3-12=}} } mutating func g() { iv = 42 } mutating func g2() { iv = 42 } func h() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} iv = 12 // expected-error {{cannot assign to property: 'self' is immutable}} } var p: Int { // Getters default to non-mutating. get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } // Setters default to mutating. set { iv = newValue } } // Defaults can be changed. var q : Int { mutating get { iv = 37 return 42 } nonmutating set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}} } } var r : Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } mutating // Redundant but OK. set { iv = newValue } } } markUsed(SomeStruct.type_let) // ok SomeStruct.type_let = 17 // expected-error {{cannot assign to property: 'type_let' is a 'let' constant}} struct TestMutableStruct { mutating func f() {} func g() {} var mutating_property : Int { mutating get {} set {} } var nonmutating_property : Int { get {} nonmutating set {} } // This property has a mutating getter and !mutating setter. var weird_property : Int { mutating get {} nonmutating set {} } @mutating func mutating_attr() {} // expected-error {{'mutating' is a declaration modifier, not an attribute}} {{3-4=}} @nonmutating func nonmutating_attr() {} // expected-error {{'nonmutating' is a declaration modifier, not an attribute}} {{3-4=}} } func test_mutability() { // Non-mutable method on rvalue is ok. TestMutableStruct().g() // Non-mutable method on let is ok. let x = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x.g() // Mutable methods on let and rvalue are not ok. x.f() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} TestMutableStruct().f() // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}} _ = TestMutableStruct().weird_property // expected-error {{cannot use mutating getter on immutable value: function call returns immutable value}} let tms = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} _ = tms.weird_property // expected-error {{cannot use mutating getter on immutable value: 'tms' is a 'let' constant}} } func test_arguments(_ a : Int, b : Int, let c : Int) { // expected-error {{'let' as a parameter attribute is not allowed}} {{21-25=}} var b = b a = 1 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} b = 2 // ok. _ = b } protocol ClassBoundProtocolMutating : class { mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func f() } protocol MutatingTestProto { mutating func mutatingfunc() func nonmutatingfunc() // expected-note {{protocol requires}} } class TestClass : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct1 : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct2 : MutatingTestProto { mutating func mutatingfunc() {} // Ok, can be mutating. func nonmutatingfunc() {} } struct TestStruct3 : MutatingTestProto { // expected-error {{type 'TestStruct3' does not conform to protocol 'MutatingTestProto'}} func mutatingfunc() {} // This is not ok, "nonmutatingfunc" doesn't allow mutating functions. mutating func nonmutatingfunc() {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } // <rdar://problem/16722603> invalid conformance of mutating setter protocol NonMutatingSubscriptable { subscript(i: Int) -> Int {get nonmutating set} // expected-note {{protocol requires subscript with type '(Int) -> Int'}} } struct MutatingSubscriptor : NonMutatingSubscriptable { // expected-error {{type 'MutatingSubscriptor' does not conform to protocol 'NonMutatingSubscriptable'}} subscript(i: Int) -> Int { get { return 42 } mutating set {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } } protocol NonMutatingGet { var a: Int { get } // expected-note {{protocol requires property 'a' with type 'Int'}} } struct MutatingGet : NonMutatingGet { // expected-error {{type 'MutatingGet' does not conform to protocol 'NonMutatingGet'}} var a: Int { mutating get { return 0 } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } func test_properties() { let rvalue = TestMutableStruct() // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} markUsed(rvalue.nonmutating_property) // ok markUsed(rvalue.mutating_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} markUsed(rvalue.weird_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.nonmutating_property = 1 // ok rvalue.mutating_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.weird_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} var lvalue = TestMutableStruct() markUsed(lvalue.mutating_property) // ok markUsed(lvalue.nonmutating_property) // ok markUsed(lvalue.weird_property) // ok lvalue.mutating_property = 1 // ok lvalue.nonmutating_property = 1 // ok lvalue.weird_property = 1 // ok } protocol OpaqueBase {} extension OpaqueBase { var x: Int { get { return 0 } set { } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } protocol OpaqueRefinement : class, OpaqueBase { var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'}} } class SetterMutatingConflict : OpaqueRefinement {} // expected-error {{type 'SetterMutatingConflict' does not conform to protocol 'OpaqueRefinement'}} struct DuplicateMutating { mutating mutating func f() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } protocol SubscriptNoGetter { subscript (i: Int) -> Int { get } } func testSubscriptNoGetter(let iis: SubscriptNoGetter) { // expected-error {{'let' as a parameter attribute is not allowed}}{{28-31=}} var _: Int = iis[17] } func testSelectorStyleArguments1(_ x: Int, bar y: Int) { var x = x var y = y x += 1 y += 1 _ = x _ = y } func testSelectorStyleArguments2(let x: Int, // expected-error {{'let' as a parameter attribute is not allowed}}{{34-37=}} let bar y: Int) { // expected-error {{'let' as a parameter attribute is not allowed}}{{34-38=}} } func testSelectorStyleArguments3(_ x: Int, bar y: Int) { ++x // expected-error {{cannot pass immutable value to mutating operator: 'x' is a 'let' constant}} ++y // expected-error {{cannot pass immutable value to mutating operator: 'y' is a 'let' constant}} } func invalid_inout(inout var x : Int) { // expected-error {{parameter may not have multiple '__owned', 'inout', '__shared', 'var', or 'let' specifiers}} {{26-30=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}{{20-25=}}{{34-34=inout }} } func invalid_var(var x: Int) { // expected-error {{'var' as a parameter attribute is not allowed}} } func takesClosure(_: (Int) -> Int) { takesClosure { (var d) in d } // expected-error {{'var' as a parameter attribute is not allowed}} } func updateInt(_ x : inout Int) {} // rdar://15785677 - allow 'let' declarations in structs/classes be initialized in init() class LetClassMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } struct LetStructMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } func QoI() { let x = 97 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x = 17 // expected-error {{cannot assign to value: 'x' is a 'let' constant}} var get_only: Int { get { return 7 } } get_only = 92 // expected-error {{cannot assign to value: 'get_only' is a get-only property}} } // <rdar://problem/17051675> Structure initializers in an extension cannot assign to constant properties struct rdar17051675_S { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S { init(newY: Int) { x = 42 } } struct rdar17051675_S2<T> { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S2 { init(newY: Int) { x = 42 } } // <rdar://problem/17400366> let properties should not be mutable in convenience initializers class ClassWithConvenienceInit { let x : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(newX: Int) { x = 42 } convenience init(newY: Int) { self.init(newX: 19) x = 67 // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } } struct StructWithDelegatingInit { let x: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(x: Int) { self.x = x } init() { self.init(x: 0); self.x = 22 } // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } func test_recovery_missing_name_2(let: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}}{{35-38=}} // expected-error @-1 {{expected parameter name followed by ':'}} // <rdar://problem/16792027> compiler infinite loops on a really really mutating function struct F { // expected-note 1 {{in declaration of 'F'}} mutating mutating mutating f() { // expected-error 2 {{duplicate modifier}} expected-note 2 {{modifier already specified here}} expected-error {{expected declaration}} } mutating nonmutating func g() { // expected-error {{method may not be declared both mutating and nonmutating}} } } protocol SingleIntProperty { var i: Int { get } } struct SingleIntStruct : SingleIntProperty { let i: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} } extension SingleIntStruct { init(_ other: SingleIntStruct) { other.i = 999 // expected-error {{cannot assign to property: 'i' is a 'let' constant}} } } // <rdar://problem/19370429> QoI: fixit to add "mutating" when assigning to a member of self in a struct // <rdar://problem/17632908> QoI: Modifying struct member in non-mutating function produces difficult to understand error message struct TestSubscriptMutability { let let_arr = [1,2,3] // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_arr = [1,2,3] func nonmutating1() { let_arr[1] = 1 // expected-error {{cannot assign through subscript: 'let_arr' is a 'let' constant}} } func nonmutating2() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} var_arr[1] = 1 // expected-error {{cannot assign through subscript: 'self' is immutable}} } func nonmutating3() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self = TestSubscriptMutability() // expected-error {{cannot assign to value: 'self' is immutable}} } subscript(a : Int) -> TestSubscriptMutability { return TestSubscriptMutability() } func test() { self[1] = TestSubscriptMutability() // expected-error {{cannot assign through subscript: subscript is get-only}} self[1].var_arr = [] // expected-error {{cannot assign to property: subscript is get-only}} self[1].let_arr = [] // expected-error {{cannot assign to property: 'let_arr' is a 'let' constant}} } } func f(_ a : TestSubscriptMutability) { a.var_arr = [] // expected-error {{cannot assign to property: 'a' is a 'let' constant}} } struct TestSubscriptMutability2 { subscript(a : Int) -> Int { get { return 42 } set {} } func test() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self[1] = 2 // expected-error {{cannot assign through subscript: 'self' is immutable}} } } struct TestBangMutability { let let_opt = Optional(1) // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_opt = Optional(1) func nonmutating1() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // expected-error {{cannot assign through '!': 'self' is immutable}} self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } mutating func nonmutating2() { let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // ok self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } subscript() -> Int? { return nil } } // <rdar://problem/21176945> mutation through ? not considered a mutation func testBindOptional() { var a : TestStruct2? = nil // Mutated through optional chaining. a?.mutatingfunc() } struct HasTestStruct2 { var t = TestStruct2() } func testConditional(b : Bool) { var x = TestStruct2() var y = TestStruct2() var z = HasTestStruct2() (b ? x : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? (b ? x : y) : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : (b ? x : y)).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : z.t).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} } // <rdar://problem/27384685> QoI: Poor diagnostic when assigning a value to a method func f(a : FooClass, b : LetStructMembers) { a.baz = 1 // expected-error {{cannot assign to property: 'baz' is a method}} b.f = 42 // expected-error {{cannot assign to property: 'f' is a method}} } // SR-2354: Reject subscript declarations with mutable parameters. class MutableSubscripts { var x : Int = 0 subscript(x: inout Int) -> () { x += 1 } // expected-error {{'inout' may not be used on subscript parameters}} subscript<T>(x: inout T) -> () { // expected-error {{'inout' may not be used on subscript parameters}} fatalError() } static func initialize(from state: inout MutableSubscripts) -> MutableSubscripts { return state } } // SR-4214: Misleading location-less diagnostic when closure parameter type // is inferred to be inout. func sr4214() { func sequence<T>(_ x : T, _ f : (T) -> T) -> T { return f(x) } // expected-error@+1 {{expression type '(inout MutableSubscripts) -> ()' is ambiguous without more context}} let closure = { val in val.x = 7 } as (inout MutableSubscripts) -> () var v = MutableSubscripts() closure(&v) // FIXME: This diagnostic isn't really all that much better // expected-error@+1 {{cannot convert value of type '(inout MutableSubscripts) -> ()' to expected argument type '(_) -> _'}} sequence(v) { (state : inout MutableSubscripts) -> () in _ = MutableSubscripts.initialize(from: &state) return () } }
apache-2.0
2a6850b52880f72ad3c79a6d8e894324
34.535714
282
0.640201
3.739324
false
true
false
false
daviwiki/Gourmet_Swift
Gourmet/Gourmet/View/Main/MainPresenter.swift
1
1994
// // LoginPresenter.swift // Gourmet // // Created by David Martinez on 08/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import Foundation import GourmetModel protocol MainPresenterInterface { func updateView (view : MainView) } class MainPresenter : NSObject, MainPresenterInterface, GetStoredAccountListener, StoreAccountObserverListener { private var getAccountInteractor : GetStoredAccount! private var accountObserverInteractor : StoreAccountObserver! private var mapper : MapAccountToAccountVM! private weak var view : MainView? init(getAccount : GetStoredAccount, accountObserver : StoreAccountObserver, mapper : MapAccountToAccountVM) { super.init() getAccountInteractor = getAccount getAccountInteractor.setListener(listener: self) accountObserverInteractor = accountObserver accountObserverInteractor.setListener(listener: self) accountObserverInteractor.execute() self.mapper = mapper } deinit { accountObserverInteractor.setListener(listener: nil) } func updateView(view: MainView) { self.view = view getAccountInteractor.execute() } // MARK: GetStoredAccountListener func onFinish(interactor: GetStoredAccount, account: Account?) { if (account == nil) { view?.showNoAccount() } else { let accountVM = self.mapper.map(source: account!) view?.showAccountInfo(account: accountVM) } } // MARK: StoreAccountObserverListener func onChange(observer: StoreAccountObserver, account: Account?) { if (account == nil) { view?.showNoAccount() } else { let accountVM = self.mapper.map(source: account!) view?.showAccountInfo(account: accountVM) view?.navigateBalance(account: account!) } } }
mit
88678a9e0358ff9d8884c998cde84256
26.680556
81
0.64576
4.849148
false
false
false
false
pinterest/plank
Sources/Core/ObjectiveCIR.swift
1
18628
// // ObjectiveCIR.swift // Plank // // Created by Rahul Malik on 7/29/15. // Copyright © 2015 Rahul Malik. All rights reserved. // import Foundation public enum ObjCMemoryAssignmentType: String { case copy case strong case weak case assign } public enum ObjCAtomicityType: String { case atomic case nonatomic } public enum ObjCMutabilityType: String { case readonly case readwrite } public enum ObjCPrimitiveType: String { case float case double case integer = "NSInteger" case boolean = "BOOL" } extension String { // Objective-C String Literal func objcLiteral() -> String { return "@\"\(self)\"" } } extension Sequence { func objcLiteral() -> String { let inner = map { "\($0)" }.joined(separator: ", ") return "@[\(inner)]" } } typealias Argument = String typealias Parameter = String typealias TypeName = String typealias SimpleProperty = (Parameter, TypeName, SchemaObjectProperty, ObjCMutabilityType) func propertyOption(propertyName aPropertyName: String, className: String, variant: String) -> String { guard !className.isEmpty, !aPropertyName.isEmpty else { fatalError("Invalid class name or property name passed propertyOption(propertyName:className:variant)") } let propertyName = Languages.objectiveC.snakeCaseToPropertyName(aPropertyName) let capitalizedFirstLetter = String(propertyName[propertyName.startIndex]).uppercased() let capitalizedPropertyName = capitalizedFirstLetter + String(propertyName.dropFirst()) return className + variant + capitalizedPropertyName } func dirtyPropertyOption(propertyName aPropertyName: String, className: String) -> String { return propertyOption(propertyName: aPropertyName, className: className, variant: "DirtyProperty") } func booleanPropertyOption(propertyName aPropertyName: String, className: String) -> String { return propertyOption(propertyName: aPropertyName, className: className, variant: "Boolean") } func enumFromStringMethodName(propertyName: String, className: String) -> String { return "\(enumTypeName(propertyName: propertyName, className: className))FromString" } func enumToStringMethodName(propertyName: String, className: String) -> String { return "\(enumTypeName(propertyName: propertyName, className: className))ToString" } func enumTypeName(propertyName: String, className: String) -> String { return "\(className)\(Languages.objectiveC.snakeCaseToCamelCase(propertyName))" } // ObjC integreal types for NS_ENUM declarations in generated code. enum EnumerationIntegralType: String { case char case unsignedChar = "unsigned char" case short case unsignedShort = "unsigned short" case int case unsignedInt = "unsigned int" case NSInteger case NSUInteger // Return the best fitting and smallest EnumerationIntegralType for the given EnumType. // In ObjC not all NS_ENUM declarations need to be NSInteger in size. Using smaller integral types // can allow the code that plank generates to use less memory in the resulting application. // As an example with an object with 2 enumerations values, each of NSInteger size, // those 2 enumerations will take 16 bytes of the objects instance size in the heap. However, // if the enumeration storage is smaller, in this case 1 byte long for an unsigned char, the // 2 enumerations will only take 8 bytes in the heap. This is because the compiler will best fit // the two unsigned char enumerations to fit into the 8 bytes natural alignment of the platform. // As more enumerations are found in a class, the better this best fitting code will save memory. static func forValue(_ values: EnumType) -> EnumerationIntegralType { let minimum: Int let maximum: Int switch values { case let .integer(options): let values = options.map { $0.defaultValue } minimum = values.min() ?? 0 maximum = values.max() ?? Int.max case let .string(options, _): minimum = 0 maximum = options.count } let underlyingIntegralType: EnumerationIntegralType let (_, overflow) = maximum.subtractingReportingOverflow(minimum) if overflow { underlyingIntegralType = minimum < 0 ? EnumerationIntegralType.NSInteger : EnumerationIntegralType.NSUInteger } else { switch max(maximum, abs(maximum - minimum)) { case 0 ... Int(UInt8.max): underlyingIntegralType = minimum < 0 ? EnumerationIntegralType.char : EnumerationIntegralType.unsignedChar case Int(UInt8.max) ... Int(UInt16.max): underlyingIntegralType = minimum < 0 ? EnumerationIntegralType.short : EnumerationIntegralType.unsignedShort case Int(UInt16.max) ... Int(UInt32.max): underlyingIntegralType = minimum < 0 ? EnumerationIntegralType.int : EnumerationIntegralType.unsignedInt default: underlyingIntegralType = minimum < 0 ? EnumerationIntegralType.NSInteger : EnumerationIntegralType.NSUInteger } } return underlyingIntegralType } } extension SchemaObjectRoot { func className(with params: GenerationParameters) -> String { if let classPrefix = params[GenerationParameterType.classPrefix] as String? { return "\(classPrefix)\(Languages.objectiveC.snakeCaseToCamelCase(name))" } else { return Languages.objectiveC.snakeCaseToCamelCase(name) } } func typeName(with params: GenerationParameters) -> String { return "\(className(with: params))Type" } } extension Schema { func memoryAssignmentType() -> ObjCMemoryAssignmentType { switch self { // Use copy for any string, date, url etc. case .string: return .copy case .boolean, .float, .integer, .enumT: return .assign default: return .strong } } } extension EnumValue { var camelCaseDescription: String { return Languages.objectiveC.snakeCaseToCamelCase(description) } func objcOptionName(param: String, className: String) -> String { return enumTypeName(propertyName: param, className: className) + camelCaseDescription } } enum MethodVisibility: Equatable { case publicM case privateM } func == (lhs: MethodVisibility, rhs: MethodVisibility) -> Bool { switch (lhs, rhs) { case (.publicM, .publicM): return true case (.privateM, .privateM): return true case (_, _): return false } } public struct ObjCIR { static func method(_ signature: String, debug: Bool = false, body: () -> [String]) -> ObjCIR.Method { return ObjCIR.Method(body: body(), signature: signature, debug: debug) } static func stmt(_ body: String) -> String { return "\(body);" } static func msg(_ variable: String, _ messages: (Parameter, Argument)...) -> String { return "[\(variable) " + messages.map { param, arg in "\(param):\(arg)" }.joined(separator: " ") + "]" } static func block(_ params: [Parameter], body: () -> [String]) -> String { return [ "^" + (params.isEmpty ? "" : "(\(params.joined(separator: ", ")))") + "{", -->body, "}", ].joined(separator: "\n") } static func scope(body: () -> [String]) -> String { return [ "{", -->body, "}", ].joined(separator: "\n") } enum SwitchCase { case caseStmt(condition: String, body: () -> [String]) case defaultStmt(body: () -> [String]) func render() -> String { switch self { case let .caseStmt(condition, body): return ["case \(condition):", -->body, -->[ObjCIR.stmt("break")]].joined(separator: "\n") case let .defaultStmt(body): return ["default:", -->body, -->[ObjCIR.stmt("break")]].joined(separator: "\n") } } } static func caseStmt(_ condition: String, body: @escaping () -> [String]) -> SwitchCase { return .caseStmt(condition: condition, body: body) } static func defaultCaseStmt(body: @escaping () -> [String]) -> SwitchCase { return .defaultStmt(body: body) } static func switchStmt(_ switchVariable: String, body: () -> [SwitchCase]) -> String { return [ "switch (\(switchVariable)) {", body().map { $0.render() }.joined(separator: "\n"), "}", ].joined(separator: "\n") } static func ifStmt(_ condition: String, body: () -> [String]) -> String { return [ "if (\(condition)) {", -->body, "}", ].joined(separator: "\n") } static func elseIfStmt(_ condition: String, _ body: () -> [String]) -> String { return [ " else if (\(condition)) {", -->body, "}", ].joined(separator: "\n") } static func elseStmt(_ body: () -> [String]) -> String { return [ " else {", -->body, "}", ].joined(separator: "\n") } static func ifElseStmt(_ condition: String, body: @escaping () -> [String]) -> (() -> [String]) -> String { return { elseBody in [ ObjCIR.ifStmt(condition, body: body) + ObjCIR.elseStmt(elseBody), ].joined(separator: "\n") } } static func forStmt(_ condition: String, body: () -> [String]) -> String { return [ "for (\(condition)) {", -->body, "}", ].joined(separator: "\n") } static func fileImportStmt(_ filename: String, headerPrefix: String?) -> String { if let headerPrefix = headerPrefix { return "#import \"\(headerPrefix)\(filename).h\"" } return "#import \"\(filename).h\"" } static func enumStmt(_ enumName: String, underlyingIntegralType: EnumerationIntegralType, body: () -> [String]) -> String { return [ "typedef NS_ENUM(\(underlyingIntegralType.rawValue), \(enumName)) {", -->[body().joined(separator: ",\n")], "};", ].joined(separator: "\n") } static func optionEnumStmt(_ enumName: String, body: () -> [String]) -> String { return [ "typedef NS_OPTIONS(NSUInteger, \(enumName)) {", -->[body().joined(separator: ",\n")], "};", ].joined(separator: "\n") } public struct Method { let body: [String] let signature: String let debug: Bool func render() -> [String] { let lines = [ signature, "{", -->body, "}", ] if debug { return ["#if DEBUG"] + lines + ["#endif"] } return lines } } enum Root: RootRenderer { case structDecl(name: String, fields: [String]) case imports(classNames: Set<String>, myName: String, parentName: String?) case category(className: String, categoryName: String?, methods: [ObjCIR.Method], properties: [SimpleProperty], variables: [(Parameter, TypeName)]) case macro(String) case function(ObjCIR.Method) case classDecl( name: String, extends: String?, methods: [(MethodVisibility, ObjCIR.Method)], properties: [SimpleProperty], protocols: [String: [ObjCIR.Method]] ) case enumDecl(name: String, values: EnumType) case optionSetEnum(name: String, values: [EnumValue<Int>]) func renderHeader(_: GenerationParameters) -> [String] { switch self { case .structDecl: // skip structs in header return [] case let .macro(macro): return [macro] case let .imports(classNames, myName, parentName): let parentImport = (parentName != nil) ? ObjCIR.fileImportStmt(parentName!, headerPrefix: nil) : "" return [ "#import <Foundation/Foundation.h>", parentImport, "#import \"\(ObjCRuntimeHeaderFile().fileName)\"", ].filter { $0 != "" } + (["\(myName)Builder"] + classNames) .sorted().map { "@class \($0.trimmingCharacters(in: .whitespaces));" } case let .classDecl(className, extends, methods, properties, protocols): let protocolList = protocols.keys.sorted().joined(separator: ", ") let protocolDeclarations = !protocols.isEmpty ? "<\(protocolList)>" : "" let superClass = extends ?? "NSObject\(protocolDeclarations)" let nullability = { (prop: SchemaObjectProperty) in prop.nullability.map { "\($0), " } ?? "" } return [ "@interface \(className) : \(superClass)", properties.sorted { $0.0 < $1.0 }.map { param, typeName, propSchema, access in "@property (\(nullability(propSchema))nonatomic, \(propSchema.schema.memoryAssignmentType().rawValue), \(access.rawValue)) \(typeName) \(Languages.objectiveC.snakeCaseToPropertyName(param));" }.joined(separator: "\n"), properties.sorted { $0.0 < $1.0 }.filter { param, _, _, _ in param.lowercased().hasPrefix("new_") || param.lowercased().hasPrefix("alloc_") || param.lowercased().hasPrefix("copy_") || param.lowercased().hasPrefix("mutable_copy_") }.map { param, typeName, _, _ in "- (\(typeName))\(Languages.objectiveC.snakeCaseToPropertyName(param)) __attribute__((objc_method_family(none)));" }.joined(separator: "\n"), methods.filter { visibility, _ in visibility == .publicM } .map { $1 }.map { $0.signature + ";" }.joined(separator: "\n"), "@end", ] case .category(className: _, categoryName: _, methods: _, properties: _, variables: _): // skip categories in header return [] case let .function(method): return ["\(method.signature);"] case let .enumDecl(name, values): return [ObjCIR.enumStmt(name, underlyingIntegralType: EnumerationIntegralType.forValue(values)) { switch values { case let .integer(options): return options.map { "\(name + $0.camelCaseDescription) = \($0.defaultValue)" } case .string(let options, _): return options.map { "\(name + $0.camelCaseDescription) /* \($0.defaultValue) */" } } }] case let .optionSetEnum(name, values): return [ObjCIR.optionEnumStmt(name) { values.map { "\(name + $0.camelCaseDescription) = 1 << \($0.defaultValue)" } }] } } func renderImplementation(_ params: GenerationParameters) -> [String] { switch self { case let .structDecl(name: name, fields: fields): return [ "struct \(name) {", fields.sorted().map { $0.indent() }.joined(separator: "\n"), "};", ] case .macro: // skip macro in impl return [] case .imports(let classNames, let myName, _): return [classNames.union(Set([myName])) .sorted() .map { $0.trimmingCharacters(in: .whitespaces) } .map { ObjCIR.fileImportStmt($0, headerPrefix: params[GenerationParameterType.headerPrefix]) } .joined(separator: "\n")] case .classDecl(name: let className, extends: _, methods: let methods, properties: _, protocols: let protocols): return [ "@implementation \(className)", methods.flatMap { $1.render() }.joined(separator: "\n"), protocols.sorted { $0.0 < $1.0 }.flatMap { (protocolName, methods) -> [String] in ["#pragma mark - \(protocolName)"] + methods.flatMap { $0.render() } }.joined(separator: "\n"), "@end", ].map { $0.trimmingCharacters(in: CharacterSet.whitespaces) }.filter { $0 != "" } case let .category(className: className, categoryName: categoryName, methods: methods, properties: properties, variables: variables): // Only render anonymous categories in the implementation guard categoryName == nil else { return [] } let variableDeclarations: String if !variables.isEmpty { let vars: [String] = variables.map { (param, typeName) -> String in "\(typeName) _\(Languages.objectiveC.snakeCaseToPropertyName(param));" } variableDeclarations = ["{", -->vars, "}"].joined(separator: "\n") } else { variableDeclarations = "" } return [ "@interface \(className) ()", variableDeclarations, properties.map { param, typeName, prop, access in "@property (nonatomic, \(prop.schema.memoryAssignmentType().rawValue), \(access.rawValue)) \(typeName) \(Languages.objectiveC.snakeCaseToPropertyName(param));" }.joined(separator: "\n"), methods.map { $0.signature + ";" }.joined(separator: "\n"), "@end", ].map { $0.trimmingCharacters(in: CharacterSet.whitespaces) }.filter { $0 != "" } case let .function(method): return method.render() case .enumDecl: return [] case .optionSetEnum: return [] } } } }
apache-2.0
07d2daa05a06d607ce01f4b5385fc089
38.547771
215
0.560369
4.797064
false
false
false
false
larryhou/swift
Tachograph/Tachograph/TCPSession.swift
1
7655
// // TCPConnection.swift // Tachograph // // Created by larryhou on 30/6/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation @objc protocol TCPSessionDelegate { func tcp(session: TCPSession, data: Data) @objc optional func tcp(session: TCPSession, state: TCPSessionState) @objc optional func tcp(session: TCPSession, sendEvent: Stream.Event) @objc optional func tcp(session: TCPSession, readEvent: Stream.Event) @objc optional func tcp(session: TCPSession, error: Error) @objc optional func tcpUpdate(session: TCPSession) @objc optional func close() } extension Stream.Event { var description: String { switch self { case .hasBytesAvailable: return "\(self) hasBytesAvailable" case .hasSpaceAvailable: return "\(self) hasSpaceAvailable" case .openCompleted: return "\(self) openCompleted" case .errorOccurred: return "\(self) errorOccurred" case .endEncountered: return "\(self) endEncountered" default: return "\(self)" } } } struct QueuedMessage { let data: Data let count: Int let offset: Int init(data: Data) { self.init(data: data, offset: -1, count: -1) } init(data: Data, count: Int) { self.init(data: data, offset: -1, count: count) } init(data: Data, offset: Int, count: Int) { self.data = data self.count = count self.offset = offset } } @objc enum TCPSessionState: Int { case none, connecting, connected, closed } class TCPSession: NSObject, StreamDelegate { static let BUFFER_SIZE = 1024 var delegate: TCPSessionDelegate? private var _readStream: InputStream! private var _sendStream: OutputStream! private var _timer: Timer! private var _state: TCPSessionState = .none private(set) var state: TCPSessionState { get {return _state} set { if _state != newValue { _state = newValue delegate?.tcp?(session: self, state: _state) } } } private var _buffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.allocate(capacity: TCPSession.BUFFER_SIZE) private var _queue: [QueuedMessage] = [] var connected: Bool { return _state == .connected } private var address: String?, port: UInt32 = 0 func connect(address: String, port: UInt32) { self.address = address self.port = port var r: Unmanaged<CFReadStream>? var w: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(nil, address as CFString, port, &r, &w) _readStream = r!.takeRetainedValue() as InputStream _readStream.delegate = self _sendStream = w!.takeRetainedValue() as OutputStream _sendStream.delegate = self _readStream.schedule(in: .current, forMode: .defaultRunLoopMode) _sendStream.schedule(in: .current, forMode: .defaultRunLoopMode) _readStream.open() _sendStream.open() state = .connecting _timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(sendUpdate), userInfo: nil, repeats: true) } func reconnect() { state = .connecting if let address = self.address, port != 0 { close() connect(address: address, port: port) } } func clear() { _queue.removeAll() } @objc private func sendUpdate() { delegate?.tcpUpdate?(session: self) guard let stream = _sendStream else { return } if stream.hasSpaceAvailable { if !connected { state = .connected } if _queue.count > 0 { send(_queue.removeFirst()) } } } func stream(_ aStream: Stream, handle eventCode: Stream.Event) { print(eventCode.description) if _readStream == nil || _sendStream == nil {return} if aStream == _readStream { delegate?.tcp?(session: self, readEvent: eventCode) if eventCode == .hasBytesAvailable { if let stream = _readStream, stream.hasBytesAvailable { delegate?.tcp(session: self, data: read()) } } } else { delegate?.tcp?(session: self, sendEvent: eventCode) } if eventCode == .errorOccurred || eventCode == .endEncountered { if let error = aStream.streamError { print(error) delegate?.tcp?(session: self, error: error) } close() } } func send(data: String) { if let data = data.data(using: .utf8) { send(data: data) } } func send(data: Dictionary<String, Any>) { do { let bytes = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) print(String(data: bytes, encoding: .utf8)!) send(data: bytes) } catch { print(error) } } func send(data: Data) { _queue.append(QueuedMessage(data: data)) } func send(data: Data, count: Int) { _queue.append(QueuedMessage(data: data, count: count)) } @discardableResult private func send(_ msg: QueuedMessage) -> Int { let data = msg.data var count = msg.count if msg.count <= -1 { count = msg.data.count } if msg.offset <= -1 { return data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in _sendStream.write(pointer, maxLength: min(count, data.count)) } } else { let offset = msg.offset return data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in let new = pointer.advanced(by: offset) let num = min(data.count - offset, count) return _sendStream.write(new, maxLength: num) } } } func send(data: Data, offset: Int, count: Int) { _queue.append(QueuedMessage(data: data, offset: offset, count: count)) } func read() -> Data { var data = Data() while read(to: &data, size: TCPSession.BUFFER_SIZE) {} return data } @discardableResult private func read(to data: inout Data, size: Int) -> Bool { guard let stream = _readStream, stream.hasBytesAvailable && stream.streamError == nil else { return false } let num = stream.read(_buffer, maxLength: size) if num > 0 { data.append(_buffer, count: num) return true } else if let error = stream.streamError { close() print(error) } return false } func read(count: Int) -> Data { var data = Data() var bytesAvailable = true while bytesAvailable { let remain = count - data.count bytesAvailable = read(to: &data, size: min(remain, TCPSession.BUFFER_SIZE)) } return data } func close() { if _readStream != nil { _readStream.close() _readStream = nil } if _sendStream != nil { _sendStream.close() _sendStream = nil } _queue.removeAll(keepingCapacity: false) _timer.invalidate() state = .closed delegate?.close?() } deinit { close() _buffer.deallocate(capacity: TCPSession.BUFFER_SIZE) } }
mit
3b23cd606be2d7359e30dc7b9c748196
27.03663
134
0.565195
4.421722
false
false
false
false
ibm-wearables-sdk-for-mobile/ios
IBMMobileEdge/IBMMobileEdge/SensorTag.swift
4
12042
/* * © Copyright 2015 IBM Corp. * * Licensed under the Mobile Edge iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 public class SensorTag : BLEDeviceConnector { private let motionSensorPeriodOperation = "motionSensorPeriod" private let accelerometerRangeOperation = "accelerometerRange"; //holds the global state of the motion sensor data characteristic private var motionSensorConfigData = OperationDataHolder(data:[0x00, 0x00]) private var motionSensorPeriodData = OperationDataHolder(data:[0x0A]) //100 ms private var accelerometerRange:UInt8 = 2; public init(){ super.init(deviceName: "SensorTag") //Accelerometer Data let accelerometerConfigData = declareNewSensorData(SensorType.Accelerometer, withID: "F000AA80-0451-4000-B000-000000000000") accelerometerConfigData.setConvertFunction(convertAccelerometerData) accelerometerConfigData.defineCharacteristicOperation(notifyOnOperation, operation: BLEOperationType.NotifyOn("F000AA81-0451-4000-B000-000000000000")) accelerometerConfigData.defineCharacteristicOperation(turnOnOperation, operation: BLEOperationType.SetValueWithOR("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData,[0x38, 0x0])) //00111000 accelerometerConfigData.defineCharacteristicOperation(turnOffOperation, operation: BLEOperationType.SetValueWithAND("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData, [0xC7, 0xFF])) //11000111 accelerometerConfigData.defineCharacteristicOperation(motionSensorPeriodOperation, operation: BLEOperationType.SetDynamicValue("F000AA83-0451-4000-B000-000000000000",motionSensorPeriodData)) accelerometerConfigData.defineCharacteristicOperation(accelerometerRangeOperation, operation: BLEOperationType.SetDynamicValue("F000AA82-0451-4000-B000-000000000000", motionSensorConfigData)) //Temperature Data let temperatureConfigData = declareNewSensorData(SensorType.Temperature, withID: "F000AA00-0451-4000-B000-000000000000") temperatureConfigData.setConvertFunction(convertTemperatureData) temperatureConfigData.defineCharacteristicOperation(notifyOnOperation, operation: BLEOperationType.NotifyOn("F000AA01-0451-4000-B000-000000000000")) temperatureConfigData.defineCharacteristicOperation(notifyOffOperation, operation: BLEOperationType.NotifyOff("F000AA01-0451-4000-B000-000000000000")) temperatureConfigData.defineCharacteristicOperation(turnOnOperation, operation: BLEOperationType.SetValue("F000AA02-0451-4000-B000-000000000000",[1])) temperatureConfigData.defineCharacteristicOperation(turnOffOperation, operation: BLEOperationType.SetValue("F000AA02-0451-4000-B000-000000000000",[0])) //Humidity Data let humidityConfigData = declareNewSensorData(SensorType.Humidity, withID: "F000AA20-0451-4000-B000-000000000000") humidityConfigData.setConvertFunction(convertHumidityData) humidityConfigData.defineCharacteristicOperation(notifyOnOperation, operation: BLEOperationType.NotifyOn("F000AA21-0451-4000-B000-000000000000")) humidityConfigData.defineCharacteristicOperation(notifyOffOperation, operation: BLEOperationType.NotifyOff("F000AA21-0451-4000-B000-000000000000")) humidityConfigData.defineCharacteristicOperation(turnOnOperation, operation: BLEOperationType.SetValue("F000AA22-0451-4000-B000-000000000000",[1])) humidityConfigData.defineCharacteristicOperation(turnOffOperation, operation: BLEOperationType.SetValue("F000AA22-0451-4000-B000-000000000000",[0])) //Magnetometer Data let magnetometerData = declareNewSensorData(SensorType.Magnetometer, withID: "F000AA80-0451-4000-B000-000000000000") magnetometerData.setConvertFunction(convertMagnetometerData) magnetometerData.defineCharacteristicOperation(notifyOnOperation, operation: BLEOperationType.NotifyOn("F000AA81-0451-4000-B000-000000000000")) magnetometerData.defineCharacteristicOperation(turnOnOperation, operation: BLEOperationType.SetValueWithOR("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData,[0x40, 0x0])) //0100 0000 magnetometerData.defineCharacteristicOperation(turnOffOperation, operation: BLEOperationType.SetValueWithAND("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData,[0xBF, 0xFF])) //1011 1111 //Gyroscope Data let gyroscopeData = declareNewSensorData(.Gyroscope, withID: "F000AA80-0451-4000-B000-000000000000") gyroscopeData.setConvertFunction(convertGyroscopeData) gyroscopeData.defineCharacteristicOperation(notifyOnOperation, operation: BLEOperationType.NotifyOn("F000AA81-0451-4000-B000-000000000000")) gyroscopeData.defineCharacteristicOperation(turnOnOperation, operation: BLEOperationType.SetValueWithOR("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData,[0x07, 0x0])) //0000 0111 gyroscopeData.defineCharacteristicOperation(turnOffOperation, operation: BLEOperationType.SetValueWithAND("F000AA82-0451-4000-B000-000000000000",motionSensorConfigData,[0xF8, 0xFF])) //1111 1000 } //can be 2,4,8 or 16 public func setAccelerometerRange(range:UInt8){ accelerometerRange = range motionSensorConfigData.data[1] = range executeOperation(accelerometerRangeOperation, forType: .Accelerometer) } public func setMotionSensorPeriod(period:UInt8){ motionSensorPeriodData.data[0] = period executeOperation(motionSensorPeriodOperation, forType: .Accelerometer) } override public func registerForEvents(systemEvents: SystemEvents){ super.registerForEvents(systemEvents) //set the default values of sensor setAccelerometerRange(8) //set the default to 8G setMotionSensorPeriod(0x0A) //set the default to 100ms } //called once for each supported sensor override func registerEventsForSensor(sensorType:SensorType, withSensorEvents sensorEvents:SensorEvents){ sensorEvents.turnOnCommand.addHandler { () -> () in self.sensorNotificationOn(sensorType) } sensorEvents.turnOffCommand.addHandler { () -> () in self.sensorNotificationOff(sensorType) } } override func onDataChangedForType(type: SensorType, data: BaseSensorData) { systemEvents.getSensorEvents(type).dataEvent.trigger(data); } func sensorNotificationOn(type:SensorType){ //set notify to true and turn the sensor on executeOperations([notifyOnOperation,turnOnOperation], forType: type) } func sensorNotificationOff(type:SensorType){ //turn the sensor off executeOperations([turnOffOperation], forType: type) } private func convertMotionData(data:NSData) -> [Int16]{ let count = data.length var array = [Int16](count: count, repeatedValue: 0) data.getBytes(&array, length:count * sizeof(Int16)) return array } func convertAccelerometerData(data:NSData) -> BaseSensorData { let accelerometerData = AccelerometerData() let array = convertMotionData(data) let accelerometerScale = 32768.0 / Double(accelerometerRange) let xIndex:Int = 3 let yIndex:Int = 4 let zIndex:Int = 5 accelerometerData.x = Double(array[xIndex]) / accelerometerScale accelerometerData.y = Double(array[yIndex]) / accelerometerScale accelerometerData.z = Double(array[zIndex]) / accelerometerScale return accelerometerData; } func convertGyroscopeData(data:NSData) -> BaseSensorData { let gyroscopeData = GyroscopeData() let array = convertMotionData(data) let gyroScale:Double = (65536.0 / 500.0) let xIndex:Int = 0 let yIndex:Int = 1 let zIndex:Int = 2 gyroscopeData.x = Double(array[xIndex]) / gyroScale gyroscopeData.y = Double(array[yIndex]) / gyroScale gyroscopeData.z = Double(array[zIndex]) / gyroScale return gyroscopeData } //conver the data to uT (micro Tesla). func convertMagnetometerData(data:NSData) -> BaseSensorData { let magnetometerData = MagnetometerData() let array = convertMotionData(data) let xIndex:Int = 6 let yIndex:Int = 7 let zIndex:Int = 8 magnetometerData.x = Double(array[xIndex]) magnetometerData.y = Double(array[yIndex]) magnetometerData.z = Double(array[zIndex]) return magnetometerData } func convertTemperatureData(data:NSData) -> BaseSensorData { let temperatureData = TemperatureData() let ambientTemperature = Float(getAmbientTemperature(data)) temperatureData.temperature = Double(getObjectTemperature(data,ambientTemperature: Double(ambientTemperature))) return temperatureData } // Get ambient temperature value func getAmbientTemperature(value : NSData) -> Double { let dataFromSensor = dataToSignedBytes16(value) let ambientTemperature = Double(dataFromSensor[1])/128 return ambientTemperature } // Get object temperature value func getObjectTemperature(value : NSData, ambientTemperature : Double) -> Double { let dataFromSensor = dataToSignedBytes16(value) let Vobj2 = Double(dataFromSensor[0]) * 0.00000015625 let Tdie2 = ambientTemperature + 273.15 let Tref = 298.15 let S0 = 6.4e-14 let a1 = 1.75E-3 let a2 = -1.678E-5 let b0 = -2.94E-5 let b1 = -5.7E-7 let b2 = 4.63E-9 let c2 = 13.4 let S = S0*(1+a1*(Tdie2 - Tref)+a2*pow((Tdie2 - Tref),2)) let Vos = b0 + b1*(Tdie2 - Tref) + b2*pow((Tdie2 - Tref),2) let fObj = (Vobj2 - Vos) + c2*pow((Vobj2 - Vos),2) let tObj = pow(pow(Tdie2,4) + (fObj/S),0.25) let objectTemperature = tObj.isNaN ? -999 : (tObj - 273.15) return objectTemperature } func dataToSignedBytes16(value : NSData) -> [Int16] { let count = value.length var array = [Int16](count: count, repeatedValue: 0) value.getBytes(&array, length:count * sizeof(Int16)) return array } func dataToUnsignedBytes16(value : NSData) -> [UInt16] { /* print(value) let count = value.length var array = [UInt16](count: count, repeatedValue: 0) value.getBytes(&array, length:count * sizeof(UInt16)) return array */ // the number of elements: let count = value.length / sizeof(UInt16) // create array of appropriate length: var array = [UInt16](count: count, repeatedValue: 0) // copy bytes into array value.getBytes(&array, length:count * sizeof(UInt16)) return array } func convertHumidityData(data:NSData) -> BaseSensorData { let humidityData = HumidityData() let dataFromSensor = dataToUnsignedBytes16(data) //let swappedValue = Double(CFSwapInt16(dataFromSensor[1])) humidityData.humidity = (Double(dataFromSensor[1]) / 65536) * 100 return humidityData } }
epl-1.0
33e6c81c2ba5d9dc2aac9917101a0f56
43.106227
212
0.699111
4.45963
false
true
false
false
jhihguan/JSON2Realm
Pods/Freddy/Sources/JSONSubscripting.swift
4
36413
// // JSONSubscripting.swift // Freddy // // Created by Zachary Waldowski on 8/15/15. // Copyright © 2015 Big Nerd Ranch. All rights reserved. // // MARK: JSONPathType /// A protocol used to define a path within an instance of `JSON` that leads to some desired value. /// /// A custom type, such as a `RawRepresentable` enum, may be made to conform to `JSONPathType` /// and used with the subscript APIs. public protocol JSONPathType { /// Use `self` to key into a `dictionary`. /// /// Unlike Swift dictionaries, failing to find a value for a key should throw /// an error rather than convert to `nil`. /// /// Upon failure, implementers should throw an error from `JSON.Error`. func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON /// Use `self` to index into an `array`. /// /// Unlike Swift array, attempting to index outside the collection's bounds /// should throw an error rather than crash. /// /// Upon failure, implementers should throw an error from `JSON.Error`. func valueInArray(array: [JSON]) throws -> JSON } extension JSONPathType { /// The default behavior for keying into a dictionary is to throw /// `JSON.Error.UnexpectedSubscript`. public func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON { throw JSON.Error.UnexpectedSubscript(type: Self.self) } /// The default behavior for indexing into an array is to throw /// `JSON.Error.UnexpectedSubscript`. public func valueInArray(array: [JSON]) throws -> JSON { throw JSON.Error.UnexpectedSubscript(type: Self.self) } } extension String: JSONPathType { /// A method used to retrieve a value from a given dictionary for a specific key. /// - throws: `.KeyNotFound` with an associated value of `self`, where `self` is a `String`, /// should the key not be present within the `JSON`. /// - returns: The `JSON` value associated with the given key. public func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON { guard let next = dictionary[self] else { throw JSON.Error.KeyNotFound(key: self) } return next } } extension Int: JSONPathType { /// A method used to retrieve a value from a given array for a specific index. /// - throws: `.IndexOutOfBounds` with an associated value of `self`, where `self` is an `Int`, /// should the index not be within the valid range for the array of `JSON`. /// - returns: The `JSON` value found at the given index. public func valueInArray(array: [JSON]) throws -> JSON { guard case array.indices = self else { throw JSON.Error.IndexOutOfBounds(index: self) } return array[self] } } // MARK: - Subscripting core private extension JSON { enum SubscriptError: ErrorType { case SubscriptIntoNull(JSONPathType) } func valueForPathFragment(fragment: JSONPathType, detectNull: Swift.Bool) throws -> JSON { switch self { case .Null where detectNull: throw SubscriptError.SubscriptIntoNull(fragment) case let .Dictionary(dict): return try fragment.valueInDictionary(dict) case let .Array(array): return try fragment.valueInArray(array) default: throw Error.UnexpectedSubscript(type: fragment.dynamicType) } } func valueAtPath(path: [JSONPathType], detectNull: Swift.Bool = false) throws -> JSON { var result = self for fragment in path { result = try result.valueForPathFragment(fragment, detectNull: detectNull) } return result } } // MARK: - Subscripting operator extension JSON { public subscript(key: Swift.String) -> JSON? { return try? valueForPathFragment(key, detectNull: false) } public subscript(index: Swift.Int) -> JSON? { return try? valueForPathFragment(index, detectNull: false) } } // MARK: - Simple member unpacking extension JSON { /// Attempts to decode into the returning type from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON`. /// - parameter type: If the context this method is called from does not /// make the return type clear, pass a type implementing `JSONDecodable` /// to disambiguate the type to decode with. /// - returns: An initialized member from the inner JSON. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A given `String` key does not exist inside a /// descendant `JSON` dictionary. /// * `IndexOutOfBounds`: A given `Int` index is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A given subscript cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of /// the `JSON` instance does not match `Decoded`. public func decode<Decoded: JSONDecodable>(path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> Decoded { return try Decoded(json: valueAtPath(path)) } /// Retrieves a `Double` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: A floating-point `Double` /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func double(path: JSONPathType...) throws -> Swift.Double { return try Swift.Double(json: valueAtPath(path)) } /// Retrieves an `Int` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: A numeric `Int` /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func int(path: JSONPathType...) throws -> Swift.Int { return try Swift.Int(json: valueAtPath(path)) } /// Retrieves a `String` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: A textual `String` /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func string(path: JSONPathType...) throws -> Swift.String { return try Swift.String(json: valueAtPath(path)) } /// Retrieves a `Bool` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: A truthy `Bool` /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func bool(path: JSONPathType...) throws -> Swift.Bool { return try Swift.Bool(json: valueAtPath(path)) } /// Retrieves a `[JSON]` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: An `Array` of `JSON` elements /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func array(path: JSONPathType...) throws -> [JSON] { return try JSON.getArray(valueAtPath(path)) } /// Attempts to decodes many values from a desendant JSON array at a path /// into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter type: If the context this method is called from does not /// make the return type clear, pass a type implementing `JSONDecodable` /// to disambiguate the type to decode with. /// - returns: An `Array` of decoded elements /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`, or /// any error that arises from decoding the contained values. /// - seealso: `JSON.decode(_:type:)` public func arrayOf<Decoded: JSONDecodable>(path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> [Decoded] { return try JSON.getArrayOf(valueAtPath(path)) } /// Retrieves a `[String: JSON]` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - returns: An `Dictionary` of `String` mapping to `JSON` elements /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. /// - seealso: `JSON.decode(_:type:)` public func dictionary(path: JSONPathType...) throws -> [Swift.String: JSON] { return try JSON.getDictionary(valueAtPath(path)) } } // MARK: - Missing-to-Optional unpacking extension JSON { private func optionalAtPath(path: [JSONPathType], ifNotFound: Swift.Bool) throws -> JSON? { do { return try valueAtPath(path, detectNull: true) } catch Error.IndexOutOfBounds where ifNotFound { return nil } catch Error.KeyNotFound where ifNotFound { return nil } catch SubscriptError.SubscriptIntoNull(_ as Swift.String) where ifNotFound { return nil } catch let SubscriptError.SubscriptIntoNull(fragment) { throw Error.UnexpectedSubscript(type: fragment.dynamicType) } } /// Optionally decodes into the returning type from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - parameter type: If the context this method is called from does not /// make the return type clear, pass a type implementing `JSONDecodable` /// to disambiguate the type to decode with. /// - returns: A decoded value from the inner JSON if found, or `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * If `ifNotFound` is `false`, `KeyNotFound`: A key `path` does not /// exist inside a descendant `JSON` dictionary. /// * If `ifNotFound` is `false`, `IndexOutOfBounds`: An index `path` is /// outside the bounds of a descendant `JSON` array. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. /// * Any error that arises from decoding the value. public func decode<Decoded: JSONDecodable>(path: JSONPathType..., ifNotFound: Swift.Bool, type: Decoded.Type = Decoded.self) throws -> Decoded? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(Decoded.init) } /// Optionally retrieves a `Double` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: A `Double` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func double(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Double? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(Swift.Double.init) } /// Optionally retrieves a `Int` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: A numeric `Int` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func int(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Int? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(Swift.Int.init) } /// Optionally retrieves a `String` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: A text `String` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func string(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.String? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(Swift.String.init) } /// Optionally retrieves a `Bool` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: A truthy `Bool` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func bool(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Bool? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(Swift.Bool.init) } /// Optionally retrieves a `[JSON]` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: An `Array` of `JSON` elements if a value could be found, /// otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func array(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [JSON]? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(JSON.getArray) } /// Optionally decodes many values from a descendant array at a path into /// JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: An `Array` of decoded elements if found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. /// * Any error that arises from decoding the value. public func arrayOf<Decoded: JSONDecodable>(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [Decoded]? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(JSON.getArrayOf) } /// Optionally retrieves a `[String: JSON]` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: A `Dictionary` of `String` mapping to `JSON` elements if a /// value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func dictionary(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [Swift.String: JSON]? { return try optionalAtPath(path, ifNotFound: ifNotFound).map(JSON.getDictionary) } } // MARK: - Missing-with-fallback unpacking extension JSON { private func mapOptionalAtPath<Value>(path: [JSONPathType], @noescape fallback: () -> Value, @noescape transform: JSON throws -> Value) throws -> Value { return try optionalAtPath(path, ifNotFound: true).map(transform) ?? fallback() } /// Attempts to decode into the returning type from a path into /// JSON, or returns a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Value to use when one is missing at the subscript. /// - returns: An initialized member from the inner JSON. /// - throws: One of the following errors contained in `JSON.Error`: /// * `UnexpectedSubscript`: A given subscript cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of /// the `JSON` instance does not match `Decoded`. public func decode<Decoded: JSONDecodable>(path: JSONPathType..., @autoclosure or fallback: () -> Decoded) throws -> Decoded { return try mapOptionalAtPath(path, fallback: fallback, transform: Decoded.init) } /// Retrieves a `Double` from a path into JSON or a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: A floating-point `Double` /// - throws: One of the `JSON.Error` cases thrown by calling `mapOptionalAtPath(_:fallback:transform:)`. /// - seealso: `optionalAtPath(_:ifNotFound)`. public func double(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Double) throws -> Swift.Double { return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Double.init) } /// Retrieves an `Int` from a path into JSON or a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: A numeric `Int` /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func int(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Int) throws -> Swift.Int { return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Int.init) } /// Retrieves a `String` from a path into JSON or a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: A textual `String` /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func string(path: JSONPathType..., @autoclosure or fallback: () -> Swift.String) throws -> Swift.String { return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.String.init) } /// Retrieves a `Bool` from a path into JSON or a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: A truthy `Bool` /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func bool(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Bool) throws -> Swift.Bool { return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Bool.init) } /// Retrieves a `[JSON]` from a path into JSON or a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: An `Array` of `JSON` elements /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func array(path: JSONPathType..., @autoclosure or fallback: () -> [JSON]) throws -> [JSON] { return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getArray) } /// Attempts to decodes many values from a desendant JSON array at a path /// into the recieving structure, returning a fallback if not found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Array to use when one is missing at the subscript. /// - returns: An `Array` of decoded elements /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. /// * Any error that arises from decoding the value. public func arrayOf<Decoded: JSONDecodable>(path: JSONPathType..., @autoclosure or fallback: () -> [Decoded]) throws -> [Decoded] { return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getArrayOf) } /// Retrieves a `[String: JSON]` from a path into JSON or a fallback if not /// found. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter fallback: Value to use when one is missing at the subscript /// - returns: An `Dictionary` of `String` mapping to `JSON` elements /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func dictionary(path: JSONPathType..., @autoclosure or fallback: () -> [Swift.String: JSON]) throws -> [Swift.String: JSON] { return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getDictionary) } } // MARK: - Null-to-Optional unpacking extension JSON { private func mapOptionalAtPath<Value>(path: [JSONPathType], ifNull: Swift.Bool, @noescape transform: JSON throws -> Value) throws -> Value? { var json: JSON? do { json = try valueAtPath(path, detectNull: ifNull) return try json.map(transform) } catch SubscriptError.SubscriptIntoNull { return nil } catch Error.ValueNotConvertible where ifNull && json == .Null { return nil } } /// Optionally decodes into the returning type from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - parameter type: If the context this method is called from does not /// make the return type clear, pass a type implementing `JSONDecodable` /// to disambiguate the type to decode with. /// - returns: A decoded value from the inner JSON if found, or `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. /// * Any error that arises from decoding the value. public func decode<Decoded: JSONDecodable>(path: JSONPathType..., ifNull: Swift.Bool, type: Decoded.Type = Decoded.self) throws -> Decoded? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: Decoded.init) } /// Optionally retrieves a `Double` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON`. /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: A `Double` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func double(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Double? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: Swift.Double.init) } /// Optionally retrieves a `Int` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: A numeric `Int` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func int(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Int? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: Swift.Int.init) } /// Optionally retrieves a `String` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: A text `String` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func string(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.String? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: Swift.String.init) } /// Optionally retrieves a `Bool` from a path into JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: A truthy `Bool` if a value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func bool(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Bool? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: Swift.Bool.init) } /// Optionally retrieves a `[JSON]` from a path into the recieving structure. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: An `Array` of `JSON` elements if a value could be found, /// otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func array(path: JSONPathType..., ifNull: Swift.Bool) throws -> [JSON]? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: JSON.getArray) } /// Optionally decodes many values from a descendant array at a path into /// JSON. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNotFound: If `true`, missing key or index errors are /// treated as `nil`. /// - returns: An `Array` of decoded elements if found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. /// * Any error that arises from decoding the value. public func arrayOf<Decoded: JSONDecodable>(path: JSONPathType..., ifNull: Swift.Bool) throws -> [Decoded]? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: JSON.getArrayOf) } /// Optionally retrieves a `[String: JSON]` from a path into the recieving /// structure. /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` /// - parameter ifNull: If `true`, target values matching `Null` are treated /// as `nil`. /// - returns: A `Dictionary` of `String` mapping to `JSON` elements if a /// value could be found, otherwise `nil`. /// - throws: One of the following errors contained in `JSON.Error`: /// * `KeyNotFound`: A key `path` does not exist inside a descendant /// `JSON` dictionary. /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a /// descendant `JSON` array. /// * `UnexpectedSubscript`: A `path` item cannot be used with the /// corresponding `JSON` value. /// * `TypeNotConvertible`: The target value's type inside of the `JSON` /// instance does not match the decoded value. public func dictionary(path: JSONPathType..., ifNull: Swift.Bool) throws -> [Swift.String: JSON]? { return try mapOptionalAtPath(path, ifNull: ifNull, transform: JSON.getDictionary) } }
mit
c4c5b1086f98eea837d1fcd3cd004bb0
51.241033
157
0.634983
4.180002
false
false
false
false
csaito/prework
TipCalculator23/ViewController.swift
1
7662
// // ViewController.swift // TipCalculator23 // import UIKit class ViewController: UIViewController, AKPickerViewDelegate, AKPickerViewDataSource, UITextFieldDelegate { var numberOfPeoplePicker : AKPickerView? var tipPercentagePicker : AKPickerView? let TAG_FOR_TIP_PERCENTAGE = 0 let TAG_FOR_NUM_OF_PEOPLE = 1 var defaultTipPercentage = -1 var defaultNumOfPeople = -1 var BILL_AMOUNT_INTERVAL_IN_SEC = 60 * 5 // Remember the previous bill amount for 5 min override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(storeActivityData), name:UIApplicationDidEnterBackgroundNotification, object:nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (!(self.tipPercentagePicker != nil)) { setupPickerViews() } self.billField.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setUIDefaultValues() self.billField.becomeFirstResponder() // start editing } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { storeActivityData() NSNotificationCenter.defaultCenter().removeObserver(self) } @IBOutlet weak var billField: UITextField! @IBOutlet weak var totalAmount: UILabel! @IBOutlet weak var tipPercentageView: UIView! @IBOutlet weak var numberOfPeopleView: UIView! @IBOutlet weak var totalPerPersonLabel: UILabel! @IBOutlet weak var tipLabel: UILabel! func updateUI() { let bill = Double(billField.text!) ?? 0 let tip = bill * Double((tipPercentagePicker?.selectedItem)!) / 100 let total = tip + bill let totalPP = total / Double((numberOfPeoplePicker?.selectedItem)! + 1) let totalString = NSMutableAttributedString(string: String(format:"$ %.2f", total)) totalString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(25.0), range: NSRange(location: 0,length: 1)) let totalPPString = NSMutableAttributedString(string: String(format:"$ %.2f", totalPP)) totalPPString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(25.0), range: NSRange(location: 0,length: 1)) tipLabel.text = String(format:"+ %.2f", tip) //totalAmount.text = String(format:"%.2f", total) //totalPerPersonLabel.text = String(format:"%.2f", totalPP) totalAmount.attributedText = totalString totalPerPersonLabel.attributedText = totalPPString } func setupPickerViews() { self.tipPercentagePicker = AKPickerView(frame: tipPercentageView.frame) self.tipPercentagePicker?.delegate = self self.tipPercentagePicker?.dataSource = self self.tipPercentagePicker?.font = UIFont(name: "HelveticaNeue-Light", size: 40)! self.tipPercentagePicker?.highlightedFont = UIFont(name: "HelveticaNeue", size: 40)! self.tipPercentagePicker?.textColor = UIColor.whiteColor() self.tipPercentagePicker?.highlightedTextColor = UIColor.whiteColor() self.tipPercentagePicker?.pickerViewStyle = .Wheel self.tipPercentagePicker?.maskDisabled = false self.tipPercentagePicker?.interitemSpacing = 25.0 self.tipPercentagePicker?.tag = TAG_FOR_TIP_PERCENTAGE self.tipPercentagePicker?.reloadData() self.numberOfPeoplePicker = AKPickerView(frame: numberOfPeopleView.frame) self.numberOfPeoplePicker?.delegate = self self.numberOfPeoplePicker?.dataSource = self self.numberOfPeoplePicker?.font = UIFont(name: "HelveticaNeue-Light", size: 40)! self.numberOfPeoplePicker?.highlightedFont = UIFont(name: "HelveticaNeue", size: 40)! self.numberOfPeoplePicker?.textColor = UIColor.whiteColor() self.numberOfPeoplePicker?.highlightedTextColor = UIColor.whiteColor() self.numberOfPeoplePicker?.pickerViewStyle = .Wheel self.numberOfPeoplePicker?.maskDisabled = false self.numberOfPeoplePicker?.interitemSpacing = 25.0 self.numberOfPeoplePicker?.tag = TAG_FOR_NUM_OF_PEOPLE self.numberOfPeoplePicker?.reloadData() self.view.addSubview(self.numberOfPeoplePicker!) self.view.addSubview(self.tipPercentagePicker!) } func setUIDefaultValues() { let defaults = NSUserDefaults.standardUserDefaults() var tipPercentage = defaults.integerForKey("DEFAULT_TIP_PERCENTAGE") if (tipPercentage == 0) { tipPercentage = 15 } var numOfPeople = defaults.integerForKey("DEFAULT_NUM_OF_PEOPLE") if (numOfPeople == 0) { numOfPeople = 1 } if (defaultTipPercentage != tipPercentage) { defaultTipPercentage = tipPercentage self.tipPercentagePicker?.selectItem(tipPercentage) } if (defaultNumOfPeople != numOfPeople) { defaultNumOfPeople = numOfPeople self.numberOfPeoplePicker?.selectItem(numOfPeople - 1) } // Bill text - only set if there's no value stored in this ViewController if (billField.text?.characters.count == 0) { let previousTimeInterval = defaults.doubleForKey("LAST_ACTIVATION_UTC") if (previousTimeInterval > 0) { let viewRestartInterval = NSDate().timeIntervalSinceDate(NSDate(timeIntervalSince1970: previousTimeInterval)) if (viewRestartInterval < Double(BILL_AMOUNT_INTERVAL_IN_SEC)) { let previousBill = defaults.doubleForKey("LAST_BILL_AMOUNT") if (previousBill > 0) { billField.text = String(format:"%.2f", previousBill) self.updateUI() } } } } } func storeActivityData() { let defaults = NSUserDefaults.standardUserDefaults() defaults.setDouble(NSDate().timeIntervalSince1970, forKey: "LAST_ACTIVATION_UTC") defaults.setDouble(Double(billField.text!) ?? 0, forKey: "LAST_BILL_AMOUNT") defaults.synchronize() } // MARK: - AKPickerViewDataSource func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int { if (pickerView.tag == self.TAG_FOR_TIP_PERCENTAGE) { return 50; } else { return 10 } } func pickerView(pickerView: AKPickerView, imageForItem item: Int) -> UIImage { return UIImage(named: "")! } func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String { if (pickerView.tag == self.TAG_FOR_TIP_PERCENTAGE) { return String(item) + "%" } else { return String(item + 1); } } // MARK: - AKPickerViewDelegate func pickerView(pickerView: AKPickerView, didSelectItem item: Int) { self.updateUI() } @IBAction func onEditChanged(sender: AnyObject) { self.updateUI() } // TextField delegate // Somehow this didn't work as a subclass @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } }
unlicense
3a9ffd629c7b9e4a04b0e7083db7ad03
38.091837
125
0.63443
4.988281
false
false
false
false
nevercry/VideoMarks
VideoMarks/VideoDetailTVC.swift
1
4974
// // VideoDetailTVC.swift // VideoMarks // // Created by nevercry on 6/16/16. // Copyright © 2016 nevercry. All rights reserved. // import UIKit class VideoDetailTVC: UITableViewController { var video: Video? // MARK: Preview actions override var previewActionItems : [UIPreviewActionItem] { let openInSafariAction = UIPreviewAction(title: NSLocalizedString("Open in Safari", comment: "在Safari中打开"), style: .default) { (_, viewController) in guard let detailViewController = viewController as? VideoDetailTVC else { return } let videoUrl = URL(string: detailViewController.video!.url) UIApplication.shared.openURL(videoUrl!) } let copyVideoLinkAction = UIPreviewAction(title: NSLocalizedString("Copy Link", comment: "复制链接"), style: .default) { (_, viewController) in guard let videDetailTVC = viewController as? VideoDetailTVC else { return } UIPasteboard.general.string = videDetailTVC.video?.url } return [copyVideoLinkAction,openInSafariAction,] } override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Video Detail", comment: "影片信息") self.clearsSelectionOnViewWillAppear = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.backBarButtonItem?.title = "返回" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } // MARK:- 分享 @IBAction func shareAction(_ sender: UIBarButtonItem) { let url = URL(string: video!.url)! let actVC = UIActivityViewController.init(activityItems: [url], applicationActivities: [OpenSafariActivity()]) actVC.modalPresentationStyle = .popover if let presenter = actVC.popoverPresentationController { presenter.barButtonItem = sender } present(actVC, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var numOfRow = 1 if video?.source.lowercased() != "unknow" { numOfRow = 2 } return numOfRow } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ if (indexPath as NSIndexPath).row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "Video Detail Cell", for: indexPath) as! VideoDetailCell cell.textView.attributedText = video?.attributeDescriptionForTextView() return cell } else if (indexPath as NSIndexPath).row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "Source Link Cell", for: indexPath) cell.textLabel?.text = NSLocalizedString("Source Link", comment: "源链接") return cell } else { return UITableViewCell() } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var height: CGFloat switch (indexPath as NSIndexPath).row { case 0: height = video!.heightForTableView(tableView.bounds.width - 16) case 1: height = 44 default: height = 0 } return height } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if ((indexPath as NSIndexPath).row == 1) { let alertC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertC.modalPresentationStyle = .popover let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: .cancel, handler: { _ in }) let openSafariAction = UIAlertAction(title: NSLocalizedString("Open in Safari", comment: "在Safari中打开"), style: .default, handler: { (action) in let sourceURL = URL(string: self.video!.source) UIApplication.shared.openURL(sourceURL!) }) alertC.addAction(cancelAction) alertC.addAction(openSafariAction) if let presenter = alertC.popoverPresentationController { presenter.sourceView = tableView.cellForRow(at: indexPath)?.textLabel presenter.sourceRect = CGRect(x: 0, y: 44, width: 44, height: 0) presenter.permittedArrowDirections = .up } present(alertC, animated: true, completion: nil) tableView.deselectRow(at: indexPath, animated: false) } } }
mit
e5b69a9ce571f4d0093f74bee30192fa
37.76378
157
0.622791
5.259615
false
false
false
false
alobanov/vps-template
rx_mvvm_controller/RxModelStateAndProtocols/RxViewModelPorotocol.swift
1
1925
// // RxViewModel.swift // // Created by Lobanov Aleksey on 08.09.16. // Copyright © 2016 All rights reserved. // import Foundation import RxSwift import RxCocoa protocol RxViewModelType { associatedtype InputDependencies associatedtype Input associatedtype Output func configure(input: Input) -> Output } protocol RxViewModelModuleType { associatedtype ModuleInput associatedtype ModuleOutput func configureModule(input: ModuleInput) -> ModuleOutput } // MARK: - Enums public enum ViewAppearState { case didLoad, didAppear, willAppear, didDisappear, willDisappear, didDeinit } public enum ModelState: Equatable { case normal // Content is available and not loading any content case empty // No Content is available case error(NSError) // Got an error case networkActivity // Network activity case unknown // State is not defiend yet // for implementation of Equatable var hash: Int { switch self { case .normal: return 0 case .empty: return 1 case .error: return 2 case .networkActivity: return 3 case .unknown: return 4 } } } // MARK: - ModelState Equatable public func == (lhs: ModelState, rhs: ModelState) -> Bool { return lhs.hash == rhs.hash } // MARK: - RxViewModelStateProtocol protocol RxViewModelStateProtocol { var state: Observable<ModelState> { get } func isRequestInProcess() -> Bool func change(state: ModelState) func show(error: NSError) } // MARK: - RxViewModelState class RxViewModelState: RxViewModelStateProtocol { var state: Observable<ModelState> { return _state.asObservable() } private var _state = BehaviorRelay<ModelState>(value: .unknown) func isRequestInProcess() -> Bool { return _state.value == .networkActivity } func change(state: ModelState) { _state.accept(state) } func show(error: NSError) { _state.accept(.error(error)) } }
mit
6a352a78dafd16564149dcdb146fe997
19.041667
77
0.705301
4.076271
false
false
false
false
rafaelcpalmeida/UFP-iOS
UFP/UFP/Carthage/Checkouts/SwiftyJSON/Example/Example/ViewController.swift
9
3340
// ViewController.swift // // Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SwiftyJSON class ViewController: UITableViewController { var json: JSON = JSON.null // MARK: - Table view data source override func viewDidLoad() { title = "SwiftyJSON(\(json.type))" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.json.type { case .array, .dictionary: return self.json.count default: return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JSONCell", for: indexPath) as UITableViewCell let row = indexPath.row switch self.json.type { case .array: cell.textLabel?.text = "\(row)" cell.detailTextLabel?.text = self.json.arrayValue.description case .dictionary: let key: Any = Array(self.json.dictionaryValue.keys)[row] let value = self.json[key as! String] cell.textLabel?.text = "\(key)" cell.detailTextLabel?.text = value.description default: cell.textLabel?.text = "" cell.detailTextLabel?.text = self.json.description } return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any!) { var nextController: UIViewController? nextController = segue.destination if let indexPath = self.tableView.indexPathForSelectedRow { let row = indexPath.row var nextJson: JSON = JSON.null switch self.json.type { case .array: nextJson = self.json[row] case .dictionary where row < self.json.dictionaryValue.count: let key = Array(self.json.dictionaryValue.keys)[row] if let value = self.json.dictionary?[key] { nextJson = value } default: print("") } (nextController as! ViewController).json = nextJson print(nextJson) } } }
mit
bf58c201548e4c7d8a08b494f8b7c2bb
35.304348
111
0.644311
4.764622
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift
1
7064
import XCTest import GRDB class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { func testTransactionCompletions() throws { // implicit transaction try assertTransaction(start: "", end: "CREATE TABLE t(a)", isNotifiedAs: .commit) // explicit commit try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) // explicit rollback try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "SAVEPOINT test", end: "ROLLBACK", isNotifiedAs: .rollback) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback) } func assertTransaction(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws { try assertTransaction_registerBefore(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion) try assertTransaction_registerBetween(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion) } func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws { class Witness { } let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in var commitCount = 0 weak var deallocationWitness: Witness? = nil do { let witness = Witness() deallocationWitness = witness // Usage test: single closure (the onCommit one) db.afterNextTransaction { _ in // use witness withExtendedLifetime(witness, { }) commitCount += 1 } } XCTAssertNotNil(deallocationWitness) XCTAssertEqual(commitCount, 0) try db.execute(sql: startSQL) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) try db.inTransaction { try db.execute(sql: "DROP TABLE IF EXISTS t; CREATE TABLE t(a); ") return .commit } switch expectedCompletion { case .commit: XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") case .rollback: XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") } } } func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws { class Witness { } let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in var commitCount = 0 var rollbackCount = 0 try db.execute(sql: startSQL) weak var deallocationWitness: Witness? = nil do { let witness = Witness() deallocationWitness = witness // Usage test: both closure db.afterNextTransaction( onCommit: { _ in // use witness withExtendedLifetime(witness, { }) commitCount += 1 }, onRollback: { _ in // use witness withExtendedLifetime(witness, { }) rollbackCount += 1 }) } XCTAssertNotNil(deallocationWitness) XCTAssertEqual(commitCount, 0) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) try db.inTransaction { try db.execute(sql: "DROP TABLE IF EXISTS t; CREATE TABLE t(a); ") return .commit } switch expectedCompletion { case .commit: XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") case .rollback: XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") } } } }
mit
a75ff8f30465055a12127559a5cca28b
50.562044
167
0.600793
4.967651
false
true
false
false
SmallwolfiOS/ChangingToSwift
ChangingToSwift02/ChangingToSwift02/AVVedioViewController.swift
1
4664
// // AVVedioViewController.swift // ChangingToSwift02 // // Created by Jason on 16/6/7. // Copyright © 2016年 Jason. All rights reserved. // import UIKit import AVFoundation class AVVedioViewController: UIViewController { @IBOutlet weak var vedioBtn: UIButton! @IBOutlet weak var cameraBtn: UIButton! @IBOutlet weak var imageView: UIImageView! var session : AVCaptureSession! var captureInput : AVCaptureDeviceInput! var imageOutput : AVCaptureStillImageOutput! var vedioLayer : AVCaptureVideoPreviewLayer! override func viewDidLoad() { super.viewDidLoad() initCapture() self.cameraBtn.hidden = true self.vedioBtn.hidden = false // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:初始化摄像头 func initCapture() { //1. 创建媒体管理会话 session = AVCaptureSession.init() //判断分辨率是否支持1280*720,支持就设置为1280*720 if session.canSetSessionPreset(AVCaptureSessionPreset1280x720) { session.sessionPreset = AVCaptureSessionPreset1280x720 } //2. 获取后置摄像头设备对象 var captureError : NSError? var device :AVCaptureDevice! let cameras = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for camera in cameras { if camera.position == AVCaptureDevicePosition.Back {//取得后置摄像头 device = camera as! AVCaptureDevice } } if device == nil { print("取得后置摄像头错误") return } //3. 创建输入数据对象 do { captureInput = try AVCaptureDeviceInput.init(device: device) } catch let error as NSError { captureError = error captureInput = nil // Nil cannot be assigned to type AVCaptureDeviceInput if captureError != nil { // new if print("error: \(captureError?.localizedDescription)") } } //4. 创建输出数据对象 imageOutput = AVCaptureStillImageOutput.init() let setting = [ AVVideoCodecKey : AVVideoCodecJPEG ] imageOutput.outputSettings = setting //5. 添加输入数据对象和输出对象到会话中 if session.canAddInput(captureInput) { session.addInput(captureInput) } if session.canAddOutput(imageOutput) { session.addOutput(imageOutput) } //6. 创建视频预览图层 vedioLayer = AVCaptureVideoPreviewLayer.init(session: session) self.view.layer.masksToBounds = true vedioLayer.frame = self.view.bounds vedioLayer.videoGravity = AVLayerVideoGravityResizeAspectFill //插入图层在拍照按钮的下方 self.view.layer .insertSublayer(vedioLayer, below: self.cameraBtn.layer) } @IBAction func cameraBtnClick(sender: UIButton) { //根据设备输出获得连接 let connection = (imageOutput?.connectionWithMediaType(AVMediaTypeVideo))! as AVCaptureConnection //通过连接获得设备输出的数据 print("about to request a capture from: \(imageOutput)") imageOutput.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: { (imageSampleBuffer : CMSampleBuffer!, error:NSError!)-> Void in print("哈哈哈哈") let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer) let image = UIImage.init(data: imageData) UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil) self.vedioLayer.hidden = true self.cameraBtn.hidden = true self.vedioBtn.hidden = false self.session.stopRunning() }) } @IBAction func vedioBtnClick(sender: UIButton) { self.vedioLayer.hidden = false; self.cameraBtn.hidden = false; self.vedioBtn.hidden = true; session.startRunning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c8ee8739661a699f3e732eba260428b7
33.81746
166
0.638249
5.036739
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/Controller/DongtaiTableViewController.swift
1
10275
// // DongtaiTableViewController.swift // News // // Created by 杨蒙 on 2018/1/3. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import SVProgressHUD class DongtaiTableViewController: UITableViewController { /// 刷新的指示器 var maxCursor = 0 var wendaCursor = "" /// 点击了 用户名 var didSelectHeaderUserID: ((_ uid: Int)->())? /// 点击了 话题 var didSelectHeaderTopicID: ((_ cid: Int)->())? /// 当前的 toptab 的类型 var currentTopTabType: TopTabType = .dongtai { didSet { switch currentTopTabType { // 如果已经显示过了,就不再刷新数据了 case .dongtai: // 动态 if !isDongtaisShown { isDongtaisShown = true // 设置 footer setupFooter(tableView, completionHandler: { self.dongtais += $0 self.tableView.reloadData() }) tableView.mj_footer.beginRefreshing() } case .article: // 文章 if !isArticlesShown { isArticlesShown = true // 设置 footer setupFooter(tableView, completionHandler: { self.articles += $0 self.tableView.reloadData() }) tableView.mj_footer.beginRefreshing() } case .video: // 视频 if !isVideosShown { isVideosShown = true // 设置 footer setupFooter(tableView, completionHandler: { self.videos += $0 self.tableView.reloadData() }) tableView.mj_footer.beginRefreshing() } case .wenda: // 问答 if !isWendasShown { isWendasShown = true tableView.ym_registerCell(cell: UserDetailWendaCell.self) tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in // 获取用户详情的问答列表更多数据 NetworkTool.loadUserDetailLoadMoreWendaList(userId: self!.userId, cursor: self!.wendaCursor, completionHandler: { if self!.tableView.mj_footer.isRefreshing { self!.tableView.mj_footer.endRefreshing() } self!.tableView.mj_footer.pullingPercent = 0.0 if $1.count == 0 { self!.tableView.mj_footer.endRefreshingWithNoMoreData() SVProgressHUD.showInfo(withStatus: "没有更多数据啦!") return } self!.wendaCursor = $0 self!.wendas += $1 self!.tableView.reloadData() }) }) } tableView.mj_footer.beginRefreshing() case .iesVideo: // 小视频 if !isIesVideosShown { isIesVideosShown = true // 设置 footer setupFooter(tableView, completionHandler: { self.iesVideos += $0 self.tableView.reloadData() }) tableView.mj_footer.beginRefreshing() } } } } /// 用户编号 var userId = 0 /// 设置 footer private func setupFooter(_ tableView: UITableView, completionHandler:@escaping ((_ datas: [UserDetailDongtai])->())) { tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in NetworkTool.loadUserDetailDongtaiList(userId: self!.userId, maxCursor: self!.maxCursor, completionHandler: { if tableView.mj_footer.isRefreshing { tableView.mj_footer.endRefreshing() } tableView.mj_footer.pullingPercent = 0.0 if $1.count == 0 { tableView.mj_footer.endRefreshingWithNoMoreData() SVProgressHUD.showInfo(withStatus: "没有更多数据啦!") return } self!.maxCursor = $0 completionHandler($1) }) }) } /// 动态数据 数组 var dongtais = [UserDetailDongtai]() var articles = [UserDetailDongtai]() var videos = [UserDetailDongtai]() var wendas = [UserDetailWenda]() var iesVideos = [UserDetailDongtai]() /// 记录当前的数据是否刷新过 var isDongtaisShown = false var isArticlesShown = false var isVideosShown = false var isWendasShown = false var isIesVideosShown = false override func viewDidLoad() { super.viewDidLoad() SVProgressHUD.configuration() if isIPhoneX { tableView.contentInset = UIEdgeInsetsMake(0, 0, 34, 0) } tableView.theme_backgroundColor = "colors.cellBackgroundColor" tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.tableFooterView = UIView() tableView.separatorStyle = .none tableView.bounces = false tableView.bouncesZoom = false if currentTopTabType == .wenda { tableView.ym_registerCell(cell: UserDetailWendaCell.self) } else { tableView.ym_registerCell(cell: UserDetailDongTaiCell.self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch currentTopTabType { case .dongtai: // 动态 return dongtais.count case .article: // 文章 return articles.count case .video: // 视频 return videos.count case .wenda: // 问答 return wendas.count case .iesVideo: // 小视频 return iesVideos.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch currentTopTabType { case .dongtai: // 动态 return cellFor(tableView, at: indexPath, with: dongtais) case .article: // 文章 return cellFor(tableView, at: indexPath, with: articles) case .video: // 视频 return cellFor(tableView, at: indexPath, with: videos) case .wenda: // 问答 let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDetailWendaCell cell.wenda = wendas[indexPath.row] return cell case .iesVideo: // 小视频 return cellFor(tableView, at: indexPath, with: iesVideos) } } /// 设置 cell private func cellFor(_ tableView: UITableView, at indexPath: IndexPath, with datas: [UserDetailDongtai]) -> UserDetailDongTaiCell { let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDetailDongTaiCell cell.dongtai = datas[indexPath.row] cell.didSelectDongtaiUserName = { [weak self] in self!.didSelectHeaderUserID?($0) } cell.didSelectDongtaiTopic = { [weak self] in self!.didSelectHeaderTopicID?($0) } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch currentTopTabType { case .dongtai: // 动态 return dongtais[indexPath.row].cellHeight case .article: // 文章 return articles[indexPath.row].cellHeight case .video: // 视频 return videos[indexPath.row].cellHeight case .wenda: // 问答 let wenda = wendas[indexPath.row] return wenda.cellHeight case .iesVideo: // 小视频 return iesVideos[indexPath.row].cellHeight } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch currentTopTabType { case .dongtai: // 动态 pushNextViewController(dongtais[indexPath.row]) case .article: // 文章 pushNextViewController(articles[indexPath.row]) case .video: // 视频 pushNextViewController(videos[indexPath.row]) case .iesVideo: // 小视频 pushNextViewController(iesVideos[indexPath.row]) case .wenda: // 问答 SVProgressHUD.showInfo(withStatus: "sslocal 参数未知,无法获取数据!") } } /// 跳转到下一个控制器 private func pushNextViewController(_ dongtai: UserDetailDongtai) { switch dongtai.item_type { case .commentOrQuoteOthers, .commentOrQuoteContent, .forwardArticle, .postContent: let dongtaiDetailVC = DongtaiDetailViewController() dongtaiDetailVC.dongtai = dongtai navigationController?.pushViewController(dongtaiDetailVC, animated: true) case .postVideo, .postVideoOrArticle, .postContentAndVideo: SVProgressHUD.showInfo(withStatus: "跳转到视频控制器") case .proposeQuestion: let wendaVC = WendaViewController() wendaVC.qid = dongtai.id wendaVC.enterForm = .dongtai navigationController?.pushViewController(wendaVC, animated: true) case .answerQuestion: SVProgressHUD.showInfo(withStatus: "sslocal 参数未知,无法获取数据!") case .postSmallVideo: SVProgressHUD.showInfo(withStatus: "请点击底部小视频 tabbar") } } override func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y if offsetY <= 0 { tableView.contentOffset = CGPoint(x: 0, y: 0) } } }
mit
e47c1fd02f2f671f0798beade1d7c88b
39.220408
138
0.561193
5.022426
false
false
false
false
PumpMagic/ostrich
gbsplayer/gbsplayer/Source/Views/CustomButton.swift
1
2785
// // CustomButton.swift // gbsplayer // // Created by Owner on 2/3/17. // Copyright © 2017 conwarez. All rights reserved. // import Cocoa /// Something that can capture user events for processing by a delegate. protocol GeneratesUIEvents { func setEventHandler(callback: @escaping (NSView) -> Void) } protocol Pushable { func getPushedImage() -> NSImage func getUnpushedImage() -> NSImage func onMouseDown() } /// A pressable button whose appearance mimics that of a Game Boy Classic's. /// Dispatches button press events to delegate registered through GeneratesUIEvents's function, if any. class CustomButton: NSView, GeneratesUIEvents { @IBInspectable var unpushedImage: NSImage? = nil @IBInspectable var pushedImage: NSImage? = nil private var currentImage: NSImage? = nil private var eventHandler: ((NSView) -> Void)? = nil /// What does the button call when it's been pressed? func setEventHandler(callback: @escaping (NSView) -> Void) { self.eventHandler = callback } /// Update our image. private func updateImage(selected: Bool) { if selected { currentImage = pushedImage } else { currentImage = unpushedImage } self.needsDisplay = true } /// Take in a point inside the window we're in, and return whether or not that point /// is part of us. private func contains(point: NSPoint) -> Bool { let relativeToSelf = self.convert(point, from: nil) if relativeToSelf.x >= 0 && relativeToSelf.x < self.bounds.width && relativeToSelf.y >= 0 && relativeToSelf.y < self.bounds.height { return true } return false } override func mouseDown(with event: NSEvent) { updateImage(selected: true) } override func mouseDragged(with event: NSEvent) { let cursorIsInUs = self.contains(point: event.locationInWindow) updateImage(selected: cursorIsInUs) } override func mouseUp(with event: NSEvent) { updateImage(selected: false) /// If the mouse was released while in our view, treat the event as a press of us if self.contains(point: event.locationInWindow) { eventHandler?(self) } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { super.init(coder: coder) } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. currentImage?.draw(in: dirtyRect) } override func viewDidMoveToWindow() { updateImage(selected: false) } }
mit
72b87935db1e2d3c8d01ac25485dc31e
27.121212
103
0.623922
4.594059
false
false
false
false
DANaini13/stanford-IOS-Assignments-Calculator-CS193P
Assn3/Clacuator/Calculator/DescriptionGenerator.swift
2
5051
// // DescriptionGenerator.swift // Clacuator // // Created by zeyong shan on 10/6/17. // Copyright © 2017 zeyong shan. All rights reserved. import Foundation /** DescriptionGenerator the descriptionGenerator is used to add, modify the descriptioons for calculator brain. */ public struct DescriptionGenerator { /** This function is used to replace the current Description with the argument that passed in. Workd with the case Operation.constant and case Operation.generateNumberFunction - parameter currentNum: store the constant that will replace the current Description. Ex. pi, 790 - Author: Zeyong Shan - Important: This function might modify the context of the description. - Version: 0.1 */ public mutating func addConstant(currentNum: String) { context = currentNum } /** This function is used to add a unary operation to description. It will replace the current description with the result description - parameters: - operation: The variable that store the function name as a string. - prefix: To declare that the function should be prefixed or postfixed. - Author: Zeyong Shan - Important: This function might modify the context of the description. - Version: 0.1 */ public mutating func addUnaryOperationToCurrentDescription(operation: String, prefix: Bool) { if context == nil { context = "0" } if prefix { context = operation + "(" + context! + ")" }else { context = "(" + context! + ")" + operation } } /** This function is used to add a binary operation to description. It will sotre the first number to take part in the operation later, then waiting for the second number to finish the operation. - parameters: - operation: The variable that store the function name as a string. - Author: Zeyong Shan - Important: This function might modify the context of the description. - Version: 0.1 */ public mutating func addBinaryOperation(operation: String) { guard pendingBinaryOperation == nil else { return } if context == nil{ context = "0" } pendingBinaryOperation = PendingBinaryOperation(operatorName: operation, firstOperand: context!) context = nil } /** This function is used to perform the binary operation that already stored by the function func addBinaryOperation(operation: Stirng, firstNum: String, replace: Bool) - Author: Zeyong Shan - Important: This function might modify the context of the description. - Version: 0.1 */ public mutating func performBinaryOperation() { guard pendingBinaryOperation != nil else { return } if context == nil { context = "0" } context = pendingBinaryOperation!.generationString(secondOperand: context!) pendingBinaryOperation = nil } /** The computed read-only variable that return the current description. the return value depends on the situation of pendingBinaryOperation and the current context. It would return the context with "..." at the end if there is binary operation are pending, return "" if no description. - Author: Zeyong Shan - Version: 0.1 */ var description: String { let returnValue:String if let pending = pendingBinaryOperation { if context != nil { returnValue = pending.contextBeforeGenerating + context! + "..." } else { returnValue = pending.contextBeforeGenerating + "..." } }else { if context != nil { returnValue = context! + "=" } else { returnValue = "" } } return returnValue } var resultIsPending: Bool { return pendingBinaryOperation != nil } /** The variable that store the main context the the description. */ private var context: String? /** The variable that store the information of the first half binary operation. */ private var pendingBinaryOperation: PendingBinaryOperation? /** TypeName: PendingBinaryOperation The data type that store the fist half the a binary operation */ private struct PendingBinaryOperation { let operatorName: String let firstOperand: String var contextBeforeGenerating: String { return firstOperand + operatorName } public func generationString(secondOperand: String) -> String { return firstOperand + operatorName + secondOperand } } }
mpl-2.0
9cba55046ebfbb8da3cbcff6f2c036fe
28.022989
104
0.604158
5.238589
false
false
false
false
BiuroCo/mega
examples/Swift/MEGA/MEGA/Contacts/ContactsTableViewController.swift
1
4411
/** * @file ContactsTableViewController.swift * @brief View controller that show your contacts * * (c) 2013-2015 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ import UIKit class ContactsTableViewController: UITableViewController, MEGARequestDelegate { var users : MEGAUserList! var filterUsers = [MEGAUser]() let megaapi : MEGASdk! = (UIApplication.sharedApplication().delegate as! AppDelegate).megaapi override func viewDidLoad() { super.viewDidLoad() users = megaapi.contacts() for var i = 0 ; i < users.size.integerValue ; i++ { let user = users.userAtIndex(i) if user.access == MEGAUserVisibility.Visible { filterUsers.append(user) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filterUsers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as! ContactTableViewCell let user = filterUsers[indexPath.row] cell.nameLabel.text = user.email let avatarFilePath = Helper.pathForUser(user, path: NSSearchPathDirectory.CachesDirectory, directory: "thumbs") let fileExists = NSFileManager.defaultManager().fileExistsAtPath(avatarFilePath) if fileExists { cell.avatarImageView.image = UIImage(named: avatarFilePath) cell.avatarImageView.layer.cornerRadius = cell.avatarImageView.frame.size.width/2 cell.avatarImageView.layer.masksToBounds = true } else { megaapi.getAvatarUser(user, destinationFilePath: avatarFilePath, delegate: self) } let numFilesShares = megaapi.inSharesForUser(user).size.integerValue if numFilesShares == 0 { cell.shareLabel.text = "No folders shared" } else if numFilesShares == 1 { cell.shareLabel.text = "\(numFilesShares) folder shared" } else { cell.shareLabel.text = "\(numFilesShares) folders shared" } return cell } // MARK: - MEGA Request delegate func onRequestFinish(api: MEGASdk!, request: MEGARequest!, error: MEGAError!) { if error.type != MEGAErrorType.ApiOk { return } switch request.type { case MEGARequestType.GetAttrUser: for tableViewCell in tableView.visibleCells as! [ContactTableViewCell] { if request?.email == tableViewCell.nameLabel.text { let filename = request.email let avatarURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0] let avatarFilePath = avatarURL.URLByAppendingPathComponent("thumbs").URLByAppendingPathComponent(filename) let fileExists = NSFileManager.defaultManager().fileExistsAtPath(avatarFilePath.path!) if fileExists { tableViewCell.avatarImageView.image = UIImage(named: avatarFilePath.path!) tableViewCell.avatarImageView.layer.cornerRadius = tableViewCell.avatarImageView.frame.size.width/2 tableViewCell.avatarImageView.layer.masksToBounds = true } } } default: break } } }
bsd-2-clause
8d032947f9fe1ec22b5933cc03e90c4e
36.067227
132
0.645432
5.11124
false
false
false
false
timfuqua/Bourgeoisie
Bourgeoisie/Pods/Buckets/Source/Matrix.swift
1
11313
// // Matrix.swift // Buckets // // Created by Mauricio Santos on 4/11/15. // Copyright (c) 2015 Mauricio Santos. All rights reserved. // import Foundation import Accelerate /// A Matrix is a fixed size generic 2D collection. /// You can set and get elements using subscript notation. Example: /// `matrix[row, column] = value` /// /// This collection also provides linear algebra functions and operators such as /// `inverse()`, `+` and `*` using Apple's Accelerate framework. Please note that /// these operations are designed to work exclusively with `Double` matrices. /// Check the `Functions` section for more information. /// /// Conforms to `SequenceType`, `MutableCollectionType`, /// `ArrayLiteralConvertible`, `Printable` and `DebugPrintable`. public struct Matrix<T> { // MARK: Creating a Matrix /// Constructs a new matrix with all positions set to the specified value. public init(rows: Int, columns: Int, repeatedValue: T) { if rows <= 0 { fatalError("Can't create matrix. Invalid number of rows.") } if columns <= 0 { fatalError("Can't create matrix. Invalid number of columns") } self.rows = rows self.columns = columns grid = Array(count: rows * columns, repeatedValue: repeatedValue) } /// Constructs a new matrix using a 1D array in row-major order. /// /// `Matrix[i,j] == grid[i*columns + j]` public init(rows: Int, columns: Int, grid: [T]) { if grid.count != rows*columns { fatalError("Can't create matrix. grid.count must equal rows*columns") } self.rows = rows self.columns = columns self.grid = grid } /// Constructs a new matrix using a 2D array. /// All columns must be the same size, otherwise an error is triggered. public init(_ rowsArray: [[T]]) { let rows = rowsArray.count if rows <= 0 { fatalError("Can't create an empty matrix.") } if rowsArray[0].count <= 0 { fatalError("Can't create a matrix column with no elements.") } let columns = rowsArray[0].count for subArray in rowsArray { if subArray.count != columns { fatalError("Can't create a matrix with different sixzed columns") } } var grid = Array<T>() grid.reserveCapacity(rows*columns) for i in 0..<rows { for j in 0..<columns { grid.append(rowsArray[i][j]) } } self.init(rows: rows, columns: columns, grid: grid) } // MARK: Querying a Matrix /// The number of rows in the matrix. public let rows: Int /// The number of columns in the matrix. public let columns: Int /// The one-dimensional array backing the matrix in row-major order. /// /// `Matrix[i,j] == grid[i*columns + j]` public private(set) var grid: [T] /// Returns the transpose of the matrix. public var transpose: Matrix<T> { var result = Matrix(rows: columns, columns: rows, repeatedValue: self[0,0]) for i in 0..<rows { for j in 0..<columns { result[j,i] = self[i,j] } } return result } // MARK: Getting and Setting elements // Provides random access for getting and setting elements using square bracket notation. // The first argument is the row number. // The first argument is the column number. public subscript(row: Int, column: Int) -> T { get { if !indexIsValidForRow(row, column: column) { fatalError("Index out of range") } return grid[(row * columns) + column] } set { if !indexIsValidForRow(row, column: column) { fatalError("Index out of range") } grid[(row * columns) + column] = newValue } } // MARK: Private Properties and Helper Methods private func indexIsValidForRow(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } } // MARK: - extension Matrix: SequenceType { // MARK: SequenceType Protocol Conformance /// Provides for-in loop functionality. /// Returns the elements in row-major order. /// /// - returns: A generator over the elements. public func generate() -> AnyGenerator<T> { return anyGenerator(IndexingGenerator(self)) } } extension Matrix: MutableCollectionType { // MARK: MutableCollectionType Protocol Conformance public typealias MatrixIndex = Int /// Always zero, which is the index of the first element when non-empty. public var startIndex : MatrixIndex { return 0 } /// Always `rows*columns`, which is the successor of the last valid subscript argument. public var endIndex : MatrixIndex { return rows*columns } /// Provides random access to elements using the matrix back-end array coordinate /// in row-major order. /// Matrix[row, column] is preferred. public subscript(position: MatrixIndex) -> T { get { return self[position/columns, position % columns] } set { self[position/columns, position % columns] = newValue } } } extension Matrix: ArrayLiteralConvertible { // MARK: ArrayLiteralConvertible Protocol Conformance /// Constructs a matrix using an array literal. public init(arrayLiteral elements: Array<T>...) { self.init(elements) } } extension Matrix: CustomStringConvertible { // MARK: CustomStringConvertible Protocol Conformance /// A string containing a suitable textual /// representation of the matrix. public var description: String { var result = "[" for i in 0..<rows { if i != 0 { result += ", " } let start = i*columns let end = start + columns result += "[" + grid[start..<end].map {"\($0)"}.joinWithSeparator(", ") + "]" } result += "]" return result } } // MARK: Matrix Standard Operators /// Returns `true` if and only if the matrices contain the same elements /// at the same coordinates. /// The underlying elements must conform to the `Equatable` protocol. public func ==<T: Equatable>(lhs: Matrix<T>, rhs: Matrix<T>) -> Bool { return lhs.columns == rhs.columns && lhs.rows == rhs.rows && lhs.grid == rhs.grid } public func !=<T: Equatable>(lhs: Matrix<T>, rhs: Matrix<T>) -> Bool { return !(lhs == rhs) } // MARK: Matrix Linear Algebra Operations // Inversion /// Returns the inverse of the given matrix or nil if it doesn't exist. /// If the argument is a non-square matrix an error is triggered. public func inverse(matrix: Matrix<Double>) -> Matrix<Double>? { if matrix.columns != matrix.rows { fatalError("Can't invert a non-square matrix.") } var invMatrix = matrix var N = __CLPK_integer(sqrt(Double(invMatrix.grid.count))) var pivots = [__CLPK_integer](count: Int(N), repeatedValue: 0) var workspace = [Double](count: Int(N), repeatedValue: 0.0) var error : __CLPK_integer = 0 // LU factorization dgetrf_(&N, &N, &invMatrix.grid, &N, &pivots, &error) if error != 0 { return nil } // Matrix inversion dgetri_(&N, &invMatrix.grid, &N, &pivots, &workspace, &N, &error) if error != 0 { return nil } return invMatrix } // Addition /// Performs matrix and matrix addition. public func +(lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { if lhs.rows != rhs.rows || lhs.columns != rhs.columns { fatalError("Impossible to add different size matrices") } var result = rhs cblas_daxpy(Int32(lhs.grid.count), 1.0, lhs.grid, 1, &(result.grid), 1) return result } /// Performs matrix and matrix addition. public func +=(inout lhs: Matrix<Double>, rhs: Matrix<Double>) { lhs.grid = (lhs + rhs).grid } /// Performs matrix and scalar addition. public func +(lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { let scalar = rhs var result = Matrix<Double>(rows: lhs.rows, columns: lhs.columns, repeatedValue: scalar) cblas_daxpy(Int32(lhs.grid.count), 1, lhs.grid, 1, &(result.grid), 1) return result } /// Performs scalar and matrix addition. public func +(lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> { return rhs + lhs } /// Performs matrix and scalar addition. public func +=(inout lhs: Matrix<Double>, rhs: Double) { lhs.grid = (lhs + rhs).grid } // Subtraction /// Performs matrix and matrix subtraction. public func -(lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { if lhs.rows != rhs.rows || lhs.columns != rhs.columns { fatalError("Impossible to substract different size matrices.") } var result = lhs cblas_daxpy(Int32(lhs.grid.count), -1.0, rhs.grid, 1, &(result.grid), 1) return result } /// Performs matrix and matrix subtraction. public func -=(inout lhs: Matrix<Double>, rhs: Matrix<Double>) { lhs.grid = (lhs - rhs).grid } /// Performs matrix and scalar subtraction. public func -(lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { return lhs + (-rhs) } /// Performs matrix and scalar subtraction. public func -=(inout lhs: Matrix<Double>, rhs: Double) { lhs.grid = (lhs - rhs).grid } // Negation /// Negates all the values in a matrix. public prefix func -(m: Matrix<Double>) -> Matrix<Double> { var result = m cblas_dscal(Int32(m.grid.count), -1.0, &(result.grid), 1) return result } // Multiplication /// Performs matrix and matrix multiplication. /// The first argument's number of columns must match the second argument's number of rows, /// otherwise an error is triggered. public func *(lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { if lhs.columns != rhs.rows { fatalError("Matrix product is undefined: first.columns != second.rows") } var result = Matrix<Double>(rows: lhs.rows, columns: rhs.columns, repeatedValue: 0.0) cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(lhs.rows), Int32(rhs.columns), Int32(lhs.columns), 1.0, lhs.grid, Int32(lhs.columns), rhs.grid, Int32(rhs.columns), 0.0, &(result.grid), Int32(result.columns)) return result } /// Performs matrix and scalar multiplication. public func *(lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { var result = lhs cblas_dscal(Int32(lhs.grid.count), rhs, &(result.grid), 1) return result } /// Performs scalar and matrix multiplication. public func *(lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> { return rhs*lhs } /// Performs matrix and scalar multiplication. public func *=(inout lhs: Matrix<Double>, rhs: Double) { lhs.grid = (lhs*rhs).grid } // Division /// Performs matrix and scalar division. public func /(lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { return lhs * (1/rhs) } /// Performs matrix and scalar division. public func /=(inout lhs: Matrix<Double>, rhs: Double) { lhs.grid = (lhs/rhs).grid }
mit
eaed59bd7d569f5b066b1dcf22fd5b36
30.254144
95
0.619111
4.066499
false
false
false
false
dukemedicine/Duke-Medicine-Mobile-Companion
Classes/Utilities/MCSettings.swift
1
4514
// // MCSettings.swift // Duke Medicine Mobile Companion // // Created by Ricky Bloomfield on 6/12/14. // Copyright (c) 2014 Duke Medicine // // 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 /** Runs the function below to register all the default values in Settings on the first run */ func registerDefaultsFromSettingsBundle() { USER_DEFAULTS().registerDefaults(defaultsFromPlistNamed("Root")) USER_DEFAULTS().synchronize() } /** Iterates through the Settings plist to find default values, setting them if needed */ func defaultsFromPlistNamed(plistName: String) -> NSDictionary { let settingsBundlePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("InAppSettings.bundle") let finalPath = settingsBundlePath.stringByAppendingPathComponent("\(plistName).plist") let settingsDict: NSDictionary = NSDictionary(contentsOfFile:finalPath)! let prefSpecifierArray = settingsDict.objectForKey("PreferenceSpecifiers") as Array<NSDictionary> var defaults = NSMutableDictionary() for prefSpecification in prefSpecifierArray { let key: String? = prefSpecification.objectForKey("Key") as? String let value: AnyObject? = prefSpecification.objectForKey("DefaultValue") if (key != nil && value != nil) { defaults.setObject(value!, forKey: key!) } let type: String? = prefSpecification.objectForKey("Type") as? String let viewControllerClass: String? = prefSpecification.objectForKey("IASKViewControllerClass") as? String if (type == "PSChildPaneSpecifier" && viewControllerClass == nil) { let file: String? = prefSpecification.objectForKey("File") as? String defaults.addEntriesFromDictionary(defaultsFromPlistNamed(file!)) } } return defaults } /** Accepts the name of the *.plist file, the key of the preference specifier and the value corresponding to the title in the PSMultiValueSpecifier. 'value' is only used if it's a PSMultiValueSpecifier. If 'value' is 'nil' it will return the 'Title' for the key. */ func titleForValueInPlistNamed(plistName: String, key: String, value: String!) -> String { let settingsBundlePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("InAppSettings.bundle") let finalPath = settingsBundlePath.stringByAppendingPathComponent("\(plistName).plist") let settingsDict: NSDictionary = NSDictionary(contentsOfFile:finalPath)! let prefSpecifierArray = settingsDict.objectForKey("PreferenceSpecifiers") as Array<NSDictionary> for prefSpecification in prefSpecifierArray { let plistKey: String? = prefSpecification.objectForKey("Key") as? String if key == plistKey { // If 'value' is present, this means it's a PSMultiValueSpecifier if (value != nil) { let titles: NSArray = prefSpecification.objectForKey("Titles") as NSArray let values: NSArray = prefSpecification.objectForKey("Values") as NSArray let index = values.indexOfObject(value) if index > -1 { return titles.objectAtIndex(index) as String } } // Otherwise, we just need to get the regular title for the key else { return prefSpecification.objectForKey("Title") as String } } } return "Title" }
mit
ad96add2b1b04d4321656b3bef0bed38
46.03125
260
0.704253
4.858988
false
false
false
false
frajaona/LiFXSwiftKit
Pods/socks/Sources/SocksCore/Address.swift
1
6736
// // Address.swift // Socks // // Created by Matthias Kreileder on 3/20/16. // // #if os(Linux) import Glibc #else import Darwin #endif // // Brief: Specify an internet address // // Example of the (assumed) main use case: // assign a string to the hostname e.g. google.com // and specify the Port via an integer // // hostname - can be set to a string that denotes // a hostname e.g. "localhost" or // an IPv4 address e.g. "127.0.0.1" or // an IPv6 address e.g. "::1" // // port - see comments for Port enum // // addressFamily - for specifying a preference for IP version // public struct InternetAddress { public let hostname: String public let port: Port public let addressFamily: AddressFamily public init(hostname: String, port: Port, addressFamily: AddressFamily = .unspecified) { self.hostname = hostname self.port = port self.addressFamily = addressFamily } static public func localhost(port: UInt16, ipVersion: AddressFamily = .inet) -> InternetAddress { let hostname: String let ipV: AddressFamily switch ipVersion { case .inet6: hostname = "::1" ipV = .inet6 default: hostname = "127.0.0.1" ipV = .inet } return InternetAddress(hostname: hostname, port: port, addressFamily: ipV) } static public func any(port: UInt16, ipVersion: AddressFamily = .inet) -> InternetAddress { let hostname: String let ipV: AddressFamily switch ipVersion { case .inet6: hostname = "::" ipV = .inet6 default: hostname = "0.0.0.0" ipV = .inet } return InternetAddress(hostname: hostname, port: port, addressFamily: ipV) } } extension InternetAddress { func resolve(with config: inout SocketConfig) throws -> ResolvedInternetAddress { return try Resolver().resolve(self, with: &config) } } public class ResolvedInternetAddress { let _raw: UnsafeMutablePointer<sockaddr_storage> var raw: UnsafeMutablePointer<sockaddr> { return UnsafeMutablePointer<sockaddr>(OpaquePointer(_raw)) } /// WARNING: this pointer MUST be +1 allocated, ResolvedInternetAddress /// will make sure of deallocating it later. init(raw: UnsafeMutablePointer<sockaddr_storage>) { self._raw = raw precondition((try! addressFamily()).isConcrete(), "Cannot create ResolvedInternetAddress with a unspecified address family") } var rawLen: socklen_t { switch try! addressFamily() { case .inet: return socklen_t(MemoryLayout<sockaddr_in>.size) case .inet6: return socklen_t(MemoryLayout<sockaddr_in6>.size) default: return 0 } } public var port: UInt16 { let val: UInt16 switch try! addressFamily() { case .inet: val = UnsafePointer<sockaddr_in>(OpaquePointer(_raw)).pointee.sin_port case .inet6: val = UnsafePointer<sockaddr_in6>(OpaquePointer(_raw)).pointee.sin6_port default: fatalError() } return htons(val) } public func addressFamily() throws -> AddressFamily { return try AddressFamily(fromCType: Int32(_raw.pointee.ss_family)) } public func ipString() -> String { guard let family = try? addressFamily() else { return "Invalid family" } let cfamily = family.toCType() let strData: UnsafeMutablePointer<Int8> let maxLen: socklen_t switch family { case .inet: maxLen = socklen_t(INET_ADDRSTRLEN) strData = UnsafeMutablePointer<Int8>.allocate(capacity: Int(maxLen)) var ptr = UnsafeMutablePointer<sockaddr_in>(OpaquePointer(raw)).pointee.sin_addr inet_ntop(cfamily, &ptr, strData, maxLen) case .inet6: maxLen = socklen_t(INET6_ADDRSTRLEN) strData = UnsafeMutablePointer<Int8>.allocate(capacity: Int(maxLen)) var ptr = UnsafeMutablePointer<sockaddr_in6>(OpaquePointer(raw)).pointee.sin6_addr inet_ntop(cfamily, &ptr, strData, maxLen) case .unspecified: fatalError("ResolvedInternetAddress should never be unspecified") } let maybeStr = String(validatingUTF8: strData) strData.deallocate(capacity: Int(maxLen)) guard let str = maybeStr else { return "Invalid ip string" } return str } public func asData() -> [UInt8] { let data = UnsafeMutablePointer<UInt8>(OpaquePointer(_raw)) let maxLen = Int(self.rawLen) let buffer = UnsafeBufferPointer(start: data, count: maxLen) let out = Array(buffer) return out } deinit { self._raw.deinitialize(count: 1) self._raw.deallocate(capacity: 1) } } extension ResolvedInternetAddress: Equatable { } public func ==(lhs: ResolvedInternetAddress, rhs: ResolvedInternetAddress) -> Bool { return lhs.asData() == rhs.asData() } extension ResolvedInternetAddress: CustomStringConvertible { public var description: String { let family: String if let fam = try? self.addressFamily() { family = String(describing: fam) } else { family = "UNRECOGNIZED FAMILY" } return "\(ipString()):\(port) \(family)" } } extension Socket { public func remoteAddress() throws -> ResolvedInternetAddress { var length = socklen_t(MemoryLayout<sockaddr_storage>.size) let addr = UnsafeMutablePointer<sockaddr_storage>.allocate(capacity: 1) let addrSockAddr = UnsafeMutablePointer<sockaddr>(OpaquePointer(addr)) let res = getpeername(descriptor, addrSockAddr, &length) guard res > -1 else { addr.deallocate(capacity: 1) throw SocksError(.remoteAddressResolutionFailed) } let clientAddress = ResolvedInternetAddress(raw: addr) return clientAddress } public func localAddress() throws -> ResolvedInternetAddress { var length = socklen_t(MemoryLayout<sockaddr_storage>.size) let addr = UnsafeMutablePointer<sockaddr_storage>.allocate(capacity: 1) let addrSockAddr = UnsafeMutablePointer<sockaddr>(OpaquePointer(addr)) let res = getsockname(descriptor, addrSockAddr, &length) guard res > -1 else { addr.deallocate(capacity: 1) throw SocksError(.localAddressResolutionFailed) } let clientAddress = ResolvedInternetAddress(raw: addr) return clientAddress } }
apache-2.0
f04b655dc300ea22f8ccc2e47b0e6623
31.858537
132
0.626039
4.425756
false
false
false
false
RoverPlatform/rover-ios
Sources/UI/UIAssembler.swift
1
4098
// // UIAssembler.swift // RoverUI // // Created by Sean Rucker on 2018-05-21. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import SafariServices #if !COCOAPODS import RoverFoundation import RoverData #endif public struct UIAssembler { public var associatedDomains: [String] public var urlSchemes: [String] public var sessionKeepAliveTime: Int public var isLifeCycleTrackingEnabled: Bool public var isVersionTrackingEnabled: Bool public init(associatedDomains: [String] = [], urlSchemes: [String] = [], sessionKeepAliveTime: Int = 30, isLifeCycleTrackingEnabled: Bool = true, isVersionTrackingEnabled: Bool = true) { self.associatedDomains = associatedDomains self.urlSchemes = urlSchemes self.sessionKeepAliveTime = sessionKeepAliveTime self.isLifeCycleTrackingEnabled = isLifeCycleTrackingEnabled self.isVersionTrackingEnabled = isVersionTrackingEnabled } } // MARK: Assembler extension UIAssembler: Assembler { public func assemble(container: Container) { // MARK: Action (openURL) container.register(Action.self, name: "openURL", scope: .transient) { (_, url: URL) in OpenURLAction(url: url) } // MARK: Action (presentView) container.register(Action.self, name: "presentView", scope: .transient) { (_, viewControllerToPresent: UIViewController) in PresentViewAction( viewControllerToPresent: viewControllerToPresent, animated: true ) } // MARK: Action (presentWebsite) container.register(Action.self, name: "presentWebsite", scope: .transient) { (resolver, url: URL) in let viewControllerToPresent = resolver.resolve(UIViewController.self, name: "website", arguments: url)! return resolver.resolve(Action.self, name: "presentView", arguments: viewControllerToPresent)! } // MARK: ImageStore container.register(ImageStore.self) { _ in let session = URLSession(configuration: URLSessionConfiguration.ephemeral) return ImageStoreService(session: session) } // MARK: LifeCycleTracker container.register(LifeCycleTracker.self) { resolver in let eventQueue = resolver.resolve(EventQueue.self)! let sessionController = resolver.resolve(SessionController.self)! return LifeCycleTrackerService(eventQueue: eventQueue, sessionController: sessionController) } // MARK: Router container.register(Router.self) { resolver in let dispatcher = resolver.resolve(Dispatcher.self)! return RouterService(associatedDomains: self.associatedDomains, urlSchemes: self.urlSchemes, dispatcher: dispatcher) } // MARK: SessionController container.register(SessionController.self) { [sessionKeepAliveTime] resolver in let eventQueue = resolver.resolve(EventQueue.self)! return SessionControllerService(eventQueue: eventQueue, keepAliveTime: sessionKeepAliveTime) } // MARK: UIViewController (website) container.register(UIViewController.self, name: "website", scope: .transient) { (_, url: URL) in SFSafariViewController(url: url) } // MARK: VersionTracker container.register(VersionTracker.self) { resolver in VersionTrackerService( bundle: Bundle.main, eventQueue: resolver.resolve(EventQueue.self)!, userDefaults: UserDefaults.standard ) } } public func containerDidAssemble(resolver: Resolver) { if isVersionTrackingEnabled { resolver.resolve(VersionTracker.self)!.checkAppVersion() } if isLifeCycleTrackingEnabled { resolver.resolve(LifeCycleTracker.self)!.enable() } } }
apache-2.0
5ed871f8152e674ae416688139b49443
34.938596
190
0.63998
5.300129
false
false
false
false
335g/TwitterAPIKit
Sources/APIs/SearchAPI.swift
1
3484
// // Search.swift // TwitterAPIKit // // Created by Yoshiki Kudo on 2015/07/07. // Copyright © 2015年 Yoshiki Kudo. All rights reserved. // import Foundation import APIKit // MARK: Request public protocol SearchRequestType: TwitterAPIRequestType {} public protocol SearchGetRequestType: SearchRequestType {} public extension SearchRequestType { public var baseURL: NSURL { return NSURL(string: "https://api.twitter.com/1.1/search")! } } public extension SearchGetRequestType { public var method: APIKit.HTTPMethod { return .GET } } // MARK: API public enum TwitterSearch { public enum ResultType: String { case Popular = "popular" case Recent = "recent" case Mixed = "mixed" } public struct Date { let year: Int let month: Int let day: Int private func dateString() -> String { let yearStr = NSString(format: "%04d", year) as String let monthStr = NSString(format: "%02d", month) as String let dayStr = NSString(format: "%02d", day) as String return yearStr + "-" + monthStr + "-" + dayStr } } public struct Geo { public enum Unit: String { case mi = "mi" case km = "km" } let latitude: String let longitude: String let unit: Unit internal func geoString() -> String { return latitude + "," + longitude + "," + unit.rawValue } } } public extension TwitterSearch { /// /// https://dev.twitter.com/rest/reference/get/search/tweets /// public struct Tweets: SearchGetRequestType { public let client: OAuthAPIClient public var path: String { return "/tweets.json" } private let _parameters: [String: AnyObject?] public var parameters: AnyObject? { return queryStringsFromParameters(_parameters) } public init( _ client: OAuthAPIClient, q: String, geocode: Geo? = nil, lang: String? = nil, locale: String? = nil, resultType: ResultType? = nil, count: Int? = 15, until: Date? = nil, sinceIDStr: String? = nil, maxIDStr: String? = nil, includeEntities: Bool = false, callback: String? = nil){ self.client = client self._parameters = [ "q": q, "geocode": geocode?.geoString(), "lang": lang, "locale": locale, "result_type": resultType?.rawValue, "count": count, "until": until?.dateString(), "since_id": sinceIDStr, "max_id": maxIDStr, "include_entities": includeEntities, "callback": callback ] } public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> SearchResult { guard let dictionary = object as? [String: AnyObject], searchResult = SearchResult(dictionary: dictionary) else { throw DecodeError.Fail } return searchResult } } }
mit
5e7e02966aa007c8e823e7a671321fdb
26.634921
114
0.515656
4.930595
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/DiscoveryParams.swift
1
5451
import Argo import Curry import Runes import Prelude public struct DiscoveryParams { public let backed: Bool? public let category: Category? public let collaborated: Bool? public let created: Bool? public let hasLiveStreams: Bool? public let hasVideo: Bool? public let includePOTD: Bool? public let page: Int? public let perPage: Int? public let query: String? public let recommended: Bool? public let seed: Int? public let similarTo: Project? public let social: Bool? public let sort: Sort? public let staffPicks: Bool? public let starred: Bool? public let state: State? public enum State: String, Decodable { case all case live case successful } public enum Sort: String, Decodable { case endingSoon = "end_date" case magic case mostFunded = "most_funded" case newest case popular = "popularity" } public static let defaults = DiscoveryParams(backed: nil, category: nil, collaborated: nil, created: nil, hasLiveStreams: nil, hasVideo: nil, includePOTD: nil, page: nil, perPage: nil, query: nil, recommended: nil, seed: nil, similarTo: nil, social: nil, sort: nil, staffPicks: nil, starred: nil, state: nil) public var queryParams: [String:String] { var params: [String:String] = [:] params["backed"] = self.backed == true ? "1" : self.backed == false ? "-1" : nil params["category_id"] = self.category?.id.description params["collaborated"] = self.collaborated?.description params["created"] = self.created?.description params["has_live_streams"] = self.hasLiveStreams?.description params["has_video"] = self.hasVideo?.description params["page"] = self.page?.description params["per_page"] = self.perPage?.description params["recommended"] = self.recommended?.description params["seed"] = self.seed?.description params["similar_to"] = self.similarTo?.id.description params["social"] = self.social == true ? "1" : self.social == false ? "-1" : nil params["sort"] = self.sort?.rawValue params["staff_picks"] = self.staffPicks?.description params["starred"] = self.starred == true ? "1" : self.starred == false ? "-1" : nil params["state"] = self.state?.rawValue params["term"] = self.query // Include the POTD only when searching when sorting by magic / not specifying sort if params["sort"] == nil || params["sort"] == DiscoveryParams.Sort.magic.rawValue { params["include_potd"] = self.includePOTD?.description } return params } } extension DiscoveryParams: Equatable {} public func == (a: DiscoveryParams, b: DiscoveryParams) -> Bool { return a.queryParams == b.queryParams } extension DiscoveryParams: Hashable { public var hashValue: Int { return self.description.hash } } extension DiscoveryParams: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return self.queryParams.description } public var debugDescription: String { return self.queryParams.debugDescription } } extension DiscoveryParams: Decodable { public static func decode(_ json: JSON) -> Decoded<DiscoveryParams> { let create = curry(DiscoveryParams.init) let tmp1 = create <^> ((json <|? "backed" >>- stringIntToBool) as Decoded<Bool?>) <*> json <|? "category" <*> ((json <|? "collaborated" >>- stringToBool) as Decoded<Bool?>) <*> ((json <|? "created" >>- stringToBool) as Decoded<Bool?>) let tmp2 = tmp1 <*> json <|? "has_live_streams" <*> ((json <|? "has_video" >>- stringToBool) as Decoded<Bool?>) <*> ((json <|? "include_potd" >>- stringToBool) as Decoded<Bool?>) <*> ((json <|? "page" >>- stringToInt) as Decoded<Int?>) <*> ((json <|? "per_page" >>- stringToInt) as Decoded<Int?>) let tmp3 = tmp2 <*> json <|? "term" <*> ((json <|? "recommended" >>- stringToBool) as Decoded<Bool?>) <*> ((json <|? "seed" >>- stringToInt) as Decoded<Int?>) <*> json <|? "similar_to" return tmp3 <*> ((json <|? "social" >>- stringIntToBool) as Decoded<Bool?>) <*> json <|? "sort" <*> ((json <|? "staff_picks" >>- stringToBool) as Decoded<Bool?>) <*> ((json <|? "starred" >>- stringIntToBool) as Decoded<Bool?>) <*> json <|? "state" } } private func stringToBool(_ string: String?) -> Decoded<Bool?> { guard let string = string else { return .success(nil) } switch string { // taken from server's `value_to_boolean` function case "true", "1", "t", "T", "true", "TRUE", "on", "ON": return .success(true) case "false", "0", "f", "F", "false", "FALSE", "off", "OFF": return .success(false) default: return .failure(.custom("Could not parse string into bool.")) } } private func stringToInt(_ string: String?) -> Decoded<Int?> { guard let string = string else { return .success(nil) } return Int(string).map(Decoded.success) ?? .failure(.custom("Could not parse string into int.")) } private func stringIntToBool(_ string: String?) -> Decoded<Bool?> { guard let string = string else { return .success(nil) } return Int(string) .filter { $0 <= 1 && $0 >= -1 } .map { .success($0 == 0 ? nil : $0 == 1) } .coalesceWith(.failure(.custom("Could not parse string into bool."))) }
apache-2.0
44c90113d17f7b3d887f1a7728f9cc14
35.583893
107
0.623739
3.9329
false
false
false
false
PiXeL16/MealPlanExchanges
MealPlanExchanges/Model/GeneralMealPlan.swift
1
1017
// // MealPlan.swift // MealPlanExchanges // // Created by Chris Jimenez on 6/1/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import UIKit /** * Represents a daily meal plan that the user setup for */ public struct GeneralMealPlan : MealPlanProtocol { public var breakfast: Meal public var morningSnack: Meal public var lunch: Meal public var afternoonSnack: Meal public var dinner: Meal public init(){ self.breakfast = Breakfast() self.morningSnack = MorningSnack() self.lunch = Lunch() self.afternoonSnack = AfternoonSnack() self.dinner = Dinner() } public init (breakfast: Meal, morningSnack: Meal, lunch: Meal, afternoonSnack: Meal, dinner: Meal){ self.breakfast = breakfast self.morningSnack = morningSnack self.lunch = lunch self.afternoonSnack = afternoonSnack self.dinner = dinner } }
mit
4ce75cde18f61e7b09c23d288c55b8d2
22.627907
103
0.607283
4.360515
false
false
false
false
LearningSwift2/LearningApps
ReminderApp/ReminderApp/DateTableViewCell.swift
1
1045
// // DateTableViewCell.swift // ReminderApp // // Created by Phil Wright on 4/8/16. // Copyright © 2016 Touchopia, LLC. All rights reserved. // import UIKit class DateTableViewCell: UITableViewCell { @IBOutlet weak var datePicker: UIDatePicker! var currentDate = NSDate() var isDatePickerHidden = true override func awakeFromNib() { super.awakeFromNib() } func configureCell(currentDate: NSDate) { datePicker.hidden = isDatePickerHidden datePicker.date = currentDate self.layoutIfNeeded() } func toggleDatePicker() { self.isDatePickerHidden = !self.isDatePickerHidden self.datePicker.hidden = self.isDatePickerHidden } @IBAction func datePickerValueChanged(sender: UIDatePicker) { self.currentDate = sender.date NSNotificationCenter.defaultCenter().postNotificationName("DateHasChanged", object: nil) } }
apache-2.0
e6219f2121da04d2364859fe67276162
19.470588
96
0.613985
5.353846
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/BasicChartTypes/HeatmapChart/HeatmapChartView.swift
1
4810
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // HeatmapChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class HeatmapChartView: HeatmapChartLayout { let height: Int32 = 200 let width: Int32 = 300 let seriesPerPeriod = 30 let timeInterval = 0.04 var _dataSeries : SCIUniformHeatmapDataSeries! var _timerIndex: Int = 0 var timer: Timer! var _running: Bool = false var data = [SCIGenericType]() override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if timer == nil { timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(updateHeatmapData), userInfo: nil, repeats: true) } } override func removeFromSuperview() { super.removeFromSuperview() if timer != nil { timer.invalidate() timer = nil } } override func initExample() { surface.leftAxisAreaForcedSize = 0.0; surface.topAxisAreaForcedSize = 0.0; let xAxis = SCINumericAxis() let yAxis = SCINumericAxis() _dataSeries = SCIUniformHeatmapDataSeries(typeX: .int32, y: .int32, z: .double, sizeX: width, y: height, startX: SCIGeneric(0.0), stepX: SCIGeneric(1.0), startY: SCIGeneric(0.0), stepY: SCIGeneric(1.0)) let countColors = 6 let gradientCoord = UnsafeMutablePointer<Float>.allocate(capacity: countColors) gradientCoord[0] = 0.0 gradientCoord[1] = 0.2 gradientCoord[2] = 0.4 gradientCoord[3] = 0.6 gradientCoord[4] = 0.8 gradientCoord[5] = 1.0 let gradientColor = UnsafeMutablePointer<uint>.allocate(capacity: 6) gradientColor[0] = 0xFF00008B; gradientColor[1] = 0xFF6495ED; gradientColor[2] = 0xFF006400; gradientColor[3] = 0xFF7FFF00; gradientColor[4] = 0xFFFFFF00; gradientColor[5] = 0xFFFF0000; let heatmapRenderableSeries = SCIFastUniformHeatmapRenderableSeries() heatmapRenderableSeries.minimum = 0.0 heatmapRenderableSeries.maximum = 200.0 heatmapRenderableSeries.colorMap = SCITextureOpenGL(gradientCoords: gradientCoord, colors: gradientColor, count: 6) heatmapRenderableSeries.dataSeries = _dataSeries createData() heatmapColourMap.minimum = heatmapRenderableSeries.minimum heatmapColourMap.maximum = heatmapRenderableSeries.maximum heatmapColourMap.colourMap = heatmapRenderableSeries.colorMap surface.xAxes.add(xAxis) surface.yAxes.add(yAxis) surface.renderableSeries.add(heatmapRenderableSeries) surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCICursorModifier()]) } fileprivate func createData() { for i in 0..<seriesPerPeriod { let angle = .pi * 2.0 * Double(i) / Double(seriesPerPeriod) let zValues = UnsafeMutablePointer<Double>.allocate(capacity: Int(width * height)) let cx = 150.0 let cy = 100.0 for x in 0..<width { for y in 0..<height { let v = (1 + sin(Double(x) * 0.04 + angle)) * 50 + (1 + sin(Double(y) * 0 + angle)) * 50 * (1 + sin(angle * 2)) let r = sqrt((Double(x) - cx) * (Double(x) - cx) + (Double(y) - cy) * (Double(y) - cy)) let exp = max(0, 1 - r * 0.008) zValues[Int(x * height + y)] = v * exp + Double(arc4random_uniform(50)) } } data.append(SCIGeneric(zValues)) } _dataSeries.updateZValues(data[0], size: Int32(height * width)) } @objc func updateHeatmapData() { SCIUpdateSuspender.usingWithSuspendable(surface, with: { self._dataSeries.updateZValues(self.data[self._timerIndex % self.seriesPerPeriod], size: Int32(self.height * self.width)) self._timerIndex += 1 }) } }
mit
fd496ff73444fb00beac64acdc638035
39.394958
210
0.601623
4.373976
false
false
false
false
dongdonggaui/FakeWeChat
FakeWeChat/src/Views/SimpleCellView.swift
1
3116
// // SimpleCellView.swift // FakeWeChat // // Created by huangluyang on 15/12/29. // Copyright © 2015年 huangluyang. All rights reserved. // import UIKit import YYKit struct SCVLayoutInfo { static let AvatarWidth = CGFloatPixelRound(CGFloat(50.0 * UIApplication.tq_windowWidth() / 320.0)) static let AvatarHeight = CGFloatPixelRound(CGFloat(50.0 * UIApplication.tq_windowWidth() / 320.0)) static let AvatarTopMargin = CGFloat(8) static let AvatarLeadingMargin = CGFloat(8) static let HPadding = CGFloat(5) static let VPadding = CGFloat(5) static let BottomMargin = CGFloat(8) } class SimpleCellView: UIView { // MARK: - Life Cycle override init(frame: CGRect) { super.init(frame: CGRectMake(0, 0, 320, 100)) addSubview(avatarView) addSubview(titleLabel) addSubview(detailLabel) addSubview(timeLabel) avatarView.snp_makeConstraints { (make) -> Void in make.width.equalTo(SCVLayoutInfo.AvatarWidth) make.height.equalTo(SCVLayoutInfo.AvatarHeight) make.top.equalTo(self).offset(SCVLayoutInfo.AvatarTopMargin) make.leading.equalTo(self).offset(SCVLayoutInfo.AvatarLeadingMargin) make.bottom.lessThanOrEqualTo(self).offset(-SCVLayoutInfo.BottomMargin) } titleLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(avatarView).offset(SCVLayoutInfo.AvatarTopMargin) make.leading.equalTo(avatarView.snp_trailing).offset(SCVLayoutInfo.HPadding) make.trailing.lessThanOrEqualTo(timeLabel).offset(-SCVLayoutInfo.HPadding) } detailLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(titleLabel.snp_bottom).offset(SCVLayoutInfo.VPadding) make.leading.equalTo(titleLabel) make.trailing.lessThanOrEqualTo(self).offset(-SCVLayoutInfo.AvatarLeadingMargin) make.bottom.lessThanOrEqualTo(self).offset(-SCVLayoutInfo.BottomMargin) } timeLabel.snp_makeConstraints { (make) -> Void in make.baseline.equalTo(titleLabel) make.trailing.equalTo(self).offset(-SCVLayoutInfo.AvatarLeadingMargin) } } convenience init() { self.init(frame: CGRectZero) } required convenience init?(coder aDecoder: NSCoder) { self.init(frame: CGRectZero) } // MARK: - Public Properties lazy var avatarView: AvatarBadgeView = { return AvatarBadgeView() }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFontOfSize(15) return label }() lazy var detailLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(14) label.textColor = UIColor.lightGrayColor() label.numberOfLines = 0 return label }() lazy var timeLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(12) label.textColor = UIColor.lightGrayColor() return label }() }
mit
8960b233425ebcd64fcc50fbe62c3561
33.977528
103
0.655959
4.341702
false
false
false
false
Eonil/Monolith.Swift
UIKitExtras/Sources/Autolayout/Anchors.swift
3
9564
// // Anchors.swift // CratesIOViewer // // Created by Hoon H. on 11/23/14. // // import Foundation #if os(iOS) import UIKit #endif #if os(OSX) import AppKit #endif /// Core type to define attachment anchoring point. public struct Anchor { #if os(iOS) public typealias Priority = UILayoutPriority public typealias View = UIView #endif #if os(OSX) public typealias Priority = NSLayoutPriority public typealias View = NSView #endif private var item:NSObjectProtocol private var x:NSLayoutAttribute private var y:NSLayoutAttribute #if os(iOS) private init(item:UILayoutSupport, x:NSLayoutAttribute, y:NSLayoutAttribute) { self.item = item self.x = x self.y = y } #endif /// Does not check `translatesAutoresizingMaskIntoConstraints` because AFAIK, /// manual-layout object also can be used for layout expressions. private init(view:View, x:NSLayoutAttribute, y:NSLayoutAttribute) { self.item = view self.x = x self.y = y } var dimensions:Int { get { let c1 = x == NA ? 0 : 1 let c2 = y == NA ? 0 : 1 return c1 + c2 } } /// Returns an anchor object of same location for the view. /// For example, if this anchor was obtained from `leftTop`, /// this returns `leftTop` of the supplied view. func forView(v:View) -> Anchor { var a1 = self a1.item = v return a1 } } // Workaround because compiler emits a link error for below code. // Patch when the error has been fixed. private let REQUIRED = 1000 as Float private let HIGH = 750 as Float private let FITTING = 50 as Float //#if os(iOS) //private let REQUIRED = UILayoutPriorityRequired //private let HIGH = UILayoutPriorityDefaultHigh //private let FITTING = UILayoutPriorityFittingSizeLevel //#endif //#if os(OSX) //private let REQUIRED = NSLayoutPriorityRequired //private let HIGH = NSLayoutPriorityDefaultHigh //private let FITTING = NSLayoutPriorityFittingSizeLevel //#endif public extension Anchor.View { /// Calls `addConstraintsWithLayoutAnchoring(:,priority:)` with `REQUIRED` priority. /// `REQUIRED` priority is too high for most situations, and you're expected to use /// `addConstraintsWithLayoutAnchoring(:,priority:)` method instead of. /// This method is likely to be deprecated... public func addConstraintsWithLayoutAnchoring(a:[AnchoringEqualityExpression]) -> [NSLayoutConstraint] { return addConstraintsWithLayoutAnchoring(a, priority: REQUIRED) } /// Builds a set of layout-constraints from anchor expressions, /// Returns array of `NSLayoutConstraint` which are added to the view. public func addConstraintsWithLayoutAnchoring(a:[AnchoringEqualityExpression], priority:Anchor.Priority) -> [NSLayoutConstraint] { let a1 = a.map({$0.constraints}) let a2 = a1.reduce([] as [NSLayoutConstraint], combine: { u, n in return u + n }) a2.map({$0.priority = priority}) addConstraints(a2) return a2 } } //public protocol LayoutAnchoringSupport { // var centerXAnchor:Anchor { get } // var centerYAnchor:Anchor { get } // var leftAnchor:Anchor { get } // var rightAnchor:Anchor { get } // var topAnchor:Anchor { get } // var bottomAnchor:Anchor { get } // var baselineAnchor:Anchor { get } // var widthAnchor:Anchor { get } // var heightAnchor:Anchor { get } // // var centerAnchor:Anchor { get } // var leftTopAnchor:Anchor { get } // var leftCenterAnchor:Anchor { get } // var leftBottomAnchor:Anchor { get } // var centerTopAnchor:Anchor { get } // var centerBottomAnchor:Anchor { get } // var rightTopAnchor:Anchor { get } // var rightCenterAnchor:Anchor { get } // var rightBottomAnchor:Anchor { get } // var leftBaselineAnchor:Anchor { get } // var rightBaselineAnchor:Anchor { get } // var sizeAnchor:Anchor { get } //} /// 1D anchors. extension Anchor.View { public var centerXAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.CenterX, y: NA) } } public var centerYAnchor:Anchor { get { return Anchor(view: self, x: NA, y: NSLayoutAttribute.CenterY) } } public var leftAnchor:Anchor { get { return Anchor(view: self, x: LEFT, y: NA) } } public var rightAnchor:Anchor { get { return Anchor(view: self, x: RIGHT, y: NA) } } public var topAnchor:Anchor { get { return Anchor(view: self, x: NA, y: TOP) } } public var bottomAnchor:Anchor { get { return Anchor(view: self, x: NA, y: BOTTOM) } } public var baselineAnchor:Anchor { get { return Anchor(view: self, x: BASELINE, y: NA) } } public var widthAnchor:Anchor { get { return Anchor(view: self, x: WIDTH, y: NA) } } public var heightAnchor:Anchor { get { return Anchor(view: self, x: NA, y: HEIGHT) } } } /// 2D anchors. extension Anchor.View { public var centerAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.CenterX, y: NSLayoutAttribute.CenterY) } } public var leftTopAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Left, y: NSLayoutAttribute.Top) } } public var leftCenterAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Left, y: NSLayoutAttribute.CenterY) } } public var leftBottomAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Left, y: NSLayoutAttribute.Bottom) } } public var centerTopAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.CenterX, y: NSLayoutAttribute.Top) } } public var centerBottomAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.CenterX, y: NSLayoutAttribute.Bottom) } } public var rightTopAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Right, y: NSLayoutAttribute.Top) } } public var rightCenterAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Right, y: NSLayoutAttribute.CenterY) } } public var rightBottomAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Right, y: NSLayoutAttribute.Bottom) } } public var leftBaselineAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Left, y: NSLayoutAttribute.Baseline) } } public var rightBaselineAnchor:Anchor { get { return Anchor(view: self, x: NSLayoutAttribute.Right, y: NSLayoutAttribute.Baseline) } } public var sizeAnchor:Anchor { get { return Anchor(view: self, x: WIDTH, y: HEIGHT) } } } #if os(iOS) extension UIViewController { public var topLayoutGuideAnchor:Anchor { get { return Anchor(item: topLayoutGuide, x: NA, y: TOP) } } public var bottomLayoutGuideAnchor:Anchor { get { return Anchor(item: bottomLayoutGuide, x: NA, y: BOTTOM) } } } #endif public struct AnchoringEqualityExpression { private let left:Anchor private let right:Anchor private let relation:NSLayoutRelation private let displacement:CGSize public var constraints:[NSLayoutConstraint] { get { precondition((left.x == NA && right.x == NA) || (left.x != NA && right.x != NA), "You cannot connect anchors with `~Only` into different axis.") precondition((left.y == NA && right.y == NA) || (left.y != NA && right.y != NA), "You cannot connect anchors with `~Only` into different axis.") var a1 = [] as [NSLayoutConstraint] if left.x != NA && right.x != NA { let c1 = NSLayoutConstraint(item: left.item, attribute: left.x, relatedBy: relation, toItem: right.item, attribute: right.x, multiplier: 1, constant: displacement.width) a1.append(c1) } if left.y != NA && right.y != NA { let c1 = NSLayoutConstraint(item: left.item, attribute: left.y, relatedBy: relation, toItem: right.item, attribute: right.y, multiplier: 1, constant: displacement.height) a1.append(c1) } return a1 } } } public struct AnchoringDisplacementExpression { private let anchor:Anchor private let displacement:CGSize } public func == (left:Anchor, right:Anchor) -> AnchoringEqualityExpression { return left == right + CGSize.zeroSize } public func == (left:Anchor, right:AnchoringDisplacementExpression) -> AnchoringEqualityExpression { return AnchoringEqualityExpression(left: left, right: right.anchor, relation: NSLayoutRelation.Equal, displacement: right.displacement) } public func >= (left:Anchor, right:Anchor) -> AnchoringEqualityExpression { return left >= right + CGSize.zeroSize } public func >= (left:Anchor, right:AnchoringDisplacementExpression) -> AnchoringEqualityExpression { return AnchoringEqualityExpression(left: left, right: right.anchor, relation: NSLayoutRelation.GreaterThanOrEqual, displacement: right.displacement) } public func <= (left:Anchor, right:Anchor) -> AnchoringEqualityExpression { return left <= right + CGSize.zeroSize } public func <= (left:Anchor, right:AnchoringDisplacementExpression) -> AnchoringEqualityExpression { return AnchoringEqualityExpression(left: left, right: right.anchor, relation: NSLayoutRelation.LessThanOrEqual, displacement: right.displacement) } public func + (left:Anchor, right:CGSize) -> AnchoringDisplacementExpression { return AnchoringDisplacementExpression(anchor: left, displacement: right) } private let NA = NSLayoutAttribute.NotAnAttribute private let LEFT = NSLayoutAttribute.Left private let RIGHT = NSLayoutAttribute.Right private let TOP = NSLayoutAttribute.Top private let BOTTOM = NSLayoutAttribute.Bottom private let BASELINE = NSLayoutAttribute.Baseline private let WIDTH = NSLayoutAttribute.Width private let HEIGHT = NSLayoutAttribute.Height private typealias ATTR = NSLayoutAttribute
mit
d63bb710549cd5fa688a8bd70ac3f53c
21.24186
174
0.712673
3.353436
false
false
false
false
gkaimakas/SwiftValidators
Example/Tests/ValidatorSpec.swift
1
28744
// // Validatorpec_v2.swift // SwiftValidator // // Created by Γιώργος Καϊμακάς on 04/08/16. // Copyright © 2016 Γιώργος Καϊμακάς. All rights reserved. // import Quick import Nimble import SwiftValidators import Foundation struct TestCase { let name: String let message: String let validator: Validator let valid: [StringConvertible?] let invalid: [StringConvertible?] } class ValidatorSpec: QuickSpec { override func spec() { super.spec() let testCases: [TestCase] = [ TestCase(name: "Logical AND", message: "should validate that Validator can be combined using logical AND", validator: Validator.required() && Validator.isTrue(), valid: [ true, "true" ], invalid: [ false, "false", "" ] ), TestCase(name: "Logical OR", message: "should validate that Validator can be combined using logical OR", validator: Validator.isFalse() || Validator.isTrue(), valid: [ true, "true", false, "false" ], invalid: [ "something", "fals_e", "", nil ] ), TestCase(name: "Logical NOT", message: "should reverse the operand's result", validator: !Validator.isTrue(), valid: [ false, "false", "" ], invalid: [ true, "true" ] ), TestCase(name: "contains", message: "should validate if the value contains the string", validator: Validator.contains("some_string"), valid: [ "some_string_asfa", "dfsgfsf_Asdafda_some_string" ], invalid: [ "abc", "sting" ]), TestCase(name: "equals", message: "should validate if the value is equal", validator: Validator.equals("some_string"), valid: [ "some_string" ], invalid: [ "some_other_string", nil ] ), TestCase(name: "exactLength", message: "should validate if the value has the exact length", validator: Validator.exactLength(5), valid: [ "12345", "abcde", "klmno" ], invalid: [ String(123), "0", "123" ] ), TestCase(name: "isASCII", message: "should validate if the value contains only ASCII charactes", validator: Validator.isASCII(), valid: [ "foobar", "0987654321", "[email protected]", "1234abcDEF" ], invalid: [ "ασφαδφ", "ασδαδafad", "13edsaαφδσ", "カタカナ" ] ), TestCase(name: "isAfter", message: "should validate if the value is after the date", validator: Validator.isAfter("25/09/1987"), valid: [ "28/03/1994", "29/03/1994" ], invalid: [ "02/06/1946" ] ), TestCase(name: "isAlpha", message: "should validate if the value contains only letters", validator: Validator.isAlpha(), valid: [ "asdsdgdfhdfASFSDGDFHFG" ], invalid: [ "3304193705b2464a98ad3910cbe0d09e", "123", nil, "asdfd464342ghj" ] ), TestCase(name: "isAlphanumeric", message: "should validate if the value contains only alphanumeric characters", validator: Validator.isAlphanumeric(), valid: [ "abc123", "ABC11", "asdfd464342ghj" ], invalid: [ "foo!!", "abc __ __ " ] ), TestCase(name: "isBase64", message: "should validate that the value is a base64 encoded string", validator: Validator.isBase64(), valid: [ "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", "Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", "U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw", "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye", "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619", "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx", "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ", "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ", "HQIDAQAB", "" ], invalid: [ "12345", "Vml2YW11cyBmZXJtZtesting123" ] ), TestCase(name: "isBefore", message: "should validate if the value is before the date", validator: Validator.isBefore("29/03/1994"), valid: [ "04/10/1992", "25/09/1987" ], invalid: [ "30/03/1994" ] ), TestCase(name: "isBool", message: "should validate if the value is true or false", validator: Validator.isBool(), valid: [ false, true, "true", "false" ], invalid: [ 1, 2, 3, "one", "on", "off", 0 ] ), TestCase(name: "isCreditCard", message: "should validate credit cards", validator: Validator.isCreditCard(), valid: [ "375556917985515", "36050234196908", "4716461583322103", "4716-2210-5188-5662", "4929 7226 5379 7141", "5398228707871527", "5398228707871528", ], invalid: [ "foo", "foobar", false ] ), TestCase(name: "isDate", message: "should validate dates", validator: Validator.isDate(), valid: [ "25/09/1987", "01/01/2000", "29/03/1994", "02/06/1946" ], invalid: [ "test", false ] ), TestCase(name: "isEmail", message: "should validate emails", validator: Validator.isEmail(), valid: [ "[email protected]", "[email protected]", "[email protected]", "[email protected]", "hans.m端[email protected]", "hans@m端ller.com", "test|123@m端ller.com", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]" ], invalid: [ "tester", "invalidemail@", "invalid.com", "@invalid.com", "[email protected].", "[email protected]." ] ), TestCase(name: "isEmpty", message: "should validate empty strings", validator: Validator.isEmpty(), valid: [ "" ], invalid: [ "not_empty" ] ), TestCase(name: "isFQDN", message: "should validate FQDN strings", validator: Validator.isFQDN(), valid: [ "domain.com", "dom.plato", "a.domain.co", "foo--bar.com", "xn--froschgrn-x9a.com", "rebecca.blackfriday", "www9.example.com", "www1.exaple.com", "w1w.example12.org" ], invalid: [ "abc", "256.0.0.0", "_.com", "*.som.com", "s!ome.com", "domain.com/", "/more.com" ] ), TestCase(name: "isFloat", message: "should validate floats", validator: Validator.isFloat(), valid: [ "1.2", (1.2 as Float), (1 as Double), (1241432 as Double), "123", "123.", "123.123", "-123.123", "-0.123", "+0.123", "0123", ".0", "0123.123", "-0.1233425364353e-307", "" ], invalid: [ "abc", "___", "0,124" ] ), TestCase(name: "isHexadecimal", message: "should validate hexadecimals", validator: Validator.isHexadecimal(), valid: [ "deadBEEF", "ff0044" ], invalid: [ "sgrl", "---", "#,dsfsdf" ] ), TestCase(name: "isHexColor", message: "should validate hex colors", validator: Validator.isHexColor(), valid: [ "#ff0034", "#CCCCCC", "fff", "#f00", ], invalid: [ "#ff", "ff00", "ff12fg", nil ] ), TestCase(name: "isIP", message: "should validate IPs", validator: Validator.isIP(), valid: [ "::1", "2001:db8:0000:1:1:1:1:1", "2001:41d0:2:a141::1", "::ffff:127.0.0.1", "::0000", "0000::", "1::", "1111:1:1:1:1:1:1:1", "fe80::a6db:30ff:fe98:e946", "::", "::ffff:127.0.0.1", "0:0:0:0:0:ffff:127.0.0.1", "192.123.23.0" ], invalid: [ "abc", "256.0.0.0", "0.0.0.256", "26.0.0.256", "::banana", "banana::", "::1::", "1:", ":1", ":1:1:1::2", "1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1", "::11111", "11111:1:1:1:1:1:1:1", "2001:db8:0000:1:1:1:1::1", "0:0:0:0:0:0:ffff:127.0.0.1", "0:0:0:0:ffff:127.0.0.1", "192.123.23.257" ] ), TestCase(name: "isIPv4", message: "should validate IPv4 addresses", validator: Validator.isIPv4(), valid: [ "192.123.23.0" ], invalid: [ "92.123.23.257" ] ), TestCase(name: "isIPv6", message: "should validate IPv6 addresses", validator: Validator.isIPv6(), valid: [ "::1", "2001:db8:0000:1:1:1:1:1", "2001:41d0:2:a141::1", "::ffff:127.0.0.1", "::0000", "0000::", "1::", "1111:1:1:1:1:1:1:1", "fe80::a6db:30ff:fe98:e946", "::", "::ffff:127.0.0.1", "0:0:0:0:0:ffff:127.0.0.1" ], invalid: [ "abc", "256.0.0.0", "0.0.0.256", "26.0.0.256", "::banana", "banana::", "::1::", "1:", ":1", ":1:1:1::2", "1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1", "::11111", "11111:1:1:1:1:1:1:1", "2001:db8:0000:1:1:1:1::1", "0:0:0:0:0:0:ffff:127.0.0.1", "0:0:0:0:ffff:127.0.0.1", "192.123.23.257" ] ), TestCase(name: "isISBN(10)", message: "should validate ISBNs v 10", validator: Validator.isISBN(.v10), valid: [ "3836221195", "1617290858", "0007269706", "3423214120", "340101319X", "3-8362-2119-5", "1-6172-9085-8", "0-0072-6970-6", "3-4232-1412-0", "3-4010-1319-X", "3 8362 2119 5", "1 6172 9085 8", "0 0072 6970 6", "3 4232 1412 0", "3 4010 1319 X", ], invalid: [ "3423214121", "978-3836221191", "123456789a", "3-423-21412-1", "9783836221191", "foo", "3 423 21412 1" ] ), TestCase(name: "isISBN(13)", message: "should validate ISBNS v13", validator: Validator.isISBN(.v13), valid: [ "9783836221191", "978-3-8362-2119-1", "978 3 8362 2119 1", "9783401013190", "978-3401013190", "978 3401013190", "9784873113685", "978-4-87311-368-5", "978 4 87311 368 5" ], invalid: [ "9783836221190", "3836221195", "01234567890ab" ] ), TestCase(name: "isIn", message: "should validate that the value exists in the array", validator: Validator.isIn(["one", "two", "three"]), valid: [ "one", "two", "three" ], invalid: [ 1, 2, 3, "oneee" ] ), TestCase(name: "isInt", message: "should validate ints", validator: Validator.isInt(), valid: [ 1, 2, 3, -1230, -1234444 ], invalid: [ "a134", 123.2, -4354.546 ] ), TestCase(name: "isLowercase", message: "should validate lowercase strings", validator: Validator.isLowercase(), valid: [ "aaaaaa a a aa aa" ] , invalid: [ "aA_asfaf", "aaaa aaa A" ] ), TestCase(name: "isMongoId", message: "should validate hexadecimal mongo ids", validator: Validator.isMongoId(), valid: [ "507f1f77bcf86cd799439011" ], invalid: [ "507f1f77bcf86cd7994390", "507f1f77bcf86cd79943901z" ] ), TestCase(name: "isNumeric", message: "should validate numeric values", validator: Validator.isNumeric(), valid: [ 123, 00123, "00123", 0, "-0", "+123" ], invalid: [ "+213 12" ] ), TestCase(name: "isPhone_el_GR", message: "should validate phone numbers from Greece", validator: Validator.isPhone(.el_GR), valid: [ "2101231231", "6944848966", "6944114280", "6978989652", "6970310751" ], invalid: [ "1231341412" ] ), TestCase(name: "isPhone_nl_BE", message: "should validate phone numbers from Belgium", validator: Validator.isPhone(.nl_BE), valid: [ "0123456789", "0032123456789", "+32123456789" ], invalid: [ "1234567890", "0412345678", "+31123456789", "01234567890" ] ), TestCase(name: "isPhone_nl_BE_mobile", message: "should validate phone numbers from Belgian mobile phones", validator: Validator.isPhone(.nl_BE_mobile), valid: [ "04123456789", "00324123456789", "+324123456789", ], invalid: [ "1234567890", "0412345678", "+31123456789", "01234567890" ] ), TestCase(name: "isPhone_nl_NL", message: "should validate phone numbers from The Netherlands", validator: Validator.isPhone(.nl_NL), valid: [ "0123456789", "0031123456789", "+31123456789" ], invalid: [ "012345678", "1234567890", "+311234567890" ] ), TestCase(name: "isPostalCode_BE", message: "should validate Belgian postal codes", validator: Validator.isPostalCode(.BE), valid: [ "1000", "9999" ], invalid: [ "123", "123456", "ABCDAB" ] ), TestCase(name: "isPostalCode_GB", message: "should validate British postal codes", validator: Validator.isPostalCode(.GB), valid: [ "B45 0HY", "CV32 7NG", "HD5 8UR" ], invalid: [ "1234", "1234A", "ABCDAB" ] ), TestCase(name: "isPostalCode_NL", message: "should validate Dutch postal codes", validator: Validator.isPostalCode(.NL), valid: [ "5171KW", "1234 AB" ], invalid: [ "1234", "1234A", "ABCDAB" ] ), TestCase(name: "isPostalCode_US", message: "should validate United-States postal codes", validator: Validator.isPostalCode(.US), valid: [ "90201", "12345-1235" ], invalid: [ "1234", "1234A", "1234AB", "ABCDAB", "123-1234-123456" ] ), TestCase(name: "isTrue", message: "should validate true", validator: Validator.isTrue(), valid: [ true, "true" ], invalid: [ false, "false" ] ), TestCase(name: "isURL", message: "should validate URLs", validator: Validator.isURL(), valid: [ "http://www.google.com", "www.google.com", "google.com", ], invalid: [ "text", "http://" ] ), TestCase(name: "isUUID", message: "should validate UUIDs", validator: Validator.isUUID(), valid: [ "33041937-05b2-464a-98ad-3910cbe0d09e", UUID().uuidString ], invalid: [ "3304193705b2464a98ad3910cbe0d09e", "123" ] ), TestCase(name: "isUppercase", message: "should validate uppercase values", validator: Validator.isUppercase(), valid: [ "AAAAAAA" ], invalid: [ "AAAAAAAaaa" ] ), TestCase(name: "maxLength", message: "should validate values that do not exceed the max length", validator: Validator.maxLength(5), valid: [ 1, 12, 123, 1234, 12345, "abced" ], invalid: [ 123456, "abcdef" ] ), TestCase(name: "minLength", message: "should validate values that exceed the min length", validator: Validator.minLength(2), valid: [ 12, 1234, 123, 1234577 ], invalid: [ 1, "" ] ), TestCase(name: "required", message: "should validate values that are not empty", validator: Validator.required(), valid: [ " ", 1234 ], invalid: [ "", nil ] ) ] for testCase in testCases { describe(testCase.name) { it(testCase.message) { for value in testCase.valid { expect(testCase.validator.apply(value)).to(equal(true)) } for value in testCase.invalid { expect(testCase.validator.apply(value)).to(equal(false)) } } } } } }
mit
fc2f2b4769d06862bbbc581b17fbc663
33.980488
103
0.301318
5.500288
false
true
false
false
seungprk/PenguinJump
PenguinJump/PenguinJump/ChargeBar.swift
1
2530
// // ChargeBar.swift // PenguinJump // // Created by Matthew Tso on 6/6/16. // Copyright © 2016 De Anza. All rights reserved. // import SpriteKit class ChargeBar: SKSpriteNode { var bar: SKSpriteNode! var barFlash: SKSpriteNode! var increment: CGFloat! var mask: SKSpriteNode! var flashing = false init(size:CGSize) { super.init(texture: nil, color: SKColor.clearColor(), size: CGSize(width: size.width, height: size.height / 3)) anchorPoint = CGPoint(x: 0.0, y: 0.5) increment = size.width / 10 mask = SKSpriteNode(color: SKColor.blackColor(), size: CGSize(width: size.width, height: size.height)) mask.anchorPoint = CGPoint(x: 0.0, y: 0.5) let crop = SKCropNode() crop.maskNode = mask bar = SKSpriteNode(color: SKColor.blackColor(), size: CGSize(width: size.width * 2, height: size.height / 3)) bar.anchorPoint = CGPoint(x: 1.0, y: 0.5) barFlash = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: size.width * 2, height: size.height / 3)) barFlash.zPosition = 10 barFlash.anchorPoint = CGPoint(x: 1.0, y: 0.5) barFlash.alpha = 0.0 bar.addChild(barFlash) crop.addChild(bar) addChild(crop) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func flash(completion block: (() -> ())? ) { flashing = true let flashUp = SKAction.fadeAlphaTo(1.0, duration: 0.1) let flashDown = SKAction.fadeAlphaTo(0.0, duration: 0.1) flashUp.timingMode = .EaseOut flashDown.timingMode = .EaseIn let wait = SKAction.waitForDuration(0.1) let flashSequence = SKAction.sequence([flashUp, wait, wait, flashDown, wait]) barFlash.runAction(SKAction.repeatAction(flashSequence, count: 3), completion: { self.barFlash.alpha = 1.0 self.flashing = false block?() }) } func flashOnce() { flashing = true let flashUp = SKAction.fadeAlphaTo(1.0, duration: 0.1) let flashDown = SKAction.fadeAlphaTo(0.0, duration: 0.1) flashUp.timingMode = .EaseOut flashDown.timingMode = .EaseIn let flashSequence = SKAction.sequence([flashUp, flashDown]) barFlash.runAction(flashSequence, completion: { self.flashing = false }) } }
bsd-2-clause
9270bff4a1b8977b3c47d0213a12332a
31.012658
122
0.595492
3.982677
false
false
false
false
Ruenzuo/fansabisu
FanSabisuKit/Sources/MediaDownloader.swift
1
4626
import Foundation public enum MediaDownloaderError: Error { case invalidURL case requestFailed case tooManyRequests case forbidden } public class MediaDownloader { let session: URLSession let responseParser: ResponseParser public init(session: URLSession) { self.session = session responseParser = ResponseParser() } public func downloadMedia(with tweetURL: URL, completionHandler: @escaping (Result<URL>) -> Void) { guard let tweetID = tweetURL.pathComponents.last else { return completionHandler(Result.failure(MediaDownloaderError.invalidURL)) } let URLString = "https://api.twitter.com/1.1/statuses/show.json?id=".appending(tweetID) guard let requestURL = URL(string: URLString) else { return completionHandler(Result.failure(MediaDownloaderError.invalidURL)) } let authorizer = Authorizer(session: session) authorizer.buildRequest(for: requestURL) { (result) in do { let request = try result.resolve() let dataTask = self.session.dataTask(with: request) { (data, response, error) in if (response as? HTTPURLResponse)?.statusCode == 429 { return DispatchQueue.main.async { completionHandler(Result.failure(MediaDownloaderError.tooManyRequests)) } } if (response as? HTTPURLResponse)?.statusCode == 403 { return DispatchQueue.main.async { completionHandler(Result.failure(MediaDownloaderError.forbidden)) } } if (response as? HTTPURLResponse)?.statusCode != 200 { return DispatchQueue.main.async { completionHandler(Result.failure(MediaDownloaderError.requestFailed)) } } if let error = error { return DispatchQueue.main.async { completionHandler(Result.failure(error)) } } guard let data = data else { return DispatchQueue.main.async { completionHandler(Result.failure(MediaDownloaderError.requestFailed)) } } let url = self.responseParser.parseStatus(with: data) switch url { case .success(let result): self.downloadVideo(with: result, completionHandler: { (result) in DispatchQueue.main.async { completionHandler(result) } }) case .failure(let error): return DispatchQueue.main.async { completionHandler(Result.failure(error)) } } } dataTask.resume() } catch TokenProviderError.tooManyRequests { return completionHandler(Result.failure(MediaDownloaderError.tooManyRequests)) } catch { return completionHandler(Result.failure(MediaDownloaderError.requestFailed)) } } } func downloadVideo(with videoUrl: URL, completionHandler: @escaping (Result<URL>) -> Void) { let dataTask = session.downloadTask(with: videoUrl) { (location, response, error) in if let error = error { return completionHandler(Result.failure(error)) } let temporaryDirectoryFilePath = URL(fileURLWithPath: NSTemporaryDirectory()) guard let response = response else { return completionHandler(Result.failure(MediaDownloaderError.requestFailed)) } guard let location = location else { return completionHandler(Result.failure(MediaDownloaderError.requestFailed)) } let suggestedFilename: String if let value = response.suggestedFilename { suggestedFilename = value } else { suggestedFilename = videoUrl.lastPathComponent } let destinationUrl = temporaryDirectoryFilePath.appendingPathComponent(suggestedFilename) if FileManager().fileExists(atPath: destinationUrl.path) { print("MediaDownloader: The file \(suggestedFilename) already exists at path \(destinationUrl.path)") } else { let data = try? Data(contentsOf: location) try? data?.write(to: destinationUrl, options: Data.WritingOptions.atomic) } completionHandler(Result.success(destinationUrl)) } dataTask.resume() } }
mit
c6c64e35d3f59d1790a0f607fba4aac0
46.204082
131
0.597276
5.76808
false
false
false
false
bormind/StackViews
StackViewsExamples/StackViewsExamples/FormExapmle/FormExampleFooterViewController.swift
1
2320
// // Created by Boris Schneiderman on 2017-03-19. // Copyright (c) 2017 bormind. All rights reserved. // import Foundation import UIKit import StackViews fileprivate enum Actions { case save case cancel case clear } class FormExampleFooterViewController: UIViewController { let saveButton = UIButton() let cancelButton = UIButton() let clearButton = UIButton() init() { super.init(nibName: nil, bundle: nil) self.view.backgroundColor = UIColor.white saveButton.setTitle("Save", for: .normal) cancelButton.setTitle("Cancel", for: .normal) clearButton.setTitle("Clear", for: .normal) [saveButton, cancelButton, clearButton].forEach(formatButton) //Stack buttons horizontally _ = stackViews( container: self.view, //pass in UIViewController's view as a container orientation: .horizontal, justify: .center, //Buttons will be arranged in the center along the stacking axis align: .fill, //Because we set align to .fill and explicitly specify height of the buttons //The full height of the footer will be determined by sum of button height and vertical insets //If we wanted the height of the footer to be determined by it's parent //we we would set the align parameter to .center instead og .fill insets: Insets(vertical: 10), //Vertical insets from the edges of the container to children views spacing: 5, //horizontal spacing between buttons views: [saveButton, cancelButton, clearButton], widths: [100, 100, 100], //For stackViews being able to justify controls in the middle of the container //We have to provide button's width explicitly heights: [25, 25, 25] //Set heights of the buttons ) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func formatButton(_ button: UIButton) { button.setTitleColor(UIColor.blue, for: .normal) // button.layer.borderWidth = 2 // button.layer.borderColor = UIColor.lightGray.cgColor } }
mit
20e5e0a5015c2f878b175760eac97960
37.032787
124
0.625
4.978541
false
false
false
false
stripe/stripe-ios
Example/Non-Card Payment Examples/Non-Card Payment Examples/KlarnaSourcesExampleViewController.swift
1
7615
// // KlarnaSourcesExampleViewController.swift // Custom Integration // // Created by David Estes on 10/28/19. // Copyright © 2019 Stripe. All rights reserved. // import Stripe import UIKit class KlarnaSourcesExampleViewController: UIViewController { @objc weak var delegate: ExampleViewControllerDelegate? var redirectContext: STPRedirectContext? var inProgress: Bool = false { didSet { navigationController?.navigationBar.isUserInteractionEnabled = !inProgress payWithAddressButton.isEnabled = !inProgress payWithoutAddressButton.isEnabled = !inProgress inProgress ? activityIndicatorView.startAnimating() : activityIndicatorView.stopAnimating() } } // UI lazy var activityIndicatorView = { return UIActivityIndicatorView(style: .gray) }() lazy var payWithoutAddressButton: UIButton = { let button = UIButton(type: .roundedRect) button.setTitle("Pay with Klarna (Unknown Customer Address)", for: .normal) button.addTarget(self, action: #selector(didTapPayButton), for: .touchUpInside) return button }() lazy var payWithAddressButton: UIButton = { let button = UIButton(type: .roundedRect) button.setTitle("Pay with Klarna (Known Customer Address)", for: .normal) button.addTarget(self, action: #selector(didTapPayButton), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Klarna" [payWithAddressButton, payWithoutAddressButton, activityIndicatorView].forEach { subview in view.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false } let constraints = [ payWithAddressButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), payWithAddressButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), payWithoutAddressButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), payWithoutAddressButton.topAnchor.constraint( equalTo: payWithAddressButton.bottomAnchor), activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor), ] NSLayoutConstraint.activate(constraints) } @objc func didTapPayButton(sender: UIButton) { guard StripeAPI.defaultPublishableKey != nil else { delegate?.exampleViewController( self, didFinishWithMessage: "Please set a Stripe Publishable Key in Constants.m") return } inProgress = true if sender == payWithAddressButton { payWithKnownCustomerInfo() } else { payWithoutCustomerInfo() } } } // MARK: - extension KlarnaSourcesExampleViewController { @objc func payWithKnownCustomerInfo() { // You can optionally pass the customer's information to Klarna. If this information is not // provided, Klarna will request it from the customer during checkout. // Note: If you do not provide all required fields (full street address, first/last names, and // email address), Stripe will not forward any address information to Klarna. let address = STPAddress() address.line1 = "29 Arlington Avenue" address.email = "[email protected]" address.city = "London" address.postalCode = "N1 7BE" address.country = "UK" address.phone = "02012267709" // Klarna requires separate first and last names for the customer. let firstName = "Arthur" let lastName = "Dent" // In some EU countries, Klarna uses the user's date of birth for a credit check. let dob = STPDateOfBirth.init() dob.day = 11 dob.month = 3 dob.year = 1952 // Klarna requires individual line items in the transaction to be broken out let items = [ STPKlarnaLineItem( itemType: .SKU, itemDescription: "Towel", quantity: 1, totalAmount: 10000), STPKlarnaLineItem( itemType: .SKU, itemDescription: "Digital Watch", quantity: 2, totalAmount: 20000), STPKlarnaLineItem( itemType: .tax, itemDescription: "Taxes", quantity: 1, totalAmount: 100), STPKlarnaLineItem( itemType: .shipping, itemDescription: "Shipping", quantity: 1, totalAmount: 100), ] let sourceParams = STPSourceParams.klarnaParams( withReturnURL: "payments-example://stripe-redirect", currency: "GBP", purchaseCountry: "UK", items: items, customPaymentMethods: [], // The CustomPaymentMethods flag is ignored outside the US billingAddress: address, billingFirstName: firstName, billingLastName: lastName, billingDOB: dob) // Klarna provides a wide variety of additional configuration options which you can use // via the `additionalAPIParameters` field. See https://stripe.com/docs/sources/klarna for details. if var additionalKlarnaParameters = sourceParams.additionalAPIParameters["klarna"] as? [String: Any] { additionalKlarnaParameters["page_title"] = "Zoo" sourceParams.additionalAPIParameters["klarna"] = additionalKlarnaParameters } payWithSourceParams(sourceParams: sourceParams) } @objc func payWithoutCustomerInfo() { // This is the minimal amount of information required for a Klarna transaction. // Klarna will request additional information from the customer during checkout. let items = [ STPKlarnaLineItem( itemType: .SKU, itemDescription: "Mysterious Item", quantity: 1, totalAmount: 10000) ] let sourceParams = STPSourceParams.klarnaParams( withReturnURL: "payments-example://stripe-redirect", currency: "USD", purchaseCountry: "US", items: items, customPaymentMethods: [.installments, .payIn4]) payWithSourceParams(sourceParams: sourceParams) } @objc func payWithSourceParams(sourceParams: STPSourceParams) { // 1. Create an Klarna Source. STPAPIClient.shared.createSource(with: sourceParams) { source, error in guard let source = source else { self.delegate?.exampleViewController(self, didFinishWithError: error) return } // 2. Redirect your customer to Klarna. self.redirectContext = STPRedirectContext(source: source) { _, _, error in guard error == nil else { self.delegate?.exampleViewController(self, didFinishWithError: error) return } // 3. Poll your backend to show the customer their order status. // This step is ommitted in the example, as our backend does not track orders. self.delegate?.exampleViewController( self, didFinishWithMessage: "Your order was received and is awaiting payment confirmation.") // 4. On your backend, use webhooks to charge the Source and fulfill the order } self.redirectContext?.startRedirectFlow(from: self) } } }
mit
8775da8106cc73b76e3abf97adce4152
40.380435
107
0.639086
5.022427
false
false
false
false
CosmicMind/Samples
Projects/Programmatic/TabsController/TabsController/CyanViewController.swift
1
2126
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use 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 CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 HOLDER 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 UIKit import Material class CyanViewController: UIViewController { let v1 = UIView() open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Color.cyan.base prepareTabItem() v1.motionIdentifier = "v1" v1.backgroundColor = Color.red.base view.layout(v1).center().width(300).height(300) } } extension CyanViewController { fileprivate func prepareTabItem() { tabItem.title = "Cyan" } }
bsd-3-clause
49bec951096203a750ce95c484bf684a
38.37037
88
0.732832
4.533049
false
false
false
false
acastano/swift-bootstrap
userinterfacekit/Sources/Classes/Views/ImageView/NetworkImageView.swift
1
3831
import UIKit import FoundationKit open class NetworkImageView: ImageView { public var currentImageURL: URL? fileprivate var placeholder = ImageView() fileprivate func setupPlaceholder(_ size:CGSize) { if placeholder.superview == nil { placeholder.frame = bounds placeholder.isHidden = true placeholder.contentMode = .center placeholder.backgroundColor = UIColor.clear addViewAtIndexWithSizeAndCenter(placeholder, index:0, size:size) } } public func addPlaceholderImage(_ image:UIImage?) { let size = image != nil ? image!.size : .zero setupPlaceholder(size) placeholder.image = image } public func addPlaceholderImage(_ image:UIImage?, contentMode: UIViewContentMode) { addPlaceholderImage(image) placeholder.contentMode = contentMode } public func loadImage(_ image:UIImage?) { placeholder.isHidden = false runOnMainThread { self.placeholder.isHidden = image != nil self.image = image } } public func loadImageWithURLString(_ image:String?, completion:VoidCompletion?) { let imageURL = image != nil ? URL(string:image!) : nil loadImageWithURL(imageURL, completion:completion) } public func loadImageWithURL(_ imageURL:URL?, completion:VoidCompletion?) { loadImageWithURL(imageURL, defaultImage: nil, completion: completion) } public func loadImageWithURLString(_ image:String?, defaultImage:String?, completion:VoidCompletion?) { let imageURL = image != nil ? URL(string:image!) : nil loadImageWithURL(imageURL, defaultImage: defaultImage, completion: completion) } public func loadImageWithURL(_ imageURL:URL?, defaultImage:String?, completion:VoidCompletion?) { if currentImageURL == nil || (currentImageURL == imageURL) == false || image == nil { cancelLoading(currentImageURL) loadImage(imageURL, defaultImage: defaultImage, completion:completion) } } fileprivate func cancelLoading(_ currentImageURL:URL?) { image = nil if let url = currentImageURL { let cache = ImageCache.imageCache cache.cancelImageForURL(url) } } fileprivate func loadImage(_ imageURL:URL?, defaultImage:String?, completion:VoidCompletion?) { placeholder.isHidden = false currentImageURL = imageURL let cache = ImageCache.imageCache let defaultUIImage = defaultImage != nil ? UIImage(named: defaultImage!) : nil image = defaultUIImage if let imageURL = imageURL { cache.loadImageWithURL(imageURL) { [weak self] image, url in if let instance = self { if url == instance.currentImageURL { instance.image = image == nil ? defaultUIImage : image instance.placeholder.isHidden = instance.image != nil } completion?() } } } } }
apache-2.0
77464ceec744299f8b8619f940d72ded
25.42069
107
0.510311
6.571184
false
false
false
false
mcomella/prox
Prox/Prox/AppDelegate.swift
1
3277
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var placeCarouselViewController: PlaceCarouselViewController? private var authorizedUser: FIRUser? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // create Window window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white; // create root view placeCarouselViewController = PlaceCarouselViewController() window?.rootViewController = placeCarouselViewController // display window?.makeKeyAndVisible() setupFirebase() BuddyBuildSDK.setup() return true } private func setupFirebase() { FIRApp.configure() if let user = FIRAuth.auth()?.currentUser { authorizedUser = user } else { FIRAuth.auth()?.signInAnonymously { (user, error) in guard let user = user else { return print("sign in failed \(error)") } self.authorizedUser = user dump(user) } } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. placeCarouselViewController!.refreshLocation() } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mpl-2.0
ad96b7a813a778e5635815afeff42a15
40.481013
285
0.702777
5.679376
false
false
false
false
aerisweather/Aeris-iOS-Library
Demo/AerisSwiftDemo/ViewController.swift
1
8529
// // ViewController.swift // AerisSwiftDemo // // Created by Nicholas Shipes on 2/2/17. // Copyright © 2017 HAMweather, LLC. All rights reserved. // import UIKit class MenuItem { var title: String var controller: UIViewController init(title: String, controller: UIViewController) { self.title = title self.controller = controller } } class MenuCategory { var title: String var items: [MenuItem]? init(title: String, items: [MenuItem]) { self.title = title self.items = items } } class ViewController: UIViewController { var tableView: UITableView! let controllerCache = NSCache<NSString, UIViewController>() var categories: [MenuCategory]! var endpoint: AWFWeatherEndpoint? override func viewDidLoad() { super.viewDidLoad() let locationItems = [MenuItem(title: "Location Search", controller: LocationSearchViewController())] let generalItems = [MenuItem(title: "Detailed Weather", controller: DetailedWeatherViewController())] categories = [MenuCategory(title: "Locations", items: locationItems), MenuCategory(title: "General Weather", items: generalItems)] // NSArray *locationItems = @[@{ @"title": NSLocalizedString(@"Location Search", nil), @"class": [LocationSearchViewController class] }]; // // NSArray *generalItems, *graphItems; // if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // generalItems = @[@{ @"title": NSLocalizedString(@"Recent Observations", nil), @"class": [RecentObservationsViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Observations", nil), @"class": [NearbyObservationsViewController class] }, // @{ @"title": NSLocalizedString(@"Daily Summaries", nil), @"class": [DailySummariesViewController class] }, // @{ @"title": NSLocalizedString(@"Weekend Forecast", nil), @"class": [WeekendWeatherViewController class] }, // @{ @"title": NSLocalizedString(@"Sun & Moon", nil), @"class": [SunMoonViewController class] }, // @{ @"title": NSLocalizedString(@"Moon Phases", nil), @"class": [MoonPhasesViewController class] }, // @{ @"title": NSLocalizedString(@"Climate Normals", nil), @"class": [NormalsViewController class] }, // @{ @"title": NSLocalizedString(@"Today's Tides", nil), @"class": [TidesViewController class] }, // @{ @"title": NSLocalizedString(@"Indices", nil), @"class": [IndicesViewController class] }, // @{ @"title": NSLocalizedString(@"Drought Monitor", nil), @"class": [DroughtMonitorViewController class] } // ]; // // graphItems = @[@{ @"title": NSLocalizedString(@"Forecast (Line)", nil), @"class": [LineGraphsViewController_iPad class] }, // @{ @"title": NSLocalizedString(@"Forecast (Bar)", nil), @"class": [BarGraphsViewController_iPad class] }, // @{ @"title": NSLocalizedString(@"Forecast Models (Line)", nil), @"class": [ModelGraphsViewController_iPad class] }]; // } // else { // generalItems = @[@{ @"title": NSLocalizedString(@"Detailed Weather", nil), @"class": [DetailedWeatherViewController class] }, // @{ @"title": NSLocalizedString(@"Extended Forecast", nil), @"class": [ForecastViewController class] }, // @{ @"title": NSLocalizedString(@"Recent Observations", nil), @"class": [RecentObservationsViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Observations", nil), @"class": [NearbyObservationsViewController class] }, // @{ @"title": NSLocalizedString(@"Weekend Forecast", nil), @"class": [WeekendWeatherViewController class] }, // @{ @"title": NSLocalizedString(@"Daily Summaries", nil), @"class": [DailySummariesViewController class] }, // @{ @"title": NSLocalizedString(@"Sun & Moon", nil), @"class": [SunMoonViewController class] }, // @{ @"title": NSLocalizedString(@"Moon Phases", nil), @"class": [MoonPhasesViewController class] }, // @{ @"title": NSLocalizedString(@"Climate Normals", nil), @"class": [NormalsViewController class] }, // @{ @"title": NSLocalizedString(@"Today's Tides", nil), @"class": [TidesViewController class] }, // @{ @"title": NSLocalizedString(@"Indices", nil), @"class": [IndicesViewController class] }, // @{ @"title": NSLocalizedString(@"Drought Monitor", nil), @"class": [DroughtMonitorViewController class] } // ]; // // graphItems = @[@{ @"title": NSLocalizedString(@"Forecast (Line)", nil), @"class": [ForecastLineGraphsViewController class] }, // @{ @"title": NSLocalizedString(@"Forecast (Bar)", nil), @"class": [ForecastBarGraphsViewController class] }, // @{ @"title": NSLocalizedString(@"Recent Obs (Line)", nil), @"class": [RecentObsGraphViewController class] }, // @{ @"title": NSLocalizedString(@"Daily Summary (Bar)", nil), @"class": [DailySummaryGraphsViewController class] }, // @{ @"title": NSLocalizedString(@"Forecast Models (Line)", nil), @"class": [ModelGraphsViewController class] }]; // } // // NSArray *severeItems = @[@{ @"title": NSLocalizedString(@"Active Advisories", nil), @"class": [AdvisoriesViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Storm Cells", nil), @"class": [StormCellsViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Storm Reports", nil), @"class": [StormReportsViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Records", nil), @"class": [RecordsViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Earthquakes", nil), @"class": [EarthquakesViewController class] }, // @{ @"title": NSLocalizedString(@"Nearby Threats", nil), @"class": [ThreatsViewController class] }, // @{ @"title": NSLocalizedString(@"Convective Outlook", nil), @"class": [ConvectiveOutlookViewController class] } // ]; // // NSArray *imageItems = @[ //@{@"title": NSLocalizedString(@"Static Map Viewer", nil), @"class": [NSObject class]}, // @{ @"title": NSLocalizedString(@"Apple Map", nil), @"class": [AppleMapViewController class] }, // @{ @"title": NSLocalizedString(@"Google Map", nil), @"class": [GoogleMapViewController class] }, // @{ @"title": NSLocalizedString(@"Mapbox Map", nil), @"class": [MapboxMapViewController class] } // ]; // // self.categories = @[@{ @"title": NSLocalizedString(@"Locations", nil), @"items": locationItems }, // @{ @"title": NSLocalizedString(@"General Weather", nil), @"items": generalItems }, // @{ @"title": NSLocalizedString(@"Graphs", nil), @"items": graphItems }, // @{ @"title": NSLocalizedString(@"Severe Weather", nil), @"items": severeItems }, // @{ @"title": NSLocalizedString(@"Maps", nil), @"items": imageItems } // ]; } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MenuCell") view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) // let place = AWFPlace(city: "seattle", state: "wa", country: "us") // // endpoint = AWFObservations() // endpoint?.get(forPlace: place, options: nil) { (result) in // if let error = result?.error { // print(error) // } else if let results = result?.results { // print(results) // } // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return categories?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories?[section].items?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) if let category = categories?[indexPath.section], let item = category.items?[indexPath.row] { cell.textLabel?.text = item.title } return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let category = categories?[indexPath.section], let item = category.items?[indexPath.row] { item.controller.title = item.title navigationController?.pushViewController(item.controller, animated: true) } } }
bsd-3-clause
1e26c7c2e438a5c3913c9bda7024acd6
46.377778
138
0.689493
3.937211
false
false
false
false
jairoeli/Habit
Zero/Sources/Utils/CharacterLimit.swift
1
1261
// // CharacterLimit.swift // Zero // // Created by Jairo Eli de Leon on 6/12/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import Foundation import UIKit extension NSRange { func range(for str: String) -> Range<String.Index>? { guard location != NSNotFound else { return nil } guard let fromUTFIndex = str.utf16.index(str.utf16.startIndex, offsetBy: location, limitedBy: str.utf16.endIndex) else { return nil } guard let toUTFIndex = str.utf16.index(fromUTFIndex, offsetBy: length, limitedBy: str.utf16.endIndex) else { return nil } guard let fromIndex = String.Index(fromUTFIndex, within: str) else { return nil } guard let toIndex = String.Index(toUTFIndex, within: str) else { return nil } return fromIndex ..< toIndex } } // MARK: - Character limit extension HabitListViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentText = textField.text ?? "" guard let stringRange = range.range(for: currentText) else { return false } let updatedText = currentText.replacingCharacters(in: stringRange, with: string) return updatedText.characters.count <= 20 } }
mit
6c5955f34b2aa8c141a5e751cae86f0c
34.971429
137
0.724384
4.100977
false
false
false
false
vchuo/Photoasis
Photoasis/Classes/Views/Views/ImageViewer/POImageViewerPhotoSavedToCameraRollToastView.swift
1
2421
// // POImageViewerPhotoSavedToCameraRollToastView.swift // イメージビューアーでフォトがカメラロールに保存した情報を伝えるトーストビュー。 // // Created by Vernon Chuo on 2017/02/28. // Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved. // import UIKit import ChuoUtil class POImageViewerPhotoSavedToCameraRollToastView: UIView { // MARK: - Views private let messageLabel = UILabel() // MARK: - Init override init(frame: CGRect) { super.init(frame: CGRectZero) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Public Functions /** ヒントを表示。 */ func display() { CUHelper.animateKeyframes( POConstants.ImageViewerPhotoSavedToCameraRollToastViewDisplayDuration, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.02) { self.alpha = 0.9 } UIView.addKeyframeWithRelativeStartTime(0.98, relativeDuration: 0.02) { self.alpha = 0 } } ) { _ in self.removeFromSuperview() } } // MARK: - Private Functions /** ビューのセットアップ。 */ private func setup() { self.bounds.size = POConstants.ImageViewerPhotoSavedToCameraRollToastViewSize self.layer.cornerRadius = POConstants.ImageViewerPhotoSavedToCameraRollToastViewCornerRadius self.clipsToBounds = true self.backgroundColor = POColors.ImageViewerPhotoSavedToCameraRollToastViewBackgroundColor self.userInteractionEnabled = false self.alpha = 0 // ヒントラベル messageLabel.text = POStrings.ImageViewerPhotoSavedToCameraRollToastViewText messageLabel.font = POFonts.ImageViewerPhotoSavedToCameraRollToastViewLabelFont messageLabel.textColor = POColors.ImageViewerPhotoSavedToCameraRollToastViewLabelTextColor messageLabel.textAlignment = .Center messageLabel.numberOfLines = 0 messageLabel.bounds.size.width = self.bounds.width - POConstants.ImageViewerPhotoSavedToCameraRollToastViewHorizontalContentInset * 2 messageLabel.sizeToFit() messageLabel.center = CUHelper.centerPointOf(self) self.addSubview(messageLabel) } }
mit
4a6afb4d4bf127c8e9a407dc11d41dac
30.861111
141
0.677855
4.691207
false
false
false
false
tqtifnypmb/armature
Sources/Armature/Connection/SingleConnection.swift
1
6759
// // SingleConnection.swift // Armature // // The MIT License (MIT) // // Copyright (c) 2016 tqtifnypmb // // 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 public class SingleConnection: Connection { var curRequest: FCGIRequest? var isMultiplex: Int var server: Server private let sock: Int32 private var stop = false private let inputStream: InputStream private let outputStream: OutputStream required public init(sock: Int32, server: Server) { self.sock = sock self.server = server self.isMultiplex = 0 self.inputStream = RawInputStream(sock: self.sock) self.outputStream = RawOutputStream(sock: self.sock) } public func loop(once: Bool) { defer { if !once { close(self.sock) } } do { while !self.stop { try waitForData(nil) try processInput() if once { break } } } catch { self.stop = true } } public func readLength(len: Int) throws -> [UInt8] { var buffer = [UInt8].init(count: len, repeatedValue: 0) let nread = try self.readInto(&buffer) if nread < len { buffer = [UInt8].init(buffer.dropLast(len - nread)) } return buffer } public func readInto(inout buffer: [UInt8]) throws -> Int { return try self.inputStream.readInto(&buffer) } public func write(inout data: [UInt8]) throws { try self.outputStream.write(&data) } public func halt() { self.stop = true } private func waitForData(timeout: UnsafeMutablePointer<timeval>) throws -> Bool { var nfd = pollfd() nfd.fd = self.sock nfd.events = Int16(POLLIN) let ret = poll(&nfd, 1, -1) if ret == -1 { throw SocketError.SelectFailed(Socket.getErrorDescription()) } return ret != 0 } private func processInput() throws { guard let record = try Record.readFrom(self) else { return } switch record.type { case .GET_VALUE: try self.handleGetValue(record) case .ABORT_REQUEST: try self.handleAbortRequest(record) case .PARAMS: try self.handleParams(record) case .STDIN: self.handleStdIn(record) case .BEGIN_REQUEST: try self.handleBeginRequest(record) case .DATA: self.handleData(record) default: try self.handleUnknownType(record) } } private func handleUnknownType(record: Record) throws { let ret = Record() ret.contentLength = 8 ret.contentData = [UInt8].init(arrayLiteral: record.type.rawValue, 0, 0, 0, 0, 0, 0, 0) ret.type = RecordType.UNKNOWN_TYPE ret.requestId = 0 try ret.writeTo(self) } func handleGetValue(record: Record) throws { guard record.contentLength != 0 , let cntData = record.contentData else { return } let ret = Record() ret.type = RecordType.GET_VALUE_RESULT ret.requestId = 0 var query = Utils.parseNameValueData(cntData) for name in query.keys { switch name { case FCGI_MAX_CONNS: query[name] = String(self.server.maxConnections) case FCGI_MAX_REQS: query[name] = String(self.server.maxRequests) case FCGI_MPXS_CONNS: query[name] = String(isMultiplex) default: break // Unknown query // Ignore it } } ret.contentData = Utils.encodeNameValueData(query) ret.contentLength = UInt16(ret.contentData!.count) try ret.writeTo(self) } func handleAbortRequest(record: Record) throws { //Just close the connection self.halt() } func handleParams(record: Record) throws { guard let req = self.curRequest else { return } guard record.contentLength != 0 , let cntData = record.contentData else { // A empty params is sent // tick the request try self.serveRequest(req) return } let params = Utils.parseNameValueData(cntData) req.params = params } func handleStdIn(record: Record) { guard let req = self.curRequest else { return } if record.contentLength > 0, let cntData = record.contentData { req.STDIN.addData(cntData) } } func handleBeginRequest(record: Record) throws { do { let req = try FCGIRequest(record: record, conn: self) self.curRequest = req } catch DataError.UnknownRole { // let unknown role error throw will tear down the connection return } } func handleData(record: Record) { guard let req = self.curRequest else { return } if record.contentLength > 0, let cntData = record.contentData { req.DATA = cntData } } func serveRequest(req: FCGIRequest) throws { let fcgiServer = self.server as! FCGIServer try fcgiServer.handleRequest(req) self.curRequest = nil } }
mit
0a2d141d915352ea027e7c451efe9f6e
28.90708
95
0.56754
4.573072
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/swifter/XCode/SwifterTestsCommon/SwifterTestsWebSocketSession.swift
1
4997
// // SwifterTests.swift // SwifterTests // // Copyright © 2016 Damian Kołakowski. All rights reserved. // import XCTest class SwifterTestsWebSocketSession: XCTestCase { class TestSocket: Socket { var content = [UInt8]() var offset = 0 init(_ content: [UInt8]) { super.init(socketFileDescriptor: -1) self.content.append(contentsOf: content) } override func read() throws -> UInt8 { if offset < content.count { let value = self.content[offset] offset = offset + 1 return value } throw SocketError.recvFailed("") } } func testParser() { do { let session = WebSocketSession(TestSocket([0])) let _ = try session.readFrame() XCTAssert(false, "Parser should throw an error if socket has not enough data for a frame.") } catch { XCTAssert(true, "Parser should throw an error if socket has not enough data for a frame.") } do { let session = WebSocketSession(TestSocket([0b0000_0001, 0b0000_0000, 0, 0, 0, 0])) let _ = try session.readFrame() XCTAssert(false, "Parser should not accept unmasked frames.") } catch WebSocketSession.WsError.unMaskedFrame { XCTAssert(true, "Parse should throw UnMaskedFrame error for unmasked message.") } catch { XCTAssert(false, "Parse should throw UnMaskedFrame error for unmasked message.") } do { let session = WebSocketSession(TestSocket([0b1000_0001, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssert(frame.fin, "Parser should detect fin flag set.") } catch { XCTAssert(false, "Parser should not throw an error for a frame with fin flag set (\(error)") } do { let session = WebSocketSession(TestSocket([0b0000_0000, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.continue, "Parser should accept Continue opcode.") } catch { XCTAssertTrue(true, "Parser should accept Continue opcode without any errors.") } do { let session = WebSocketSession(TestSocket([0b0000_0001, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.text, "Parser should accept Text opcode.") } catch { XCTAssert(false, "Parser should accept Text opcode without any errors.") } do { let session = WebSocketSession(TestSocket([0b0000_0010, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.binary, "Parser should accept Binary opcode.") } catch { XCTAssert(false, "Parser should accept Binary opcode without any errors.") } do { let session = WebSocketSession(TestSocket([0b1000_1000, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.close, "Parser should accept Close opcode.") } catch let e { XCTAssert(false, "Parser should accept Close opcode without any errors. \(e)") } do { let session = WebSocketSession(TestSocket([0b1000_1001, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.ping, "Parser should accept Ping opcode.") } catch let e { XCTAssert(false, "Parser should accept Ping opcode without any errors. \(e)") } do { let session = WebSocketSession(TestSocket([0b1000_1010, 0b1000_0000, 0, 0, 0, 0])) let frame = try session.readFrame() XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.pong, "Parser should accept Pong opcode.") } catch let e { XCTAssert(false, "Parser should accept Pong opcode without any errors. \(e)") } for opcode in [3, 4, 5, 6, 7, 11, 12, 13, 14, 15] { do { let session = WebSocketSession(TestSocket([UInt8(opcode), 0b1000_0000, 0, 0, 0, 0])) let _ = try session.readFrame() XCTAssert(false, "Parse should throw an error for unknown opcode: \(opcode)") } catch WebSocketSession.WsError.unknownOpCode(_) { XCTAssert(true, "Parse should throw UnknownOpCode error for unknown opcode.") } catch { XCTAssert(false, "Parse should throw UnknownOpCode error for unknown opcode (was \(error)).") } } } }
gpl-3.0
8c85f85be8182019b32512aabb62b60c
40.97479
115
0.579179
4.595216
false
true
false
false
victorpimentel/MarvelAPI
MarvelAPI.playground/Sources/Requests/GetComics.swift
1
896
import Foundation public struct GetComics: APIRequest { // When encountered with this kind of enums, it will spit out the raw value public enum ComicFormat: String, Encodable { case comic = "comic" case digital = "digital comic" case hardcover = "hardcover" } public typealias Response = [Comic] public var resourceName: String { return "comics" } // Parameters public let title: String? public let titleStartsWith: String? public let format: ComicFormat? public let limit: Int? public let offset: Int? // Note that nil parameters will not be used public init(title: String? = nil, titleStartsWith: String? = nil, format: ComicFormat? = nil, limit: Int? = nil, offset: Int? = nil) { self.title = title self.titleStartsWith = titleStartsWith self.format = format self.limit = limit self.offset = offset } }
apache-2.0
b5b6a6a4dbb4a43c42bfce1d876d76f4
23.888889
76
0.677455
3.612903
false
false
false
false
banxi1988/BXAppKit
BXForm/View/CircleImageView.swift
1
1592
// // CircleImageView.swift // // Created by Haizhen Lee on 14/12/10. // import UIKit //@IBDesignable // reduce performance open class CircleImageView: UIImageView { // @IBInspectable open var borderWidth:CGFloat=3.0{ didSet{ updateBorderStyle() } } // @IBInspectable open var borderColor:UIColor=UIColor(white: 0.5, alpha: 0.5){ didSet{ updateBorderStyle() } } open func updateBorderStyle(){ layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } func commonInit(){ layer.cornerRadius = frame.size.width * 0.5 clipsToBounds = true updateBorderStyle() } open lazy var maskLayer : CAShapeLayer = { [unowned self] in let maskLayer = CAShapeLayer() maskLayer.frame = self.frame self.layer.mask = maskLayer return maskLayer }() open override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = bounds.width * 0.5 maskLayer.frame = bounds maskLayer.path = UIBezierPath(ovalIn:bounds).cgPath } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public override init(image: UIImage?) { super.init(image: image) commonInit() } public override init(image: UIImage?, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) commonInit() } }
mit
97cc75b0ad43dd6aa3debc0df1d938ae
19.675325
69
0.660176
4.337875
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift
3
1186
// // FillRenderer.swift // lottie-swift // // Created by Brandon Withrow on 1/30/19. // import CoreGraphics import Foundation import QuartzCore extension FillRule { var cgFillRule: CGPathFillRule { switch self { case .evenOdd: return .evenOdd default: return .winding } } var caFillRule: CAShapeLayerFillRule { switch self { case .evenOdd: return CAShapeLayerFillRule.evenOdd default: return CAShapeLayerFillRule.nonZero } } } // MARK: - FillRenderer /// A rendered for a Path Fill final class FillRenderer: PassThroughOutputNode, Renderable { var shouldRenderInContext = false var color: CGColor? { didSet { hasUpdate = true } } var opacity: CGFloat = 0 { didSet { hasUpdate = true } } var fillRule: FillRule = .none { didSet { hasUpdate = true } } func render(_: CGContext) { // do nothing } func setupSublayers(layer _: CAShapeLayer) { // do nothing } func updateShapeLayer(layer: CAShapeLayer) { layer.fillColor = color layer.opacity = Float(opacity) layer.fillRule = fillRule.caFillRule hasUpdate = false } }
apache-2.0
47279051434d9c1af8b058f7ab6f85f2
15.704225
61
0.642496
4.176056
false
false
false
false
xmartlabs/Bender
Sources/Layers/Scale.swift
1
1391
// // LanczosLayer.swift // Bender // // Created by Mathias Claassen on 4/24/17. // Copyright © 2017 Xmartlabs. All rights reserved. // import MetalPerformanceShaders import MetalPerformanceShadersProxy /// Scales the input image to a given size open class Scale: NetworkLayer { public var lanczos: MPSImageLanczosScale! public init(layerSize: LayerSize, id: String? = nil) { super.init(id: id) self.outputSize = layerSize } open override func validate() { let incoming = getIncoming() assert(incoming.count == 1, "Scale must have one input, not \(incoming.count)") } open override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) { super.initialize(network: network, device: device, temporaryImage: temporaryImage) lanczos = MPSImageLanczosScale(device: device) createOutputs(size: outputSize, temporary: temporaryImage) } open override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) { let input = getIncoming()[0].getOutput(index: index) let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index) lanczos.encode(commandBuffer: commandBuffer, sourceTexture: input.texture, destinationTexture: output.texture) input.setRead() } }
mit
43a2d440d5bd554bc4257096e3fe81ce
32.902439
101
0.679856
4.412698
false
false
false
false
dflax/Anagrams
Anagrams/HUDView.swift
1
1244
// // HUDView.swift // Anagrams // // Created by Daniel Flax on 4/30/15. // Copyright (c) 2015 Caroline. All rights reserved. // import UIKit class HUDView: UIView { var stopwatch: StopwatchView var gamePoints: CounterLabelView // this should never be called required init(coder aDecoder:NSCoder) { fatalError("use init(frame:") } override init(frame:CGRect) { self.stopwatch = StopwatchView(frame:CGRectMake(ScreenWidth/2-150, 0, 300, MarginTop)) self.stopwatch.setSeconds(0) // Dynamic points label self.gamePoints = CounterLabelView(font: FontHUD, frame: CGRectMake(ScreenWidth-200, 30, 200, 70)) gamePoints.textColor = UIColor(red: 0.38, green: 0.098, blue: 0.035, alpha: 1) gamePoints.value = 0 super.init(frame:frame) self.addSubview(self.stopwatch) // Add the Points HUD to the scene self.addSubview(gamePoints) //"points" label var pointsLabel = UILabel(frame: CGRectMake(ScreenWidth-340, 30, MarginTop * 1.5, 70)) pointsLabel.backgroundColor = UIColor.clearColor() pointsLabel.font = FontHUD pointsLabel.text = " Points:" self.addSubview(pointsLabel) // Turn off user interactions for the HUD, so touches flow through to the game self.userInteractionEnabled = false } }
mit
9a2d37f88702b7e937612e01e6058110
24.387755
100
0.724277
3.398907
false
false
false
false
thkl/NetatmoSwift
netatmoclient/NetatmoStationProvider.swift
1
2764
// // NetatmoStationProvider.swift // netatmoclient // // Created by Thomas Kluge on 04.10.15. // Copyright © 2015 kSquare.de. All rights reserved. // import Foundation import CoreData struct NetatmoStation: Equatable { var id: String var stationName: String! var type: String! var lastUpgrade : Date! var firmware : Int! var moduleIds : Array<String> = [] var lastStatusStore : Date = Date() } func ==(lhs: NetatmoStation, rhs: NetatmoStation) -> Bool { return lhs.id == rhs.id } extension NetatmoStation { init(managedObject : NSManagedObject) { self.id = managedObject.value(forKey: "stationid") as! String self.stationName = managedObject.value(forKey: "stationname") as! String self.type = managedObject.value(forKey: "stationtype") as! String } var measurementTypes : [NetatmoMeasureType] { switch self.type { case "NAMain": return [.Temperature,.CO2,.Humidity,.Pressure,.Noise] case "NAModule1","NAModule4": return [.Temperature,.Humidity] case "NAModule3": return [.Rain] case "NAModule2": return [.WindStrength,.WindAngle] default: return [] } } } class NetatmoStationProvider { fileprivate let coreDataStore: CoreDataStore! init(coreDataStore : CoreDataStore?) { if (coreDataStore != nil) { self.coreDataStore = coreDataStore } else { self.coreDataStore = CoreDataStore() } } func save() { try! coreDataStore.managedObjectContext.save() } func stations()->Array<NetatmoStation> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Station") fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] return results.map{NetatmoStation(managedObject: $0 )} } func createStation(_ id: String, name: String, type : String)->NSManagedObject { let newStation = NSManagedObject(entity: coreDataStore.managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName["Station"]!, insertInto: coreDataStore.managedObjectContext) newStation.setValue(id, forKey: "stationid") newStation.setValue(name, forKey: "stationname") newStation.setValue(type, forKey: "stationtype") try! coreDataStore.managedObjectContext.save() return newStation } func getStationWithId(_ id: String)->NSManagedObject? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Station") fetchRequest.predicate = NSPredicate(format: "stationid == %@", argumentArray: [id]) fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] return results.first } }
apache-2.0
3dc2fd67d3b42cf81823ef0cbe485388
28.084211
202
0.706478
4.24424
false
false
false
false
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDK/BSCurrenciesViewController.swift
1
4406
// // BSCurrenciesViewController.swift // BluesnapSDK // // Created by Shevie Chen on 11/05/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import UIKit class BSCurrenciesViewController: BSBaseListController { // MARK: private properties fileprivate var oldSelectedItem : (name: String, code: String)? fileprivate var bsCurrencies : BSCurrencies? fileprivate var filteredItems : BSCurrencies? // the callback function that gets called when a currency is selected; // this is just a default fileprivate var updateFunc : (BSCurrency?, BSCurrency)->Void = { oldCurrency, newCurrency in NSLog("Currency \(newCurrency.getCode() ?? "None") was selected") } // MARK: init currencies /** init the screen variables, re-load rates */ func initCurrencies(currencyCode : String, currencies : BSCurrencies, updateFunc : @escaping (BSCurrency?, BSCurrency)->Void) { self.updateFunc = updateFunc self.bsCurrencies = currencies if let bsCurrency = currencies.getCurrencyByCode(code: currencyCode) { self.selectedItem = (name: bsCurrency.getName(), code: bsCurrency.getCode()) self.oldSelectedItem = self.selectedItem } } // MARK: Override functions of BSBaseListController override func setTitle() { self.title = BSLocalizedStrings.getString(BSLocalizedString.Title_Currency_Screen) } override func doFilter(_ searchText : String) { if searchText == "" { filteredItems = self.bsCurrencies } else if let bsCurrencies = self.bsCurrencies { let filtered = bsCurrencies.currencies.filter{(x) -> Bool in (x.name.uppercased().range(of:searchText.uppercased())) != nil } filteredItems = BSCurrencies(baseCurrency: bsCurrencies.baseCurrency, currencies: filtered) } else { filteredItems = BSCurrencies(baseCurrency: "USD", currencies: []) } generateGroups() self.tableView.reloadData() } override func selectItem(newItem: (name: String, code: String)) { if let bsCurrencies = bsCurrencies { var oldBsCurrency : BSCurrency? if let oldItem = oldSelectedItem { oldBsCurrency = bsCurrencies.getCurrencyByCode(code: oldItem.code) } oldSelectedItem = newItem let newBsCurrency = bsCurrencies.getCurrencyByCode(code: newItem.code) // call updateFunc updateFunc(oldBsCurrency, newBsCurrency!) } } override func createTableViewCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reusableCell = tableView.dequeueReusableCell(withIdentifier: "CurrencyTableViewCell", for: indexPath) let cell = reusableCell as! BSCurrencyTableViewCell let firstLetter = groupSections[indexPath.section] if let currency = groups[firstLetter]?[indexPath.row] { cell.CurrencyUILabel.text = currency.name + " " + currency.code cell.checkMarkImage.image = nil if (currency.code == selectedItem.code) { if let image = BSViewsManager.getImage(imageName: "blue_check_mark") { cell.checkMarkImage.image = image } } else { cell.checkMarkImage.image = nil } } return cell } // MARK: private functions private func generateGroups() { groups = [String: [(name: String, code: String)]]() for bsCurrency: BSCurrency in (filteredItems?.currencies)! { let currency: (name: String, code: String) = (name: bsCurrency.getName(), code: bsCurrency.getCode()) let name = currency.name let firstLetter = "\(name[name.startIndex])".uppercased() if var currenciesByFirstLetter = groups[firstLetter] { currenciesByFirstLetter.append(currency) groups[firstLetter] = currenciesByFirstLetter } else { groups[firstLetter] = [currency] } } groupSections = [String](groups.keys) groupSections = groupSections.sorted() } }
mit
c6e2755ec25d2c98b33424488c498986
36.330508
137
0.613621
5.028539
false
false
false
false
haawa799/Metal-Flaps
SimpleMetal/Main/MetalView.swift
1
3500
// // MetalView.swift // Triangle // // Created by Andrew K. on 6/24/14. // Copyright (c) 2014 Andrew Kharchyshyn. All rights reserved. // import UIKit import QuartzCore import Metal @objc public protocol MetalViewProtocol { @objc func render(metalView : MetalView) @objc func reshape(metalView : MetalView) } @objc public class MetalView: UIView { //Public API @objc public var metalViewDelegate: MetalViewProtocol? var frameBuffer: AnyObject! func setFPSLabelHidden(hidden: Bool){ if let label = fpsLabel{ label.isHidden = hidden } } override init(frame: CGRect) { super.init(frame: frame) // Initialization code setup() } required init(coder aDecoder: NSCoder){ super.init(coder: aDecoder)! setup() } func display() { let frameBuf = frameBuffer as! FrameBuffer frameBuf.drawableSize = self.bounds.size frameBuf.drawableSize.width *= self.contentScaleFactor; frameBuf.drawableSize.height *= self.contentScaleFactor; var size = self.bounds.size size.width *= self.contentScaleFactor size.height *= self.contentScaleFactor frameBuf.display(withDrawableSize: size) } //Private var lastFrameTimestamp: CFTimeInterval? var _metalLayer: CAMetalLayer! var fpsLabel: UILabel! public override class var layerClass: AnyClass { return CAMetalLayer.self } public override func layoutSubviews(){ let rightConstraint = NSLayoutConstraint(item: fpsLabel!, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -10.0) let botConstraint = NSLayoutConstraint(item: fpsLabel!, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -40.0) let heightConstraint = NSLayoutConstraint(item: fpsLabel!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 25.0) let widthConstraint = NSLayoutConstraint(item: fpsLabel!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 60.0) self.addConstraints([rightConstraint,botConstraint,widthConstraint,heightConstraint]) (frameBuffer as! FrameBuffer).layerSizeDidUpdate = true super.layoutSubviews() } func setup(){ fpsLabel = UILabel() fpsLabel.translatesAutoresizingMaskIntoConstraints = false fpsLabel.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6) self.addSubview(fpsLabel!) self.isOpaque = true self.backgroundColor = nil // setting this to yes will allow Main thread to display framebuffer when // view:setNeedDisplay: is called by main thread _metalLayer = self.layer as? CAMetalLayer self.contentScaleFactor = UIScreen.main.scale _metalLayer.presentsWithTransaction = false _metalLayer.drawsAsynchronously = true let device = MTLCreateSystemDefaultDevice() _metalLayer.device = device _metalLayer.pixelFormat = MTLPixelFormat.bgra8Unorm _metalLayer.framebufferOnly = true frameBuffer = FrameBuffer(metalView: self) } }
mit
f8b953d15e405ac7987f503ee34d7d02
31.110092
179
0.645143
4.748982
false
false
false
false
anto0522/AdMate
AdDataKit2/GetData.swift
1
15289
// // GetData.swift // AdMate // // Created by Antonin Linossier on 11/2/15. // Copyright © 2015 Antonin Linossier. All rights reserved. // import Foundation import SQLite import Cocoa import p2_OAuth2 import AdMateOAuth public let settings = [ "client_id": "1079482800287-7njdh0lfjvsnsf50pp00iikquusduuua.apps.googleusercontent.com", "client_secret": "", "authorize_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "scope": "https://www.googleapis.com/auth/adsense", "redirect_uris": ["com.googleusercontent.apps.1079482800287-7njdh0lfjvsnsf50pp00iikquusduuua:/"], "title": "AdMate", "response_type": "token", "verbose": true, "approval_prompt" : "auto" // TO BE CHANGED TO AUTO // optional title to show in views ] as OAuth2JSON public let oauth2 = OAuth2CodeGrant(settings: settings) public func GetDataFromDb(completion: (Done: [AdData]) -> Void){ var RetrievedData = [AdData]() let calendar = NSCalendar.autoupdatingCurrentCalendar() let MyFormatter = NSDateFormatter() MyFormatter.dateFormat = "yyyy-MM-dd" let DbPath = getPath("AdMate.db").absoluteString print("DBPATH READ") print(DbPath) let db = try! Connection(DbPath) for i in 0...70 { // Insert some dummy data to fill blanks so we don't have to worry about nil values. let Date = calendar.dateByAddingUnit( [.Day], value: -i, toDate: NSDate(), options: [])! let formatedDate = MyFormatter.stringFromDate(Date) let insert = AdDataTable.insert(AdRequestData <- "\(0)", AdRequestCoverageData <- "\(0)", AdRequestCTRData <- "\(0)", AdRequestRPMData <- "\(0)", ClicksData <- "\(0)", CostPerClickData <- "\(0)", EarningsData <- "\(0)", PageViewRPMData <- "\(0)", PageViewsData <- "\(0)", MatchedAdREquestData <- "\(0)", DateData <- "\(formatedDate)") do { try db.run(insert) } catch _ { // print("Data does exist for date \(formatedDate)") } } // Maybe add closure to make sure the dummy data gets inserted before reading it do { for AdDB in try db.prepare(AdDataTable) { // need to unwarp here RetrievedData.append(AdData(AdRequest: AdDB[AdRequestData], AdRequestCoverage: AdDB[AdRequestCoverageData], AdRequestCTR: AdDB[AdRequestCTRData], AdRequestRPM: AdDB[AdRequestRPMData], AdClicks: AdDB[ClicksData], AdCostPerClick: AdDB[CostPerClickData], Earnings: AdDB[EarningsData], PageViews: AdDB[PageViewsData], PageViewRPM: AdDB[PageViewRPMData], MatchedAdRequest: AdDB[MatchedAdREquestData], Date: AdDB[DateData])) } } catch _ { // print("Data does exist for date \(formatedDate)") } completion(Done: RetrievedData) // } else { // // print("could not get DB path") // // // } // completion(UpdateStatus: false) } public func FetchDataFromAPI(AccountID:String, completion: (UpdateStatus: Bool) -> Void){ let url = "https://www.googleapis.com/adsense/v1.4/reports" let calendar = NSCalendar.autoupdatingCurrentCalendar() let TodayDate = NSDate() let MyFormatter = NSDateFormatter() MyFormatter.dateFormat = "yyyy-MM-dd" let EndDate = calendar.dateByAddingUnit( [.Day], value: -70, toDate: NSDate(), options: [])! let EndDateString = MyFormatter.stringFromDate(EndDate) let TodayDateString = MyFormatter.stringFromDate(TodayDate) print(TodayDateString) print("HERE") let params = ["endDate": TodayDateString, "startDate": EndDateString, "metric": "AD_REQUESTS", "accountId": AccountID] as Dictionary<String, String> // Calls basic parameters such as start and end date + User ID + One parameter // The number of ad units that requested ads (for content ads) or search queries (for search ads). An ad request may result in zero, one, or multiple individual ad impressions depending on the size of the ad unit and whether any ads were available. let AdRequestConverage = ["metric": "AD_REQUESTS_COVERAGE"] as Dictionary<String, String> // The ratio of requested ad units or queries to the number returned to the site. let Ctr = ["metric": "AD_REQUESTS_CTR"] as Dictionary<String, String> // The ratio of ad requests that resulted in a click. let AdRequestRpm = ["metric": "AD_REQUESTS_RPM"] as Dictionary<String, String> // The revenue per thousand ad requests. This is calculated by dividing estimated revenue by the number of ad requests multiplied by 1000. let Clicks = ["metric": "CLICKS"] as Dictionary<String, String> // The number of times a user clicked on a standard content ad. let CostPerClick = ["metric": "COST_PER_CLICK"] as Dictionary<String, String> // The amount you earn each time a user clicks on your ad. CPC is calculated by dividing the estimated revenue by the number of clicks received. let Earnings = ["metric": "EARNINGS"] as Dictionary<String, String> // The estimated earnings of the publisher. Note that earnings up to yesterday are accurate, more recent earnings are estimated due to the possibility of spam, or exchange rate fluctuations. let PageViews = ["metric": "PAGE_VIEWS"] as Dictionary<String, String> // The number of page views. let PageViewsRPM = ["metric": "PAGE_VIEWS_RPM"] as Dictionary<String, String> // The revenue per thousand page views. This is calculated by dividing your estimated revenue by the number of page views multiplied by 1000. let MatchedAdRequest = ["metric": "MATCHED_AD_REQUESTS"] as Dictionary<String, String> // The number of ad units (for content ads) or search queries (for search ads) that showed ads. A matched ad request is counted for each ad request that returns at least one ad to the site. let DateDimension = ["dimension": "DATE"] as Dictionary<String, String> // Dimensions let parameterString = params.stringFromHttpParameters() + "&" + AdRequestConverage.stringFromHttpParameters() + "&" + Ctr.stringFromHttpParameters() + "&" + AdRequestRpm.stringFromHttpParameters() + "&" + Clicks.stringFromHttpParameters() + "&" + CostPerClick.stringFromHttpParameters() + "&" + Earnings.stringFromHttpParameters() + "&" + PageViews.stringFromHttpParameters() + "&" + PageViewsRPM.stringFromHttpParameters() + "&" + PageViews.stringFromHttpParameters() + "&" + DateDimension.stringFromHttpParameters() + "&" + MatchedAdRequest.stringFromHttpParameters() let requestURL = NSURL(string:"\(url)?\(parameterString)")! let req = oauth2.request(forURL: requestURL) NSLog("AdMate initiated an API request: %@", requestURL) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(req) { data, response, error in if nil != error { dispatch_async(dispatch_get_main_queue()) { print(error?.localizedDescription) completion(UpdateStatus: false) } } else { do { if let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { if let HeaderDict = dict["headers"] { let DbPath = getPath("AdMate.db").absoluteString print("DBPATH INSERT") print(DbPath) let db = try! Connection(DbPath) // Crash here var headerdict = [String:Int]() var CurrencyDict = [String:String]() for i in 0...11 { // Getting the headers names if HeaderDict[i]["name"] != nil{ if let dimention = (dict["headers"]![i]["name"] as? String) { headerdict[dimention] = i } else { print("Error Getting Headers") completion(UpdateStatus: false) } } if let currency = (dict["headers"]![i]["currency"] as? String) { CurrencyDict["currency"] = currency // Getting the currency symbol } } // Saving the currency symbol after getting the $ if CurrencyDict["currency"] != nil { let Symbol = GetCurrencySymbol(CurrencyDict["currency"]!) defaults.setObject(Symbol, forKey: "CCYSYMBOL") defaults.synchronize() } if let RowData = dict["rows"] { if RowData.count != 0 { print(RowData) try db.run(AdDataTable.delete()) print("Deleting ...") for i in 0...RowData.count - 1 { // Parsing the data let CurrentRow = dict.objectForKey("rows")!.objectAtIndex(i) as! [String] // print(CurrentRow[headerdict["DATE"]!]) let insert = AdDataTable.insert(AdRequestData <- "\(CurrentRow[headerdict["AD_REQUESTS"]!])", AdRequestCoverageData <- "\(CurrentRow[headerdict["AD_REQUESTS_COVERAGE"]!])", AdRequestCTRData <- "\(CurrentRow[headerdict["AD_REQUESTS_CTR"]!])", AdRequestRPMData <- "\(CurrentRow[headerdict["AD_REQUESTS_RPM"]!])", ClicksData <- "\(CurrentRow[headerdict["CLICKS"]!])", CostPerClickData <- "\(CurrentRow[headerdict["COST_PER_CLICK"]!])", EarningsData <- "\(CurrentRow[headerdict["EARNINGS"]!])", PageViewRPMData <- "\(CurrentRow[headerdict["PAGE_VIEWS_RPM"]!])", PageViewsData <- "\(CurrentRow[headerdict["PAGE_VIEWS"]!])", MatchedAdREquestData <- "\(CurrentRow[headerdict["MATCHED_AD_REQUESTS"]!])", DateData <- "\(CurrentRow[headerdict["DATE"]!])") do { try db.run(insert) } catch _ { print("Insert Failed") completion(UpdateStatus: false) } } dispatch_async(dispatch_get_main_queue()) { defaults.setObject(NSDate(), forKey: "LastUpdateTimeStamp") defaults.synchronize() completion(UpdateStatus: true) // Main Queue } } } } else { if let ErrorDict = dict["error"] { if let ErrorMessage = ErrorDict["errors"]!![0]!["message"]{ print(ErrorMessage) NSLog("ErrorMessage") // Send notificationt to re-authenticate defaults.setObject(nil, forKey: UserIDDefault) defaults.synchronize() NSNotificationCenter.defaultCenter().postNotificationName("ReValidateUser", object: nil) } } NSLog("Could not get headers") completion(UpdateStatus: false) } } else { NSLog("Unable to parse JSON") completion(UpdateStatus: false) } } catch let error { dispatch_async(dispatch_get_main_queue()) { print(error) completion(UpdateStatus: false) } } } } task.resume() }
mit
e9281cf9310c47cf965e999b06a4eef4
39.768
782
0.451727
6.047468
false
false
false
false
lorentey/swift
test/APINotes/versioned-objc.swift
3
9068
// RUN: %empty-directory(%t) // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 5 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-5 %s // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s // REQUIRES: objc_interop import APINotesFrameworkTest // CHECK-DIAGS-5-NOT: versioned-objc.swift:[[@LINE-1]]: class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember { // CHECK-DIAGS-4: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied func requirement() -> Any? { return nil } } func testNonGeneric() { // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int' let _: Int = NewlyGenericSub.defaultElement() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: generic class 'NewlyGenericSub' requires that 'Int' be a class type // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub' let _: Int = NewlyGenericSub<Base>.defaultElement() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int' } func testRenamedGeneric() { // CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: OldRenamedGeneric<Base> = RenamedGeneric<Base>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' // CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: RenamedGeneric<Base> = OldRenamedGeneric<Base>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' class SwiftClass {} // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: OldRenamedGeneric<SwiftClass> = RenamedGeneric<SwiftClass>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base' // CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: RenamedGeneric<SwiftClass> = OldRenamedGeneric<SwiftClass>() // CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' } func testRenamedClassMembers(obj: ClassWithManyRenames) { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(swift4Factory:)' _ = ClassWithManyRenames.classWithManyRenamesForInt(0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(for:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(swift4Factory:)' _ = ClassWithManyRenames(forInt: 0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(for:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift4Factory: 0) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Factory:)' has been renamed to 'init(for:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(for:)' has been renamed to 'init(swift4Factory:)' _ = ClassWithManyRenames(for: 0) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)' _ = ClassWithManyRenames(boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift4Boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)' _ = ClassWithManyRenames(finalBoolean: false) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift4DoImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty' _ = ClassWithManyRenames.importantClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames.swift4ClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty' _ = ClassWithManyRenames.finalClassProperty // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: } func testRenamedProtocolMembers(obj: ProtoWithManyRenames) { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)' _ = type(of: obj).init(boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).init(swift4Boolean: false) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)' _ = type(of: obj).init(finalBoolean: false) // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift4DoImportantThings() // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty' _ = type(of: obj).importantClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).swift4ClassProperty // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty' _ = type(of: obj).finalClassProperty // CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}: } extension PrintingRenamed { func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print() // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print(self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } static func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method print() // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method print(self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } } extension PrintingInterference { func testDroppingRenamedPrints() { // CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method print(self) // CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: missing argument for parameter 'extra' in call // CHECK-DIAGS-4-NOT: [[@LINE+1]]:{{[0-9]+}}: print(self, extra: self) // CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}: } } let unrelatedDiagnostic: Int = nil
apache-2.0
fd8a7a2eb3eaeb5bd0d4574703591a65
50.231638
227
0.647662
3.630104
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/model/geom2d/Ellipse.swift
1
413
import Foundation open class Ellipse: Locus { open let cx: Double open let cy: Double open let rx: Double open let ry: Double public init(cx: Double = 0, cy: Double = 0, rx: Double = 0, ry: Double = 0) { self.cx = cx self.cy = cy self.rx = rx self.ry = ry } // GENERATED NOT open func arc(shift: Double, extent: Double) -> Arc { return Arc(ellipse: self, shift: shift, extent: extent) } }
mit
86315dfecf53f29a73143c5cc862f068
17.772727
78
0.644068
2.828767
false
false
false
false
benlangmuir/swift
test/Concurrency/Runtime/async_task_locals_groups.swift
9
3116
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: rdar82092187 // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.1, *) enum TL { @TaskLocal static var number = 0 } @available(SwiftStdlib 5.1, *) @discardableResult func printTaskLocal<V>( _ key: TaskLocal<V>, _ expected: V? = nil, file: String = #file, line: UInt = #line ) -> V? { let value = key.get() print("\(key) (\(value)) at \(file):\(line)") if let expected = expected { assert("\(expected)" == "\(value)", "Expected [\(expected)] but found: \(value), at \(file):\(line)") } return expected } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.1, *) func groups() async { // no value _ = await withTaskGroup(of: Int.self) { group in printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) } // no value in parent, value in child let x1: Int = await withTaskGroup(of: Int.self) { group in group.spawn { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) // inside the child task, set a value _ = TL.$number.withValue(1) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (1) } printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) return TL.$number.get() // 0 } return await group.next()! } assert(x1 == 0) // value in parent and in groups await TL.$number.withValue(2) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) let x2: Int = await withTaskGroup(of: Int.self) { group in printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) group.spawn { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) async let childInsideGroupChild = printTaskLocal(TL.$number) _ = await childInsideGroupChild // CHECK: TaskLocal<Int>(defaultValue: 0) (2) return TL.$number.get() } printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) return await group.next()! } assert(x2 == 2) } } @available(SwiftStdlib 5.1, *) func taskInsideGroup() async { Task { print("outside") // CHECK: outside _ = await withTaskGroup(of: Int.self) { group -> Int in print("in group") // CHECK: in group printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) for _ in 0..<5 { Task { printTaskLocal(TL.$number) print("some task") } } return 0 } } // CHECK: some task // CHECK: some task // CHECK: some task // CHECK: some task await Task.sleep(5 * 1_000_000_000) // await t.value } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { await groups() await taskInsideGroup() } }
apache-2.0
d4fa17d1f31e879d29d0c754a7851be9
25.632479
130
0.604621
3.700713
false
false
false
false
xtrinch/MRCountryPicker
MRCountryPicker/Classes/SwiftCountryPicker.swift
1
5362
import UIKit import CoreTelephony @objc public protocol MRCountryPickerDelegate { func countryPhoneCodePicker(_ picker: MRCountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage) } struct Country { var code: String? var name: String? var phoneCode: String? var flag: UIImage? { guard let code = self.code else { return nil } return UIImage(named: "SwiftCountryPicker.bundle/Images/\(code.uppercased())", in: Bundle(for: MRCountryPicker.self), compatibleWith: nil) } init(code: String?, name: String?, phoneCode: String?) { self.code = code self.name = name self.phoneCode = phoneCode } } open class MRCountryPicker: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource { var countries: [Country]! open var selectedLocale: Locale? open weak var countryPickerDelegate: MRCountryPickerDelegate? open var showPhoneNumbers: Bool = true override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { countries = countryNamesByCode() if let code = Locale.current.languageCode { self.selectedLocale = Locale(identifier: code) } super.dataSource = self super.delegate = self } // MARK: - Locale Methods open func setLocale(_ locale: String) { self.selectedLocale = Locale(identifier: locale) } // MARK: - Country Methods open func setCountry(_ code: String) { for index in 0..<countries.count { if countries[index].code == code { return self.setCountryByRow(row: index) } } } open func setCountryByPhoneCode(_ phoneCode: String) { for index in 0..<countries.count { if countries[index].phoneCode == phoneCode { return self.setCountryByRow(row: index) } } } open func setCountryByName(_ name: String) { for index in 0..<countries.count { if countries[index].name == name { return self.setCountryByRow(row: index) } } } func setCountryByRow(row: Int) { self.selectRow(row, inComponent: 0, animated: true) let country = countries[row] if let countryPickerDelegate = countryPickerDelegate { countryPickerDelegate.countryPhoneCodePicker(self, didSelectCountryWithName: country.name!, countryCode: country.code!, phoneCode: country.phoneCode!, flag: country.flag!) } } // Populates the metadata from the included json file resource func countryNamesByCode() -> [Country] { var countries = [Country]() let frameworkBundle = Bundle(for: type(of: self)) guard let jsonPath = frameworkBundle.path(forResource: "SwiftCountryPicker.bundle/Data/countryCodes", ofType: "json"), let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else { return countries } do { if let jsonObjects = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? NSArray { for jsonObject in jsonObjects { guard let countryObj = jsonObject as? NSDictionary else { return countries } guard let code = countryObj["code"] as? String, let phoneCode = countryObj["dial_code"] as? String, let name = countryObj["name"] as? String else { return countries } let country = Country(code: code, name: name, phoneCode: phoneCode) countries.append(country) } } } catch { return countries } return countries } // MARK: - Picker Methods open func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return countries.count } open func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var resultView: SwiftCountryView if view == nil { resultView = SwiftCountryView() } else { resultView = view as! SwiftCountryView } resultView.setup(countries[row], locale: self.selectedLocale) if !showPhoneNumbers { resultView.countryCodeLabel.isHidden = true } return resultView } open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let country = countries[row] if let countryPickerDelegate = countryPickerDelegate { countryPickerDelegate.countryPhoneCodePicker(self, didSelectCountryWithName: country.name!, countryCode: country.code!, phoneCode: country.phoneCode!, flag: country.flag!) } } }
mit
01905a8ccd2ccb89cab3f268e6d7f53e
33.152866
202
0.604066
5.053723
false
false
false
false
frootloops/swift
test/SwiftSyntax/LazyCaching.swift
5
1009
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // REQUIRES: objc_interop import StdlibUnittest import Foundation import Dispatch import SwiftSyntax var LazyCaching = TestSuite("LazyCaching") LazyCaching.test("Pathological") { let tuple = SyntaxFactory.makeVoidTupleType() DispatchQueue.concurrentPerform(iterations: 100) { _ in expectEqual(tuple.leftParen, tuple.leftParen) } } LazyCaching.test("TwoAccesses") { let tuple = SyntaxFactory.makeVoidTupleType() let queue1 = DispatchQueue(label: "queue1") let queue2 = DispatchQueue(label: "queue2") var node1: TokenSyntax? var node2: TokenSyntax? let group = DispatchGroup() queue1.async(group: group) { node1 = tuple.leftParen } queue2.async(group: group) { node2 = tuple.leftParen } group.wait() let final = tuple.leftParen expectNotNil(node1) expectNotNil(node2) expectEqual(node1, node2) expectEqual(node1, final) expectEqual(node2, final) } runAllTests()
apache-2.0
c683ccfdb36d2f0e9e7fdd52c6855794
19.591837
57
0.731417
3.750929
false
true
false
false
frootloops/swift
test/SILGen/nested_types_referencing_nested_functions.swift
4
1004
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s do { func foo() { bar(2) } func bar<T>(_: T) { foo() } class Foo { // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo { init() { foo() } // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> () func zim() { foo() } // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_C4zangyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> () func zang<T>(_ x: T) { bar(x) } // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> () deinit { foo() } } let x = Foo() x.zim() x.zang(1) _ = Foo.zim _ = Foo.zang as (Foo) -> (Int) -> () _ = x.zim _ = x.zang as (Int) -> () }
apache-2.0
1433448a7753bc09fa369f0a69970b4d
29.424242
151
0.586653
2.988095
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Breadcrumbs/Solution/BackgroundTest/BCOptions.swift
2
4469
// // BCOptions.swift // Breadcrumbs // // Created by Nicholas Outram on 04/12/2015. // Copyright © 2015 Plymouth University. All rights reserved. // import Foundation import CoreLocation import MapKit /// A structure that encapsualtes the functionality for passing, updating and persisting the options for the Bread Crumbs app /// - note: If there are two copies, it is not clear if races can occur when writing userdefaults with `updateDefaults()`. It is reccomended you only call `updateDefaults()` on one copy OR if you do, call `commit()` immediately after. /// - author: Nicholas Outram, Plymouth University /// - version: 1.0 struct BCOptions { //This structure uses NSUserDefaults - designed to store a heirarchy of Foundation Class objects (NSNumber in this case) //Swift types Bool and Float will be bridged automatically to Foundation class types /// Factory defaults - if no user default is set, these will be used /// Read key-value pairs from a plist file static let defaultsDictionary : [String : AnyObject] = { let fp = Bundle.main.path(forResource: "factoryDefaults", ofType: "plist") return NSDictionary(contentsOfFile: fp!) as! [String : AnyObject] }() ///Access the standardUserDefaults via this property to ensure factory settings (registration domain) are initialised. ///In the event that no userdefaults have been set yet, it will fall back the factory default. static let defaults : UserDefaults = { //Initiaised lazily (in part because it is static) using a closure. let ud = UserDefaults.standard ud.register(defaults: BCOptions.defaultsDictionary) ud.synchronize() return ud }() // Note the parenthesis on the end // Public properties - these are value-type variable backed, so independent copies can be made // These parameters are NOT static and are storage backed. // I want to exploit the value-type semantics as I pass this forward through the navigation stack // They are all initalised using the userdefaults /// determines if the GPS will continue to log data when the app is running in the background. Has an impact on battery drain. lazy var backgroundUpdates : Bool = BCOptions.defaults.bool(forKey: "backgroundUpdates") /// Read only property to determine if heading data is available from the device lazy var headingAvailable : Bool = CLLocationManager.headingAvailable() /// determines if the map is rotated so the heading is always towards the top of the screen lazy var headingUP : Bool = { //Note - user defaults are backed up, so can end up in an invalid state if restored on an older device return CLLocationManager.headingAvailable() && BCOptions.defaults.bool(forKey: "headingUP") }() /// Computed property to return the user tracking mode - mutating is there becase this can cause `headingUp` to mutate var userTrackingMode : MKUserTrackingMode { mutating get { return headingUP ? .followWithHeading : .follow } } /// determines if the traffic is shown on the map lazy var showTraffic : Bool = BCOptions.defaults.bool(forKey: "showTraffic") /// distance (in meters) you must travel before another GPS location is reported. A higher value may results in extended battery time lazy var distanceBetweenMeasurements : Double = BCOptions.defaults.double(forKey: "distanceBetweenMeasurements") /// requried prevision of the GPS (in meters). Higher values are less specific, but are faster to obtain and may require less battery lazy var gpsPrecision : Double = BCOptions.defaults.double(forKey: "gpsPrecision") /// Save the current record set to userdefaults (note - userdefaults may be cached, so call commit before allowing the application to close) mutating func updateDefaults() { BCOptions.defaults.set(backgroundUpdates, forKey: "backgroundUpdates") BCOptions.defaults.set(headingUP, forKey: "headingUP") BCOptions.defaults.set(showTraffic, forKey: "showTraffic") BCOptions.defaults.set(distanceBetweenMeasurements, forKey: "distanceBetweenMeasurements") BCOptions.defaults.set(gpsPrecision, forKey: "gpsPrecision") } /// Given that userdefaults are cached and only saved periodically, calling this forces them to be saved static func commit() { BCOptions.defaults.synchronize() } }
mit
18ff262fa17930b7b409f9e6971bda70
53.487805
234
0.723366
4.799141
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/DiscreteTransitionFactor.swift
1
1095
// // DiscreteTransitionFactor.swift // // // Frank Dellaert and Marc Rasi // July 2020 import _Differentiation import Foundation import PenguinStructures /// A factor on two discrete labels evaluation the transition probability struct DiscreteTransitionFactor : Factor { typealias Variables = Tuple2<Int, Int> /// The IDs of the variables adjacent to this factor. public let edges: Variables.Indices /// The number of states. let stateCount: Int /// Entry `i * stateCount + j` is the probability of transitioning from state `j` to state `i`. let transitionMatrix: [Double] init( _ inputId1: TypedID<Int>, _ inputId2: TypedID<Int>, _ stateCount: Int, _ transitionMatrix: [Double] ) { precondition(transitionMatrix.count == stateCount * stateCount) self.edges = Tuple2(inputId1, inputId2) self.stateCount = stateCount self.transitionMatrix = transitionMatrix } func error(at q: Variables) -> Double { let (label1, label2) = (q.head, q.tail.head) return -log(transitionMatrix[label2 * stateCount + label1]) } }
apache-2.0
341feed340b1f4b74fb3cbb920d2418d
25.707317
97
0.696804
3.924731
false
false
false
false
sensorberg-dev/ios-sdk
SBDemoAppSwift/BeaconsViewController.swift
1
2747
// // BeaconsViewController.swift // SensorbergSDK // // Created by Andrei Stoleru on 14/07/16. // Copyright © 2016 Sensorberg GmbH. All rights reserved. // import UIKit import SensorbergSDK import SensorbergSDK.NSString_SBUUID class BeaconsViewController: UITableViewController { var beacons = NSMutableArray() let cellIdentifier = "beaconCell" override func viewDidLoad() { super.viewDidLoad() //TODO: Enter API key let kAPIKey = "<< !!! ENTER API KEY HERE !!! >>" SBManager.shared().setApiKey(kAPIKey, delegate: self) SBManager.shared().requestLocationAuthorization(true) beacons = []; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { self.title = "Beacons" } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return beacons.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) let beacon:SBMBeacon = beacons.object(at: (indexPath as NSIndexPath).row) as! SBMBeacon let proximityUUID:String = beacon.uuid.uppercased() let beaconID:String = SensorbergSDK.defaultBeaconRegions()![proximityUUID] as! String if (!beaconID.isEmpty) { cell.textLabel?.text = beaconID } else { cell.textLabel?.text = beacon.uuid } cell.detailTextLabel?.text = "Major: " + String(beacon.major) + " Minor: " + String(beacon.minor) return cell } /* The method names have to be in the form "on"+<Event name> So, `SBEventLocationAuthorization` becomes `onSBEventLocationAuthorization` The full list of events is available at */ @objc public func onSBEventLocationAuthorization(_ event:SBEventLocationAuthorization) { // print(event) SBManager.shared().startMonitoring() } @objc public func onSBEventPerformAction(_ event:SBEventPerformAction) { print(event) } @objc public func onSBEventRegionEnter(_ event:SBEventRegionEnter) { beacons.add(event.beacon) self.tableView.reloadData() } @objc public func onSBEventRegionExit(_ event:SBEventRegionExit) { beacons.remove(event.beacon) self.tableView.reloadData() } }
mit
6ea9ede16f09da72f511307e45b6f9c0
26.46
109
0.643846
4.678024
false
false
false
false
naithar/Kitura-net
Tests/KituraNetTests/FastCGIProtocolTests.swift
1
12935
/** * Copyright IBM Corporation 2016 * * 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 XCTest @testable import KituraNet import Foundation #if os(Linux) import Glibc #else import Darwin #endif // // Test that the FastCGI Record Creator and Parses classes work as expected. // This is technically not a pure test since we're not using a reference // implementation to generate the test packets but it does show that the parser and creator, // which don't share code other than constants and exceptions, can interoperate. // // It would be embarrasingly broken if they did not... // class FastCGIProtocolTests: XCTestCase { // All tests // static var allTests : [(String, (FastCGIProtocolTests) -> () throws -> Void)] { return [ ("testNoRequestId", testNoRequestId), ("testBadRecordType", testBadRecordType), ("testRequestBeginKeepalive", testRequestBeginKeepalive), ("testRequestBeginNoKeepalive", testRequestBeginNoKeepalive), ("testParameters", testParameters), ("testDataOutput", testDataOutput), ("testDataInput", testDataOutput), ("testOversizeDataOutput", testOversizeDataOutput), ("testOversizeDataInput", testOversizeDataInput), ("testEndRequestSuccess", testEndRequestSuccess), ("testEndRequestUnknownRole", testEndRequestUnknownRole), ("testEndRequestCannotMultiplex", testEndRequestCannotMultiplex) ] } // Perform a request end test (FCGI_END_REQUEST) with a varying protocol status. // func executeRequestEnd(protocolStatus: UInt8) { do { let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = FastCGI.Constants.FCGI_END_REQUEST creator.requestId = 1 creator.protocolStatus = protocolStatus let parser : FastCGIRecordParser = FastCGIRecordParser.init(try creator.create()) let remainingData = try parser.parse() XCTAssert(remainingData == nil, "Parser returned overflow data where not should have been present") XCTAssert(parser.type == FastCGI.Constants.FCGI_END_REQUEST, "Record type received was incorrect") XCTAssert(parser.requestId == 1, "Request ID received was incorrect") XCTAssert(parser.protocolStatus == protocolStatus, "Protocol status received incorrect.") } catch { XCTFail("Exception thrown: \(error)") } } // Test an FCGI_END_REQUEST record exchange with FCGI_REQUEST_COMPLETE (done/ok) // func testEndRequestSuccess() { executeRequestEnd(protocolStatus: FastCGI.Constants.FCGI_REQUEST_COMPLETE) } // Test an FCGI_END_REQUEST record exchange with FCGI_UNKNOWN_ROLE (requested role is unknown) // func testEndRequestUnknownRole() { executeRequestEnd(protocolStatus: FastCGI.Constants.FCGI_UNKNOWN_ROLE) } // Test an FCGI_END_REQUEST record exchange with FCGI_CANT_MPX_CONN (multiplexing not available) // func testEndRequestCannotMultiplex() { executeRequestEnd(protocolStatus: FastCGI.Constants.FCGI_CANT_MPX_CONN) } // Generate a block of random data for our test suite to use. // func generateRandomData(_ numberOfBytes: Int) -> Data { var bytes = [UInt8](repeating: 0, count: numberOfBytes) #if os(Linux) for index in stride(from: 0, to: numberOfBytes, by: MemoryLayout<CLong>.size) { var random : CLong = Glibc.random() memcpy(&bytes+index ,&random, MemoryLayout<CLong>.size) } #else Darwin.arc4random_buf(&bytes, numberOfBytes) #endif return Data(bytes: bytes) } // Test an FCGI_STDOUT or FCGI_STDIN exchange with overly large bundle. // func executeOversizeDataExchangeTest(ofType: UInt8) { do { // 128k worth of data let testData = self.generateRandomData(128 * 1024) let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = ofType creator.requestId = 1 creator.data = testData let _ = try creator.create() XCTFail("Creator allowed the creation of an enormous payload (>64k)") } catch FastCGI.RecordErrors.oversizeData { // this is fine - is expected. } catch { XCTFail("Exception thrown: \(error)") } } // Test an FCGI_STDOUT record exchange with overly large bundle (forbidden) // func testOversizeDataOutput() { executeOversizeDataExchangeTest(ofType: FastCGI.Constants.FCGI_STDOUT) } // Test an FCGI_STDOUT record exchange with overly large bundle (forbidden) // func testOversizeDataInput() { executeOversizeDataExchangeTest(ofType: FastCGI.Constants.FCGI_STDIN) } // Test an FCGI_STDOUT or FCGI_STDIN record exchange // func executeDataExchangeTest(ofType: UInt8) { do { let testData = self.generateRandomData(32 * 1024) let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = ofType creator.requestId = 1 creator.data = testData let parser : FastCGIRecordParser = FastCGIRecordParser.init(try creator.create()) let remainingData = try parser.parse() XCTAssert(remainingData == nil, "Parser returned overflow data where not should have been present") XCTAssert(parser.type == ofType, "Record type received was incorrect") XCTAssert(parser.requestId == 1, "Request ID received was incorrect") XCTAssert(parser.data != nil, "No data was received") if parser.data != nil { XCTAssert(testData == parser.data!, "Data received was not data sent.") } } catch { XCTFail("Exception thrown: \(error)") } } // Test an FCGI_STDOUT record exchange // func testDataOutput() { executeDataExchangeTest(ofType: FastCGI.Constants.FCGI_STDOUT) } // Test an FCGI_STDOUT record exchange // func testDataInput() { executeDataExchangeTest(ofType: FastCGI.Constants.FCGI_STDIN) } // Test to verify that the record creator won't make absurd // records. This is a casual test but it ensures basic sanity. // func testNoRequestId() { do { let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = FastCGI.Constants.FCGI_STDOUT var _ = try creator.create() XCTFail("Record creator allowed record with no record ID to be created.") } catch FastCGI.RecordErrors.invalidRequestId { // ignore this - expected behaviour } catch { XCTFail("Record creator threw unexpected exception") } } // Test to verify that the record creator won't make absurd // records. This is a casual test but it ensures basic sanity. // func testBadRecordType() { do { let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = 111 // this is just insane creator.requestId = 1 var _ = try creator.create() XCTFail("Record creator allowed strange record to be created.") } catch FastCGI.RecordErrors.invalidType { // ignore this - expected behaviour } catch { XCTFail("Record creator threw unexpected exception.") } } // Perform a testRequestBeginXKeepalive() test. // // This tests to determine if the parser and encoder can create FCGI_BEGIN_REQUEST // records that are interoperable. // func executeRequestBegin(keepalive: Bool) { do { let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = FastCGI.Constants.FCGI_BEGIN_REQUEST creator.requestId = 1 creator.requestRole = FastCGI.Constants.FCGI_RESPONDER creator.keepAlive = keepalive let parser : FastCGIRecordParser = FastCGIRecordParser.init(try creator.create()) let remainingData = try parser.parse() XCTAssert(remainingData == nil, "Parser returned overflow data where not should have been present") XCTAssert(parser.type == FastCGI.Constants.FCGI_BEGIN_REQUEST, "Record type received was incorrect") XCTAssert(parser.requestId == 1, "Request ID received was incorrect") XCTAssert(parser.role == FastCGI.Constants.FCGI_RESPONDER, "Role received was incorrect") XCTAssert(parser.keepalive == keepalive, "Keep alive state was received incorrectly.") } catch { XCTFail("Exception thrown: \(error)") } } // Test an FCGI_BEGIN_REQUEST record exchange with keep alive requested. // func testRequestBeginKeepalive() { self.executeRequestBegin(keepalive: true) } // Test an FCGI_BEGIN_REQUEST record exchange WITHOUT keep alive requested. // func testRequestBeginNoKeepalive() { self.executeRequestBegin(keepalive: false) } // Perform a parameter record test. // // This tests to determine if the parser and encoder can create FCGI_PARAMS // records that are interoperable. // func testParameters() { do { // Make a long string var longString : String = "" for _ in 1...256 { longString = longString + "X" } // create some parameters to tests var parameters : [(String,String)] = [] parameters.append(("SHORT_KEY_A", "SHORT_VALUE")) parameters.append(("SHORT_KEY_B", "LONG_VALUE_" + longString)) parameters.append(("LONG_KEY_A_" + longString, "SHORT_VALUE")) parameters.append(("LONG_KEY_A_" + longString, "LONG_VALUE_" + longString)) // test sending those parameters let creator : FastCGIRecordCreate = FastCGIRecordCreate() creator.recordType = FastCGI.Constants.FCGI_PARAMS creator.requestId = 1 for currentHeader : (String,String) in parameters { creator.parameters.append((currentHeader.0, currentHeader.1)) } let parser : FastCGIRecordParser = FastCGIRecordParser.init(try creator.create()) let remainingData = try parser.parse() XCTAssert(remainingData == nil, "Parser returned overflow data where not should have been present") XCTAssert(parser.type == FastCGI.Constants.FCGI_PARAMS, "Record type received was incorrect") XCTAssert(parser.requestId == 1, "Request ID received was incorrect") // Check what we received was what we expected. for sourceHeader : (String,String) in parameters { var pairReceived : Bool = false for currentHeader : Dictionary<String,String> in parser.headers { let currentHeaderName : String? = currentHeader["name"] let currentHeaderValue : String? = currentHeader["value"] if currentHeaderName == sourceHeader.0 && currentHeaderValue == sourceHeader.1 { pairReceived = true break } } XCTAssert(pairReceived, "Key \(sourceHeader.0), Value \(sourceHeader.1) sent but not received") } } catch { XCTFail("Exception thrown: \(error)") } } }
apache-2.0
010cd3fecd80f419a43842ec1a57c85a
36.384393
112
0.600077
4.971176
false
true
false
false