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
zmian/xcore.swift
Example/Models/Menu.swift
1
2757
// // Xcore // Copyright © 2020 Xcore // MIT license, see LICENSE file for details // import SwiftUI struct Menu: Identifiable { let id: UUID let title: String let subtitle: String? let content: () -> AnyView init<Content: View>( id: UUID = UUID(), title: String, subtitle: String? = nil, content: @autoclosure @escaping () -> Content ) { self.id = id self.title = title self.subtitle = subtitle self.content = { content() .navigationTitle(title) .eraseToAnyView() } } init<Content: View>( id: UUID = UUID(), title: String, subtitle: String? = nil, @ViewBuilder content: @escaping () -> Content ) { self.id = id self.title = title self.subtitle = subtitle self.content = { content() .navigationTitle(title) .eraseToAnyView() } } } // MARK: - CaseIterable extension Menu: CaseIterable { static var allCases: [Self] = [ separators, buttons, capsules, xstack, popups, textFields, activitySheet, crypt ] } // MARK: - Items extension Menu { private static let separators = Self( title: "Separators", subtitle: "UIKit", content: SeparatorViewController().embedInView() ) private static let buttons = Self( title: "Buttons", content: ButtonsView() ) private static let capsules = Self( title: "Capsule", content: { if #available(iOS 15.0, *) { Samples.capsuleViewPreviews } else { EmptyView() } } ) private static let xstack = Self( title: "XStack", content: XStackView() ) private static let popups = Self( title: "Popups", content: { if #available(iOS 15.0, *) { Samples.popupPreviews } else { EmptyView() } } ) private static let textFields = Self( title: "TextFields", content: { if #available(iOS 15.0, *) { Samples.dynamicTextFieldPreviews } else { EmptyView() } } ) private static let activitySheet = Self( title: "Activity Sheet", content: ActivitySheetView() ) private static let crypt = Self( title: "Crypt", content: { if #available(iOS 15.0, *) { CryptView() } else { EmptyView() } } ) }
mit
85a441edc03fff26a3e2788bd5cd24a7
20.2
56
0.484035
4.655405
false
false
false
false
joeyg/ios_yelp_swift
Yelp/BusinessesViewController.swift
1
3738
// // BusinessesViewController.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FilterViewControllerDelegate, UISearchBarDelegate { @IBOutlet weak var tableView: UITableView! var businesses: [Business]? var searchView: UISearchBar? override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 120 setupSearchBar() Business.searchWithTerm("Restaurants", sort: .Distance, categories: ["asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses for business in businesses { println(business.name!) println(business.address!) } self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Business") as! BusinessTableViewCell let business = self.businesses?[indexPath.row] cell.setFromBusiness(business!) return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let businesses = self.businesses { return businesses.count } return 0 } private func setupSearchBar() { searchView = UISearchBar() searchView?.placeholder = "Search for restaurants in SF" self.navigationItem.titleView = searchView searchView?.delegate = self } func filterViewController(filterViewController: FilterViewController, didUpdateFilters filters: [String : AnyObject]) { println(filters) let categories = filters["categories"] as? [String] let sort = YelpSortMode(rawValue:filters["sort"] as! Int) let radius = filters["radius"] as? String let deals = filters["deals"] as? Bool let searchTerm = searchView?.text ?? "Restaurants" Business.searchWithTerm(searchTerm, sort: sort, categories: categories, deals: deals) { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses self.tableView.reloadData() } } // 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?) { let navigationController = segue.destinationViewController as! UINavigationController let filtersViewController = navigationController.topViewController as! FilterViewController filtersViewController.delegate = self } func searchBarSearchButtonClicked(searchBar: UISearchBar) { view.endEditing(true) if let term = searchBar.text { Business.searchWithTerm(term, completion: { (business:[Business]!, error:NSError!) -> Void in self.businesses = business self.tableView.reloadData() }) } } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } }
mit
ae17f7d8389ca503616fe1dcce6df128
33.934579
172
0.646335
5.529586
false
false
false
false
vineeth89/UIView-Constraints-Extension
UIVIew+Extension.swift
1
1514
// // UIVIew+Extension.swift // // Created by Vineeth Venugopal Ravindra on 5/31/17. // import Foundation import UIKit extension UIView { func createViewDict(views: [UIView]) -> [String: UIView] { var retDict = [String: UIView]() for (index, view) in views.enumerated() { view.translatesAutoresizingMaskIntoConstraints = false let key = "v\(index)" retDict[key] = view } return retDict } func addConstraint(withFormat format: String, forViews views: UIView...) { guard views.count > 0 else { return } let viewDict = createViewDict(views: views) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDict)) } func learnModuleConstraints(forView view: UIView, segmentedControll: UISegmentedControl) { addConstraint(withFormat: "H:|-16-[v0]-16-|", forViews: view) addConstraint(NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: segmentedControll, attribute: .bottom, multiplier: 1 , constant: 20)) addConstraint(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1 , constant: -10)) } }
mit
910d2e8e23aafb126c6f7eab619be7e3
39.918919
123
0.5786
5.013245
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/Home/HistoryPanel.swift
2
24984
/* 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 Shared import Storage import XCGLogger import Deferred private let log = Logger.browserLogger private typealias SectionNumber = Int private typealias CategoryNumber = Int private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int) private struct HistoryPanelUX { static let WelcomeScreenItemTextColor = UIColor.gray static let WelcomeScreenItemWidth = 170 static let IconSize = 23 static let IconBorderColor = UIColor(white: 0, alpha: 0.1) static let IconBorderWidth: CGFloat = 0.5 } private func getDate(_ dayOffset: Int) -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date()) let today = calendar.date(from: nowComponents)! return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])! } class HistoryPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? private var currentSyncedDevicesCount: Int? var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged] var refreshControl: UIRefreshControl? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(HistoryPanel.longPress(_:))) }() private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView() private let QueryLimit = 100 private let NumSections = 5 private let Today = getDate(0) private let Yesterday = getDate(-1) private let ThisWeek = getDate(-7) private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset). private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category. var syncDetailText = "" var hasRecentlyClosed: Bool { return self.profile.recentlyClosedTabs.tabs.count > 0 } // MARK: - Lifecycle init() { super.init(nibName: nil, bundle: nil) events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) } } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "History List" updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for // the refresh to finish before removing the control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } else if refreshControl?.isRefreshing == false { removeRefreshControl() } updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } if indexPath.section != 0 { presentContextMenu(for: indexPath) } } // MARK: - History Data Store func updateNumberOfSyncedDevices(_ count: Int?) { if let count = count, count > 0 { syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count) } else { syncDetailText = "" } self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic) } func updateSyncedDevicesCount() -> Success { return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in self.currentSyncedDevicesCount = tabsAndClients.count return succeed() } } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory: if self.profile.hasSyncableAccount() { resyncHistory() } break case NotificationDynamicFontChanged: if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverlayView() resyncHistory() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } private func fetchData() -> Deferred<Maybe<Cursor<Site>>> { return profile.history.getSitesByLastVisit(QueryLimit) } private func setData(_ data: Cursor<Site>) { self.data = data self.computeSectionOffsets() } func resyncHistory() { profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in if result.isSuccess { self.reloadData() } else { self.endRefreshing() } self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount) } } } // MARK: - Refreshing TableView func addRefreshControl() { let refresh = UIRefreshControl() refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged) self.refreshControl = refresh self.tableView.addSubview(refresh) } func removeRefreshControl() { self.refreshControl?.removeFromSuperview() self.refreshControl = nil } func endRefreshing() { // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !self.profile.hasSyncableAccount() { self.removeRefreshControl() } } @objc func refresh() { self.refreshControl?.beginRefreshing() resyncHistory() } override func reloadData() { self.fetchData().uponQueue(DispatchQueue.main) { result in if let data = result.successValue { self.setData(data) self.tableView.reloadData() self.updateEmptyPanelState() } self.endRefreshing() } } // MARK: - Empty State private func updateEmptyPanelState() { if data.count == 0 { if self.emptyStateOverlayView.superview == nil { self.tableView.addSubview(self.emptyStateOverlayView) self.emptyStateOverlayView.snp.makeConstraints { make -> Void in make.left.right.bottom.equalTo(self.view) make.top.equalTo(self.view).offset(100) } } } else { self.tableView.alwaysBounceVertical = true self.emptyStateOverlayView.removeFromSuperview() } } private func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() overlayView.backgroundColor = UIColor.white let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle welcomeLabel.textAlignment = NSTextAlignment.center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth) } return overlayView } // MARK: - TableView Row Helpers func computeSectionOffsets() { var counts = [Int](repeating: 0, count: NumSections) // Loop over all the data. Record the start of each "section" of our list. for i in 0..<data.count { if let site = data[i] { counts[categoryForDate(site.latestVisit!.date) + 1] += 1 } } var section = 0 var offset = 0 self.categories = [CategorySpec]() for i in 0..<NumSections { let count = counts[i] if i == 0 { sectionLookup[section] = i section += 1 } if count > 0 { log.debug("Category \(i) has \(count) rows, and thus is section \(section).") self.categories.append((section: section, rows: count, offset: offset)) sectionLookup[section] = i offset += count section += 1 } else { log.debug("Category \(i) has 0 rows, and thus has no section.") self.categories.append((section: nil, rows: 0, offset: offset)) } } } fileprivate func siteForIndexPath(_ indexPath: IndexPath) -> Site? { let offset = self.categories[sectionLookup[indexPath.section]!].offset return data[indexPath.row + offset] } private func categoryForDate(_ date: MicrosecondTimestamp) -> Int { let date = Double(date) if date > (1000000 * Today.timeIntervalSince1970) { return 0 } if date > (1000000 * Yesterday.timeIntervalSince1970) { return 1 } if date > (1000000 * ThisWeek.timeIntervalSince1970) { return 2 } return 3 } private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool { return self.categoryForDate(date) == category } // UI sections disappear as categories empty. We need to translate back and forth. private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber { for i in 0..<self.categories.count { if let s = self.categories[i].section, s == section { return i } } return 0 } private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? { return self.categories[category].section } // MARK: - TableView Delegate / DataSource override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.accessoryType = UITableViewCellAccessoryType.none if indexPath.section == 0 { cell.imageView!.layer.borderWidth = 0 return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath) } else { return configureSite(cell, for: indexPath) } } func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle cell.detailTextLabel!.text = "" cell.imageView!.image = UIImage(named: "recently_closed") cell.imageView?.backgroundColor = UIColor.white if !hasRecentlyClosed { cell.textLabel?.alpha = 0.5 cell.imageView!.alpha = 0.5 cell.selectionStyle = .none } cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell" return cell } func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle cell.detailTextLabel!.text = self.syncDetailText cell.imageView!.image = UIImage(named: "synced_devices") cell.imageView?.backgroundColor = UIColor.white cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell" return cell } func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in if site.tileURL == url { cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize)) cell.imageView?.backgroundColor = color cell.imageView?.contentMode = .center } }) } return cell } func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { var count = 1 for category in self.categories where category.rows > 0 { count += 1 } return count } func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { if indexPath.section == 0 { self.tableView.deselectRow(at: indexPath, animated: true) return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs() } if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) { let visitType = VisitType.typed // Means History, too. if let homePanelDelegate = homePanelDelegate { homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType) } return } log.warning("No site or no URL when selecting row.") } func pinTopSite(_ site: Site) { _ = profile.history.addPinnedTopSite(site).value } func showSyncedTabs() { let nextController = RemoteTabsPanel() nextController.homePanelDelegate = self.homePanelDelegate nextController.profile = self.profile self.refreshControl?.endRefreshing() self.navigationController?.pushViewController(nextController, animated: true) } func showRecentlyClosed() { guard hasRecentlyClosed else { return } let nextController = RecentlyClosedTabsPanel() nextController.homePanelDelegate = self.homePanelDelegate nextController.profile = self.profile self.refreshControl?.endRefreshing() self.navigationController?.pushViewController(nextController, animated: true) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = String() switch sectionLookup[section]! { case 0: return nil case 1: title = NSLocalizedString("Today", comment: "History tableview section header") case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header") case 3: title = NSLocalizedString("Last week", comment: "History tableview section header") case 4: title = NSLocalizedString("Last month", comment: "History tableview section header") default: assertionFailure("Invalid history section \(section)") } return title } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } return super.tableView(tableView, viewForHeaderInSection: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } return self.categories[uiSectionToCategory(section)].rows } func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } fileprivate func removeHistoryForURLAtIndexPath(indexPath: IndexPath) { if let site = self.siteForIndexPath(indexPath) { // Why the dispatches? Because we call success and failure on the DB // queue, and so calling anything else that calls through to the DB will // deadlock. This problem will go away when the history API switches to // Deferred instead of using callbacks. self.profile.history.removeHistoryForURL(site.url) .upon { res in self.fetchData().uponQueue(DispatchQueue.main) { result in // If a section will be empty after removal, we must remove the section itself. if let data = result.successValue { let oldCategories = self.categories self.data = data self.computeSectionOffsets() let sectionsToDelete = NSMutableIndexSet() var rowsToDelete = [IndexPath]() let sectionsToAdd = NSMutableIndexSet() var rowsToAdd = [IndexPath]() for (index, category) in self.categories.enumerated() { let oldCategory = oldCategories[index] // don't bother if we're not displaying this category if oldCategory.section == nil && category.section == nil { continue } // 1. add a new section if the section didn't previously exist if oldCategory.section == nil && category.section != oldCategory.section { log.debug("adding section \(category.section ?? 0)") sectionsToAdd.add(category.section!) } // 2. add a new row if there are more rows now than there were before if oldCategory.rows < category.rows { log.debug("adding row to \(category.section ?? 0) at \(category.rows-1)") rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!)) } // if we're dealing with the section where the row was deleted: // 1. if the category no longer has a section, then we need to delete the entire section // 2. delete a row if the number of rows has been reduced // 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same if oldCategory.section == indexPath.section { if category.section == nil { log.debug("deleting section \(indexPath.section)") sectionsToDelete.add(indexPath.section) } else if oldCategory.section == category.section { if oldCategory.rows > category.rows { log.debug("deleting row from \(category.section ?? 0) at \(indexPath.row)") rowsToDelete.append(indexPath) } else if category.rows == oldCategory.rows { log.debug("in section \(category.section ?? 0), removing row at \(indexPath.row) and inserting row at \(category.rows-1)") rowsToDelete.append(indexPath) rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section)) } } } } self.tableView.beginUpdates() if sectionsToAdd.count > 0 { self.tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left) } if sectionsToDelete.count > 0 { self.tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right) } if !rowsToDelete.isEmpty { self.tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right) } if !rowsToAdd.isEmpty { self.tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right) } self.tableView.endUpdates() self.updateEmptyPanelState() } } } } } func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? { if indexPath.section == 0 { return [] } let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) return [delete] } } extension HistoryPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { return siteForIndexPath(indexPath) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil } let removeAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinTopSite(site) }) actions.append(pinTopSite) actions.append(removeAction) return actions } }
mpl-2.0
29f707a20ad7e81b0708c73795a2c435
42.150259
166
0.610871
5.714547
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
SechQueryComposer/SechQueryComposer/recommendationCTRL.swift
1
2518
// // recommendationCTRL.swift // SechQueryComposer // // Copyright © 2015 Peter Stoehr. All rights reserved. // import Foundation class RecommendationCTRL { func getRecommendsForKeyWords(keywordInfo : (kw:[String], mainTopicIndex:Int?), dataSource : RecommendationDataSource, update: () -> Void) { let c = Connection() let rec = RecommendationJSON(keywordInfo: keywordInfo) let url = Preferences().url + "/recommend" c.post(rec.jsonObject, url: url){ (succeeded: Bool, msg: NSData) -> () in if (succeeded) { guard let recommJson = JsonRecommendation(data: msg) else { print ("Versagen 1") return } let recomms = recommJson.recommendations dataSource.data = recomms! update() for i in recomms! { print ("\(i)") } } else { print("Versagen 2") } } } } class RecommendationJSON { var jsonObject : [String : AnyObject] = [:] private func addOrigin () { let eInfos = EEXCESSOrigin() var originInfo : [String : AnyObject] = [:] originInfo["clientType"] = eInfos.clientType originInfo["clientVersion"] = eInfos.clientVersion originInfo["userID"] = eInfos.userID originInfo["module"] = eInfos.module jsonObject["origin"] = originInfo } private func addMetaInfo() { let mInfos = EEXCESSMetaInfo() //jsonObject["ageRange"] = mInfos.ageRange jsonObject["gender"] = mInfos.gender jsonObject["numResults"] = mInfos.numResult } private func addKontextKeywords(keywordInfo : (kw:[String], mainTopicIndex:Int?)) { var allKWS : [AnyObject] = [] for i in 0 ..< keywordInfo.kw.count { var newEntry : [String : AnyObject] = [:] newEntry["text"] = keywordInfo.kw[i] if (keywordInfo.kw.count > 2) { newEntry["isMainTopic"] = (keywordInfo.mainTopicIndex! == i) } allKWS.append(newEntry) } jsonObject["contextKeywords"] = allKWS } init(keywordInfo : (kw:[String], mainTopicIndex:Int?)) { addOrigin() addMetaInfo() addKontextKeywords(keywordInfo) } }
mit
f89c5c6b413cc3bfa30b20c6aae07d15
26.966667
142
0.528407
4.431338
false
false
false
false
marksands/SwiftLensLuncheon
UserListValueTypes/UserController.swift
1
1399
// // Created by Christopher Trott on 1/14/16. // Copyright © 2016 twocentstudios. All rights reserved. // import Foundation import ReactiveCocoa import LoremIpsum /// UserController is the data source for User objects. The underlying data source could be disk, network, etc. /// /// In this architecture, Controller objects obscure the data source from the ViewModel layer and provide /// a consistent interface. Controller objects cannot access members of the View or ViewModel layers. /// /// UserController is a reference-type because it may implement its own layer of caching. class UserController { /// Asynchronous fetch. func fetchRandomUsersProducer(count: Int = 100) -> SignalProducer<[User], NoError> { return SignalProducer { observer, disposable in observer.sendNext(UserController.fetchRandomUsers(count)) observer.sendCompleted() } // .delay(2, onScheduler: QueueScheduler()) /// Simulate a network delay. } /// Generate the specified number of random User objects. private static func fetchRandomUsers(count: Int) -> [User] { return (0..<count).map { i in let name = LoremIpsum.name() let avatarURL = NSURL(string: "http://dummyimage.com/96x96/000/fff.jpg&text=\(i)")! let user = User(name: name, avatarURL: avatarURL) return user } } }
mit
3da98099bbfa5224b22380749a8bce17
38.942857
111
0.680973
4.598684
false
false
false
false
TarangKhanna/Inspirator
WorkoutMotivation/BWWalkthroughPageViewController.swift
6
4759
// // BWWalkthroughPageViewController.swift // BWWalkthrough // // Created by Yari D'areglia on 17/09/14. // Copyright (c) 2014 Yari D'areglia. All rights reserved. // import UIKit enum WalkthroughAnimationType{ case Linear case Curve case Zoom case InOut static func fromString(str:String)->WalkthroughAnimationType{ switch(str){ case "Linear": return .Linear case "Curve": return .Curve case "Zoom": return .Zoom case "InOut": return .InOut default: return .Linear } } } class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { // Edit these values using the Attribute inspector or modify directly the "User defined runtime attributes" in IB @IBInspectable var speed:CGPoint = CGPoint(x: 0.0, y: 0.0); // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var speedVariance:CGPoint = CGPoint(x: 0.0, y: 0.0) // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var animationType:String = "Linear" // @IBInspectable var animateAlpha:Bool = false // private var subsWeights:[CGPoint] = Array() override func viewDidLoad() { super.viewDidLoad() self.view.layer.masksToBounds = true subsWeights = Array() for v in view.subviews{ speed.x += speedVariance.x speed.y += speedVariance.y subsWeights.append(speed) } } // MARK: BWWalkthroughPage Implementation func walkthroughDidScroll(position: CGFloat, offset: CGFloat) { for(var i = 0; i < subsWeights.count ;i++){ // Perform Transition/Scale/Rotate animations switch WalkthroughAnimationType.fromString(animationType){ case WalkthroughAnimationType.Linear: animationLinear(i, offset) case WalkthroughAnimationType.Zoom: animationZoom(i, offset) case WalkthroughAnimationType.Curve: animationCurve(i, offset) case WalkthroughAnimationType.InOut: animationInOut(i, offset) } // Animate alpha if(animateAlpha){ animationAlpha(i, offset) } } } // MARK: Animations (WIP) private func animationAlpha(index:Int, var _ offset:CGFloat){ let cView = view.subviews[index] as! UIView if(offset > 1.0){ offset = 1.0 + (1.0 - offset) } cView.alpha = (offset) } private func animationCurve(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subsWeights[index].x, (pow(x,3) - (x * 20)) * subsWeights[index].y, 0 ) view.subviews[index].layer.transform = transform } private func animationZoom(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } var scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) view.subviews[index].layer.transform = transform } private func animationLinear(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subsWeights[index].x, mx * subsWeights[index].y, 0 ) view.subviews[index].layer.transform = transform } private func animationInOut(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subsWeights[index].x * 100, (1.0 - tmpOffset) * subsWeights[index].y * 100, 0) view.subviews[index].layer.transform = transform } }
apache-2.0
163472131c49c1fd18fa6ae9a56192e7
32.758865
230
0.57449
4.749501
false
false
false
false
silence0201/Swift-Study
Learn/12.构造和析构/默认构造函数.playground/section-1.swift
1
394
//struct Rectangle { class Rectangle { var width: Double = 0.0 var height: Double = 0.0 // init() { // // } // init(width: Double, height: Double) { // self.width = width // self.height = height // } } var rect = Rectangle() rect.width = 320.0 rect.height = 480.0 print("长方形:\(rect.width) x \(rect.height)")
mit
e7628838b9f8482a5899133dc930f2eb
15.869565
47
0.5
3.260504
false
false
false
false
RigaDevDay/RigaDevDays-Swift
RigaDevDays/Timeslot.swift
1
1910
// Copyright © 2017 RigaDevDays. All rights reserved. import Foundation import Firebase class Timeslot: DataObject { let startTime: String? let endTime: String? var sessionIDs: [Int] = [] var tracks: [Track] = [] var sessions: [Session] { get { var temp: [Session] = [] for index in 0..<self.sessionIDs.count { let sID = self.sessionIDs[index] if let s = DataManager.sharedInstance.getSession(by: sID) { self.tracks.indices.contains(index) s.track = self.tracks.indices.contains(index) ? self.tracks[index] : self.tracks.first s.timeslot = self temp.append(s) } } return temp } } init(snapshot: DataSnapshot, dayTracks: [Track]) { let snapshotValue = snapshot.value as! [String: AnyObject] startTime = snapshotValue["startTime"] as? String endTime = snapshotValue["endTime"] as? String tracks = dayTracks switch SwissKnife.app { case .rdd: for timeslotSnapshot in snapshot.childSnapshot(forPath: "sessions").children { for tempEnum in (timeslotSnapshot as! DataSnapshot).childSnapshot(forPath: "items").children { let firstItem = (tempEnum as! DataSnapshot).value as! Int sessionIDs.append(firstItem) } } case .devfest, .frontcon, .devopsdaysriga: for timeslotSnapshot in snapshot.childSnapshot(forPath: "sessions").children { if let tmpsessionIDs = (timeslotSnapshot as! DataSnapshot).value as? [Int], let firstItem = tmpsessionIDs.first { sessionIDs.append(firstItem) } } } super.init(snapshot: snapshot) } }
mit
49f6e019a9283b80394d87201376aa96
33.089286
110
0.559979
4.588942
false
false
false
false
AshuMishra/PhotoGallery
PhotoGallery/PhotoGallery/Utility/Reachability.swift
1
989
// // Reachability.swift // PhotoGallery // // Created by Ashutosh Mishra on 28/12/15. // Copyright © 2015 Ashu.com. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } }
mit
ce2958736b292cf01b6158b90f24a730
27.257143
137
0.736842
3.905138
false
false
false
false
Enziferum/iosBoss
iosBoss/Presenter.swift
1
3052
// // Presenter.swift // iosBoss // // Created by AlexRaag on 30/08/2017. // Copyright © 2017 AlexRaag. All rights reserved. // import Foundation //MARK:presenterDelegate /** presenterDelegate - protocol for binding Presenter && View. get View Interface */ public protocol presenterDelegate:class{ init(view:viewDelegate) /** sendRequest - method is .Get Request */ func sendRequest() } /** presenterPrepareDelegate - protocol for binding Model */ public protocol presenterPrepareDelegate { //MARK:prepareViewModel - sets Number of sections //,rows in section , reuseID,segueID func prepareViewModel() } open class Presenter:presenterDelegate{ required public init(view:viewDelegate) { self.view = view request = Request() url = "" rows=[] posts=[] sections = 0 } open func sendRequest(){ try! request.accomplishString(withUrl: url, handler: {(responce) in self.posts = self.delegate.parsePage(htmlCode: responce) DispatchQueue.main.async { self.view.ReloadData() } }) } /** set Url for request */ public func setURL(val:String){ url = val } public var delegate:ParserDelegate! unowned open var view:viewDelegate open var posts:[Post] open var request:Request open var url:String fileprivate var sections:Int fileprivate var rows:[Int] } extension Presenter:dataGetter{ /** - Returns Int: Position in post Array */ private func countPosts(section: Int, row:Int)->Int { var index = -1 if section == 0 { index = 0 } for it in 0...section{ index += it } index += row return index } /** - Returns Int: number of Sections in bind View */ public func getSections() -> Int { if sections > 0 { return sections } return 0 } /** _ Parameter section - Returns Int: number of Rows in bind View by section */ public func getRows(for section:Int)->Int{ if section > -1 && sections > 0{ return rows[section] } return 0 } /** _ Parameter indexPath:IndexPath - Returns Post: by parameter get Fully Filled Post(Model) */ public func getPost(for indexPath:IndexPath) -> Post { if !posts.isEmpty { let index = countPosts(section: indexPath.section ,row: indexPath.row) return posts[index] } return Post()! } } extension Presenter:dataSetter { public func setSections(val:Int){ sections = val } public func setRows(val:Int,section:Int){ if section >= rows.count { rows.append(val) } else { rows[section] = val } } }
mit
8dd1a70de92ab22104eaf91cb3426af8
19.47651
75
0.552606
4.553731
false
false
false
false
nearfri/Strix
Sources/Strix/Error/ErrorOutputBuffer.swift
1
832
import Foundation struct ErrorOutputBuffer: ErrorOutputStream { var indent: Indent = .init() private(set) var text: String = "" mutating func write(_ string: String) { var indentedString = "" string.enumerateSubstrings( in: string.startIndex..<string.endIndex, options: [.byLines, .substringNotRequired] ) { [self] _, _, enclosingRange, _ in if enclosingRange.lowerBound == string.startIndex { if text.isEmpty || text.last?.isNewline == true { indentedString += indent.toString() } } else { indentedString += indent.toString() } indentedString += string[enclosingRange] } text += indentedString } }
mit
8690824dea8d249537376d66ec2fd9fa
29.814815
65
0.532452
5.333333
false
false
false
false
Antuaaan/ECWeather
ECWeather/Pods/SwiftSky/Source/Distance.swift
1
3013
// // Distance.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Foundation /// Contains a value, unit and label describing distance public struct Distance { /// `Float` representing distance private(set) public var value : Float = 0 /// `DistanceUnit` of the value public let unit : DistanceUnit /// Human-readable representation of the value and unit together public var label : String { return label(as: unit) } /** Same as `Distance.label`, but converted to a specific unit - parameter unit: `DistanceUnit` to convert label to - returns: String */ public func label(as unit : DistanceUnit) -> String { let converted = (self.unit == unit ? value : convert(value, from: self.unit, to: unit)) switch unit { case .mile: return "\(converted.oneDecimal) mi" case .yard: return "\(converted.noDecimal) yd" case .kilometer: return "\(converted.oneDecimal) km" case .meter: return "\(converted.noDecimal) m" } } /** Same as `Distance.value`, but converted to a specific unit - parameter unit: `DistanceUnit` to convert value to - returns: Float */ public func value(as unit : DistanceUnit) -> Float { return convert(value, from: self.unit, to: unit) } private func convert(_ value : Float, from : DistanceUnit, to : DistanceUnit) -> Float { switch from { case .mile: switch to { case .mile: return value case .yard: return value * 1760 case .kilometer: return value * 1.609344 case .meter: return value * 1609.344 } case .yard: switch to { case .yard: return value case .mile: return value / 1760 case .kilometer: return value * 0.0009144 case .meter: return value * 0.9144 } case .kilometer: switch to { case .kilometer: return value case .mile: return value / 1.609344 case .yard: return value / 0.0009144 case .meter: return value * 1000 } case .meter: switch to { case .meter: return value case .mile: return value / 1609.344 case .yard: return value / 0.9144 case .kilometer: return value / 1000 } } } init(_ value : Float, withUnit : DistanceUnit) { unit = SwiftSky.units.distance self.value = convert(value, from: withUnit, to: unit) } }
mit
2a2596020b248e3a31aae671d38aeef0
26.888889
95
0.508632
4.684292
false
false
false
false
Senspark/ee-x
src/ios/ee/iron_source/IronSourceBannerAd.swift
1
4586
// // IronSourceBannerAd.swift // ee-x-d542b565 // // Created by eps on 1/25/21. // private let kTag = "\(IronSourceBannerAd.self)" internal class IronSourceBannerAd: NSObject, IBannerAd, ISBannerDelegate { private let _bridge: IMessageBridge private let _logger: ILogger private let _adId: String private let _adSize: ISBannerSize private let _messageHelper: MessageHelper private var _helper: BannerAdHelper? private let _viewHelper: ViewHelper private var _isLoaded = false private var _ad: ISBannerView? init(_ bridge: IMessageBridge, _ logger: ILogger, _ adId: String, _ adSize: ISBannerSize, _ bannerHelper: IronSourceBannerHelper) { _bridge = bridge _logger = logger _adId = adId _adSize = adSize _messageHelper = MessageHelper("IronSourceBannerAd", _adId) _viewHelper = ViewHelper(CGPoint.zero, bannerHelper.getSize(adSize: adSize), false) super.init() _helper = BannerAdHelper(_bridge, self, _messageHelper) IronSource.setBannerDelegate(self) registerHandlers() createInternalAd() } func destroy() { deregisterHandler() destroyInternalAd() // Cannot clear delegates. } func registerHandlers() { _helper?.registerHandlers() } func deregisterHandler() { _helper?.deregisterHandlers() } func createInternalAd() { Thread.runOnMainThread { if self._ad != nil { return } self._isLoaded = false } } func destroyInternalAd() { Thread.runOnMainThread { guard let ad = self._ad else { return } self._isLoaded = false ad.removeFromSuperview() IronSource.destroyBanner(ad) self._ad = nil self._viewHelper.view = nil } } var isLoaded: Bool { return _isLoaded } func load() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") guard let rootView = Utils.getCurrentRootViewController() else { assert(false, "Root view is null") return } IronSource.loadBanner(with: rootView, size: self._adSize, placement: self._adId) } } var isVisible: Bool { get { return _viewHelper.isVisible } set(value) { _viewHelper.isVisible = value } } var position: CGPoint { get { return _viewHelper.position } set(value) { _viewHelper.position = value } } var size: CGSize { get { return _viewHelper.size } set(value) { _viewHelper.size = value } } func bannerDidLoad(_ bannerView: ISBannerView) { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") self._ad = bannerView self._viewHelper.view = bannerView let rootView = Utils.getCurrentRootViewController() rootView?.view.addSubview(bannerView) self._isLoaded = true self._bridge.callCpp(self._messageHelper.onLoaded) } } func bannerDidFailToLoadWithError(_ error: Error) { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId) message = \(error.localizedDescription)") self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [ "code": (error as NSError).code, "message": error.localizedDescription ])) } } func bannerDidShow() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") } } func didClickBanner() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") self._bridge.callCpp(self._messageHelper.onClicked) } } func bannerWillPresentScreen() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") } } func bannerDidDismissScreen() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") } } func bannerWillLeaveApplication() { Thread.runOnMainThread { self._logger.debug("\(kTag): \(#function): id = \(self._adId)") } } }
mit
236201959d88440532b6e57730a340cc
28.210191
115
0.569341
4.618328
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Services/Scan/CognitoService.swift
2
2207
// // CognitoService.swift // SmartReceipts // // Created by Bogdan Evsenev on 12/09/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import AWSCore import RxSwift fileprivate let COGNITO_TOKEN_KEY = "cognito.token" fileprivate let COGNITO_IDENTITY_ID_KEY = "cognito.identity.id" class CognitoService: AWSCognitoCredentialsProviderHelper { private let bag = DisposeBag() override init() { super.init(regionType: .USEast1, identityPoolId: "us-east-1:cdcc971a-b67f-4bc0-9a12-291b5d416518", useEnhancedFlow: true, identityProviderManager: nil) AuthService.shared.loggedInObservable .filter { $0 } .flatMap { _ in return AuthService.shared.getUser() } .subscribe(onNext: { [weak self] user in self?.saveCognitoData(user: user) }).disposed(by: bag) } override var identityProviderName: String { return "cognito-identity.amazonaws.com" } override func token() -> AWSTask<NSString> { if AuthService.shared.isLoggedIn, let token = cognitoToken, let id = cognitoIdentityId { identityId = id return AWSTask(result: NSString(string: token)) } else { return AWSTask(result: nil) } } override func logins() -> AWSTask<NSDictionary> { if AuthService.shared.isLoggedIn { return super.logins() } else { return AWSTask(result: nil) } } override func clear() { super.clear() } // MARK: User Defaults func saveCognitoData(user: User?) { cognitoToken = user?.cognitoToken cognitoIdentityId = user?.identityId UserDefaults.standard.synchronize() } private var cognitoToken: String? { get { return UserDefaults.standard.string(forKey: COGNITO_TOKEN_KEY) } set { UserDefaults.standard.set(newValue, forKey: COGNITO_TOKEN_KEY) } } private var cognitoIdentityId: String? { get { return UserDefaults.standard.string(forKey: COGNITO_IDENTITY_ID_KEY) } set { UserDefaults.standard.set(newValue, forKey: COGNITO_IDENTITY_ID_KEY) } } }
agpl-3.0
bc3ef41239971523cec2b67cd819ca23
30.070423
159
0.633273
4.108007
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Add a point scene layer/AddPointSceneLayerViewController.swift
1
2172
// // Copyright © 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import ArcGIS class AddPointSceneLayerViewController: UIViewController { @IBOutlet var sceneView: AGSSceneView! { didSet { sceneView.scene = makeScene() } } /// Creates a scene with an point scene layer. /// /// - Returns: A new `AGSScene` object. func makeScene() -> AGSScene { let scene = AGSScene(basemapStyle: .arcGISImagery) // Create the elevation source. let elevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")! let elevationSource = AGSArcGISTiledElevationSource(url: elevationServiceURL) // Create the surface and add it to the scene. let surface = AGSSurface() surface.elevationSources = [elevationSource] scene.baseSurface = surface /// Add a point scene layer with points at world airport locations let pointSceneLayerURL = URL(string: "https://tiles.arcgis.com/tiles/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Airports_PointSceneLayer/SceneServer/layers/0")! // scene layer let sceneLayer = AGSArcGISSceneLayer(url: pointSceneLayerURL) scene.operationalLayers.add(sceneLayer) return scene } override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["AddPointSceneLayerViewController"] } }
apache-2.0
1170236e3ae81d01b8bd5ba0372bbf26
37.087719
163
0.68678
4.439673
false
false
false
false
SuPair/firefox-ios
Shared/GeneralUtils.swift
1
3127
/* 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 // Wraps NimbleDroid to ensure it is disabled in release // Use underscores between words, as these constants are stringified for reporting. public class Profiler { public enum Bookend { case url_autocomplete case intro_did_appear case history_panel_fetch case load_url case find_in_page } public static var shared: Profiler? private init() { NDScenario.setup() } public static func appDidFinishLaunching() { assert(shared == nil) let args = ProcessInfo.processInfo.arguments if args.contains("nimbledroid") { shared = Profiler() } } public func appIsActive() { // Workaround: delay for a few ms so that ND profiler doesn't hang up DispatchQueue.main.asyncAfter(deadline: .now() + 0.005) { Profiler.shared?.coldStartupEnd() Profiler.shared?.begin(bookend: .intro_did_appear) } } public func coldStartupEnd() { NDScenario.coldStartupEnd() } public func begin(bookend: Bookend) { NDScenario.begin(bookendID: "\(bookend)") } // This triggers a screenshot, and a delay is needed here in some cases to capture the correct screen // (otherwise the screen prior to this step completing is captured). public func end(bookend: Bookend, delay: TimeInterval = 0.0) { if delay > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { NDScenario.end(bookendID: "\(bookend)") } } else { NDScenario.end(bookendID: "\(bookend)") } } } /** Assertion for checking that the call is being made on the main thread. - parameter message: Message to display in case of assertion. */ public func assertIsMainThread(_ message: String) { assert(Thread.isMainThread, message) } // Simple timer for manual profiling. Not for production use. // Prints only if timing is longer than a threshold (to reduce noisy output). open class PerformanceTimer { let startTime: CFAbsoluteTime var endTime: CFAbsoluteTime? let threshold: Double let label: String public init(thresholdSeconds: Double = 0.001, label: String = "") { self.threshold = thresholdSeconds self.label = label startTime = CFAbsoluteTimeGetCurrent() } public func stopAndPrint() { if let t = stop() { print("Ran for \(t) seconds. [\(label)]") } } public func stop() -> String? { endTime = CFAbsoluteTimeGetCurrent() if let duration = duration { return "\(duration)" } return nil } public var duration: CFAbsoluteTime? { if let endTime = endTime { let time = endTime - startTime return time > threshold ? time : nil } else { return nil } } }
mpl-2.0
80661700f9aeb9bc904236c5a28d6e15
28.5
105
0.619763
4.467143
false
false
false
false
kousun12/RxSwift
RxSwift/DataStructures/Queue.swift
8
4693
// // Queue.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Data structure that represents queue. Complexity of `enqueue`, `dequeue` is O(1) when number of operations is averaged over N operations. Complexity of `peek` is O(1). */ public struct Queue<T>: SequenceType { /** Type of generator. */ public typealias Generator = AnyGenerator<T> private let _resizeFactor = 2 private var _storage: ContiguousArray<T?> private var _count: Int private var _pushNextIndex: Int private var _initialCapacity: Int /** Creates new queue. - parameter capacity: Capacity of newly created queue. */ public init(capacity: Int) { _initialCapacity = capacity _count = 0 _pushNextIndex = 0 if capacity > 0 { _storage = ContiguousArray<T?>(count: capacity, repeatedValue: nil) } else { _storage = ContiguousArray<T?>() } } private var dequeueIndex: Int { get { let index = _pushNextIndex - count return index < 0 ? index + _storage.count : index } } /** - returns: Is queue empty. */ public var empty: Bool { get { return count == 0 } } /** - returns: Number of elements inside queue. */ public var count: Int { get { return _count } } /** - returns: Element in front of a list of elements to `dequeue`. */ public func peek() -> T { precondition(count > 0) return _storage[dequeueIndex]! } mutating private func resizeTo(size: Int) { var newStorage = ContiguousArray<T?>(count: size, repeatedValue: nil) let count = _count let dequeueIndex = self.dequeueIndex let spaceToEndOfQueue = _storage.count - dequeueIndex // first batch is from dequeue index to end of array let countElementsInFirstBatch = min(count, spaceToEndOfQueue) // second batch is wrapped from start of array to end of queue let numberOfElementsInSecondBatch = count - countElementsInFirstBatch newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] _count = count _pushNextIndex = count _storage = newStorage } /** Enqueues `element`. - parameter element: Element to enqueue. */ public mutating func enqueue(element: T) { if count == _storage.count { resizeTo(max(_storage.count, 1) * _resizeFactor) } _storage[_pushNextIndex] = element _pushNextIndex++ _count = _count + 1 if _pushNextIndex >= _storage.count { _pushNextIndex -= _storage.count } } private mutating func dequeueElementOnly() -> T { precondition(count > 0) let index = dequeueIndex let value = _storage[index]! _storage[index] = nil _count = _count - 1 return value } /** Dequeues element and returns it, or returns `nil` in case queue is empty. - returns: Dequeued element. */ public mutating func tryDequeue() -> T? { if self.count == 0 { return nil } return dequeue() } /** Dequeues element or throws an exception in case queue is empty. - returns: Dequeued element. */ public mutating func dequeue() -> T { let value = dequeueElementOnly() let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) if _count < downsizeLimit && downsizeLimit >= _initialCapacity { resizeTo(_storage.count / _resizeFactor) } return value } /** - returns: Generator of contained elements. */ public func generate() -> Generator { var i = dequeueIndex var count = _count return anyGenerator { if count == 0 { return nil } count-- if i >= self._storage.count { i -= self._storage.count } return self._storage[i++] } } }
mit
fe847c7cf381fac51573b9c62869f30d
24.096257
157
0.548476
5.008538
false
false
false
false
mortorqrobotics/morscout-ios
MorScout/View Controllers/ProfileVC.swift
1
8205
// // ProfileVC.swift // MorScout // // Created by Farbod Rafezy on 3/7/16. // Copyright © 2016 MorTorq. All rights reserved. // import Foundation import SwiftyJSON class ProfileVC: UIViewController { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var profileName: UILabel! @IBOutlet weak var assigmentsScrollView: UIScrollView! @IBOutlet weak var scoutCaptainSwitch: UISwitch! @IBOutlet weak var matchReports: UILabel! @IBOutlet weak var pitReports: UILabel! @IBOutlet weak var teamsScouted: UILabel! @IBOutlet weak var assignmentsComplete: UILabel! @IBOutlet weak var assignmentsIncomplete: UILabel! @IBOutlet weak var assignmentCompletion: UILabel! var container = UIView() var assignmentsTopMargin: CGFloat = 0 var userId = storage.string(forKey: "_id")! var firstName = "" var lastName = "" var position = "" var profilePicturePath = "" var isScoutCaptain = false override func viewDidLoad() { super.viewDidLoad() scoutCaptainSwitch.isEnabled = false assigmentsScrollView.addSubview(container) if let savedFirstName = storage.string(forKey: "firstname"), let savedLastName = storage.string(forKey: "lastname") { profileName.text = savedFirstName + " " + savedLastName } if let savedProfPicPath = storage.string(forKey: "profpicpath") { profileImageView.kf.setImage( with: URL(string: "https://www.morteam.com" + savedProfPicPath)!, options: [.requestModifier(modifier)]) } if Reachability.isConnectedToNetwork() { getUserData(userId) getUserStats(userId) getUserTasks(userId) } else { alert( title: "No Internet Connection", message: "Could not load all user data", buttonText: "OK", viewController: self) } setupMenu(menuButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Acquires user data from the server and populates the relevant fields. */ func getUserData(_ _id: String) { httpRequest(morTeamURL + "/users/id/\(_id)", type: "GET") { responseText in if responseText != "null" { let user = parseJSON(responseText) self.firstName = String(describing: user["firstname"]) self.lastName = String(describing: user["lastname"]) self.position = String(describing: user["position"]) self.profilePicturePath = String(describing: user["profpicpath"]) self.isScoutCaptain = user["scoutCaptain"].boolValue DispatchQueue.main.async(execute: { self.profileName.text = self.firstName + " " + self.lastName self.profileImageView.kf.setImage( with: URL(string: "https://www.morteam.com" + self.profilePicturePath + "-300")!, options: [.requestModifier(modifier)]) self.scoutCaptainSwitch.setOn(self.isScoutCaptain, animated: false) self.scoutCaptainSwitch.isEnabled = self.isScoutCaptain || self.position == "admin" || self.position == "leader" }) self.scoutCaptainSwitch.addTarget(self, action: #selector(ProfileVC.scoutCaptainStateChanged(_:)), for: UIControlEvents.valueChanged) } } } func getUserStats(_ _id: String) { httpRequest(baseURL + "/getUserStats", type: "POST", data: ["userID": _id]) { responseText in let stats = parseJSON(responseText) DispatchQueue.main.async(execute: { self.matchReports.text = stats["matchesScouted"].stringValue self.pitReports.text = stats["pitsScouted"].stringValue self.teamsScouted.text = stats["teamsScouted"].stringValue }) } } func getUserTasks(_ _id: String) { httpRequest(baseURL + "/showTasks", type: "POST", data: ["scoutID": _id]) { responseText in let tasks = parseJSON(responseText) DispatchQueue.main.async(execute: { var completedMatches = [String]() for(_, subJson):(String, JSON) in tasks["matchesDone"] { completedMatches.append(subJson.stringValue) } if completedMatches.count == 0 { self.assignmentsComplete.text = "none" } else { self.assignmentsComplete.text = completedMatches.joined(separator: ", ") } var incompleteMatches = [String]() for(_, subJson):(String, JSON) in tasks["matchesNotDone"] { incompleteMatches.append(subJson.stringValue) } if incompleteMatches.count == 0 { self.assignmentsIncomplete.text = "none" } else { self.assignmentsIncomplete.text = incompleteMatches.joined(separator: ", ") } if tasks["assignments"].array?.count == 0 { let label = UILabel(frame: CGRect(x: 0, y: self.assignmentsTopMargin, width: self.view.frame.width, height: 21)) label.text = "None" label.font = UIFont(name: "Helvetica", size: 17) self.container.addSubview(label) } else { for(_, subJson):(String, JSON) in tasks["assignments"] { print(subJson) print("----") let label = UILabel(frame: CGRect(x: 0, y: self.assignmentsTopMargin, width: self.view.frame.width, height: 21)) label.text = "• From match \(subJson["startMatch"]) to \(subJson["endMatch"]), \(subJson["alliance"]) alliance, Team \(subJson["teamSection"])" label.font = UIFont(name: "Helvetica", size: 14.5) self.container.addSubview(label) self.assignmentsTopMargin += label.frame.height + 7 } } let totalMatches = (tasks["matchesDone"].array?.count)! + (tasks["matchesNotDone"].array?.count)! self.assignmentCompletion.text = String((tasks["matchesDone"].array?.count)!) + "/" + String(totalMatches) }) } } /* This is called when a user toggles the "is scout captain" switch */ func scoutCaptainStateChanged(_ switchState: UISwitch) { if switchState.isOn { httpRequest(baseURL + "/setSC", type: "POST", data: [ "isSC": "true", "userID": userId ]) { responseText in if responseText == "fail" { alert( title: "Failed", message: "Oops. Something went wrong.", buttonText: "OK", viewController: self) DispatchQueue.main.async(execute: { self.scoutCaptainSwitch.setOn(false, animated: true) }) } } } else { httpRequest(baseURL + "/setSC", type: "POST", data: [ "isSC": "false", "userID": userId ]) { responseText in if responseText == "fail" { alert( title: "Failed", message: "Oops. Something went wrong.", buttonText: "OK", viewController: self) DispatchQueue.main.async(execute: { self.scoutCaptainSwitch.setOn(true, animated: true) }) } } } } }
mit
74d1addf7d2495b7e278a4675198e95b
40.424242
167
0.534504
5.04118
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/MultilineArgumentsBracketsRule.swift
1
5899
import SwiftSyntax struct MultilineArgumentsBracketsRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "multiline_arguments_brackets", name: "Multiline Arguments Brackets", description: "Multiline arguments should have their surrounding brackets in a new line.", kind: .style, nonTriggeringExamples: [ Example(""" foo(param1: "Param1", param2: "Param2", param3: "Param3") """), Example(""" foo( param1: "Param1", param2: "Param2", param3: "Param3" ) """), Example(""" func foo( param1: "Param1", param2: "Param2", param3: "Param3" ) """), Example(""" foo { param1, param2 in print("hello world") } """), Example(""" foo( bar( x: 5, y: 7 ) ) """), Example(""" AlertViewModel.AlertAction(title: "some title", style: .default) { AlertManager.shared.presentNextDebugAlert() } """), Example(""" views.append(ViewModel(title: "MacBook", subtitle: "M1", action: { [weak self] in print("action tapped") })) """, excludeFromDocumentation: true), Example(""" public final class Logger { public static let shared = Logger(outputs: [ OSLoggerOutput(), ErrorLoggerOutput() ]) } """), Example(""" let errors = try self.download([ (description: description, priority: priority), ]) """), Example(""" return SignalProducer({ observer, _ in observer.sendCompleted() }).onMainQueue() """), Example(""" SomeType(a: [ 1, 2, 3 ], b: [1, 2]) """), Example(""" SomeType( a: 1 ) { print("completion") } """), Example(""" SomeType( a: 1 ) { print("completion") } """), Example(""" SomeType( a: .init() { print("completion") } ) """), Example(""" SomeType( a: .init() { print("completion") } ) """), Example(""" SomeType( a: 1 ) {} onError: {} """) ], triggeringExamples: [ Example(""" foo(↓param1: "Param1", param2: "Param2", param3: "Param3" ) """), Example(""" foo( param1: "Param1", param2: "Param2", param3: "Param3"↓) """), Example(""" foo(↓param1: "Param1", param2: "Param2", param3: "Param3"↓) """), Example(""" foo(↓bar( x: 5, y: 7 ) ) """), Example(""" foo( bar( x: 5, y: 7 )↓) """), Example(""" SomeOtherType(↓a: [ 1, 2, 3 ], b: "two"↓) """), Example(""" SomeOtherType( a: 1↓) {} """), Example(""" SomeOtherType( a: 1↓) { print("completion") } """), Example(""" views.append(ViewModel( title: "MacBook", subtitle: "M1", action: { [weak self] in print("action tapped") }↓)) """, excludeFromDocumentation: true) ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } } private extension MultilineArgumentsBracketsRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: FunctionCallExprSyntax) { guard let firstArgument = node.argumentList.first, let leftParen = node.leftParen, let rightParen = node.rightParen else { return } let hasMultilineFirstArgument = hasLeadingNewline(firstArgument) let hasMultilineArgument = node.argumentList .contains { argument in hasLeadingNewline(argument) } let hasMultilineRightParen = hasLeadingNewline(rightParen) if !hasMultilineFirstArgument, hasMultilineArgument { violations.append(leftParen.endPosition) } if !hasMultilineArgument, hasMultilineRightParen { violations.append(leftParen.endPosition) } if !hasMultilineRightParen, hasMultilineArgument { violations.append(rightParen.position) } } private func hasLeadingNewline(_ syntax: SyntaxProtocol) -> Bool { guard let leadingTrivia = syntax.leadingTrivia else { return false } return leadingTrivia.pieces.contains { $0.isNewline } } } }
mit
fdfdd98572f69c3c15a232a725595302
28.094059
97
0.418921
5.618547
false
false
false
false
shotaroikeda/flashcard-ios
flashcard-ios/flashCardData.swift
1
2195
// // flashCardData.swift // flashcard-ios // // Created by Shotaro Ikeda on 2/27/16. // Copyright © 2016 Shotaro Ikeda. All rights reserved. // import Foundation import SwiftyJSON class Question : AnyObject { var question : String var ans : String var weight : Double var right : Int var total : Int func reset() { weight = 1.0 right = 0 total = 0 } /* Initializers */ init() { question = "Question not set" ans = "Answer not set" weight = 1.0 right = 0 total = 0 } init(question : String, answer : String) { self.question = question self.ans = answer self.weight = 1.0 self.right = 0 self.total = 0 } init(question : String, answer : String, weight : Double, right_attempted : Int, total_attempted : Int) { self.question = question self.ans = answer self.weight = weight self.right = right_attempted self.total = total_attempted } init(json : JSON) { // TODO: Appropriate Association based off of results question = json["question"].stringValue ans = json["ans"].stringValue weight = json["weight"].doubleValue right = json["right"].intValue total = json["total"].intValue } /* Initializers */ } class FlashCardData : AnyObject { var classNames : [String] var flashCards : [String : [Question]] init() { classNames = [] flashCards = [:] } init(classNamesArr : [String], flashCardsMap : [String : [Question]]) { classNames = classNamesArr flashCards = flashCardsMap } func addClass(className : String, questionJSONArr : [JSON]) { classNames.append(className) let questionObjs = questionJSONArr.map({ Question(json: $0) }) flashCards[className] = questionObjs } func getQuestions(className : String) -> [Question] { if let questions = flashCards[className] { return questions } else { return [] } } }
mit
00db2d3b30708b0f7da063af23353939
21.161616
107
0.554239
4.219231
false
false
false
false
FiRiN59/Bond
Sources/Observable2DArray.swift
1
11780
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 ReactiveKit public enum Observable2DArrayChange { case reset case insertItems([IndexPath]) case deleteItems([IndexPath]) case updateItems([IndexPath]) case moveItem(IndexPath, IndexPath) case insertSections(IndexSet) case deleteSections(IndexSet) case updateSections(IndexSet) case moveSection(Int, Int) case beginBatchEditing case endBatchEditing } public protocol Observable2DArrayEventProtocol { associatedtype SectionMetadata associatedtype Item var change: Observable2DArrayChange { get } var source: Observable2DArray<SectionMetadata, Item> { get } } public struct Observable2DArrayEvent<SectionMetadata, Item> { public let change: Observable2DArrayChange public let source: Observable2DArray<SectionMetadata, Item> } /// Represents a section in 2D array. /// Section contains its metadata (e.g. header string) and items. public struct Observable2DArraySection<Metadata, Item> { public var metadata: Metadata public var items: [Item] public init(metadata: Metadata, items: [Item] = []) { self.metadata = metadata self.items = items } } public class Observable2DArray<SectionMetadata, Item>: Collection, SignalProtocol { fileprivate var sections: [Observable2DArraySection<SectionMetadata, Item>] fileprivate let subject = PublishSubject<Observable2DArrayEvent<SectionMetadata, Item>, NoError>() fileprivate let lock = NSRecursiveLock(name: "com.reactivekit.bond.observable2darray") public init(_ sections: [Observable2DArraySection<SectionMetadata, Item>] = []) { self.sections = sections } public var numberOfSections: Int { return sections.count } public func numberOfItems(inSection section: Int) -> Int { return sections[section].items.count } public var startIndex: IndexPath { return IndexPath(item: 0, section: 0) } public var endIndex: IndexPath { if numberOfSections == 0 { return IndexPath(item: 1, section: 0) } else { let lastSection = sections[numberOfSections-1] return IndexPath(item: lastSection.items.count, section: numberOfSections - 1) } } public func index(after i: IndexPath) -> IndexPath { if i.section < sections.count { let section = sections[i.section] if i.item + 1 >= section.items.count && i.section + 1 < sections.count { return IndexPath(item: 0, section: i.section + 1) } else { return IndexPath(item: i.item + 1, section: i.section) } } else { return endIndex } } public var isEmpty: Bool { return sections.reduce(true) { $0 && $1.items.isEmpty } } public var count: Int { return sections.reduce(0) { $0 + $1.items.count } } public subscript(index: IndexPath) -> Item { get { return sections[index.section].items[index.item] } } public subscript(index: Int) -> Observable2DArraySection<SectionMetadata, Item> { get { return sections[index] } } public func observe(with observer: @escaping (Event<Observable2DArrayEvent<SectionMetadata, Item>, NoError>) -> Void) -> Disposable { observer(.next(Observable2DArrayEvent(change: .reset, source: self))) return subject.observe(with: observer) } } public class MutableObservable2DArray<SectionMetadata, Item>: Observable2DArray<SectionMetadata, Item> { /// Append new section at the end of the 2D array. public func appendSection(_ section: Observable2DArraySection<SectionMetadata, Item>) { lock.lock(); defer { lock.unlock() } sections.append(section) let sectionIndex = sections.count - 1 let indices = 0..<section.items.count let indexPaths = indices.map { IndexPath(item: $0, section: sectionIndex) } if indices.count > 0 { subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self)) subject.next(Observable2DArrayEvent(change: .insertSections([sectionIndex]), source: self)) subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self)) subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self)) } else { subject.next(Observable2DArrayEvent(change: .insertSections([sectionIndex]), source: self)) } } /// Append `item` to the section `section` of the array. public func appendItem(_ item: Item, toSection section: Int) { lock.lock(); defer { lock.unlock() } sections[section].items.append(item) let indexPath = IndexPath(item: sections[section].items.count - 1, section: section) subject.next(Observable2DArrayEvent(change: .insertItems([indexPath]), source: self)) } /// Insert section at `index` with `items`. public func insert(section: Observable2DArraySection<SectionMetadata, Item>, at index: Int) { lock.lock(); defer { lock.unlock() } sections.insert(section, at: index) let indices = 0..<section.items.count let indexPaths = indices.map { IndexPath(item: $0, section: index) } if indices.count > 0 { subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self)) subject.next(Observable2DArrayEvent(change: .insertSections([index]), source: self)) subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self)) subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self)) } else { subject.next(Observable2DArrayEvent(change: .insertSections([index]), source: self)) } } /// Insert `item` at `indexPath`. public func insert(item: Item, at indexPath: IndexPath) { lock.lock(); defer { lock.unlock() } sections[indexPath.section].items.insert(item, at: indexPath.item) subject.next(Observable2DArrayEvent(change: .insertItems([indexPath]), source: self)) } /// Insert `items` at index path `indexPath`. public func insert(contentsOf items: [Item], at indexPath: IndexPath) { lock.lock(); defer { lock.unlock() } sections[indexPath.section].items.insert(contentsOf: items, at: indexPath.item) let indices = indexPath.item..<indexPath.item+items.count let indexPaths = indices.map { IndexPath(item: $0, section: indexPath.section) } subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self)) } /// Move the section at index `fromIndex` to index `toIndex`. public func moveSection(from fromIndex: Int, to toIndex: Int) { lock.lock(); defer { lock.unlock() } let section = sections.remove(at: fromIndex) sections.insert(section, at: toIndex) subject.next(Observable2DArrayEvent(change: .moveSection(fromIndex, toIndex), source: self)) } /// Move the item at `fromIndexPath` to `toIndexPath`. public func moveItem(from fromIndexPath: IndexPath, to toIndexPath: IndexPath) { lock.lock(); defer { lock.unlock() } let item = sections[fromIndexPath.section].items.remove(at: fromIndexPath.item) sections[toIndexPath.section].items.insert(item, at: toIndexPath.item) subject.next(Observable2DArrayEvent(change: .moveItem(fromIndexPath, toIndexPath), source: self)) } /// Remove and return the section at `index`. @discardableResult public func removeSection(at index: Int) -> Observable2DArraySection<SectionMetadata, Item> { lock.lock(); defer { lock.unlock() } let element = sections.remove(at: index) subject.next(Observable2DArrayEvent(change: .deleteSections([index]), source: self)) return element } /// Remove and return the item at `indexPath`. @discardableResult public func removeItem(at indexPath: IndexPath) -> Item { lock.lock(); defer { lock.unlock() } let element = sections[indexPath.section].items.remove(at: indexPath.item) subject.next(Observable2DArrayEvent(change: .deleteItems([indexPath]), source: self)) return element } /// Remove all items from the array. Keep empty sections. public func removeAllItems() { lock.lock(); defer { lock.unlock() } let indexPaths = sections.enumerated().reduce([]) { (indexPaths, section) -> [IndexPath] in indexPaths + section.element.items.indices.map { IndexPath(item: $0, section: section.offset) } } for index in sections.indices { sections[index].items.removeAll() } subject.next(Observable2DArrayEvent(change: .deleteItems(indexPaths), source: self)) } /// Remove all items and sections from the array. public func removeAllItemsAndSections() { lock.lock(); defer { lock.unlock() } let indices = sections.indices sections.removeAll() subject.next(Observable2DArrayEvent(change: .deleteSections(IndexSet(integersIn: indices)), source: self)) } public override subscript(index: IndexPath) -> Item { get { return sections[index.section].items[index.item] } set { lock.lock(); defer { lock.unlock() } sections[index.section].items[index.item] = newValue subject.next(Observable2DArrayEvent(change: .updateItems([index]), source: self)) } } /// Perform batched updates on the array. public func batchUpdate(_ update: (MutableObservable2DArray<SectionMetadata, Item>) -> Void) { lock.lock(); defer { lock.unlock() } subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self)) update(self) subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self)) } /// Change the underlying value withouth notifying the observers. public func silentUpdate(_ update: (inout [Observable2DArraySection<SectionMetadata, Item>]) -> Void) { lock.lock(); defer { lock.unlock() } update(&sections) } } // MARK: DataSourceProtocol conformation extension Observable2DArrayEvent: DataSourceEventProtocol { public var kind: DataSourceEventKind { switch change { case .reset: return .reload case .insertItems(let indexPaths): return .insertItems(indexPaths) case .deleteItems(let indexPaths): return .deleteItems(indexPaths) case .updateItems(let indexPaths): return .reloadItems(indexPaths) case .moveItem(let from, let to): return .moveItem(from, to) case .insertSections(let indices): return .insertSections(indices) case .deleteSections(let indices): return .deleteSections(indices) case .updateSections(let indices): return .reloadSections(indices) case .moveSection(let from, let to): return .moveSection(from, to) case .beginBatchEditing: return .beginUpdates case .endBatchEditing: return .endUpdates } } public var dataSource: Observable2DArray<SectionMetadata, Item> { return source } } extension Observable2DArray: DataSourceProtocol { }
mit
13982cc6622fc28261c975c424a7054b
36.160883
135
0.713158
4.186212
false
false
false
false
khizkhiz/swift
test/IDE/complete_exception.swift
8
11247
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH1 | FileCheck %s -check-prefix=CATCH1 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=THROW1 > %t.throw1 // RUN: FileCheck %s -check-prefix=THROW1 < %t.throw1 // RUN: FileCheck %s -check-prefix=THROW1-LOCAL < %t.throw1 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH2 | FileCheck %s -check-prefix=CATCH2 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=THROW2 | FileCheck %s -check-prefix=THROW2 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH3 | FileCheck %s -check-prefix=CATCH3 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CATCH1 | FileCheck %s -check-prefix=CATCH1 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_THROW1 | FileCheck %s -check-prefix=THROW1 // FIXME: <rdar://problem/21001526> No dot code completion results in switch case or catch stmt at top-level // RUNdisabled: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CATCH2 | FileCheck %s -check-prefix=CATCH2 // RUNdisabled: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_THROW2 | FileCheck %s -check-prefix=THROW2 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH1 > %t.inside_catch1 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch1 // RUN: FileCheck %s -check-prefix=IMPLICIT_ERROR < %t.inside_catch1 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH2 > %t.inside_catch2 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch2 // RUN: FileCheck %s -check-prefix=EXPLICIT_ERROR_E < %t.inside_catch2 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH3 > %t.inside_catch3 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch3 // RUN: FileCheck %s -check-prefix=EXPLICIT_NSERROR_E < %t.inside_catch3 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH4 > %t.inside_catch4 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch4 // RUN: FileCheck %s -check-prefix=EXPLICIT_ERROR_PAYLOAD_I < %t.inside_catch4 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH5 > %t.inside_catch5 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch5 // RUN: FileCheck %s -check-prefix=EXPLICIT_ERROR_E < %t.inside_catch5 // RUN: FileCheck %s -check-prefix=NO_ERROR_AND_A < %t.inside_catch5 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH6 > %t.inside_catch6 // RUN: FileCheck %s -check-prefix=STMT < %t.inside_catch6 // RUN: FileCheck %s -check-prefix=NO_E < %t.inside_catch6 // RUN: FileCheck %s -check-prefix=NO_ERROR_AND_A < %t.inside_catch6 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT1 | FileCheck %s -check-prefix=ERROR_DOT // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT2 | FileCheck %s -check-prefix=ERROR_DOT // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT3 | FileCheck %s -check-prefix=NSERROR_DOT // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT4 | FileCheck %s -check-prefix=INT_DOT // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_INSIDE_CATCH1 > %t.top_level_inside_catch1 // RUN: FileCheck %s -check-prefix=STMT < %t.top_level_inside_catch1 // RUN: FileCheck %s -check-prefix=IMPLICIT_ERROR < %t.top_level_inside_catch1 // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_INSIDE_CATCH_ERR_DOT1 | FileCheck %s -check-prefix=ERROR_DOT // REQUIRES: objc_interop import Foundation // importer SDK protocol ErrorPro1 : ErrorProtocol {} class Error1 : ErrorProtocol {} class Error2 : ErrorProtocol {} class Error3 {} extension Error3 : ErrorProtocol{} enum Error4 : ErrorProtocol { case E1 case E2(Int32) } class NoneError1 {} func getError1() -> Error1 { return Error1() } func getNSError() -> NSError { return NSError(domain: "", code: 1, userInfo: [:]) } func test001() { do {} catch #^CATCH1^# // CATCH1: Begin completions // CATCH1-DAG: Decl[Enum]/CurrModule: Error4[#Error4#]; name=Error4{{$}} // CATCH1-DAG: Decl[Class]/CurrModule: Error3[#Error3#]; name=Error3{{$}} // CATCH1-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2{{$}} // CATCH1-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1{{$}} // CATCH1-DAG: Keyword[let]/None: let{{; name=.+$}} // CATCH1-DAG: Decl[Class]/CurrModule: NoneError1[#NoneError1#]; name=NoneError1{{$}} // CATCH1-DAG: Decl[Class]/OtherModule[Foundation]: NSError[#NSError#]{{; name=.+$}} } func test002() { let text = "NonError" let e1 = Error1() let e2 = Error2() throw #^THROW1^# // THROW1: Begin completions // THROW1-DAG: Decl[Enum]/CurrModule: Error4[#Error4#]; name=Error4{{$}} // THROW1-DAG: Decl[Class]/CurrModule: Error3[#Error3#]; name=Error3{{$}} // THROW1-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2{{$}} // THROW1-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1{{$}} // THROW1-DAG: Decl[Protocol]/CurrModule: ErrorPro1[#ErrorPro1#]; name=ErrorPro1{{$}} // THROW1-DAG: Decl[FreeFunction]/CurrModule: getError1()[#Error1#]{{; name=.+$}} // THROW1-DAG: Decl[FreeFunction]/CurrModule: getNSError()[#NSError#]{{; name=.+$}} // If we could prove that there is no way to get to an ErrorProtocol value by // starting from these, we could remove them. But that may be infeasible in // the presence of overloaded operators. // THROW1-DAG: Decl[Class]/CurrModule: NoneError1[#NoneError1#]; name=NoneError1{{$}} // THROW1-LOCAL: Decl[LocalVar]/Local: text[#String#]; name=text{{$}} // THROW1-LOCAL: Decl[LocalVar]/Local: e1[#Error1#]; name=e1{{$}} // THROW1-LOCAL: Decl[LocalVar]/Local: e2[#Error2#]; name=e2{{$}} } func test003() { do {} catch Error4.#^CATCH2^# // CATCH2: Begin completions // CATCH2: Decl[EnumElement]/CurrNominal: E1[#Error4#]{{; name=.+$}} // CATCH2: Decl[EnumElement]/CurrNominal: E2({#Int32#})[#(Int32) -> Error4#]{{; name=.+$}} // CATCH2: End completions } func test004() { throw Error4.#^THROW2^# // THROW2: Begin completions // THROW2: Decl[EnumElement]/CurrNominal: E1[#Error4#]{{; name=.+$}} // THROW2: Decl[EnumElement]/CurrNominal: E2({#Int32#})[#(Int32) -> Error4#]{{; name=.+$}} // THROW2: End completions } func test005() { do {} catch Error4.E2#^CATCH3^# // CATCH3: Begin completions // CATCH3: Pattern/ExprSpecific: ({#Int32#})[#Error4#]{{; name=.+$}} // CATCH3: End completions } //===--- Top-level throw/catch do {} catch #^TOP_LEVEL_CATCH1^# {} throw #^TOP_LEVEL_THROW1^# do {} catch Error4.#^TOP_LEVEL_CATCH2^# {} throw Error4.#^TOP_LEVEL_THROW2^# //===--- Inside catch body // Statement-level code completions. This isn't exhaustive. // STMT: Begin completions // STMT-DAG: Keyword[if]/None: if; name=if // STMT-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1 // STMT-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2 // STMT-DAG: Decl[FreeFunction]/CurrModule: getError1()[#Error1#]; name=getError1() // STMT-DAG: Decl[FreeFunction]/CurrModule: getNSError()[#NSError#]; name=getNSError() // STMT: End completions func test006() { do { } catch { #^INSIDE_CATCH1^# } // IMPLICIT_ERROR: Decl[LocalVar]/Local: error[#ErrorProtocol#]; name=error } func test007() { do { } catch let e { #^INSIDE_CATCH2^# } // EXPLICIT_ERROR_E: Decl[LocalVar]/Local: e[#ErrorProtocol#]; name=e } func test008() { do { } catch let e as NSError { #^INSIDE_CATCH3^# } // EXPLICIT_NSERROR_E: Decl[LocalVar]/Local: e[#NSError#]; name=e } func test009() { do { } catch Error4.E2(let i) { #^INSIDE_CATCH4^# } // FIXME: we're getting parentheses around the type when it's unnamed... // EXPLICIT_ERROR_PAYLOAD_I: Decl[LocalVar]/Local: i[#(Int32)#]; name=i } func test010() { do { } catch let awesomeError { } catch let e { #^INSIDE_CATCH5^# } catch {} // NO_ERROR_AND_A-NOT: awesomeError // NO_ERROR_AND_A-NOT: Decl[LocalVar]/Local: error } func test011() { do { } catch let awesomeError { } catch let excellentError { } catch {} #^INSIDE_CATCH6^# // NO_E-NOT: excellentError } func test012() { do { } catch { error.#^INSIDE_CATCH_ERR_DOT1^# } // ERROR_DOT-NOT: Begin completions } func test013() { do { } catch let e { e.#^INSIDE_CATCH_ERR_DOT2^# } } func test014() { do { } catch let e as NSError { e.#^INSIDE_CATCH_ERR_DOT3^# } // NSERROR_DOT: Begin completions // NSERROR_DOT-DAG: Decl[InstanceVar]/CurrNominal: domain[#String#]; name=domain // NSERROR_DOT-DAG: Decl[InstanceVar]/CurrNominal: code[#Int#]; name=code // NSERROR_DOT-DAG: Decl[InstanceVar]/Super: hashValue[#Int#]; name=hashValue // NSERROR_DOT-DAG: Decl[InstanceMethod]/Super: myClass()[#AnyClass!#]; name=myClass() // NSERROR_DOT-DAG: Decl[InstanceMethod]/Super: isEqual({#(other): NSObject!#})[#Bool#]; name=isEqual(other: NSObject!) // NSERROR_DOT-DAG: Decl[InstanceVar]/Super: hash[#Int#]; name=hash // NSERROR_DOT-DAG: Decl[InstanceVar]/Super: description[#String#]; name=description // NSERROR_DOT: End completions } func test015() { do { } catch Error4.E2(let i) where i == 2 { i.#^INSIDE_CATCH_ERR_DOT4^# } } // Check that we can complete on the bound value; Not exhaustive.. // INT_DOT: Begin completions // INT_DOT-DAG: Decl[InstanceVar]/CurrNominal: bigEndian[#Int32#]; name=bigEndian // INT_DOT-DAG: Decl[InstanceVar]/CurrNominal: littleEndian[#Int32#]; name=littleEndian // INT_DOT: End completions //===--- Inside catch body top-level do { } catch { #^TOP_LEVEL_INSIDE_CATCH1^# } do { } catch { error.#^TOP_LEVEL_INSIDE_CATCH_ERR_DOT1^# }
apache-2.0
52cd5b6446c962059647c89e27c24818
45.475207
192
0.678403
3.130253
false
true
false
false
xqz001/MLSwiftBasic
Demo/MLSwiftBasic/Demo/Demo8ViewController.swift
8
3498
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // Demo8ViewController.swift // MLSwiftBasic // // Created by 张磊 on 15/7/23. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit /// 上拉加载更多/下拉刷新Demo Refresh class Demo8ViewController: MBBaseViewController,UITableViewDataSource,UITableViewDelegate{ var listsCount = 20 override func viewDidLoad() { super.viewDidLoad() self.setNavBarViewBackgroundColor(UIColor(rgba: "0c8eee")) self.setupTableView() } func setupTableView(){ var tableView = UITableView(frame: self.view.frame, style: .Plain) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.dataSource = self tableView.delegate = self self.view.insertSubview(tableView, atIndex: 0) // 自定义动画,需要传个数组 var animationImages = [UIImage]() for i in 0..<73{ var str = "PullToRefresh_00\(i)" if (i > 9){ str = "PullToRefresh_0\(i)" } if var image = UIImage(named: ZLSwiftRefreshBundleName.stringByAppendingPathComponent(str)) { animationImages.append(image) } } // 上拉动画 tableView.headerViewRefreshAnimationStatus(.headerViewRefreshPullAnimation, images: animationImages) // 加载动画 var loadAnimationImages = [UIImage]() for i in 73..<141{ var str = "PullToRefresh_0\(i)" if (i > 99){ str = "PullToRefresh_\(i)" } if var image = UIImage(named: ZLSwiftRefreshBundleName.stringByAppendingPathComponent(str)){ loadAnimationImages.append(image) } } tableView.headerViewRefreshAnimationStatus(.headerViewRefreshLoadingAnimation, images: loadAnimationImages) // 上啦加载更多 tableView.toLoadMoreAction({ () -> () in println("toLoadMoreAction success") if (self.listsCount < 100){ self.listsCount += 20 tableView.reloadData() tableView.doneRefresh() }else{ tableView.endLoadMoreData() } }) // 及时上拉刷新 tableView.nowRefresh({ () -> Void in dispatch_after(dispatch_time( DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), { () -> Void in // 结束动画 tableView.doneRefresh() }) }) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listsCount } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "cell" var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = "Test \(indexPath.row)" return cell } override func titleStr() -> String { return "下拉刷新/上拉加载更多 自定义动画" } }
mit
4b670b71fc004b120f16ad5d405ebdfc
32.366337
135
0.582196
4.963181
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/SidebarCapViewController.swift
1
4933
// // SidebarCapViewController.swift // Telegram // // Created by keepcoder on 28/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import TelegramCore import SwiftSignalKit class SidebarCapView : View { private let text:NSTextField = NSTextField() fileprivate let close:TitleButton = TitleButton() fileprivate var restrictedByPeer: Bool = false required init(frame frameRect: NSRect) { super.init(frame: frameRect) text.font = .normal(.header) text.drawsBackground = false // text.backgroundColor = .clear text.isSelectable = false text.isEditable = false text.isBordered = false text.focusRingType = .none text.isBezeled = false addSubview(text) close.set(font: .medium(.title), for: .Normal) addSubview(close) updateLocalizationAndTheme(theme: theme) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) text.textColor = theme.colors.grayText text.stringValue = restrictedByPeer ? strings().sidebarPeerRestricted : strings().sidebarAvalability text.setFrameSize(text.sizeThatFits(NSMakeSize(300, 100))) self.background = theme.colors.background.withAlphaComponent(0.97) close.set(color: theme.colors.accent, for: .Normal) close.set(text: strings().sidebarHide, for: .Normal) _ = close.sizeToFit() needsLayout = true } override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() } override func scrollWheel(with event: NSEvent) { } override var isFlipped: Bool { return true } override func layout() { super.layout() text.center() close.centerX(y: text.frame.maxY + 10) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SidebarCapViewController: GenericViewController<SidebarCapView> { private let context:AccountContext private let globalPeerDisposable = MetaDisposable() private var inChatAbility: Bool = true { didSet { navigationWillChangeController() } } init(_ context:AccountContext) { self.context = context super.init() } override func viewDidLoad() { super.viewDidLoad() self.navigationController = context.bindings.rootNavigation() (navigationController as? MajorNavigationController)?.add(listener: WeakReference(value: self)) genericView.close.set(handler: { [weak self] _ in self?.context.bindings.rootNavigation().closeSidebar() FastSettings.toggleSidebarShown(false) self?.context.bindings.entertainment().closedBySide() }, for: .Click) let postbox = self.context.account.postbox globalPeerDisposable.set((context.globalPeerHandler.get() |> mapToSignal { value -> Signal<Bool, NoError> in if let value = value { switch value { case .peer: return postbox.peerView(id: value.peerId) |> map { return peerViewMainPeer($0)?.canSendMessage(false) ?? false } case .thread: return postbox.peerView(id: value.peerId) |> map { return peerViewMainPeer($0)?.canSendMessage(true) ?? false } } } else { return .single(false) } } |> deliverOnMainQueue).start(next: { [weak self] accept in self?.readyOnce() self?.inChatAbility = accept })) } deinit { } override func viewDidChangedNavigationLayout(_ state: SplitViewState) { super.viewDidChangedNavigationLayout(state) navigationWillChangeController() } override func navigationWillChangeController() { self.genericView.restrictedByPeer = !inChatAbility self.genericView.updateLocalizationAndTheme(theme: theme) self.view.setFrameSize(context.bindings.entertainment().frame.size) if let controller = navigationController as? MajorNavigationController, controller.genericView.state != .dual { view.removeFromSuperview() } else if context.bindings.rootNavigation().controller is ChatController, inChatAbility { view.removeFromSuperview() } else { context.bindings.entertainment().addSubview(view) } // NotificationCenter.default.post(name: NSWindow.didBecomeKeyNotification, object: mainWindow) } }
gpl-2.0
5c129262e3823c457f3846b8a8cb5a1c
30.819355
119
0.613747
5.202532
false
false
false
false
eurofurence/ef-app_ios
Eurofurence/SwiftUI/Experiences/Tab/TabExperience.swift
1
1999
import EurofurenceKit import SwiftUI struct TabExperience: View { private enum Tab: Hashable { case news case schedule case dealers case information case more } @EnvironmentObject private var model: EurofurenceModel @State private var selectedTab: Tab = .news var body: some View { TabView(selection: $selectedTab) { NavigationView { NewsView() .navigationTitle("News") } .tabItem { NewsLabel(isSelected: selectedTab == .news) } .tag(Tab.news) NavigationView { ScheduleView(schedule: model.makeSchedule()) .navigationTitle("Schedule") } .navigationViewStyle(.stack) .tabItem { ScheduleLabel(isSelected: selectedTab == .schedule) } .tag(Tab.schedule) NavigationView { DealersView() .navigationTitle("Dealers") } .tabItem { DealersLabel(isSelected: selectedTab == .dealers) } .tag(Tab.information) NavigationView { InformationView() .navigationTitle("Information") } .tabItem { InformationLabel(isSelected: selectedTab == .information) } .tag(Tab.information) NavigationView { MoreView() .navigationTitle("More") } .tabItem { MoreLabel(isSelected: selectedTab == .more) } .tag(Tab.more) } } } struct TabExperience_Previews: PreviewProvider { static var previews: some View { EurofurenceModel.preview { _ in TabExperience() } } }
mit
bef090d1432a2c7c753d2aa562d8271e
24.961039
73
0.471736
5.98503
false
false
false
false
joonhocho/react-native-google-sign-in
ios/RNGoogleSignIn/RNGoogleSignInEvents.swift
1
4285
// // RNGoogleSignInEvents.swift // // Created by Joon Ho Cho on 1/17/17. // Copyright © 2017 Facebook. All rights reserved. // import Foundation @objc(RNGoogleSignInEvents) class RNGoogleSignInEvents: RCTEventEmitter, GIDSignInDelegate { var observing = false override init() { super.init() GIDSignIn.sharedInstance().delegate = self RNGoogleSignIn.sharedInstance.events = self } override func supportedEvents() -> [String] { return ["signIn", "signInError", "disconnect", "disconnectError", "dispatch"] } override func startObserving() { observing = true } override func stopObserving() { observing = false } static func userToJSON(_ user: GIDGoogleUser?) -> [String: Any]? { if let user = user { var body: [String: Any] = [:] if let userID = user.userID { body["userID"] = userID } if let profile = user.profile { if let email = profile.email { body["email"] = email } if let name = profile.name { body["name"] = name } if let givenName = profile.givenName { body["givenName"] = givenName } if let familyName = profile.familyName { body["familyName"] = familyName } if profile.hasImage { if let url = profile.imageURL(withDimension: 320)?.absoluteString { body["imageURL320"] = url } if let url = profile.imageURL(withDimension: 640)?.absoluteString { body["imageURL640"] = url } if let url = profile.imageURL(withDimension: 1280)?.absoluteString { body["imageURL1280"] = url } } } if let authentication = user.authentication { if let clientID = authentication.clientID { body["clientID"] = clientID } if let accessToken = authentication.accessToken { body["accessToken"] = accessToken } if let accessTokenExpirationDate = authentication.accessTokenExpirationDate { body["accessTokenExpirationDate"] = accessTokenExpirationDate.timeIntervalSince1970 } if let refreshToken = authentication.refreshToken { body["refreshToken"] = refreshToken } if let idToken = authentication.idToken { body["idToken"] = idToken } if let idTokenExpirationDate = authentication.idTokenExpirationDate { body["idTokenExpirationDate"] = idTokenExpirationDate.timeIntervalSince1970 } } if let accessibleScopes = user.accessibleScopes { body["accessibleScopes"] = accessibleScopes } if let hostedDomain = user.hostedDomain { body["hostedDomain"] = hostedDomain } if let serverAuthCode = user.serverAuthCode { body["serverAuthCode"] = serverAuthCode } return body } else { return nil } } func signIn(user: GIDGoogleUser?) { if (!observing) { return } sendEvent(withName: "signIn", body: RNGoogleSignInEvents.userToJSON(user)) } func signInError(error: Error?) { if (!observing) { return } sendEvent(withName: "signInError", body: [ "description": error?.localizedDescription ?? "", ]) } func disconnect(user: GIDGoogleUser?) { if (!observing) { return } sendEvent(withName: "disconnect", body: RNGoogleSignInEvents.userToJSON(user)) } func disconnectError(error: Error?) { if (!observing) { return } sendEvent(withName: "disconnectError", body: [ "description": error?.localizedDescription ?? "", ]) } func dispatch(error: Error?) { if (!observing) { return } sendEvent(withName: "dispatch", body: [ "description": error?.localizedDescription ?? "", ]) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser?, withError error: Error?) { if (error == nil && user != nil) { self.signIn(user: user) } else { self.signInError(error: error) } } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser?, withError error: Error?) { if (error == nil) { self.disconnect(user: user) } else { self.disconnectError(error: error) } } }
mit
f6635355c7bf2d27eba0e7750633d8a6
27.370861
100
0.610411
4.671756
false
false
false
false
easyui/Alamofire
Example/Source/MasterViewController.swift
4
4057
// // MasterViewController.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import UIKit class MasterViewController: UITableViewController { // MARK: - Properties @IBOutlet var titleImageView: UIImageView! var detailViewController: DetailViewController? private var reachability: NetworkReachabilityManager! // MARK: - View Lifecycle override func awakeFromNib() { super.awakeFromNib() navigationItem.titleView = titleImageView clearsSelectionOnViewWillAppear = true reachability = NetworkReachabilityManager.default monitorReachability() } // MARK: - UIStoryboardSegue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navigationController = segue.destination as? UINavigationController, let detailViewController = navigationController.topViewController as? DetailViewController { func requestForSegue(_ segue: UIStoryboardSegue) -> Request? { switch segue.identifier! { case "GET": detailViewController.segueIdentifier = "GET" return AF.request("https://httpbin.org/get") case "POST": detailViewController.segueIdentifier = "POST" return AF.request("https://httpbin.org/post", method: .post) case "PUT": detailViewController.segueIdentifier = "PUT" return AF.request("https://httpbin.org/put", method: .put) case "DELETE": detailViewController.segueIdentifier = "DELETE" return AF.request("https://httpbin.org/delete", method: .delete) case "DOWNLOAD": detailViewController.segueIdentifier = "DOWNLOAD" let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory, in: .userDomainMask) return AF.download("https://httpbin.org/stream/1", to: destination) default: return nil } } if let request = requestForSegue(segue) { detailViewController.request = request } } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 3 && indexPath.row == 0 { print("Reachability Status: \(reachability.status)") tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Private - Reachability private func monitorReachability() { reachability.startListening { status in print("Reachability Status Changed: \(status)") } } }
mit
f54e06d98536ff354d10a2c67fe09282
39.168317
105
0.635445
5.534789
false
false
false
false
justinhester/hacking-with-swift
src/Project38/Project38/AppDelegate.swift
1
3352
// // AppDelegate.swift // Project38 // // Created by Justin Lawrence Hester on 2/26/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
gpl-3.0
4184b72c52bac70d1c902e9565174f9d
53.934426
285
0.765742
6.182657
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1236-swift-constraints-constraintsystem-gettypeofmemberreference.swift
12
1959
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} func a(b: Int = 0) { } let c = a func some<S: SequenceType, T where Optional<T> == S.Generator.Element>(xs : S) -> T? { for (mx : T?) in xs { if let x = mx { } } } protocol a : a { } protocol a { } class b: a { } struct d<f : e, g: e where g.h == f.h> { } protocol e { } protocol A { } struct B<T : A> { } protocol C { } struct D : C { func g<T where T.E == F>(f: B<T>) { } } func ^(a: BooleanType, Bool) -> Bool { } protocol A { } struct B : A { } struct C<D, E: A where D.C == E> { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { } class a { } class c { func b((Any, c))(a: (Any, AnyObject)) { } } func f() { } class A: A { } class B : C { } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } func i(c: () -> ()) { } class a { var _ = i() { } } protocol A { } class B { func d() -> String { } } class C: B, A { override func d() -> String { } func c() -> String { } } func e<T where T: A, T: B>(t: T) { } protocol A { } struct X<Y> : A { func b(b: X.Type) { } } var f1: Int -> Int = { } let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in }(x1, f1) let crashes: Int = { x, f in }(x1, f1) func c<d { enum c { } } protocol b { } struct c { func e() { } struct c<d : SequenceType> { } func a<d>() -> [c<d>] { } func a(b: Int = 0) { } func c<d { enum c { } } func ^(a: BooleanType, Bool) -> Bool { } protocol a { for (mx : T?) in xs { rth): \(g())" } } func a<T>() { enum b { } } } } struct e : d { } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } protocol b { } struct c { func e() { } } enum S<T> { } struct c<d : SequenceType> { } func a<d>() -> [c<d>] {
apache-2.0
d2ee8adb5e7a349a560b96230f419d9a
11.720779
87
0.514038
2.213559
false
false
false
false
adib/Core-ML-Playgrounds
Photo-Explorations/PhotoPlays.playground/Sources/VGG16.swift
1
3637
/*: VGG16 Model Wrapper *K. Simonyan, A. Zisserman* **Very Deep Convolutional Networks for Large-Scale Image Recognition** arXiv technical report, 2014 http://www.robots.ox.ac.uk/~vgg/research/very_deep/ */ import CoreML /// Model Prediction Input Type public class VGG16Input : MLFeatureProvider { /// Input image to be classified as BGR image buffer, 224 pixels wide by 224 pixels high var image: CVPixelBuffer public var featureNames: Set<String> { get { return ["image"] } } public func featureValue(for featureName: String) -> MLFeatureValue? { if (featureName == "image") { return MLFeatureValue(pixelBuffer: image) } return nil } public init(image: CVPixelBuffer) { self.image = image } } /// Model Prediction Output Type public class VGG16Output : MLFeatureProvider { /// Probability of each category as dictionary of strings to doubles public let classLabelProbs: [String : Double] /// Most likely image category as string value public let classLabel: String public var featureNames: Set<String> { get { return ["classLabelProbs", "classLabel"] } } public func featureValue(for featureName: String) -> MLFeatureValue? { if (featureName == "classLabelProbs") { return try! MLFeatureValue(dictionary: classLabelProbs as [NSObject : NSNumber]) } if (featureName == "classLabel") { return MLFeatureValue(string: classLabel) } return nil } public init(classLabelProbs: [String : Double], classLabel: String) { self.classLabelProbs = classLabelProbs self.classLabel = classLabel } } /// Class for model loading and prediction public class VGG16 { var model: MLModel /** Construct a model with explicit path to mlmodel file - parameters: - url: the file url of the model - throws: an NSError object that describes the problem */ public init(contentsOf url: URL) throws { self.model = try MLModel(contentsOf: url) } /// Construct a model that automatically loads the model from the app's bundle public convenience init() { let bundle = Bundle(for: VGG16.self) let assetPath = bundle.url(forResource: "VGG16", withExtension:"mlmodelc") try! self.init(contentsOf: assetPath!) } /** Make a prediction using the structured interface - parameters: - input: the input to the prediction as VGG16Input - throws: an NSError object that describes the problem - returns: the result of the prediction as VGG16Output */ public func prediction(input: VGG16Input) throws -> VGG16Output { let outFeatures = try model.prediction(from: input) let result = VGG16Output(classLabelProbs: outFeatures.featureValue(for: "classLabelProbs")!.dictionaryValue as! [String : Double], classLabel: outFeatures.featureValue(for: "classLabel")!.stringValue) return result } /** Make a prediction using the convenience interface - parameters: - image: Input image to be classified as BGR image buffer, 224 pixels wide by 224 pixels high - throws: an NSError object that describes the problem - returns: the result of the prediction as VGG16Output */ public func prediction(image: CVPixelBuffer) throws -> VGG16Output { let input_ = VGG16Input(image: image) return try self.prediction(input: input_) } }
bsd-3-clause
1d96c4d508c56cfc0be1859b626caa03
30.626087
208
0.648062
4.506815
false
false
false
false
Ivacker/swift
test/SourceKit/SourceDocInfo/related_idents.swift
3
1110
class C1 { init() {} } func test1() { var x : C1 = C1() } extension C1 {} test1() import Swift class C2 { lazy var lazy_bar : Int = { let x = 0 return x }() } // RUN: %sourcekitd-test -req=related-idents -pos=6:17 %s -- -module-name related_idents %s | FileCheck -check-prefix=CHECK1 %s // CHECK1: START RANGES // CHECK1-NEXT: 1:7 - 2 // CHECK1-NEXT: 6:11 - 2 // CHECK1-NEXT: 6:16 - 2 // CHECK1-NEXT: 9:11 - 2 // CHECK1-NEXT: END RANGES // RUN: %sourcekitd-test -req=related-idents -pos=5:9 %s -- -module-name related_idents %s | FileCheck -check-prefix=CHECK2 %s // CHECK2: START RANGES // CHECK2-NEXT: 5:6 - 5 // CHECK2-NEXT: 11:1 - 5 // CHECK2-NEXT: END RANGES // RUN: %sourcekitd-test -req=related-idents -pos=13:10 %s -- -module-name related_idents %s | FileCheck -check-prefix=CHECK3 %s // CHECK3: START RANGES // CHECK3-NEXT: END RANGES // RUN: %sourcekitd-test -req=related-idents -pos=18:12 %s -- -module-name related_idents %s | FileCheck -check-prefix=CHECK4 %s // CHECK4: START RANGES // CHECK4-NEXT: 17:9 - 1 // CHECK4-NEXT: 18:12 - 1 // CHECK4-NEXT: END RANGES
apache-2.0
7a10c6e60861c0c7f250db56f53c6b14
24.227273
128
0.640541
2.599532
false
true
false
false
Kianoosh76/UIScrollView-InfiniteScroll
InfiniteScrollViewDemoSwift/CollectionViewController.swift
1
9305
// // CollectionViewController.swift // InfiniteScrollViewDemoSwift // // Created by pronebird on 5/3/15. // Copyright (c) 2015 pronebird. All rights reserved. // import UIKit import SafariServices class CollectionViewController: UICollectionViewController { fileprivate let downloadQueue = DispatchQueue(label: "ru.codeispoetry.downloadQueue", qos: DispatchQoS.background) fileprivate let cellIdentifier = "PhotoCell" fileprivate let apiURL = "https://api.flickr.com/services/feeds/photos_public.gne?nojsoncallback=1&format=json" fileprivate var items = [FlickrModel]() fileprivate var cache = NSCache<NSURL, UIImage>() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Set custom indicator collectionView?.infiniteScrollIndicatorView = CustomInfiniteIndicator(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) // Set custom indicator margin collectionView?.infiniteScrollIndicatorMargin = 40 // Add infinite scroll handler collectionView?.addInfiniteScroll { [weak self] (scrollView) -> Void in self?.fetchData() { scrollView.finishInfiniteScroll() } } // load initial data collectionView?.beginInfiniteScroll(true) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionViewLayout.invalidateLayout() } // MARK: - Private fileprivate func downloadPhoto(_ url: URL, completion: @escaping (_ url: URL, _ image: UIImage) -> Void) { downloadQueue.async(execute: { () -> Void in if let image = self.cache.object(forKey: url as NSURL) { DispatchQueue.main.async { completion(url, image) } return } do { let data = try Data(contentsOf: url) if let image = UIImage(data: data) { DispatchQueue.main.async { self.cache.setObject(image, forKey: url as NSURL) completion(url, image) } } else { print("Could not decode image") } } catch { print("Could not load URL: \(url): \(error)") } }) } fileprivate func fetchData(_ handler: ((Void) -> Void)?) { let requestURL = URL(string: apiURL)! let task = URLSession.shared.dataTask(with: requestURL, completionHandler: { (data, response, error) in DispatchQueue.main.async { self.handleResponse(data, response: response, error: error, completion: handler) UIApplication.shared.stopNetworkActivity() } }) UIApplication.shared.startNetworkActivity() // I run task.resume() with delay because my network is too fast let delay = (items.count == 0 ? 0 : 5) * Double(NSEC_PER_SEC) let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { task.resume() }) } fileprivate func handleResponse(_ data: Data!, response: URLResponse!, error: Error!, completion: ((Void) -> Void)?) { if let error = error { showAlertWithError(error) completion?() return; } var jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) // Fix broken Flickr JSON jsonString = jsonString?.replacingOccurrences(of: "\\'", with: "'") as NSString? let fixedData = jsonString?.data(using: String.Encoding.utf8.rawValue) let responseDict: Any do { responseDict = try JSONSerialization.jsonObject(with: fixedData!, options: JSONSerialization.ReadingOptions()) } catch { showAlertWithError(error) completion?() return } // extract data guard let payload = responseDict as? [String: Any], let results = payload["items"] as? [[String: Any]] else { completion?() return } // create new models let newModels = results.flatMap { FlickrModel($0) } // create new index paths let photoCount = items.count let (start, end) = (photoCount, newModels.count + photoCount) let indexPaths = (start..<end).map { return IndexPath(row: $0, section: 0) } // update data source items.append(contentsOf: newModels) // update collection view collectionView?.performBatchUpdates({ () -> Void in self.collectionView?.insertItems(at: indexPaths) }, completion: { (finished) -> Void in completion?() }); } fileprivate func showAlertWithError(_ error: Error) { let alert = UIAlertController(title: NSLocalizedString("collectionView.errorAlert.title", comment: ""), message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("collectionView.errorAlert.dismiss", comment: ""), style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("collectionView.errorAlert.retry", comment: ""), style: .default, handler: { _ in self.fetchData(nil) })) self.present(alert, animated: true, completion: nil) } } // MARK: - UICollectionViewDelegateFlowLayout extension CollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let collectionWidth = collectionView.bounds.width; var itemWidth = collectionWidth / 3 - 1; if(UI_USER_INTERFACE_IDIOM() == .pad) { itemWidth = collectionWidth / 4 - 1; } return CGSize(width: itemWidth, height: itemWidth); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1 } } // MARK: - UICollectionViewDataSource extension CollectionViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! PhotoCell let model = items[indexPath.item] let image = cache.object(forKey: model.media.medium as NSURL) cell.imageView.backgroundColor = UIColor(white: 0.95, alpha: 1) cell.imageView.image = image if image == nil { downloadPhoto(model.media.medium, completion: { (url, image) -> Void in collectionView.reloadItems(at: [indexPath]) }) } return cell } } // MARK: - UICollectionViewDelegate extension CollectionViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let model = items[indexPath.row] if #available(iOS 9.0, *) { let safariController = SFSafariViewController(url: model.link) safariController.delegate = self let safariNavigationController = UINavigationController(rootViewController: safariController) safariNavigationController.setNavigationBarHidden(true, animated: false) present(safariNavigationController, animated: true) } else { UIApplication.shared.openURL(model.link) } collectionView.deselectItem(at: indexPath, animated: true) } } // MARK: - SFSafariViewControllerDelegate @available(iOS 9.0, *) extension CollectionViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true) } } // MARK: - Actions extension CollectionViewController { @IBAction func handleRefresh() { collectionView?.beginInfiniteScroll(true) } }
mit
711c1a9871148352d4ae73164253c515
34.926641
175
0.601182
5.558542
false
false
false
false
barteljan/VISPER
Example/VISPER-Wireframe-Tests/DefaultWireframeTests.swift
1
44051
// // DefaultRouterRoutingTests.swift // VISPER-Wireframe_Tests // // Created by bartel on 21.11.17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import VISPER_Wireframe import VISPER_Core class DefaultWireframeTests: XCTestCase { func testAddsRoutePatternToRouter() throws { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let pattern = "/das/ist/ein/pattern" //Act try wireframe.add(routePattern:pattern) //Assert XCTAssert(router.invokedAdd) XCTAssertEqual(router.invokedAddParameters?.routePattern, pattern) } func testAddRoutingOptionProviderCallsComposedOptionProvider() throws { //Arrange let mockProvider = MockRoutingOptionProvider() let composedRoutingOptionProvider = MockComposedOptionProvider() let wireframe = DefaultWireframe(composedOptionProvider: composedRoutingOptionProvider) let priority = 10 //Act wireframe.add(optionProvider: mockProvider, priority: priority) //Assert AssertThat(composedRoutingOptionProvider.invokedAddParameters?.optionProvider, isOfType: MockRoutingOptionProvider.self, andEquals: mockProvider) XCTAssertEqual(composedRoutingOptionProvider.invokedAddParameters?.priority, priority) } func testAddHandlerCallsHandlerContainer(){ //Arrange let container = MockRoutingHandlerContainer() let wireframe = DefaultWireframe(routingHandlerContainer: container) let routeResult = DefaultRouteResult(routePattern: "/some/pattern", parameters: [:]) var didCallResponsibleHandler = false let responsibleHandler = { (routeResult: RouteResult) -> Bool in didCallResponsibleHandler = true return true } var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } let priority = 42 //Act XCTAssertNoThrow(try wireframe.add(priority: priority, responsibleFor: responsibleHandler, handler: handler)) //Assert XCTAssertTrue(container.invokedAdd) XCTAssertEqual(container.invokedAddParameters?.priority, priority) guard let responsibleHandlerParam = container.invokedAddResponsibleForParam else { XCTFail("responsibleHandler was not forwarded to handler container") return } XCTAssertFalse(didCallResponsibleHandler) _ = responsibleHandlerParam(routeResult) XCTAssertTrue(didCallResponsibleHandler) guard let handlerParam = container.invokedAddHandlerParam else { XCTFail("handler was not forwarded to handler container") return } XCTAssertFalse(didCallHandler) handlerParam(routeResult) XCTAssertTrue(didCallHandler) } func testAddControllerProviderCallsComposedControllerProvider() { //Arrange let mockProvider = MockControllerProvider() let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(composedControllerProvider: composedControllerProvider) let priority = 10 //Act wireframe.add(controllerProvider: mockProvider, priority: priority) //Assert AssertThat(composedControllerProvider.invokedAddParameters?.controllerProvider, isOfType: MockControllerProvider.self, andEquals: mockProvider) XCTAssertEqual(composedControllerProvider.invokedAddParameters?.priority, priority) } func testAddRoutingObserverCallsComposedRoutingObserver() { //Arrange let mockObserver = MockComposedRoutingObserver() let wireframe = DefaultWireframe(composedRoutingObserver: mockObserver) let priority = 10 let routePattern = "/test/pattern" //Act wireframe.add(routingObserver: mockObserver, priority: priority, routePattern: routePattern) //Assert AssertThat(mockObserver.invokedAddParameters?.routingObserver, isOfType: MockComposedRoutingObserver.self, andEquals: mockObserver) XCTAssertEqual(mockObserver.invokedAddParameters?.routePattern, routePattern) XCTAssertEqual(mockObserver.invokedAddParameters?.priority, priority) } func testAddRoutingPresenterCallsComposedRoutingPresenter() { //Arrange let mockPresenter = MockRoutingPresenter() let composedRoutingPresenter = MockComposedRoutingPresenter() let wireframe = DefaultWireframe(composedRoutingPresenter: composedRoutingPresenter) let priority = 10 //Act wireframe.add(routingPresenter: mockPresenter, priority: priority) //Assert AssertThat(composedRoutingPresenter.invokedAddParameters?.routingPresenter, isOfType: MockRoutingPresenter.self, andEquals: mockPresenter) XCTAssertEqual(composedRoutingPresenter.invokedAddParameters?.priority, priority) } func testCallsRouterOnRoute() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //Act //throws error since mock router does not give a result XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) let invokedParams = NSDictionary(dictionary:(router.invokedRouteUrlRoutingOptionParametersParameters?.parameters)!) XCTAssertEqual(invokedParams, NSDictionary(dictionary:parameters)) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: MockRoutingOption.self, andEquals: option) } func testCallsRouterOnController() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] //Act //throws error since mock router does not give a result XCTAssertThrowsError( try wireframe.controller(url: url, parameters: parameters) ) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) let invokedParams = NSDictionary(dictionary:(router.invokedRouteUrlRoutingOptionParametersParameters?.parameters)!) XCTAssertEqual(invokedParams, NSDictionary(dictionary:parameters)) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: RoutingOptionGetController.self) } func testCanRouteCallsRouterForRouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //let routeResult = DefaultRouteResult(routePattern: url.absoluteURL, parameters: parameters, routingOption: option) let router = MockRouter() let wireframe = DefaultWireframe(router: router) //Act XCTAssertNoThrow(try wireframe.canRoute(url: url, parameters: parameters, option: option)) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) guard let invokedParams = router.invokedRouteUrlRoutingOptionParametersParameters?.parameters else { XCTFail("parameter psrameters should be invoked in routers route function") return } let invokedParamsDict = NSDictionary(dictionary: invokedParams) let paramsDict = NSDictionary(dictionary: parameters) XCTAssertEqual(invokedParamsDict, paramsDict) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: MockRoutingOption.self, andEquals: option) } func testCanRouteReturnsFalseIfRouterResolvesNoRouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let router = MockRouter() router.stubbedRouteResult = nil let wireframe = DefaultWireframe(router: router) //Act var canRoute = false XCTAssertNoThrow(canRoute = try wireframe.canRoute(url: url, parameters: parameters, option: option)) //Assert XCTAssertFalse(canRoute) } func testCanRouteReturnsTrueIfRouterResolvesARouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let routeResult = DefaultRouteResult(routePattern: url.absoluteString, parameters: parameters, routingOption: option) let router = MockRouter() router.stubbedRouteUrlRoutingOptionParametersResult = routeResult let wireframe = DefaultWireframe(router: router) //Act var canRoute = false XCTAssertNoThrow( canRoute = try wireframe.canRoute(url: url, parameters: parameters, option: option) ) //Assert XCTAssertTrue(canRoute) } func testRouteThrowsErrorWhenNoRoutePatternWasFound() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //Act + Assert //throws error since mock router does not give a result XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw DefaultWireframeError.noRoutePatternFoundFor") { error in switch error { case DefaultWireframeError.noRoutePatternFoundFor(let errorUrl, let errorParameters): XCTAssertEqual(errorUrl, url) XCTAssertEqual(NSDictionary(dictionary: errorParameters), NSDictionary(dictionary:parameters)) default: XCTFail("should throw DefaultWireframeError.noRoutePatternFoundFor") } } } func testRouteCallsComposedRoutingOptionProviderWithRoutersRoutingResult() { //Arrange let router = MockRouter() let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedOptionProvider = MockComposedOptionProvider() let wireframe = DefaultWireframe(router: router,composedOptionProvider:composedOptionProvider) //Act //throws error since no controller can be provided afterwards, not important for this test XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedOptionProvider.invokedOption) AssertThat(composedOptionProvider.invokedOptionParameters?.routeResult, isOfType: DefaultRouteResult.self, andEquals: stubbedRouteResult) } func testRouteModifiesOptionByComposedRoutingObserver() { //Arrange let router = MockRouter() let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedOptionProvider = MockComposedOptionProvider() let optionProvidersOption = MockRoutingOption() composedOptionProvider.stubbedOptionResult = optionProvidersOption let wireframe = DefaultWireframe(router: router,composedOptionProvider:composedOptionProvider) // Act // throws error since no controller can be provided // the error should contain our modified routing option, // since it is called after modifing the route result by our option providers XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw DefaultWireframeError.canNotHandleRoute ") { error in switch error { case DefaultWireframeError.canNotHandleRoute(let result): //Assert AssertThat(result.routingOption, isOfType: MockRoutingOption.self, andEquals: optionProvidersOption) default: XCTFail("should throw DefaultWireframeError.canNotHandleRoute") } } } func testRouteCallsHandlerFromRoutingHandlerContainer() { //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false var handlerResult : RouteResult? let handler = { (routeResult: RouteResult) -> Void in handlerResult = routeResult didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer) //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertTrue(didCallHandler) XCTAssertTrue(handlerContainer.invokedPriorityOfHighestResponsibleProvider) XCTAssertTrue(handlerContainer.invokedHandler) guard let routeResult = handlerResult else { XCTFail("since the handler should be called there should be a result") return } XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) } func testRouteCallsCompletionWhenRoutingToHandler(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() handlerContainer.stubbedHandlerResult = { (routeResult: RouteResult) -> Void in } handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer) var didCallCompletion = false let completion = { didCallCompletion = true } //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: completion)) //Assert XCTAssertTrue(didCallCompletion) } func testRouteChecksIfComposedControllerProviderIsResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure composed controller provider let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testRouteDoesNotCallComposedControllerProviderIfItIsNotResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertFalse(composedControllerProvider.invokedMakeController) } func testRouteDoesThrowErrorIfComposedControllerProviderIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw an error") { error in //Assert switch error { case DefaultWireframeError.canNotHandleRoute(let routeResult): XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) default: XCTFail("should throw a DefaultWireframeError.canNotHandleRoute error") } } } func testRouteDoesCallComposedControllerProviderIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertTrue(composedControllerProvider.invokedMakeController) } func testRouteDoesCallComposedPresenterProviderIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true let controller = UIViewController() composedControllerProvider.stubbedMakeControllerResult = controller //configure mock presenter provider let composedPresenterProvider = MockComposedPresenterProvider() let mockPresenter = MockPresenter() composedPresenterProvider.stubbedMakePresentersResult = [mockPresenter] let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider, composedPresenterProvider: composedPresenterProvider) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedPresenterProvider.invokedMakePresenters) AssertThat(composedPresenterProvider.invokedMakePresentersParameters?.routeResult, isOfType: DefaultRouteResult.self, andEquals: stubbedRouteResult) XCTAssertEqual(composedPresenterProvider.invokedMakePresentersParameters?.controller, controller) } func testRouteChecksIfComposedRoutingPresenterIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() let wireframe = DefaultWireframe(router: router, composedControllerProvider:composedControllerProvider, composedRoutingPresenter: composedRoutingPresenter) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) } func testRouteThrowsErrorIfComposedRoutingPresenterIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() composedRoutingPresenter.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router, composedControllerProvider:composedControllerProvider, composedRoutingPresenter: composedRoutingPresenter) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "Should throw an DefaultWireframeError.noRoutingPresenterFoundFor error") { error in switch error { case DefaultWireframeError.noRoutingPresenterFoundFor(let routeResult): XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) default: XCTFail("Should throw an DefaultWireframeError.noRoutingPresenterFoundFor error") } } //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) } func testRouteCallsComposedRoutingPresenterIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() composedRoutingPresenter.stubbedIsResponsibleResult = true //configure mock routing delegate let routingDelegate = MockRoutingDelegate() let wireframe = DefaultWireframe(router: router, composedControllerProvider: composedControllerProvider, composedRoutingPresenter: composedRoutingPresenter, routingDelegate: routingDelegate) var didCallCompletion = false let completion = { didCallCompletion = true } // Act XCTAssertNoThrow(try wireframe.route(url: url, parameters: parameters, option: option, completion: completion)) //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) XCTAssertTrue(composedRoutingPresenter.invokedPresent) //assert params XCTAssertEqual(composedRoutingPresenter.invokedPresentParameters?.controller, composedControllerProvider.stubbedMakeControllerResult) AssertThat(composedRoutingPresenter.invokedPresentParameters?.routeResult, isOfType: DefaultRouteResult.self, andEquals: stubbedRouteResult) guard let wireframeParam = composedRoutingPresenter.invokedPresentParameters?.wireframe as? DefaultWireframe else { XCTFail("diden't foward wireframe to presenter") return } XCTAssertTrue(wireframe === wireframeParam) AssertThat(composedRoutingPresenter.invokedPresentParameters?.delegate, isOfType: MockRoutingDelegate.self, andEquals: routingDelegate) guard let complete = composedRoutingPresenter.invokedPresentParametersCompletion else { XCTFail("didn't forward completion to presenter") return } XCTAssertFalse(didCallCompletion) complete() XCTAssertTrue(didCallCompletion) } func testRouteChoosesHandlerIfItHasAHigherPriorityThanTheController(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //configure composed controller provider to return a lower priority for the controller let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedPriorityOfHighestResponsibleProviderResult = 21 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer, composedControllerProvider: composedControllerProvider) //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertTrue(didCallHandler) XCTAssertFalse(composedControllerProvider.invokedIsResponsible) } func testRouteChoosesControllerIfItHasAHigherPriorityThanAHandler(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 21 //configure composed controller provider to return a lower priority for the controller let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedPriorityOfHighestResponsibleProviderResult = 42 composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer, composedControllerProvider: composedControllerProvider) //Act // throws error since no presenter is available XCTAssertThrowsError(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertFalse(didCallHandler) XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testControllerChecksIfComposedControllerProviderIsResponsible() { let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure composed controller provider let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) XCTAssertNoThrow(try wireframe.controller(url: url, parameters: parameters)) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testControllerDoesNotCallComposedControllerProviderIfItIsNotResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) XCTAssertNoThrow( try wireframe.controller(url: url,parameters: parameters) ) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertFalse(composedControllerProvider.invokedMakeController) } func testControllerReturnsNilIfComposedControllerProviderIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided var controller : UIViewController? XCTAssertNoThrow( controller = try wireframe.controller(url: url, parameters: parameters) ) XCTAssertNil(controller) } func testControllerDoesCallComposedControllerProviderIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) var controller : UIViewController? XCTAssertNoThrow( controller = try wireframe.controller(url: url, parameters: parameters) ) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertTrue(composedControllerProvider.invokedMakeController) XCTAssertEqual(controller,composedControllerProvider.stubbedMakeControllerResult) } }
mit
6b3494fd911ef2e04bdd54c743d6b3fd
41.808552
164
0.593258
6.453267
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatModule/Chat/View/Message/JCMessageVideoContentView.swift
1
5527
// // JCMessageVideoContentView.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import AVKit import AVFoundation open class JCMessageVideoContentView: UIImageView, JCMessageContentViewType { public override init(image: UIImage?) { super.init(image: image) _commonInit() } public override init(image: UIImage?, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) _commonInit() } public override init(frame: CGRect) { super.init(frame: frame) _commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _commonInit() } open func apply(_ message: JCMessageType) { guard let content = message.content as? JCMessageVideoContent else { return } _message = message _delegate = content.delegate weak var weakSelf = self percentLabel.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height) if message.options.state == .sending { percentLabel.backgroundColor = UIColor.black.withAlphaComponent(0.3) percentLabel.isHidden = false percentLabel.textColor = .white content.uploadVideo = { (percent: Float ) -> Void in DispatchQueue.main.async { let p = Int(percent * 100) weakSelf?.percentLabel.text = "\(p)%" if percent == 1.0 { weakSelf?.percentLabel.isHidden = true weakSelf?.percentLabel.text = "" } } } } else { percentLabel.textColor = .clear percentLabel.backgroundColor = .clear _data = content.data } if content.image != nil { DispatchQueue.main.async { self.image = content.image } }else{ self.image = UIImage.createImage(color: UIColor(netHex: 0xCDD0D1), size: self.size) content.videoContent?.videoThumbImageData({ (data, id, error) in if data != nil { DispatchQueue.main.async { self.image = UIImage(data: data!) } } }) } _playImageView.center = CGPoint(x: self.width / 2, y: self.height / 2) } private weak var _delegate: JCMessageDelegate? private var _data: Data? private var _playImageView: UIImageView! private var _message: JCMessageType! private lazy var percentLabel: UILabel = { var percentLabel = UILabel(frame: CGRect(x: 20, y: 40, width: 50, height: 20)) percentLabel.isUserInteractionEnabled = false percentLabel.textAlignment = .center percentLabel.textColor = .white percentLabel.font = UIFont.systemFont(ofSize: 17) return percentLabel }() private func _commonInit() { isUserInteractionEnabled = true layer.cornerRadius = 2 layer.masksToBounds = true _tapGesture() _playImageView = UIImageView(frame: CGRect(x: 0, y: 50, width: 41, height: 41)) _playImageView.image = UIImage.loadImage("com_icon_play") addSubview(_playImageView) addSubview(self.percentLabel) } func _tapGesture() { let tap = UITapGestureRecognizer(target: self, action: #selector(_clickCell)) tap.numberOfTapsRequired = 1 addGestureRecognizer(tap) } @objc func _clickCell() { percentLabel.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height) percentLabel.textColor = .clear percentLabel.backgroundColor = .clear if _data != nil { printLog("local is have video data.") _delegate?.message?(message: _message, videoData: _data) }else{ guard let content = _message.content as? JCMessageVideoContent else { return } percentLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7) percentLabel.isHidden = false percentLabel.textColor = .white weak var weakSelf = self content.videoContent?.videoData(progress: { (percent, msgid) in let p = Int(percent * 100) weakSelf?.percentLabel.text = "\(p)%" }, completionHandler: { (data, id, error) in weakSelf?._data = data; weakSelf?.percentLabel.isHidden = true weakSelf?.percentLabel.text = "" weakSelf?._delegate?.message?(message: self._message, videoData: weakSelf?._data) }) content.videoFileContent?.fileData(progress: { (percent, msgid) in DispatchQueue.main.async { let p = Int(percent * 100) weakSelf?.percentLabel.text = "\(p)%" } }, completionHandler: { (data, id, error) in DispatchQueue.main.async { weakSelf?._data = data; weakSelf?.percentLabel.isHidden = true weakSelf?.percentLabel.text = "" weakSelf?._delegate?.message?(message: self._message, videoData: weakSelf?._data) } }) } } }
mit
6838e21153def3cace7040f45c742567
35.582781
101
0.557024
4.820244
false
false
false
false
bre7/buzzer-swift
Sources/App/Models/User.swift
1
404
import Foundation import Vapor struct User { let id: UInt let name: String let team: String init?(json: [String : Polymorphic]) { guard let id = json["id"]?.uint, let name = json["name"]?.string, let team = json["team"]?.string else { return nil } self.id = id self.name = name self.team = team } }
mit
3a374bc3c71557f03ac2a736b8a52142
19.2
50
0.50495
4.122449
false
false
false
false
tattn/SPAJAM2017-Final
SPAJAM2017Final/Domain/PushNotificationManager.swift
1
2092
// // PushNotificationManager.swift // HackathonStarter // // Created by 田中 達也 on 2016/07/21. // Copyright © 2016年 tattn. All rights reserved. // import UIKit import UserNotifications struct DeviceToken { let data: Data init(data: Data) { self.data = data } } extension DeviceToken: CustomStringConvertible { public var description: String { return data.map { String(format: "%.2hhx", $0) }.joined() } } struct PushNotificationManager { static func allowToPushNotification(with appDelegate: AppDelegate) { let application = UIApplication.shared if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() center.delegate = appDelegate center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if let error = error { print(error) return } if granted { print("Push notification is granted") application.registerForRemoteNotifications() } else { print("Push notification is NOT granted") } } } else { let type: UIUserNotificationType = [.alert, .badge, .sound] let setting = UIUserNotificationSettings(types: type, categories: nil) application.registerUserNotificationSettings(setting) } } static func send(_ token: DeviceToken) { if UserDefaults.standard.string(for: .deviceToken) != token.description { UserDefaults.standard.set(token.description, for: .deviceToken) // send devicetoken to server } } static func handlePushNotification(_ userInfo: [AnyHashable: Any], state: UIApplicationState) { switch state { case .inactive: // Launch via push notification break case .active: break case .background: break } } }
mit
7222e6debad13679ab0c7c2d2f428409
27.875
99
0.572872
5.1975
false
false
false
false
danger/danger-swift
Sources/RunnerLib/Runtime.swift
1
2671
import Foundation // Bunch of Danger runtime util funcs public enum Runtime { public static let supportedPaths = [ "Dangerfile.swift", "Danger.swift", "danger/Dangerfile.swift", "Danger/Dangerfile.swift" ] /// Finds a Dangerfile from the current working directory public static func getDangerfile() -> String? { supportedPaths.first { FileManager.default.fileExists(atPath: $0) } } /// Is this a dev build: e.g. running inside a cloned danger/danger-swift public static let potentialLibraryFolders = [ ".build/debug", // Working in Xcode / CLI ".build/x86_64-unknown-linux/debug", // Danger Swift's CI ".build/release", // Testing prod "/usr/local/lib/danger", // Intel Homebrew installs lib stuff to here "/opt/homebrew/lib/danger" // Apple Silicon Homebrew installs lib stuff to here ] /// Finds a path to add at runtime to the compiler, which links /// to the library Danger public static func getLibDangerPath() -> String? { let fileManager = FileManager.default // Was danger-swift installed via marathon? // e.g "~/.marathon/Scripts/Temp/https:--github.com-danger-danger-swift.git/clone/.build/release" let marathonDangerDLDir = NSHomeDirectory() + "/.marathon/Scripts/Temp/" let marathonScripts = try? fileManager.contentsOfDirectory(atPath: marathonDangerDLDir) var depManagerDangerLibPaths: [String] = [] if marathonScripts != nil { // TODO: Support running from a fork? let dangerSwiftPath = marathonScripts!.first { $0.contains("danger-swift") } if dangerSwiftPath != nil { let path = marathonDangerDLDir + dangerSwiftPath! + "/clone/.build/release" depManagerDangerLibPaths.append(path) } } let commandArgPath = CommandLine.arguments.first.map { arg in [arg.removingLastPathComponent()] } ?? [] // Check and find where we can link to libDanger from let libPaths = commandArgPath + potentialLibraryFolders + depManagerDangerLibPaths func isTheDangerLibPath(path: String) -> Bool { fileManager.fileExists(atPath: path + "/libDanger.dylib") || // OSX fileManager.fileExists(atPath: path + "/libDanger.so") // Linux } guard let path = libPaths.first(where: isTheDangerLibPath) else { return nil } // Always return an absolute path if path.starts(with: "/") { return path } return fileManager.currentDirectoryPath.appendingPath(path) } }
mit
b7f8d1aaf35bd55ad2f0fd6976fac2c3
38.279412
105
0.637589
4.422185
false
false
false
false
LQJJ/demo
125-iOSTips-master/Demo/50.GCD定时器/GCDTimer/GCD/GCDQueuePriority.swift
1
2135
// // GCDQueuePriority.swift // GCDTimer // // Created by Dariel on 2019/4/2. // Copyright © 2019 Dariel. All rights reserved. // import UIKit enum GCDQueuePriority { case BackgroundPriority // DISPATCH_QUEUE_PRIORITY_BACKGROUND case LowPriority // DISPATCH_QUEUE_PRIORITY_LOW case DefaultPriority // DISPATCH_QUEUE_PRIORITY_DEFAULT case HighPriority // DISPATCH_QUEUE_PRIORITY_HIGH case userInteractive case unspecified func getDispatchQoSClass() -> DispatchQoS.QoSClass { var qos: DispatchQoS.QoSClass switch self { case GCDQueuePriority.BackgroundPriority: qos = .background break case GCDQueuePriority.LowPriority: qos = .utility break case GCDQueuePriority.DefaultPriority: qos = .default break case GCDQueuePriority.HighPriority: qos = .userInitiated break case GCDQueuePriority.userInteractive: qos = .userInteractive break case GCDQueuePriority.unspecified: qos = .unspecified break } return qos } func getDispatchQoS() -> DispatchQoS { var qos: DispatchQoS switch self { case GCDQueuePriority.BackgroundPriority: qos = .background break case GCDQueuePriority.LowPriority: qos = .utility break case GCDQueuePriority.DefaultPriority: qos = .default break case GCDQueuePriority.HighPriority: qos = .userInitiated break case GCDQueuePriority.userInteractive: qos = .userInteractive break case GCDQueuePriority.unspecified: qos = .unspecified break } return qos } }
apache-2.0
09e3a8c97ce8d20ca97c25e27c85d17e
23.25
71
0.52015
6.276471
false
false
false
false
yagiz/Bagel
mac/Bagel/Workers/BagelController/Common/BagelExtensions.swift
1
1054
// // BagelExtensions.swift // Bagel // // Created by Yagiz Gurgul on 21.10.2018. // Copyright © 2018 Yagiz Lab. All rights reserved. // import Cocoa extension String { var base64Data: Data? { return Data(base64Encoded: self, options: .ignoreUnknownCharacters) } } extension URL { func toKeyValueArray() -> [KeyValue] { var array = [KeyValue]() if let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems { for queryItem in queryItems { array.append(KeyValue(key: queryItem.name, value: queryItem.value)) } } return array } } extension Dictionary where Key == String, Value == String { func toKeyValueArray() -> [KeyValue] { var array = [KeyValue]() for key in self.keys { array.append(KeyValue(key: key, value: self[key])) } return array } }
apache-2.0
42e26a0d1b6279a74feaad234b6f5b0c
20.06
98
0.532764
4.743243
false
false
false
false
LeTchang/mapApp
MapApp/extension.swift
1
727
// // extension.swift // MapApp // // Created by Tchang on 21/06/16. // Copyright © 2016 Tchang. All rights reserved. // import UIKit import MapKit extension String { func trim() -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } extension MKMapView { func annotation(name: String, latitude: Double, longitude: Double) { let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = name annotation.subtitle = "Maybe someone knows this place..." self.addAnnotation(annotation) } }
mit
556ee2956664beeb37914f1d9fa22444
24.068966
92
0.680441
4.683871
false
false
false
false
VicFrolov/Markit
iOS/Markit/Markit/LGHorizontalLinearFlowLayout.swift
1
3972
// // LGHorizontalLinearFlowLayout.swift // Markit // // Created by Trixie on 12/15/16. // Copyright © 2016 Victor Frolov. All rights reserved. // import UIKit public class LGHorizontalLinearFlowLayout: UICollectionViewFlowLayout { private var lastCollectionViewSize: CGSize = CGSize.zero public var scalingOffset: CGFloat = 110 public var minimumScaleFactor: CGFloat = 0.5 public var scaleItems: Bool = true static func configureLayout(collectionView: UICollectionView, itemSize: CGSize, minimumLineSpacing: CGFloat) -> LGHorizontalLinearFlowLayout { let layout = LGHorizontalLinearFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = minimumLineSpacing layout.itemSize = itemSize collectionView.decelerationRate = UIScrollViewDecelerationRateFast collectionView.collectionViewLayout = layout return layout } override public func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) if self.collectionView == nil { return } let currentCollectionViewSize = self.collectionView!.bounds.size if !currentCollectionViewSize.equalTo(self.lastCollectionViewSize) { self.configureInset() self.lastCollectionViewSize = currentCollectionViewSize } } private func configureInset() -> Void { if self.collectionView == nil { return } let inset = self.collectionView!.bounds.size.width / 2 - self.itemSize.width / 2 self.collectionView!.contentInset = UIEdgeInsetsMake(0, inset, 0, inset) self.collectionView!.contentOffset = CGPoint(x: -inset, y: 0) } public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if self.collectionView == nil { return proposedContentOffset } let collectionViewSize = self.collectionView!.bounds.size let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionViewSize.width, height: collectionViewSize.height) let layoutAttributes = self.layoutAttributesForElements(in: proposedRect) if layoutAttributes == nil { return proposedContentOffset } var candidateAttributes: UICollectionViewLayoutAttributes? let proposedContentOffsetCenterX = proposedContentOffset.x + collectionViewSize.width / 2 for attributes: UICollectionViewLayoutAttributes in layoutAttributes! { if attributes.representedElementCategory != .cell { continue } if candidateAttributes == nil { candidateAttributes = attributes continue } if fabs(attributes.center.x - proposedContentOffsetCenterX) < fabs(candidateAttributes!.center.x - proposedContentOffsetCenterX) { candidateAttributes = attributes } } if candidateAttributes == nil { return proposedContentOffset } var newOffsetX = candidateAttributes!.center.x - self.collectionView!.bounds.size.width / 2 let offset = newOffsetX - self.collectionView!.contentOffset.x if (velocity.x < 0 && offset > 0) || (velocity.x > 0 && offset < 0) { let pageWidth = self.itemSize.width + self.minimumLineSpacing newOffsetX += velocity.x > 0 ? pageWidth : -pageWidth } return CGPoint(x: newOffsetX, y: proposedContentOffset.y) } public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
apache-2.0
dddbcbf693bff8891b33343c6370dce1
36.11215
155
0.646185
5.962462
false
false
false
false
timvermeulen/DraughtsCloud
Sources/App/Models/Draughts/Draughts.Game+extensions.swift
1
6758
import Draughts import Fluent extension Game { enum Keys { static let pdn = "pdn" } } extension Decorator where Value == Game { static var fen: Decorator { return Decorator { game, json in try json.set(PositionKeys.JSON.fen, game.startPosition.fen) } } static var pdn: Decorator { return Decorator { game, json in try json.set(Game.Keys.pdn, game.pdnWithoutRedundantVariations) } } static var positionBitboards: Decorator { return Decorator { game, json in try json.set(PositionKeys.JSON.bitboards, Bitboards(position: game.startPosition)) } } } extension Game: JSONRepresentable, ResponseRepresentable { public func makeJSON() throws -> JSON { return JSON() } } extension Game: RequestDecoratable { func decorated(by request: Request) throws -> Decorated<Game> { return self .decorated(by: .fen, .pdn, where: request.flag(.verbose)) .decorated(by: .positionBitboards, .pdn, where: request.flag(.basic)) // TODO: add a pdn substitute } } extension Game { @discardableResult func save(isTactic: Bool) throws -> Identifier { guard !isTactic || isValidTactic else { throw Abort.badRequest } var position = try AnyPosition(startPosition, isTactic: isTactic).savedOrUpdated() let id = try position.assertExists() for (move, variations) in zip(moves, variations) { let endPosition = try AnyPosition(move.endPosition, isTactic: false).savedOrUpdated() let move = try AnyMove(move, from: position, to: endPosition).savedOrUpdated() position.mainResponse = try move.assertExists() try position.save() for (move, variation) in variations { let endPosition = try AnyPosition(variation.startPosition, isTactic: false).savedOrUpdated() try AnyMove(move, from: position, to: endPosition).saveOrUpdate() try variation.save(isTactic: false) } position = endPosition } return id } func saveAsTactic() throws -> WhitePosition { let id = try save(isTactic: true) guard let result = try WhitePosition.find(id) else { throw Abort.serverError } return result } private struct Result: Comparable { let startID, endID: Identifier let black1, white, black2: Bitboards let white1IsMain, blackIsMain, white2IsMain: Bool init(_ node: Node) throws { startID = try node.get("id1") endID = try node.get("id3") let white1: UInt64 = try node.get("white1") let black1: UInt64 = try node.get("black1") let kings1: UInt64 = try node.get("kings1") let white2: UInt64 = try node.get("white2") let black2: UInt64 = try node.get("black2") let kings2: UInt64 = try node.get("kings2") let white3: UInt64 = try node.get("white3") let black3: UInt64 = try node.get("black3") let kings3: UInt64 = try node.get("kings3") self.black1 = Bitboards(white: Bitboard(white1), black: Bitboard(black1), kings: Bitboard(kings1)) self.white = Bitboards(white: Bitboard(white2), black: Bitboard(black2), kings: Bitboard(kings2)) self.black2 = Bitboards(white: Bitboard(white3), black: Bitboard(black3), kings: Bitboard(kings3)) white1IsMain = try node.get("white1_is_main") blackIsMain = try node.get("black_is_main") white2IsMain = try node.get("white2_is_main") } static func == (left: Result, right: Result) -> Bool { return left.startID == right.startID && left.black1 == right.black1 && left.white == right.white && left.black2 == right.black2 } static func < (left: Result, right: Result) -> Bool { guard left.white1IsMain == right.white1IsMain else { return left.white1IsMain } guard left.blackIsMain == right.blackIsMain else { return left.blackIsMain } guard left.white2IsMain == right.white2IsMain else { return left.white2IsMain } return left != right // FIXME } } init<P: Position>(_ position: P, from driver: Driver) throws { var seenIDs: [Identifier] = [] let startID = try position.assertExists() let raw = try driver.raw(WhitePosition.gameQuery(for: startID)) guard let nodes = raw.array else { throw Abort.serverError } let results = try nodes.map(Result.init).sorted() func getResults(for startID: Identifier) -> [Result] { return results.filter { $0.startID == startID } } let helper = GameHelper(position: Draughts.Position(position)) func play(_ whiteMove1: Draughts.Move, _ blackMove: Draughts.Move, _ whiteMove2: Draughts.Move, id: Identifier) throws { guard helper.play(whiteMove1) && helper.play(blackMove) && helper.play(whiteMove2) && helper.backward() else { throw Abort.serverError } try load(id) guard helper.backward() && helper.backward() else { throw Abort.serverError } } func load(_ id: Identifier) throws { guard !seenIDs.contains(id) else { return } seenIDs.append(id) for result in getResults(for: id) { guard let whiteMove1 = helper.position.legalMoves.first(where: { Bitboards(position: $0.endPosition) == result.black1 }), let blackMove = whiteMove1.endPosition.legalMoves.first(where: { Bitboards(position: $0.endPosition) == result.white }), let whiteMove2 = blackMove.endPosition.legalMoves.first(where: { Bitboards(position: $0.endPosition) == result.black2 }) else { throw Abort.serverError } try play(whiteMove1, blackMove, whiteMove2, id: result.endID) } } try load(startID) self = helper.game } init?(fen: String, pdn: String) { guard let position = Draughts.Position(fen: fen) else { return nil } self.init(pdn: pdn, position: position) } } extension Draughts.Game: VisuallyRepresentable { func makeVisualRepresentation() -> String { return "\(startPosition.makeVisualRepresentation())\n\(pdnWithoutRedundantVariations)\n\(endPosition.makeVisualRepresentation())" } }
mit
47cde0d0db65566c1f349665139f346d
38.988166
148
0.595886
4.105711
false
false
false
false
qiuncheng/study-for-swift
YLShareManager/YLShareManager/WXSendMessageToReq+YL.swift
1
1870
// // WXSendMessageToReq+YL.swift // YLShareManager // // Created by vsccw on 2017/5/3. // Copyright © 2017年 Qiun Cheng. All rights reserved. // extension SendMessageToWXReq { static func imageMessage(content: YLShareImageContent) -> SendMessageToWXReq? { if let image = content.images.first { let mediaMsg = WXMediaMessage() mediaMsg.thumbData = UIImageJPEGRepresentation(image, 0.1) let imageObj = WXImageObject() imageObj.imageData = UIImageJPEGRepresentation(image, 1.0) mediaMsg.mediaObject = imageObj let req = SendMessageToWXReq() req.bText = false req.message = mediaMsg return req } else { return nil } } static func urlMessage(content: YLShareUrlContent) -> SendMessageToWXReq { let mediaMsg = WXMediaMessage() mediaMsg.title = content.title mediaMsg.description = content.desc if let imageStr = content.thumbImage as? String { if let url = URL(string: imageStr) { do { let data = try Data(contentsOf: url) mediaMsg.thumbData = data } catch let err { print(err) } } } else if let imageData = content.thumbImage as? Data { mediaMsg.thumbData = imageData } else if let image = content.thumbImage as? UIImage { mediaMsg.setThumbImage(image) } let webpageObj = WXWebpageObject() webpageObj.webpageUrl = content.urlStr mediaMsg.mediaObject = webpageObj let req = SendMessageToWXReq() req.bText = false req.message = mediaMsg return req } }
mit
c647b699fda9fb5e6c5a2507d40027ea
30.116667
83
0.55383
4.632754
false
false
false
false
donmccaughey/Lunch
LunchKit/LunchKit/Venues.swift
1
2406
// // Venues.swift // LunchKit // // Created by Don McCaughey on 4/19/16. // Copyright © 2016 Don McCaughey. All rights reserved. // import Foundation public class Venues { public var all: [Venue] = [] var indexByID: [String:Venue] = [:] public init() { } init(_ venues: [Venue]) { for venue in venues { insertVenue(venue) } } public init?(fromFoursquareJSONArray array: [AnyObject]) { for venueObject in array { guard let venueDictionary = venueObject as? [String:AnyObject], let venue = Venue(fromFoursquareJSONDictionary: venueDictionary) else { return nil } insertVenue(venue) } } public init?(fromPlistArray array: [AnyObject]) { for venueObject in array { guard let venueDictionary = venueObject as? [String:AnyObject], let venue = Venue(fromPlistDictionary: venueDictionary) else { return nil } insertVenue(venue) } } public func getThumbsDownVenues() -> [Venue] { return all.filter({ $0.thumbsDown }) } public func getThumbsUpVenues() -> [Venue] { return all.filter({ !$0.thumbsDown }) } func insertVenue(venue: Venue) -> Bool { if indexByID[venue.id] != nil { return false } all.append(venue) indexByID[venue.id] = venue return true } func updateVenue(venue: Venue) -> Bool { if indexByID[venue.id] == nil { return false } let i = all.indexOf({ $0.id == venue.id }) all[i!] = venue indexByID[venue.id] = venue return true } public func includeVenue(venue: Venue) { if !updateVenue(venue) { insertVenue(venue) } } public func removeVenue(venue: Venue) { let i = all.indexOf({ $0.id == venue.id }) all.removeAtIndex(i!) indexByID[venue.id] = nil } public func asPlistArray() -> [AnyObject] { return all.map({ $0.asPlistDictionary() }) } public func update(venues: Venues) { for venue in venues.all { updateVenue(venue) } } }
bsd-2-clause
999feca0d7d55074dd0b1120732d8d87
23.292929
80
0.515177
4.404762
false
false
false
false
ndevenish/KerbalHUD
KerbalHUD/InstrumentPanel.swift
1
8694
// // InstrumentPanel.swift // KerbalHUD // // Created by Nicholas Devenish on 26/08/2015. // Copyright © 2015 Nicholas Devenish. All rights reserved. // import Foundation import GLKit private class PanelEntry { var instrument : Instrument let framebuffer : Framebuffer var bounds : Bounds init(instrument: Instrument, buffer: Framebuffer, bounds: Bounds) { self.instrument = instrument self.framebuffer = buffer self.bounds = bounds } } private enum PanelLayout { case None case Horizontal case Vertical } class InstrumentPanel { var connection : TelemachusInterface? { didSet { for (index, i) in instruments.enumerate() { if !connected.contains(index) { i.instrument.connect(connection!) connected.insert(index) } } } } private let drawing : DrawingTools private var instruments : [PanelEntry] = [] private var previousArrangement : (layout: PanelLayout, frame: Double) = (.None, -1) private var focus : PanelEntry? = nil private var drawOrder : [Int] = [] private var connected = Set<Int>() init(tools : DrawingTools) { drawing = tools } deinit { for i in instruments { drawing.deleteFramebuffer(i.framebuffer) } } func update() { for (index, i) in instruments.enumerate() { // If it's connected, update the instruments if connected.contains(index) { i.instrument.update() } // If the instrument is not the focus, and has ended // it's animation, then disconnect it if let bound = i.bounds as? BoundsInterpolator, let focus = self.focus where focus !== i && bound.complete { i.bounds = FixedBounds(bounds: bound) i.instrument.disconnect(connection!) connected.remove(index) } } } func draw() { processGLErrors() if focus == nil { layout() } // Generate the textures for every instrument for (index, i) in instruments.enumerate() { if !connected.contains(index) { continue } // Bind the framebuffer for this instrument drawing.bind(i.framebuffer) // Reassign the projection matrix drawing.setOrthProjection(left: 0, right: Float(i.instrument.screenSize.w), bottom: 0, top: Float(i.instrument.screenSize.h)) i.instrument.draw() } // Revert back to the main framebuffer drawing.bind(Framebuffer.Default) drawing.setOrthProjection(left: 0, right: drawing.screenSizePhysical.aspect, bottom: 0, top: 1) drawing.program.setColor(red: 1, green: 1, blue: 1) for instrument in drawOrder.map({instruments[$0]}) { // Now, draw the textured square drawing.bind(instrument.framebuffer.texture) drawing.DrawTexturedSquare(instrument.bounds) } processGLErrors() } func AddInstrument(item : Instrument) { // Work out the maximum size this is required on a full screen let drawSize = item.screenSize let screenSize = Size2D(w: Float(UIScreen.mainScreen().bounds.size.width * UIScreen.mainScreen().scale), h: Float(UIScreen.mainScreen().bounds.size.height * UIScreen.mainScreen().scale)) let maxScale = max(drawSize.scaleForFitInto(screenSize), drawSize.scaleForFitInto(screenSize.flipped)) let pixelSize = (drawSize * maxScale).map { Int($0) } let buffer = drawing.createTextureFramebuffer(pixelSize, depth: false, stencil: true) // Create the instrument entry let newInst = PanelEntry(instrument: item, buffer: buffer, bounds: ErrorBounds()) drawOrder.append(instruments.count) instruments.append(newInst) // Recalculate the layouts layout() } func layout() { // Work out the packing for instruments, assuming they are all square // Work out the size of the entire array vertically let arraySize = Size2D(w: 1.0, h: Float(instruments.count)) let screenSize = Size2D(w: drawing.screenSizePhysical.aspect, h: 1) // See if we scale better vertically, or horizontally let bestVertically = arraySize.scaleForFitInto(screenSize) > arraySize.scaleForFitInto(screenSize.flipped) let layout : PanelLayout = bestVertically ? .Vertical : .Horizontal let instrumentSize : Size2D<Float> var offset : Size2D<Float> = Size2D(w: 0.0, h: 0.0) if layout == .Vertical { // Layout vertically, top-to-bottom if arraySize.constrainingSide(screenSize) == .Width { offset = Size2D(w: 0, h: (1-(Float(screenSize.w) / arraySize.aspect))/2) } instrumentSize = Size2D(w: screenSize.aspect, h: 1/Float(instruments.count)) } else { // We layout horizontally let hSize = arraySize.flipped if hSize.constrainingSide(screenSize) == .Height { offset = Size2D(w: (1-Float(screenSize.h)*hSize.aspect)/2, h: 0) } instrumentSize = Size2D(w: screenSize.aspect/Float(instruments.count), h: 1) } for (i, instrument) in instruments.enumerate() { let scale = instrument.instrument.screenSize.scaleForFitInto(instrumentSize) let drawSize = instrument.instrument.screenSize * scale let newBounds : Bounds if layout == .Vertical { let y = (1 - instrumentSize.h * Float(i+1)) - offset.h // Center horizontally let x = (screenSize.aspect-drawSize.w)*0.5 newBounds = FixedBounds(left: x, bottom: y, right: x+drawSize.w, top: y+drawSize.h) } else { let x = instrumentSize.w * Float(i) + offset.w let y = (1-drawSize.h)*0.5 newBounds = FixedBounds(left: x, bottom: y, right: x+drawSize.w, top: y+drawSize.h) } // If we do not match the previous arrangement, jump. Else animate. if previousArrangement.frame == Clock.time || previousArrangement.layout != layout || instrument.bounds is ErrorBounds { // Jump instrument.bounds = newBounds // instruments[i].bounds = newBounds } else { // Animate if let exB = instrument.bounds as? BoundsInterpolator { if FixedBounds(bounds: exB.end) != FixedBounds(bounds: newBounds) { instrument.bounds = BoundsInterpolator(from: exB, to: newBounds, seconds: 1) } } else { let previous = FixedBounds(bounds: instrument.bounds) instrument.bounds = BoundsInterpolator(from: previous, to: newBounds, seconds: 1) } } } previousArrangement = (layout, Clock.time) } func registerTap(loc: Point2D) { let myLoc = Point2D(x: loc.x*drawing.renderTargetPixels.aspect, y: 1-loc.y) print (myLoc) // Find which instrument this corresponds to if focus != nil { setFocus(nil) } else { if let target = drawOrder.reverse().map({instruments[$0]}).filter({$0.bounds.contains(myLoc)}).first { setFocus(target) } } } private func setFocus(pe : PanelEntry?) { if let panel = pe { let fullScreenPanel = FixedBounds(left: 0, bottom: 0, right: drawing.screenSizePhysical.aspect, top: 1) let scale = panel.bounds.size.scaleForFitInto(fullScreenPanel.size) let size = panel.bounds.size * scale let newBound = FixedBounds(left: (drawing.screenSizePhysical.aspect-size.w)/2, bottom: (1-size.h)/2, right: (drawing.screenSizePhysical.aspect-size.w)/2 + size.w, top: (1-size.h)/2 + size.h) // let index = instruments.indexOf({$0.framebuffer == panel.framebuffer})! // instruments[index].bounds = let oldSize = panel.bounds.size panel.bounds = BoundsInterpolator(from: panel.bounds, to: newBound, seconds: 1) // Reorder let index = instruments.indexOf({$0 === panel})! drawOrder.removeAtIndex(drawOrder.indexOf({$0 == index})!) drawOrder.append(index) focus = panel // Move all the others to the middle let middlePos = FixedBounds(left: (drawing.screenSizePhysical.aspect-oldSize.w)/2, bottom: (1-oldSize.h)/2, width: oldSize.w, height: oldSize.h) for other in instruments.filter({$0 !== panel}) { other.bounds = BoundsInterpolator(from: other.bounds, to: middlePos, seconds: 1) } } else { focus = nil // Make sure everything else is reconnected for (index, i) in instruments.enumerate() { if !connected.contains(index) { i.instrument.connect(connection!) connected.insert(index) } } } } }
mit
99a34f63d0a57043e1b47e6709f1bf0f
33.094118
131
0.631313
4.043256
false
false
false
false
BeSmartBeMobile/VMSlideMenu
VMSlideMenu/Classes/Utils/Array+Shift.swift
1
573
import Foundation extension Array { func shift(withDistance distance: Int = 1) -> [Element] { let offsetIndex = distance >= 0 ? self.index(startIndex, offsetBy: distance, limitedBy: endIndex) : self.index(endIndex, offsetBy: distance, limitedBy: startIndex) guard let index = offsetIndex else { return self } return Array(self[index ..< endIndex] + self[startIndex ..< index]) } mutating func shifted(withDistance distance: Int = 1) { self = shift(withDistance: distance) } }
mit
67ae0ddd742114b7d600b4057063ed1e
27.65
77
0.617801
4.620968
false
false
false
false
uasys/swift
stdlib/public/core/Comparable.swift
5
8895
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that can be compared using the relational operators `<`, `<=`, `>=`, /// and `>`. /// /// The `Comparable` protocol is used for types that have an inherent order, /// such as numbers and strings. Many types in the standard library already /// conform to the `Comparable` protocol. Add `Comparable` conformance to your /// own custom types when you want to be able to compare instances using /// relational operators or use standard library methods that are designed for /// `Comparable` types. /// /// The most familiar use of relational operators is to compare numbers, as in /// the following example: /// /// let currentTemp = 73 /// /// if currentTemp >= 90 { /// print("It's a scorcher!") /// } else if currentTemp < 65 { /// print("Might need a sweater today.") /// } else { /// print("Seems like picnic weather!") /// } /// // Prints "Seems like picnic weather!" /// /// You can use special versions of some sequence and collection operations /// when working with a `Comparable` type. For example, if your array's /// elements conform to `Comparable`, you can call the `sort()` method without /// using arguments to sort the elements of your array in ascending order. /// /// var measurements = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// measurements.sort() /// print(measurements) /// // Prints "[1.1, 1.2, 1.2, 1.3, 1.5, 1.5, 2.9]" /// /// Conforming to the Comparable Protocol /// ===================================== /// /// Types with Comparable conformance implement the less-than operator (`<`) /// and the equal-to operator (`==`). These two operations impose a strict /// total order on the values of a type, in which exactly one of the following /// must be true for any two values `a` and `b`: /// /// - `a == b` /// - `a < b` /// - `b < a` /// /// In addition, the following conditions must hold: /// /// - `a < a` is always `false` (Irreflexivity) /// - `a < b` implies `!(b < a)` (Asymmetry) /// - `a < b` and `b < c` implies `a < c` (Transitivity) /// /// To add `Comparable` conformance to your custom types, define the `<` and /// `==` operators as static methods of your types. The `==` operator is a /// requirement of the `Equatable` protocol, which `Comparable` extends---see /// that protocol's documentation for more information about equality in /// Swift. Because default implementations of the remainder of the relational /// operators are provided by the standard library, you'll be able to use /// `!=`, `>`, `<=`, and `>=` with instances of your type without any further /// code. /// /// As an example, here's an implementation of a `Date` structure that stores /// the year, month, and day of a date: /// /// struct Date { /// let year: Int /// let month: Int /// let day: Int /// } /// /// To add `Comparable` conformance to `Date`, first declare conformance to /// `Comparable` and implement the `<` operator function. /// /// extension Date: Comparable { /// static func < (lhs: Date, rhs: Date) -> Bool { /// if lhs.year != rhs.year { /// return lhs.year < rhs.year /// } else if lhs.month != rhs.month { /// return lhs.month < rhs.month /// } else { /// return lhs.day < rhs.day /// } /// } /// /// This function uses the least specific nonmatching property of the date to /// determine the result of the comparison. For example, if the two `year` /// properties are equal but the two `month` properties are not, the date with /// the lesser value for `month` is the lesser of the two dates. /// /// Next, implement the `==` operator function, the requirement inherited from /// the `Equatable` protocol. /// /// static func == (lhs: Date, rhs: Date) -> Bool { /// return lhs.year == rhs.year && lhs.month == rhs.month /// && lhs.day == rhs.day /// } /// } /// /// Two `Date` instances are equal if each of their corresponding properties is /// equal. /// /// Now that `Date` conforms to `Comparable`, you can compare instances of the /// type with any of the relational operators. The following example compares /// the date of the first moon landing with the release of David Bowie's song /// "Space Oddity": /// /// let spaceOddity = Date(year: 1969, month: 7, day: 11) // July 11, 1969 /// let moonLanding = Date(year: 1969, month: 7, day: 20) // July 20, 1969 /// if moonLanding > spaceOddity { /// print("Major Tom stepped through the door first.") /// } else { /// print("David Bowie was following in Neil Armstrong's footsteps.") /// } /// // Prints "Major Tom stepped through the door first." /// /// Note that the `>` operator provided by the standard library is used in this /// example, not the `<` operator implemented above. /// /// - Note: A conforming type may contain a subset of values which are treated /// as exceptional---that is, values that are outside the domain of /// meaningful arguments for the purposes of the `Comparable` protocol. For /// example, the special "not a number" value for floating-point types /// (`FloatingPoint.nan`) compares as neither less than, greater than, nor /// equal to any normal floating-point value. Exceptional values need not /// take part in the strict total order. public protocol Comparable : Equatable { /// Returns a Boolean value indicating whether the value of the first /// argument is less than that of the second argument. /// /// This function is the only requirement of the `Comparable` protocol. The /// remainder of the relational operator functions are implemented by the /// standard library for any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func < (lhs: Self, rhs: Self) -> Bool /// Returns a Boolean value indicating whether the value of the first /// argument is less than or equal to that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func <= (lhs: Self, rhs: Self) -> Bool /// Returns a Boolean value indicating whether the value of the first /// argument is greater than or equal to that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func >= (lhs: Self, rhs: Self) -> Bool /// Returns a Boolean value indicating whether the value of the first /// argument is greater than that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func > (lhs: Self, rhs: Self) -> Bool } extension Comparable { /// Returns a Boolean value indicating whether the value of the first argument /// is greater than that of the second argument. /// /// This is the default implementation of the greater-than operator (`>`) for /// any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_inlineable public static func > (lhs: Self, rhs: Self) -> Bool { return rhs < lhs } /// Returns a Boolean value indicating whether the value of the first argument /// is less than or equal to that of the second argument. /// /// This is the default implementation of the less-than-or-equal-to /// operator (`<=`) for any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_inlineable public static func <= (lhs: Self, rhs: Self) -> Bool { return !(rhs < lhs) } /// Returns a Boolean value indicating whether the value of the first argument /// is greater than or equal to that of the second argument. /// /// This is the default implementation of the greater-than-or-equal-to operator /// (`>=`) for any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. /// - Returns: `true` if `lhs` is greater than or equal to `rhs`; otherwise, /// `false`. @_inlineable public static func >= (lhs: Self, rhs: Self) -> Bool { return !(lhs < rhs) } }
apache-2.0
1c8ae84aa660ee9a45e82c4daeef19be
39.431818
81
0.624058
4.069076
false
false
false
false
wookay/Look
samples/LookSample/Pods/C4/C4/UI/C4Shape+Creation.swift
3
4671
// Copyright © 2014 C4 // // 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 CoreGraphics /// Extension for C4Shape that provides functionality for adding elements to a receiver's path. extension C4Shape { /// Appends a circle to the end of the receiver's path. /// /// ```` /// var l = C4Line([C4Point(),C4Point(100,100)]) /// l.addCircle(center: l.path!.currentPoint, radius: 20) /// canvas.add(l) /// ```` /// /// - parameter center: The center of the new circle /// - parameter radius: The radius of the new circle public func addCircle(center center: C4Point, radius: Double) { var newPath = path if newPath == nil { newPath = C4Path() } let r = C4Rect(center.x - radius, center.y - radius, radius*2, radius*2) newPath!.addEllipse(r) path = newPath adjustToFitPath() } /// Appends a polygon to the end of the receiver's path. /// /// ```` /// var l = C4Line([C4Point(),C4Point(100,100)]) /// var points = [C4Point]() /// for i in 0...10 { /// let x = random01()*100.0 /// let y = random01()*100.0 /// points.append(C4Point(x,y)) /// } /// l.addPolygon(points: points, closed: true) /// canvas.add(l) /// ```` /// /// - parameter points: An array of C4Point structs that defines the new polygon /// - parameter closed: If true then the polygon will have an additional line between its first and last points public func addPolygon(points points: [C4Point], closed: Bool = true) { var newPath = path if newPath == nil { newPath = C4Path() } if !points.isEmpty { newPath!.moveToPoint(points[0]) } for point in points { newPath!.addLineToPoint(point) } if closed { newPath!.closeSubpath() } path = newPath adjustToFitPath() } /// Appends a line segment to the end of the receiver's path. /// /// ```` /// var l = C4Line([C4Point(),C4Point(100,100)]) /// l.addLine([C4Point(100,100),C4Point(100,0)]) /// canvas.add(l) /// ```` /// /// - parameter points: An array of C4Point structs that defines the new line public func addLine(points:[C4Point]) { let newPath = path if path == nil { path = C4Path() } if newPath!.currentPoint != points[0] { newPath!.moveToPoint(points[0]) } newPath!.addLineToPoint(points[1]) path = newPath adjustToFitPath() } /// Appends a bezier curve to the end of the receiver's path. /// /// ```` /// var l = C4Line([C4Point(),C4Point(100,100)]) /// let pts = [C4Point(100,100),C4Point(100,0)] /// let ctrls = [C4Point(150,100),C4Point(150,0)] /// l.addCurve(points: pts, controls: ctrls) /// canvas.add(l) /// ```` /// /// - parameter points: An array of C4Point structs that defines the beginning and end points of the curve /// - parameter controls: An array of C4Point structs used to define the shape of the curve public func addCurve(points points:[C4Point], controls:[C4Point]) { let newPath = path if path == nil { path = C4Path() } if newPath!.currentPoint != points[0] { newPath!.moveToPoint(points[0]) } newPath!.addCurveToPoint(controls[0], control2: controls[1], point: points[1]); path = newPath adjustToFitPath() } }
mit
12fa31eed6da6f5a1dfb659fd6a76474
34.378788
115
0.603212
4.114537
false
false
false
false
wookay/Look
samples/LookSample/Pods/C4/C4/Core/C4Point.swift
3
6122
// Copyright © 2014 C4 // // 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 CoreGraphics ///A structure that contains a point in a two-dimensional coordinate system. public struct C4Point : Equatable, CustomStringConvertible { ///The x value of the coordinate. public var x: Double = 0 /// The y value of the coordinate. public var y: Double = 0 /// Initializes a new point with the coordinates {0,0} /// /// ```` /// let p = C4Point() /// ```` public init() { } /// Initializes a new point with the specified coordinates {x,y} /// /// ```` /// let p = C4Point(10.5,10.5) /// ```` /// /// - parameter x: a Double value /// - parameter y: a Double value public init(_ x: Double, _ y: Double) { self.x = x self.y = y } /// Initializes a new point with the specified coordinates {x,y}, converting integer values to doubles /// /// ```` /// let p = C4Point(10,10) /// ```` public init(_ x: Int, _ y: Int) { self.x = Double(x) self.y = Double(y) } /// Initializes a C4Point initialized with a CGPoint. /// /// - parameter point: a previously initialized CGPoint /// /// - returns: a C4Point whose values are the same as the CGPoint public init(_ point: CGPoint) { x = Double(point.x) y = Double(point.y) } /// Returns true if the point's coordinates are {0,0}, otherwise returns false public func isZero() -> Bool { return x == 0 && y == 0 } /// Transforms the point. /// /// ```` /// var p = C4Point(10,10) /// let v = C4Vector(x: 0, y: 0, z: 1) /// let t = C4Transform.makeRotation(M_PI, axis: v) /// p.transform(t) // -> {-10.0, -10.0} /// ```` /// /// - parameter t: A C4Transform to apply to the point public mutating func transform(t: C4Transform) { x = x * t[0, 0] + y * t[0, 1] + t[3, 0] y = x * t[1, 0] + y * t[1, 1] + t[3, 1] } /// A string representation of the point. /// /// ```` /// let p = C4Point() /// println(p) /// ```` /// /// - returns: A string formatted to look like {x,y} public var description : String { get { return "{\(x), \(y)}" } } } /// Translate a point by the given vector. /// /// - parameter lhs: a C4Point to translate /// - parameter rhs: a C4Vector whose values will be applied to the point public func += (inout lhs: C4Point, rhs: C4Vector) { lhs.x += rhs.x lhs.y += rhs.y } /// Translate a point by the negative of the given vector /// /// - parameter lhs: a C4Point to translate /// - parameter rhs: a C4Vector whose values will be applied to the point public func -= (inout lhs: C4Point, rhs: C4Vector) { lhs.x -= rhs.x lhs.y -= rhs.y } /// Calculate the vector between two points /// /// - parameter lhs: a C4Point /// - parameter rhs: a C4Point /// /// - returns: a C4Vector whose value is the left-hand side _minus_ the right-hand side public func - (lhs: C4Point, rhs: C4Point) -> C4Vector { return C4Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// Translate a point by the given vector. /// /// - parameter lhs: a C4Point to translate /// - parameter rhs: a C4Vector whose values will be applied to the point /// /// - returns: A new point whose coordinates have been translated by the values from the vector (e.g. point.x = lhs.x + rhs.x) public func + (lhs: C4Point, rhs: C4Vector) -> C4Point { return C4Point(lhs.x + rhs.x,lhs.y + rhs.y) } /// Calculates the distance between two points. /// /// - parameter lhs: left-hand point /// - parameter rhs: right-hand point /// /// - returns: The linear distance between two points public func distance(lhs: C4Point, rhs: C4Point) -> Double { let dx = rhs.x - lhs.x let dy = rhs.y - lhs.y return sqrt(dx*dx + dy*dy) } /// Checks to see if two points are equal. /// /// - parameter lhs: a C4Point /// - parameter rhs: a C4Point /// /// - returns: true if the two structs have identical coordinates public func == (lhs: C4Point, rhs: C4Point) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } /// Linear interpolation. /// /// For any two points `a` and `b` return a point that is the linear interpolation between a and b /// for interpolation parameter `param`. For instance, a parameter of 0 will return `a`, a parameter of 1 will return `b` /// and a parameter of 0.5 will return the midpoint between `a` and `b`. /// /// - parameter a: the first point /// - parameter b: the second point /// - parameter param: a Double value (between 0.0 and 1.0) used to calculate the point between a and b /// /// - returns: an interpolated point public func lerp(a a: C4Point, b: C4Point, param: Double) -> C4Point { return a + (b - a) * param } public extension CGPoint { ///Initializes a CGPoint from a C4Point public init(_ point: C4Point) { x = CGFloat(point.x) y = CGFloat(point.y) } }
mit
00e76381f1f3b4b9476ddb96033cfbf6
31.56383
127
0.614932
3.519839
false
false
false
false
fs/Social-iOS
SocialNetworks/Source/Social.swift
2
4150
import UIKit //MARK: - SocialNetwork protocol public typealias SocialNetworkSignInCompletionHandler = ((success: Bool, error: NSError?) -> Void) public typealias SocialNetworkSignOutCompletionHandler = (() -> Void) public protocol SocialNetwork : NSObjectProtocol { static var name: String { get } static var isAuthorized: Bool { get } static func authorization(completion: SocialNetworkSignInCompletionHandler?) static func logout(completion: SocialNetworkSignOutCompletionHandler?) } extension SocialNetwork where Self: Equatable {} public func == (lhs: SocialNetwork, rhs: SocialNetwork) -> Bool { return lhs.dynamicType.name == rhs.dynamicType.name } //MARK: - Abstract SocialOperation public enum SocialOperationState { case Waiting case Sending case Successed case Failed case Cancelled } public typealias SocialOperationCompletionBlock = (operation: SocialOperation, result: AnyObject?) -> Void public typealias SocialOperationDidChangeStateBlock = (operation: SocialOperation, newState: SocialOperationState) -> Void public typealias SocialOperationFailureBlock = (operation: SocialOperation, error: NSError?, isCancelled: Bool) -> Void public class SocialOperation: NSOperation { private(set) public var state : SocialOperationState = .Waiting { didSet { social_performInMainThreadSync {[weak self] () -> Void in guard let sself = self else { return } sself.didChangeState?(operation: sself, newState: sself.state) } } } private(set) internal var result : AnyObject? = nil private(set) internal var error : NSError? = nil public let completion: SocialOperationCompletionBlock public let failure: SocialOperationFailureBlock public var didChangeState: SocialOperationDidChangeStateBlock? public init(completion: SocialOperationCompletionBlock, failure: SocialOperationFailureBlock) { self.completion = completion self.failure = failure super.init() if self.isMemberOfClass(SocialOperation.self) { fatalError("SocialOperation is abstract class") } } //MARK: - updating current state final func setSendingState() { let newState = SocialOperationState.Sending self.validateNewState(newState) self.state = newState } final func setSuccessedState(result: AnyObject?) { let newState = SocialOperationState.Successed self.validateNewState(newState) self.result = result self.state = newState social_performInMainThreadSync {[weak self] () -> Void in guard let sself = self else { return } sself.completion(operation: sself, result: result) } } final func setFailedState(error: NSError?) { let newState = SocialOperationState.Failed self.validateNewState(newState) self.error = error self.state = newState social_performInMainThreadSync {[weak self] () -> Void in guard let sself = self else { return } sself.failure(operation: sself, error: error, isCancelled: false) } } //MARK: - override override public func cancel() { let newState = SocialOperationState.Cancelled self.validateNewState(newState) self.state = newState social_performInMainThreadSync {[weak self] () -> Void in guard let sself = self else { return } sself.failure(operation: sself, error: nil, isCancelled: true) } super.cancel() } //MARK: - private private func validateNewState(newState: SocialOperationState) { switch self.state { case let x where x == .Successed || x == .Failed || x == .Cancelled: fatalError("Repeated attempts to install state of \(self) operation with \(newState) when operation is \(x)") default: break } } }
mit
185c38782dd69b0bca2cb79032726317
31.677165
129
0.647229
5.16812
false
false
false
false
jbennett/Bugology
Bugology/SifterProject.swift
1
906
// // SifterProject.swift // Bugology // // Created by Jonathan Bennett on 2016-01-20. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import Foundation public struct SifterProject: Project { public let name: String public let apiURL: NSURL public let issuesURL: NSURL public init(name: String, apiURL: NSURL, issuesURL: NSURL) { self.name = name self.apiURL = apiURL self.issuesURL = issuesURL } public init(data: [String: AnyObject]) throws { guard let apiURLString = data["api_url"] as? String, apiURL = NSURL(string: apiURLString), issuesURLString = data["api_issues_url"] as? String, issuesURL = NSURL(string: issuesURLString) else { throw NSError(domain: "com.jbennett.parseError", code: 1, userInfo: nil) } self.name = data["name"] as? String ?? "" self.apiURL = apiURL self.issuesURL = issuesURL } }
mit
54a4cee0fc7e05396b46588a9db98bb7
24.138889
80
0.670718
3.693878
false
false
false
false
mgadda/swift-parse
Sources/SwiftParse/Operators.swift
1
11379
// // Operators.swift // SwiftParse // // Created by Matt Gadda on 11/30/19. // // MARK: ~ (compose) infix operator ~: MultiplicationPrecedence public func ~<T, U, V, LeftParsedValue, RightParsedValue>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>, _ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V> ) -> Parser<T, (LeftParsedValue, RightParsedValue), V> { return compose(left(), right()) } public func ~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>( _ left: ParserTU, _ right: ParserUV ) -> Parser< ParserTU.InputType.Element, (ParserTU.ParsedValueType, ParserUV.ParsedValueType), ParserUV.OutputType.Element> where ParserTU.OutputType == ParserUV.InputType { return compose(left, right) } func ~<T, U, LeftParsedValue, ParserUV: ParserConvertible>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>, _ right: ParserUV ) -> Parser<T, (LeftParsedValue, ParserUV.ParsedValueType), ParserUV.OutputType.Element> where U == ParserUV.InputType.Element { return compose(left(), right) } func ~<ParserTU: ParserConvertible, U, V, RightParsedValue>( _ left: ParserTU, _ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V> ) -> Parser<ParserTU.InputType.Element, (ParserTU.ParsedValueType, RightParsedValue), V> where ParserTU.OutputType.Element == U { return compose(left, right()) } // MARK: ~> (compose, ignore right) infix operator ~>: MultiplicationPrecedence public func ~><T, U, V, LeftParsedValue, RightParsedValue>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>, _ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V> ) -> Parser<T, LeftParsedValue, V> { return map(compose(left(), right())) { (left, _) in left } } public func ~><ParserTU: ParserConvertible, ParserUV: ParserConvertible>( _ left: ParserTU, _ right: ParserUV ) -> Parser<ParserTU.InputType.Element, ParserTU.ParsedValueType, ParserUV.OutputType.Element> where ParserTU.OutputType == ParserUV.InputType { left.mkParser() ~> right.mkParser() } public func ~><ParserLike: ParserConvertible, V, RightParsedValue>( _ left: ParserLike, _ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V> ) -> Parser<ParserLike.InputType.Element, ParserLike.ParsedValueType, V> { left.mkParser() ~> right() } public func ~><T, LeftParsedValue, ParserLike: ParserConvertible>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>, _ right: ParserLike ) -> Parser<T, LeftParsedValue, ParserLike.OutputType.Element> { left() ~> right.mkParser() } // MARK: <~ (compose, ignore left) infix operator <~: MultiplicationPrecedence public func <~ <T, U, V, LeftParsedValue, RightParsedValue>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>, _ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V> ) -> Parser<T, RightParsedValue, V> { return map(compose(left(), right())) { (_, right) in right } } public func <~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>( _ left: ParserTU, _ right: ParserUV ) -> Parser<ParserTU.InputType.Element, ParserUV.ParsedValueType, ParserUV.OutputType.Element> where ParserTU.OutputType == ParserUV.InputType { left.mkParser() <~ right.mkParser() } public func <~<ParserLike: ParserConvertible, V, RightParsedValue>( _ left: ParserLike, _ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V> ) -> Parser<ParserLike.InputType.Element, RightParsedValue, V> { left.mkParser() <~ right() } public func <~<T, LeftParsedValue, ParserLike: ParserConvertible>( _ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>, _ right: ParserLike ) -> Parser<T, ParserLike.ParsedValueType, ParserLike.OutputType.Element> { left() <~ right.mkParser() } // MARK: | (or) public func |<T, U, ParsedValue>( _ left: @autoclosure @escaping () -> Parser<T, ParsedValue, U>, _ right: @autoclosure @escaping () -> Parser<T, ParsedValue, U> ) -> Parser<T, ParsedValue, U> { return or(left(), right()) } public func |<ParserLike: ParserConvertible>( _ left: ParserLike, _ right: ParserLike ) -> ParserFrom<ParserLike> { or(left, right) } public func |<ParserLike: ParserConvertible>( _ left: @autoclosure @escaping () -> ParserFrom<ParserLike>, _ right: ParserLike ) -> ParserFrom<ParserLike> { or(left(), right) } public func |<ParserLike: ParserConvertible>( _ left: ParserLike, _ right: @autoclosure @escaping () -> ParserFrom<ParserLike> ) -> ParserFrom<ParserLike> { or(left, right()) } // MARK: ^^ (map) precedencegroup MapGroup { higherThan: AssignmentPrecedence lowerThan: AdditionPrecedence } infix operator ^^: MapGroup public func ^^<T, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, T, OutputElement>, fn: @escaping (T) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> { map(parser, fn: fn) } public func ^^<T1, T2, T3, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, ((T1, T2), T3), OutputElement>, fn: @escaping (T1, T2, T3) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == ((T1, T2), T3) { map(parser, fn: fn) } public func ^^<T1, T2, T3, T4, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, (((T1, T2), T3), T4), OutputElement>, fn: @escaping (T1, T2, T3, T4) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, T4, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == (((T1, T2), T3), T4) { map(parser, fn: fn) } public func ^^<T1, T2, T3, T4, T5, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, ((((T1, T2), T3), T4), T5), OutputElement>, fn: @escaping (T1, T2, T3, T4, T5) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, T4, T5, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == ((((T1, T2), T3), T4), T5) { map(parser, fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, (((((T1, T2), T3), T4), T5), T6), OutputElement>, fn: @escaping (T1, T2, T3, T4, T5, T6) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == (((((T1, T2), T3), T4), T5), T6) { map(parser, fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, T7, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, ((((((T1, T2), T3), T4), T5), T6), T7), OutputElement>, fn: @escaping (T1, T2, T3, T4, T5, T6, T7) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, T7, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == ((((((T1, T2), T3), T4), T5), T6), T7) { map(parser, fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, InputElement, OutputElement>( _ parser: @autoclosure @escaping () -> Parser<InputElement, (((((((T1, T2), T3), T4), T5), T6), T7), T8), OutputElement>, fn: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> U ) -> Parser<InputElement, U, OutputElement> { return map(parser(), fn: fn) } public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, ParserLike: ParserConvertible>( _ parser: ParserLike, fn: @escaping (ParserLike.ParsedValueType) -> U ) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> where ParserLike.ParsedValueType == (((((((T1, T2), T3), T4), T5), T6), T7), T8) { map(parser, fn: fn) } // MARK: * (rep) postfix operator * public postfix func *<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> { rep(parser()) } public postfix func *<ParserLike: ParserConvertible>( _ parser: ParserLike ) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]> where ParserLike.InputType == ParserLike.OutputType { rep(parser.mkParser()) } // MARK: + (rep1) postfix operator + public postfix func +<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> { return rep1(parser()) } public postfix func +<ParserLike: ParserConvertible>( _ parser: ParserLike ) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]> where ParserLike.InputType == ParserLike.OutputType { rep1(parser) } // MARK: *? (opt) postfix operator *? public postfix func *?<InputElement, T>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, T?, InputElement> { return opt(parser()) } public postfix func *?<ParserLike: ParserConvertible>( _ parser: ParserLike ) -> StandardParser<ParserLike.InputType, ParserLike.ParsedValueType?> where ParserLike.InputType == ParserLike.OutputType { return opt(parser) } // MARK: & (and) infix operator &: MultiplicationPrecedence public func &<T, U, V, LeftValue, RightValue>( _ left: @autoclosure @escaping () -> Parser<T, LeftValue, U>, _ right: @autoclosure @escaping () -> Parser<T, RightValue, V>) -> Parser<T, LeftValue, U> { and(left(), right()) } public func &<V, RightValue, ParserTU: ParserConvertible>( _ left: ParserTU, _ right: @autoclosure @escaping () -> Parser<ParserTU.InputType.Element, RightValue, V> ) -> ParserFrom<ParserTU> { and(left, right()) } public func &<U, LeftValue, ParserTV: ParserConvertible>( _ left: @autoclosure @escaping () -> Parser<ParserTV.InputType.Element, LeftValue, U>, _ right: ParserTV ) -> Parser<ParserTV.InputType.Element, LeftValue, U> { and(left(), right) } public func &<ParserTU: ParserConvertible, ParserTV: ParserConvertible>( _ left: ParserTU, _ right: ParserTV) -> ParserFrom<ParserTU> where ParserTU.InputType == ParserTV.InputType { and(left, right) }
mit
60f337197e527d4badf1b938798ffefd
33.692073
161
0.686088
3.270767
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/Home/ActivityStreamPanel.swift
1
42814
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import UIKit import Deferred import Storage import WebImage import XCGLogger import Telemetry import SnapKit private let log = Logger.browserLogger private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites" // MARK: - Lifecycle struct ASPanelUX { static let backgroundColor = UIColor(white: 1.0, alpha: 0.5) static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20 static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 200 static let sectionInsetsForSizeClass = UXSizeClasses(compact: 0, regular: 101, other: 14) static let numberOfItemsPerRowForSizeClassIpad = UXSizeClasses(compact: 3, regular: 4, other: 2) static let SectionInsetsForIpad: CGFloat = 101 static let SectionInsetsForIphone: CGFloat = 14 static let MinimumInsets: CGFloat = 14 static let BookmarkHighlights = 2 } /* Size classes are the way Apple requires us to specify our UI. Split view on iPad can make a landscape app appear with the demensions of an iPhone app Use UXSizeClasses to specify things like offsets/itemsizes with respect to size classes For a primer on size classes https://useyourloaf.com/blog/size-classes/ */ struct UXSizeClasses { var compact: CGFloat var regular: CGFloat var unspecified: CGFloat init(compact: CGFloat, regular: CGFloat, other: CGFloat) { self.compact = compact self.regular = regular self.unspecified = other } subscript(sizeClass: UIUserInterfaceSizeClass) -> CGFloat { switch sizeClass { case .compact: return self.compact case .regular: return self.regular case .unspecified: return self.unspecified } } } class ActivityStreamPanel: UICollectionViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? fileprivate let profile: Profile fileprivate let telemetry: ActivityStreamTracker fileprivate let pocketAPI = Pocket() fileprivate let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() fileprivate let topSitesManager = ASHorizontalScrollCellManager() fileprivate var showHighlightIntro = false fileprivate var sessionStart: Timestamp? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:))) }() // Not used for displaying. Only used for calculating layout. lazy var topSiteCell: ASHorizontalScrollCell = { let customCell = ASHorizontalScrollCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 0)) customCell.delegate = self.topSitesManager return customCell }() var highlights: [Site] = [] var pocketStories: [PocketStory] = [] init(profile: Profile, telemetry: ActivityStreamTracker? = nil) { self.profile = profile self.telemetry = telemetry ?? ActivityStreamTracker(eventsTracker: PingCentre.clientForTopic(.ActivityStreamEvents, clientID: profile.clientID), sessionsTracker: PingCentre.clientForTopic(.ActivityStreamSessions, clientID: profile.clientID)) super.init(collectionViewLayout: flowLayout) self.collectionView?.delegate = self self.collectionView?.dataSource = self collectionView?.addGestureRecognizer(longPressRecognizer) NotificationCenter.default.addObserver(self, selector: #selector(didChangeFontSize(notification:)), name: NotificationDynamicFontChanged, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) } self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") self.collectionView?.register(ASFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer") collectionView?.backgroundColor = ASPanelUX.backgroundColor collectionView?.keyboardDismissMode = .onDrag self.profile.panelDataObservers.activityStream.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) sessionStart = Date.now() reloadAll() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) telemetry.reportSessionStop(Date.now() - (sessionStart ?? 0)) sessionStart = nil } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) 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) } self.collectionViewLayout.invalidateLayout() self.collectionView?.reloadData() }, completion: nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.topSitesManager.currentTraits = self.traitCollection } func didChangeFontSize(notification: Notification) { // Don't need to invalidate the data for a font change. Just reload the UI. reloadAll() } } // MARK: - Section management extension ActivityStreamPanel { enum Section: Int { case topSites case pocket case highlights case highlightIntro static let count = 4 static let allValues = [topSites, pocket, highlights, highlightIntro] var title: String? { switch self { case .highlights: return Strings.ASHighlightsTitle case .pocket: return Strings.ASPocketTitle case .topSites: return nil case .highlightIntro: return nil } } var headerHeight: CGSize { switch self { case .highlights, .pocket: return CGSize(width: 50, height: 40) case .topSites: return CGSize(width: 0, height: 0) case .highlightIntro: return CGSize(width: 50, height: 2) } } var footerHeight: CGSize { switch self { case .highlights, .highlightIntro, .pocket: return CGSize.zero case .topSites: return CGSize(width: 50, height: 5) } } func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat { switch self { case .highlights, .pocket: return ASPanelUX.highlightCellHeight case .topSites: return 0 //calculated dynamically case .highlightIntro: return 200 } } /* There are edge cases to handle when calculating section insets - An iPhone 7+ is considered regular width when in landscape - An iPad in 66% split view is still considered regular width */ func sectionInsets(_ traits: UITraitCollection, frameWidth: CGFloat) -> CGFloat { var currentTraits = traits if (traits.horizontalSizeClass == .regular && UIScreen.main.bounds.size.width != frameWidth) || UIDevice.current.userInterfaceIdiom == .phone { currentTraits = UITraitCollection(horizontalSizeClass: .compact) } switch self { case .highlights, .pocket: var insets = ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] insets = insets + ASPanelUX.MinimumInsets return insets case .topSites: return ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] case .highlightIntro: return ASPanelUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] } } func numberOfItemsForRow(_ traits: UITraitCollection) -> CGFloat { switch self { case .highlights, .pocket: var numItems: CGFloat = ASPanelUX.numberOfItemsPerRowForSizeClassIpad[traits.horizontalSizeClass] if UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } if traits.horizontalSizeClass == .compact && UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } return numItems case .topSites, .highlightIntro: return 1 } } func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize { let height = cellHeight(traits, width: frameWidth) let inset = sectionInsets(traits, frameWidth: frameWidth) * 2 switch self { case .highlights, .pocket: let numItems = numberOfItemsForRow(traits) return CGSize(width: floor(((frameWidth - inset) - (ASPanelUX.MinimumInsets * (numItems - 1))) / numItems), height: height) case .topSites: return CGSize(width: frameWidth - inset, height: height) case .highlightIntro: return CGSize(width: frameWidth - inset - (ASPanelUX.MinimumInsets * 2), height: height) } } var headerView: UIView? { switch self { case .highlights, .highlightIntro, .pocket: let view = ASHeaderView() view.title = title return view case .topSites: return nil } } var cellIdentifier: String { switch self { case .topSites: return "TopSiteCell" case .highlights: return "HistoryCell" case .pocket: return "PocketCell" case .highlightIntro: return "HighlightIntroCell" } } var cellType: UICollectionViewCell.Type { switch self { case .topSites: return ASHorizontalScrollCell.self case .highlights, .pocket: return ActivityStreamHighlightCell.self case .highlightIntro: return HighlightIntroCell.self } } init(at indexPath: IndexPath) { self.init(rawValue: indexPath.section)! } init(_ section: Int) { self.init(rawValue: section)! } } } // MARK: - Tableview Delegate extension ActivityStreamPanel: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView let title = Section(indexPath.section).title switch Section(indexPath.section) { case .highlights, .highlightIntro, .pocket: view.title = title return view case .topSites: return UICollectionReusableView() } case UICollectionElementKindSectionFooter: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", for: indexPath) as! ASFooterView switch Section(indexPath.section) { case .highlights, .highlightIntro: return UICollectionReusableView() case .topSites, .pocket: return view } default: return UICollectionReusableView() } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.longPressRecognizer.isEnabled = false selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width) switch Section(indexPath.section) { case .highlights: if highlights.isEmpty { return CGSize.zero } return cellSize case .topSites: // Create a temporary cell so we can calculate the height. let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0)) return CGSize(width: cellSize.width, height: estimatedLayout.size.height) case .highlightIntro, .pocket: return cellSize } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { switch Section(section) { case .highlights: return highlights.isEmpty ? CGSize.zero : CGSize(width: self.view.frame.size.width, height: Section(section).headerHeight.height) case .highlightIntro: return !highlights.isEmpty ? CGSize.zero : CGSize(width: self.view.frame.size.width, height: Section(section).headerHeight.height) case .topSites, .pocket: return Section(section).headerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { switch Section(section) { case .highlights, .highlightIntro, .pocket: return CGSize.zero case .topSites: return Section(section).footerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return ASPanelUX.rowSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let insets = Section(section).sectionInsets(self.traitCollection, frameWidth: self.view.frame.width) return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets) } fileprivate func showSiteWithURLHandler(_ url: URL) { let visitType = VisitType.bookmark homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType) } } // MARK: - Tableview Data Source extension ActivityStreamPanel { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 4 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numItems: CGFloat = ASPanelUX.numberOfItemsPerRowForSizeClassIpad[self.traitCollection.horizontalSizeClass] if UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } if self.traitCollection.horizontalSizeClass == .compact && UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { numItems = numItems - 1 } switch Section(section) { case .topSites: return topSitesManager.content.isEmpty ? 0 : 1 case .highlights: return self.highlights.count case .pocket: return pocketStories.isEmpty ? 0: Int(numItems) case .highlightIntro: return self.highlights.isEmpty && showHighlightIntro ? 1 : 0 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = Section(indexPath.section).cellIdentifier let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) switch Section(indexPath.section) { case .topSites: return configureTopSitesCell(cell, forIndexPath: indexPath) case .highlights: return configureHistoryItemCell(cell, forIndexPath: indexPath) case .pocket: return configurePocketItemCell(cell, forIndexPath: indexPath) case .highlightIntro: return configureHighlightIntroCell(cell, forIndexPath: indexPath) } } //should all be collectionview func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let topSiteCell = cell as! ASHorizontalScrollCell topSiteCell.delegate = self.topSitesManager topSiteCell.setNeedsLayout() topSiteCell.collectionView.reloadData() return cell } func configureHistoryItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let site = highlights[indexPath.row] let simpleHighlightCell = cell as! ActivityStreamHighlightCell simpleHighlightCell.configureWithSite(site) return simpleHighlightCell } func configurePocketItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let pocketStory = pocketStories[indexPath.row] let pocketItemCell = cell as! ActivityStreamHighlightCell pocketItemCell.configureWithPocketStory(pocketStory) return pocketItemCell } func configureHighlightIntroCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let introCell = cell as! HighlightIntroCell //The cell is configured on creation. No need to configure. But leave this here in case we need it. return introCell } } // MARK: - Data Management extension ActivityStreamPanel: DataObserverDelegate { fileprivate func reportMissingData(sites: [Site], source: ASPingSource) { let missingImagePings: [[String: Any]] = sites.flatMap { site in if site.metadata?.mediaURL == nil { return self.telemetry.pingFor(badState: .MissingMetadataImage, source: source) } return nil } let missingFaviconPings: [[String: Any]] = sites.flatMap { site in if site.icon == nil { return self.telemetry.pingFor(badState: .MissingFavicon, source: source) } return nil } let badPings = missingImagePings + missingFaviconPings self.telemetry.eventsTracker.sendBatch(badPings, validate: true) } // Reloads both highlights and top sites data from their respective caches. Does not invalidate the cache. // See ActivityStreamDataObserver for invalidation logic. func reloadAll() { self.getPocketSites().uponQueue(.main) { _ in self.collectionView?.reloadData() } accumulate([self.getHighlights, self.getTopSites]).uponQueue(.main) { _ in // If there is no pending cache update and highlights are empty. Show the onboarding screen self.showHighlightIntro = self.highlights.isEmpty self.collectionView?.reloadData() // Refresh the AS data in the background so we'll have fresh data next time we show. self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: false) } } func getHighlights() -> Success { let count = ASPanelUX.BookmarkHighlights // Fetch 2 bookmarks return self.profile.recommendations.getHighlights().both(self.profile.recommendations.getRecentBookmarks(count)).bindQueue(.main) { (highlights, bookmarks) in guard let highlights = highlights.successValue?.asArray(), let bookmarks = bookmarks.successValue?.asArray() else { return succeed() } let sites = bookmarks + highlights // Scan through the fetched highlights and report on anything that might be missing. self.reportMissingData(sites: sites, source: .Highlights) self.highlights = sites return succeed() } } func getPocketSites() -> Success { return pocketAPI.globalFeed(items: 4).bindQueue(.main) { pStory in self.pocketStories = pStory return succeed() } } func getTopSites() -> Success { return self.profile.history.getTopSitesWithLimit(16).both(self.profile.history.getPinnedTopSites()).bindQueue(.main) { (topsites, pinnedSites) in guard let mySites = topsites.successValue?.asArray(), let pinned = pinnedSites.successValue?.asArray() else { return succeed() } // How sites are merged together. We compare against the urls second level domain. example m.youtube.com is compared against `youtube` let unionOnURL = { (site: Site) -> String in return URL(string: site.url)?.hostSLD ?? "" } // Fetch the default sites let defaultSites = self.defaultTopSites() // create PinnedSite objects. used by the view layer to tell topsites apart let pinnedSites: [Site] = pinned.map({ PinnedSite(site:$0) }) // Merge default topsites with a user's topsites. let mergedSites = mySites.union(defaultSites, f: unionOnURL) // Merge pinnedSites with sites from the previous step let allSites = pinnedSites.union(mergedSites, f: unionOnURL) // Favour topsites from defaultSites as they have better favicons. But keep PinnedSites let newSites = allSites.map { site -> Site in if let _ = site as? PinnedSite { return site } let domain = URL(string: site.url)?.hostSLD return defaultSites.find { $0.title.lowercased() == domain } ?? site } // Don't report bad states for default sites we provide self.reportMissingData(sites: mySites, source: .TopSites) self.topSitesManager.currentTraits = self.view.traitCollection if newSites.count > Int(ActivityStreamTopSiteCacheSize) { self.topSitesManager.content = Array(newSites[0..<Int(ActivityStreamTopSiteCacheSize)]) } else { self.topSitesManager.content = newSites } self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in self.longPressRecognizer.isEnabled = false self.telemetry.reportEvent(.Click, source: .TopSites, position: indexPath.item) self.showSiteWithURLHandler(url as URL) } return succeed() } } // Invoked by the ActivityStreamDataObserver when highlights/top sites invalidation is complete. func didInvalidateDataSources(forceHighlights highlights: Bool, forceTopSites topSites: Bool) { // Do not reload panel unless we're currently showing the highlight intro or if we // force-reloaded the highlights or top sites. This should prevent reloading the // panel after we've invalidated in the background on the first load. if showHighlightIntro || highlights || topSites { reloadAll() } } func hideURLFromTopSites(_ site: Site) { guard let host = site.tileURL.normalizedHost else { return } let url = site.tileURL.absoluteString // if the default top sites contains the siteurl. also wipe it from default suggested sites. if defaultTopSites().filter({$0.url == url}).isEmpty == false { deleteTileForSuggestedSite(url) } profile.history.removeHostFromTopSites(host).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func pinTopSite(_ site: Site) { profile.history.addPinnedTopSite(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func removePinTopSite(_ site: Site) { profile.history.removeFromPinnedTopSites(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) } } func hideFromHighlights(_ site: Site) { profile.recommendations.removeHighlightForURL(site.url).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: false) } } fileprivate func deleteTileForSuggestedSite(_ siteURL: String) { var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] deletedSuggestedSites.append(siteURL) profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey) } func defaultTopSites() -> [Site] { let suggested = SuggestedSites.asArray() let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] return suggested.filter({deleted.index(of: $0.url) == .none}) } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let point = longPressGestureRecognizer.location(in: self.collectionView) guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return } switch Section(indexPath.section) { case .highlights, .pocket: presentContextMenu(for: indexPath) case .topSites: let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView) guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return } presentContextMenu(for: topSiteIndexPath) case .highlightIntro: break } } fileprivate func fetchBookmarkStatus(for site: Site, with indexPath: IndexPath, forSection section: Section, completionHandler: @escaping () -> Void) { profile.bookmarks.modelFactory >>== { $0.isBookmarked(site.url).uponQueue(.main) { result in guard let isBookmarked = result.successValue else { log.error("Error getting bookmark status: \(result.failureValue ??? "nil").") return } site.setBookmarked(isBookmarked) completionHandler() } } } func selectItemAtIndex(_ index: Int, inSection section: Section) { let site: Site? switch section { case .highlights: site = self.highlights[index] case .pocket: site = Site(url: pocketStories[index].url.absoluteString, title: pocketStories[index].title) case .topSites, .highlightIntro: return } if let site = site { telemetry.reportEvent(.Click, source: .Highlights, position: index) showSiteWithURLHandler(URL(string:site.url)!) } } } extension ActivityStreamPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { fetchBookmarkStatus(for: site, with: indexPath, forSection: Section(indexPath.section)) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } } func getSiteDetails(for indexPath: IndexPath) -> Site? { let site: Site switch Section(indexPath.section) { case .highlights: site = highlights[indexPath.row] case .pocket: site = Site(url: pocketStories[indexPath.row].dedupeURL.absoluteString, title: pocketStories[indexPath.row].title) case .topSites: site = topSitesManager.content[indexPath.item] case .highlightIntro: return nil } return site } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } let pingSource: ASPingSource let index: Int var sourceView: UIView? switch Section(indexPath.section) { case .topSites: pingSource = .TopSites index = indexPath.item if let topSiteCell = self.collectionView?.cellForItem(at: IndexPath(row: 0, section: 0)) as? ASHorizontalScrollCell { sourceView = topSiteCell.collectionView.cellForItem(at: indexPath) } case .highlights: pingSource = .Highlights index = indexPath.row sourceView = self.collectionView?.cellForItem(at: indexPath) case .pocket: pingSource = .Pocket index = indexPath.item sourceView = self.collectionView?.cellForItem(at: indexPath) case .highlightIntro: return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) self.telemetry.reportEvent(.NewTab, source: pingSource, position: index) LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Activity Stream Long Press Context Menu" as AnyObject]) } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } let bookmarkAction: PhotonActionSheetItem if site.bookmarked ?? false { bookmarkAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in self.profile.bookmarks.modelFactory >>== { $0.removeByURL(siteURL.absoluteString) site.setBookmarked(false) } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: false, forceTopSites: true) self.telemetry.reportEvent(.RemoveBookmark, source: pingSource, position: index) }) } else { bookmarkAction = PhotonActionSheetItem(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon) _ = self.profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) site.setBookmarked(true) self.telemetry.reportEvent(.AddBookmark, source: pingSource, position: index) LeanplumIntegration.sharedInstance.track(eventName: .savedBookmark) }) } let deleteFromHistoryAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in self.telemetry.reportEvent(.Delete, source: pingSource, position: index) self.profile.history.removeHistoryForURL(site.url).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceHighlights: true, forceTopSites: true) } }) let shareAction = PhotonActionSheetItem(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in let helper = ShareExtensionHelper(url: siteURL, tab: nil, activities: []) let controller = helper.createActivityViewController { completed, activityType in self.telemetry.reportEvent(.Share, source: pingSource, position: index, shareProvider: activityType) } if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad, let popoverController = controller.popoverPresentationController { let cellRect = sourceView?.frame ?? CGRect.zero let cellFrameInSuperview = self.collectionView?.convert(cellRect, to: self.collectionView) ?? CGRect.zero popoverController.sourceView = sourceView popoverController.sourceRect = CGRect(origin: CGPoint(x: cellFrameInSuperview.size.width/2, y: cellFrameInSuperview.height/2), size: .zero) popoverController.permittedArrowDirections = [.up, .down, .left] popoverController.delegate = self } self.present(controller, animated: true, completion: nil) }) let removeTopSiteAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.telemetry.reportEvent(.Remove, source: pingSource, position: index) self.hideURLFromTopSites(site) }) let dismissHighlightAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index) self.hideFromHighlights(site) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinTopSite(site) }) let removePinTopSite = PhotonActionSheetItem(title: Strings.RemovePinTopsiteActionTitle, iconString: "action_unpin", handler: { action in self.removePinTopSite(site) }) let topSiteActions: [PhotonActionSheetItem] if let _ = site as? PinnedSite { topSiteActions = [removePinTopSite] } else { topSiteActions = [pinTopSite, removeTopSiteAction] } var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction] switch Section(indexPath.section) { case .highlights: actions.append(contentsOf: [dismissHighlightAction, deleteFromHistoryAction]) case .pocket: actions.append(dismissHighlightAction) case .topSites: actions.append(contentsOf: topSiteActions) case .highlightIntro: break } return actions } } extension ActivityStreamPanel: UIPopoverPresentationControllerDelegate { // Dismiss the popover if the device is being rotated. // This is used by the Share UIActivityViewController action sheet on iPad func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) { popoverPresentationController.presentedViewController.dismiss(animated: false, completion: nil) } } // MARK: Telemetry enum ASPingEvent: String { case Click = "CLICK" case Delete = "DELETE" case Dismiss = "DISMISS" case Share = "SHARE" case NewTab = "NEW_TAB" case AddBookmark = "ADD_BOOKMARK" case RemoveBookmark = "REMOVE_BOOKMARK" case Remove = "REMOVE" } enum ASPingBadStateEvent: String { case MissingMetadataImage = "MISSING_METADATA_IMAGE" case MissingFavicon = "MISSING_FAVICON" } enum ASPingSource: String { case Highlights = "HIGHLIGHTS" case TopSites = "TOP_SITES" case HighlightsIntro = "HIGHLIGHTS_INTRO" case Pocket = "POCKET" } struct ActivityStreamTracker { let eventsTracker: PingCentreClient let sessionsTracker: PingCentreClient private var baseASPing: [String: Any] { return [ "app_version": AppInfo.appVersion, "build": AppInfo.buildNumber, "locale": Locale.current.identifier, "release_channel": AppConstants.BuildChannel.rawValue ] } func pingFor(badState: ASPingBadStateEvent, source: ASPingSource) -> [String: Any] { var eventPing: [String: Any] = [ "event": badState.rawValue, "page": "NEW_TAB", "source": source.rawValue, ] eventPing.merge(with: baseASPing) return eventPing } func reportEvent(_ event: ASPingEvent, source: ASPingSource, position: Int, shareProvider: String? = nil) { var eventPing: [String: Any] = [ "event": event.rawValue, "page": "NEW_TAB", "source": source.rawValue, "action_position": position, ] if let provider = shareProvider { eventPing["share_provider"] = provider } eventPing.merge(with: baseASPing) eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true) } func reportSessionStop(_ duration: UInt64) { sessionsTracker.sendPing([ "session_duration": NSNumber(value: duration), "app_version": AppInfo.appVersion, "build": AppInfo.buildNumber, "locale": Locale.current.identifier, "release_channel": AppConstants.BuildChannel.rawValue ] as [String: Any], validate: true) } } // MARK: - Section Header View struct ASHeaderViewUX { static let SeperatorColor = UIColor(rgb: 0xedecea) static let TextFont = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS static let SeperatorHeight = 1 static let Insets: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad + ASPanelUX.MinimumInsets : ASPanelUX.MinimumInsets static let TitleTopInset: CGFloat = 5 } class ASFooterView: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) let seperatorLine = UIView() seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor self.backgroundColor = UIColor.clear addSubview(seperatorLine) seperatorLine.snp.makeConstraints { make in make.height.equalTo(ASHeaderViewUX.SeperatorHeight) make.leading.equalTo(self.snp.leading) make.trailing.equalTo(self.snp.trailing) make.top.equalTo(self.snp.top) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ASHeaderView: UICollectionReusableView { lazy fileprivate var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.text = self.title titleLabel.textColor = UIColor.gray titleLabel.font = ASHeaderViewUX.TextFont return titleLabel }() var title: String? { willSet(newTitle) { titleLabel.text = newTitle } } var constraint: Constraint? var titleInsets: CGFloat { get { return UIScreen.main.bounds.size.width == self.frame.size.width && UIDevice.current.userInterfaceIdiom == .pad ? ASHeaderViewUX.Insets : ASPanelUX.MinimumInsets } } override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) titleLabel.snp.makeConstraints { make in self.constraint = make.leading.equalTo(self).inset(titleInsets).constraint make.trailing.equalTo(self).inset(-ASHeaderViewUX.Insets) make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset) make.bottom.equalTo(self) } } override func layoutSubviews() { super.layoutSubviews() constraint?.update(offset: titleInsets) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class PinnedSite: Site { let isPinnedSite = true init(site: Site) { super.init(url: site.url, title: site.title, bookmarked: site.bookmarked) self.icon = site.icon self.metadata = site.metadata } }
mpl-2.0
facccf99e6c93d0801d3539fa8aa4f14
42.246465
249
0.657659
5.2481
false
false
false
false
zimcherDev/ios
Zimcher/Constants/Styling.swift
1
1798
import UIKit struct COLORSCHEME{ struct TAB_BAR { static let TINT = PALETTE.CORN_FLOWER_BLUE static let BAR_TINT = UIColor.whiteColor() } struct ENTRY_FIELD { static let SEPARATOR_BG = PALETTE.WARM_GRAY.colorWithAlphaComponent(0.6) static let HEADER_FOOTER_BG = UIColor.blackColor().colorWithAlphaComponent(0.2) static let PROMPT_TEXT_FG = PALETTE.DARK static let PLACEHOLDER_TEXT_FG = PALETTE.WARM_GRAY static let INPUT_TEXT_FG = UIColor.blackColor() } struct SETTINGS { static let BG = PALETTE.PALE_GRAY static let NAVIGATION_BAR_BG = PALETTE.CORN_FLOWER_BLUE } struct ROUNDEDCORNER_BUTTON { static let TINT = UIColor.whiteColor() static let BG = PALETTE.CORN_FLOWER_BLUE.colorWithAlphaComponent(0.9) } struct NAVIGATION_BAR { static let TINT = UIColor.whiteColor() } struct MYZIMS { static let TABBAR = PALETTE.CORN_FLOWER_BLUE static let NAVIGATION_BAR = PALETTE.DARK } } struct UI { struct ENTRY_FIELD { static let SEPARATOR_HEIGHT = CGFloat(1) static let SEPARATOR_INDENT = CGFloat(15) static let CELL_INDENT = 2 + SEPARATOR_INDENT static let BASIC_CELL_HEIGHT = CGFloat(49) } static let LOGIN_BUTTON_CORNER_RADIUS = CGFloat(3) struct MYZIMS { static let TABBAR_HEIGHT = CGFloat(45) static let TABBAR_BORDER_HEIGHT = CGFloat(4) } struct CAMERA_ROLL { static let CELL_SIZE = CGSize(width: 88, height: 88) } } struct FONTS { static let SF_SEMIBOLD = UIFont(name: "SFUIDisplay-Semibold", size: 16)! static let SF_MEDIUM = UIFont(name: "SFUIDisplay-Medium", size: 16)! }
apache-2.0
f98c211369fe2d652c8a7ad056c5bd8c
27.555556
87
0.627364
3.654472
false
false
false
false
akrio714/Wbm
Wbm/Campaign/Detail/View/AxisItemModel.swift
1
525
// // AxisItemModel.swift // Wbm // // Created by akrio on 2017/7/27. // Copyright © 2017年 akrio. All rights reserved. // import Foundation struct AxisItemModel { /// 第一行描述信息 var description:String = "" /// 创建时间 var createTime:String? = nil /// 持续时间 var durations:String? = nil /// 截图 var image:String? = nil /// 喜欢数量 var likes:Int = 0 /// 评论数量 var comments:Int = 0 /// 超时描述 var delayed:String? = nil }
apache-2.0
69218a91d4dc9b4f03e7098085b2ca28
17.56
49
0.581897
3.2
false
false
false
false
cohix/MaterialKit
Source/MaterialButton.swift
3
4688
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import UIKit public class MaterialButton : UIButton { // // :name: backgroundColorView // internal lazy var backgroundColorView: UIView = UIView() // // :name: pulseView // internal var pulseView: UIView? /** :name: backgroundColor */ public override var backgroundColor: UIColor? { get { return backgroundColorView.backgroundColor } set(value) { backgroundColorView.backgroundColor = value } } /** :name: pulseColor */ public var pulseColor: UIColor? = MaterialTheme.white.color /** :name: init */ public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareView() } /** :name: init */ public required override init(frame: CGRect) { super.init(frame: frame) prepareView() } /** :name: init */ public convenience init() { self.init(frame: CGRectZero) } /** :name: touchesBegan */ public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) pulseBegan(touches, withEvent: event) } /** :name: touchesEnded */ public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) shrink() pulseEnded(touches, withEvent: event) } /** :name: touchesCancelled */ public override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) shrink() pulseEnded(touches, withEvent: event) } /** :name: drawRect */ final public override func drawRect(rect: CGRect) { prepareContext(rect) prepareBackgroundColorView() prepareButton() } // // :name: prepareView // internal func prepareView() { setTranslatesAutoresizingMaskIntoConstraints(false) } // // :name: prepareButton // internal func prepareButton() {} // // :name: prepareShadow // internal func prepareShadow() { layer.shadowColor = MaterialTheme.black.color.CGColor layer.shadowOffset = CGSizeMake(0.1, 0.1) layer.shadowOpacity = 0.4 layer.shadowRadius = 2 } // // :name: pulseBegan // internal func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent) { pulseView = UIView(frame: CGRectMake(0, 0, bounds.height, bounds.height)) pulseView!.layer.cornerRadius = bounds.height / 2 pulseView!.center = (touches.first as! UITouch).locationInView(self) pulseView!.backgroundColor = pulseColor?.colorWithAlphaComponent(0.5) backgroundColorView.addSubview(pulseView!) } // // :name: pulseEnded // internal func pulseEnded(touches: Set<NSObject>, withEvent event: UIEvent) { UIView.animateWithDuration(0.3, animations: { _ in self.pulseView?.alpha = 0 } ) { _ in self.pulseView?.removeFromSuperview() self.pulseView = nil } } // // :name: prepareContext // private func prepareContext(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context); CGContextAddEllipseInRect(context, rect) CGContextSetFillColorWithColor(context, MaterialTheme.clear.color.CGColor) CGContextFillPath(context) CGContextRestoreGState(context); } // // :name: prepareBackgroundColorView // private func prepareBackgroundColorView() { backgroundColorView.setTranslatesAutoresizingMaskIntoConstraints(false) backgroundColorView.layer.masksToBounds = true backgroundColorView.clipsToBounds = true backgroundColorView.userInteractionEnabled = false insertSubview(backgroundColorView, atIndex: 0) Layout.expandToParent(self, child: backgroundColorView) } // // :name: shrink // private func shrink() { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10, options: nil, animations: { self.transform = CGAffineTransformIdentity }, completion: nil ) } }
agpl-3.0
92252b735d405161571c94c5bd155a26
23.290155
92
0.720563
3.653936
false
false
false
false
siemensikkema/Fairness
FairnessTests/Participant.swift
1
856
import UIKit typealias NameChangeCallback = () -> () class Participant { var balance = 0.0 var nameOrNil: String? { didSet { nameChangeCallback?() } } var nameChangeCallback: NameChangeCallback? init(name: String? = nil, nameChangeCallback: NameChangeCallback? = nil, balance: Double = 0.0) { self.balance = balance self.nameOrNil = name self.nameChangeCallback = nameChangeCallback } } extension Participant: DebugPrintable { var debugDescription: String { return "name: \(nameOrNil), balance: \(balance) hash: \(hashValue)" } } extension Participant: Hashable, Equatable { var hashValue: Int { return ObjectIdentifier(self).hashValue } } func ==(lhs: Participant, rhs: Participant) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
mit
027c3ccc1c7bcba85c8110287b895217
24.205882
104
0.660047
4.301508
false
false
false
false
amraboelela/swift
test/IRGen/protocol_resilience_descriptors.swift
1
6290
// RUN: %empty-directory(%t) // Resilient protocol definition // RUN: %target-swift-frontend -emit-ir -enable-resilience -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s // Resilient protocol usage // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE // ---------------------------------------------------------------------------- // Resilient protocol definition // ---------------------------------------------------------------------------- // CHECK: @"default assoc type x" = linkonce_odr hidden constant // CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0 // CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" = // Protocol descriptor // CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( dllexport)?}}{{( protected)?}} constant // CHECK-DEFINITION-SAME: @"default associated conformance2T218resilient_protocol29ProtocolWithAssocTypeDefaultsP_AB014OtherResilientD0" // Associated type default + flags // CHECK-DEFINITION-SAME: [[INT]] add // CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP" // CHECK-DEFINITION-SAME: [[INT]] 1 // Protocol requirements base descriptor // CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1) // Associated conformance descriptor for inherited protocol // CHECK-DEFINITION-LABEL: s18resilient_protocol24ResilientDerivedProtocolPAA0c4BaseE0Tb" ={{( dllexport)?}}{{( protected)?}} alias // Associated type and conformance // CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias // CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias // Default associated conformance witnesses // CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN" import resilient_protocol // ---------------------------------------------------------------------------- // Resilient witness tables // ---------------------------------------------------------------------------- // CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" = // CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl // CHECK-USAGE-SAME: @"symbolic x" public struct ConformsToProtocolWithRequirements<Element> : ProtocolWithRequirements { public typealias T = Element public func first() { } public func second() { } } public protocol P { } public struct ConditionallyConforms<Element> { } public struct Y { } // CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" = // CHECK-USAGE-SAME: i32 131072, // CHECK-USAGE-SAME: i16 0, // CHECK-USAGE-SAME: i16 0, // CHECK-USAGE-SAME: i32 0 extension Y: OtherResilientProtocol { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" = // CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn // CHECK-USAGE-SAME: @"associated conformance 31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0" public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc" extension ConditionallyConforms: ProtocolWithRequirements where Element: ProtocolWithRequirements, Element.T == Y { public typealias T = Element.T public func first() { } public func second() { } } // CHECK-USAGE: @"$s31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAAMc" = // CHECK-SAME: @"associated conformance 31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAaD0h4BaseI0" public struct ConformsToDerived : ResilientDerivedProtocol { public func requirement() -> Int { return 0 } } // ---------------------------------------------------------------------------- // Resilient protocol usage // ---------------------------------------------------------------------------- // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type*, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]]) public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type { // CHECK-USAGE: call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl") return PWR.T.self } func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { } // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF" public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) { // CHECK-USAGE: swift_getAssociatedConformanceWitness useOtherResilientProtocol(T.T2.self) }
apache-2.0
d847e0b9ff7896c55212034bafce2f8b
58.904762
444
0.730366
4.121887
false
false
false
false
gregomni/swift
test/SILGen/lifetime.swift
5
32727
// RUN: %target-swift-emit-silgen -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -primary-file %s | %FileCheck %s struct Buh<T> { var x: Int { get {} set {} } } class Ref { init() { } } struct Val { } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime13local_valtypeyyF func local_valtype() { var b: Val // CHECK: [[B:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[MARKED_B:%.*]] = mark_uninitialized [var] [[B]] // CHECK: [[MARKED_B_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_B]] // CHECK: end_borrow [[MARKED_B_LIFETIME]] // CHECK: destroy_value [[MARKED_B]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime20local_valtype_branch{{[_0-9a-zA-Z]*}}F func local_valtype_branch(_ a: Bool) { var a = a // CHECK: [[A:%[0-9]+]] = alloc_box ${ var Bool } if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: br [[EPILOG:bb[0-9]+]] var x:Int // CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_X:%.*]] = mark_uninitialized [var] [[X]] // CHECK: [[MARKED_X_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_B]] if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] while a { // CHECK: cond_br if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK-NOT: destroy_value [[X]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] var y:Int // CHECK: [[Y:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_Y:%.*]] = mark_uninitialized [var] [[Y]] // CHECK: [[MARKED_Y_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_Y]] if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: end_borrow [[MARKED_Y_LIFETIME]] // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] if true { var z:Int // CHECK: [[Z:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_Z:%.*]] = mark_uninitialized [var] [[Z]] // CHECK: [[MARKED_Z_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_Z]] if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Z]] // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Z]] // CHECK: destroy_value [[MARKED_Y]] // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] // CHECK: destroy_value [[MARKED_Z]] } if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK: br } // CHECK: destroy_value [[MARKED_X]] // CHECK: [[EPILOG]]: // CHECK: return } func reftype_func() -> Ref {} func reftype_func_with_arg(_ x: Ref) -> Ref {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime14reftype_returnAA3RefCyF func reftype_return() -> Ref { return reftype_func() // CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NOT: destroy_value // CHECK: [[RET:%[0-9]+]] = apply [[RF]]() // CHECK-NOT: destroy_value // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime11reftype_argyyAA3RefCF : $@convention(thin) (@guaranteed Ref) -> () { // CHECK: bb0([[A:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[A_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[AADDR]] // CHECK: [[PA:%[0-9]+]] = project_box [[A_LIFETIME]] // CHECK: [[A_COPY:%.*]] = copy_value [[A]] // CHECK: store [[A_COPY]] to [init] [[PA]] // CHECK: destroy_value [[AADDR]] // CHECK-NOT: destroy_value [[A]] // CHECK: return // CHECK: } // end sil function '$s8lifetime11reftype_argyyAA3RefCF' func reftype_arg(_ a: Ref) { var a = a } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime26reftype_call_ignore_returnyyF func reftype_call_ignore_return() { reftype_func() // CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK: destroy_value [[R]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime27reftype_call_store_to_localyyF func reftype_call_store_to_local() { var a = reftype_func() // CHECK: [[A:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[A_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[A]] // CHECK-NEXT: [[PB:%.*]] = project_box [[A_LIFETIME]] // CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK-NOT: copy_value [[R]] // CHECK: store [[R]] to [init] [[PB]] // CHECK-NOT: destroy_value [[R]] // CHECK: destroy_value [[A]] // CHECK-NOT: destroy_value [[R]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_call_argyyF func reftype_call_arg() { reftype_func_with_arg(reftype_func()) // CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_func{{[_0-9a-zA-Z]*}}F // CHECK: [[R1:%[0-9]+]] = apply [[RF]] // CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]]) // CHECK: destroy_value [[R2]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime21reftype_call_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[A1:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[A_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[AADDR]] // CHECK: [[PB:%.*]] = project_box [[A_LIFETIME]] // CHECK: [[A1_COPY:%.*]] = copy_value [[A1]] // CHECK: store [[A1_COPY]] to [init] [[PB]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[A2:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: [[RESULT:%.*]] = apply [[RFWA]]([[A2]]) // CHECK: destroy_value [[RESULT]] // CHECK: destroy_value [[AADDR]] // CHECK-NOT: destroy_value [[A1]] // CHECK: return func reftype_call_with_arg(_ a: Ref) { var a = a reftype_func_with_arg(a) } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_reassign{{[_0-9a-zA-Z]*}}F func reftype_reassign(_ a: inout Ref, b: Ref) { var b = b // CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[B_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[BADDR]] // CHECK: [[PBB:%.*]] = project_box [[B_LIFETIME]] a = b // CHECK: destroy_value // CHECK: return } func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime28tuple_with_ref_ignore_returnyyF func tuple_with_ref_ignore_return() { tuple_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime23tuple_with_ref_elementsAA3ValV_AA3RefC_ADtAFtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]] // CHECK: ([[T0:%.*]], [[T1_0:%.*]], [[T1_1:%.*]], [[T2:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T2]] // CHECK: destroy_value [[T1_0]] // CHECK: return } struct Aleph { var a:Ref var b:Val // -- loadable value constructor: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime5AlephV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph // CHECK: bb0([[A:%.*]] : @owned $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type): // CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Beth { var a:Val var b:Aleph var c:Ref func gimel() {} } protocol Unloadable {} struct Daleth { var a:Aleph var b:Beth var c:Unloadable // -- address-only value constructor: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime6DalethV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> @out Daleth { // CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : @owned $Aleph, [[B:%.*]] : @owned $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type): // CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a // CHECK-NEXT: store [[A]] to [init] [[A_ADDR]] // CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b // CHECK-NEXT: store [[B]] to [init] [[B_ADDR]] // CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c // CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } class He { // -- default allocator: // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick He.Type) -> @owned He { // CHECK: bb0({{%.*}} : $@thick He.Type): // CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He // CHECK-NEXT: // function_ref lifetime.He.init // CHECK-NEXT: [[INIT:%.*]] = function_ref @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He // CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]]) // CHECK-NEXT: return [[THIS1]] // CHECK-NEXT: } // -- default initializer: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He { // CHECK: bb0([[SELF:%.*]] : @owned $He): // CHECK-NEXT: debug_value // CHECK-NEXT: [[UNINITIALIZED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]] // CHECK-NEXT: [[UNINITIALIZED_SELF_COPY:%.*]] = copy_value [[UNINITIALIZED_SELF]] // CHECK-NEXT: destroy_value [[UNINITIALIZED_SELF]] // CHECK-NEXT: return [[UNINITIALIZED_SELF_COPY]] // CHECK: } // end sil function '$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc' init() { } } struct Waw { var a:(Ref, Val) var b:Val // -- loadable value initializer with tuple destructuring: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3WawV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw // CHECK: bb0([[A0:%.*]] : @owned $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type): // CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}}) // CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Zayin { var a:(Unloadable, Val) var b:Unloadable // -- address-only value initializer with tuple destructuring: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime5ZayinV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> @out Zayin // CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type): // CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a // CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0 // CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1 // CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]] // CHECK-NEXT: store [[A1]] to [trivial] [[THIS_A1_ADDR]] // CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b // CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } func fragile_struct_with_ref_elements() -> Beth {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime29struct_with_ref_ignore_returnyyF func struct_with_ref_ignore_return() { fragile_struct_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: destroy_value [[STRUCT]] : $Beth // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime28struct_with_ref_materializedyyF func struct_with_ref_materialized() { fragile_struct_with_ref_elements().gimel() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: [[METHOD:%[0-9]+]] = function_ref @$s8lifetime4BethV5gimel{{[_0-9a-zA-Z]*}}F // CHECK: apply [[METHOD]]([[STRUCT]]) } class RefWithProp { var int_prop: Int { get {} set {} } var aleph_prop: Aleph { get {} set {} } } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime015logical_lvalue_A0yyAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@guaranteed RefWithProp, Int, Val) -> () { func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) { var r = r var i = i var v = v // CHECK: [[RADDR:%[0-9]+]] = alloc_box ${ var RefWithProp } // CHECK: [[R_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[RADDR]] // CHECK: [[PR:%[0-9]+]] = project_box [[R_LIFETIME]] // CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[I_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[IADDR]] // CHECK: [[PI:%[0-9]+]] = project_box [[I_LIFETIME]] // CHECK: store %1 to [trivial] [[PI]] // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[V_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[VADDR]] // CHECK: [[PV:%[0-9]+]] = project_box [[V_LIFETIME]] // -- Reference types need to be copy_valued as property method args. r.int_prop = i // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]] // CHECK: [[R1:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter : (RefWithProp) -> (Int) -> (), $@convention(method) (Int, @guaranteed RefWithProp) -> () // CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]]) // CHECK: destroy_value [[R1]] r.aleph_prop.b = v // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]] // CHECK: [[R2:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[R2BORROW:%[0-9]+]] = begin_borrow [[R2]] // CHECK: [[MODIFY:%[0-9]+]] = class_method [[R2BORROW]] : $RefWithProp, #RefWithProp.aleph_prop!modify : // CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[R2BORROW]]) // CHECK: end_apply [[TOKEN]] } func bar() -> Int {} class Foo<T> { var x : Int var y = (Int(), Ref()) var z : T var w = Ref() class func makeT() -> T {} // Class initializer init() { // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]]) // CHECK: return [[INIT_THIS]] // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc : // CHECK: bb0([[THISIN:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized // -- initialization for y // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.y // CHECK: [[Y_INIT:%[0-9]+]] = function_ref @$s8lifetime3FooC1ySi_AA3RefCtvpfi : $@convention(thin) <τ_0_0> () -> (Int, @owned Ref) // CHECK: [[THIS_Y_0:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 0 // CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 1 // CHECK: [[Y_VALUE:%[0-9]+]] = apply [[Y_INIT]]<T>() // CHECK: ([[Y_EXTRACTED_0:%.*]], [[Y_EXTRACTED_1:%.*]]) = destructure_tuple // CHECK: store [[Y_EXTRACTED_0]] to [trivial] [[THIS_Y_0]] // CHECK: store [[Y_EXTRACTED_1]] to [init] [[THIS_Y_1]] // CHECK: end_borrow [[BORROWED_THIS]] // -- Initialization for w // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] // CHECK: [[Z_FUNC:%.*]] = function_ref @$s{{.*}}8lifetime3FooC1wAA3RefCvpfi : $@convention(thin) <τ_0_0> () -> @owned Ref // CHECK: [[Z_RESULT:%.*]] = apply [[Z_FUNC]]<T>() // CHECK: store [[Z_RESULT]] to [init] [[THIS_Z]] // CHECK: end_borrow [[BORROWED_THIS]] // -- Initialization for x // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int // CHECK: assign {{.*}} to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] x = bar() z = Foo<T>.makeT() // CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type // CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT : // CHECK: ref_element_addr // -- cleanup this lvalue and return this // CHECK: [[THIS_RESULT:%.*]] = copy_value [[THIS]] // -- TODO: This copy should be unnecessary. // CHECK: destroy_value [[THIS]] // CHECK: return [[THIS_RESULT]] } init(chi:Int) { var chi = chi z = Foo<T>.makeT() // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]]) // CHECK: return [[INIT_THIS]] // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC3chiACyxGSi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> { // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized [rootself] [[THISIN]] // -- First we initialize #Foo.y. // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : $Foo<T>, #Foo.y // CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 0 // CHECK: [[THIS_Y_2:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 1 // CHECK: store {{.*}} to [trivial] [[THIS_Y_1]] : $*Int // CHECK: store {{.*}} to [init] [[THIS_Y_2]] : $*Ref // CHECK: end_borrow [[BORROWED_THIS]] // -- Then we create a box that we will use to perform a copy_addr into #Foo.x a bit later. // CHECK: [[CHIADDR:%[0-9]+]] = alloc_box ${ var Int }, var, name "chi" // CHECK: [[CHI_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[CHIADDR]] // CHECK: [[PCHI:%[0-9]+]] = project_box [[CHI_LIFETIME]] // CHECK: store [[CHI]] to [trivial] [[PCHI]] // -- Then we initialize #Foo.z // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.z // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*T // CHECK: copy_addr [take] {{.*}} to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] // -- Then initialize #Foo.x using the earlier stored value of CHI to THIS_Z. x = chi // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PCHI]] // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int // CHECK: assign [[X]] to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] // -- cleanup chi // CHECK: destroy_value [[CHIADDR]] // -- Then begin the epilogue sequence // CHECK: [[THIS_RETURN:%.*]] = copy_value [[THIS]] // CHECK: destroy_value [[THIS]] // CHECK: return [[THIS_RETURN]] // CHECK: } // end sil function '$s8lifetime3FooC3chiACyxGSi_tcfc' } // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc : init<U:Intifiable>(chi:U) { z = Foo<T>.makeT() x = chi.intify() } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfd : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject deinit { // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $Foo<T>): bar() // CHECK: function_ref @$s8lifetime3barSiyF // CHECK: apply // -- don't need to destroy_value x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x // -- destroy_value y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y // CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]] // CHECK: destroy_addr [[YADDR_ACCESS]] // CHECK: end_access [[YADDR_ACCESS]] // -- destroy_value z // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z // CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]] // CHECK: destroy_addr [[ZADDR_ACCESS]] // CHECK: end_access [[ZADDR_ACCESS]] // -- destroy_value w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w // CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]] // CHECK: destroy_addr [[WADDR_ACCESS]] // CHECK: end_access [[WADDR_ACCESS]] // -- return back this // CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : $Foo<T> to $Builtin.NativeObject // CHECK: [[PTR_OWNED:%.*]] = unchecked_ownership_conversion [[PTR]] : $Builtin.NativeObject, @guaranteed to @owned // CHECK: return [[PTR_OWNED]] // CHECK: } // end sil function '$s8lifetime3FooCfd' } // Deallocating destructor for Foo. // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfD : $@convention(method) <T> (@owned Foo<T>) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[BORROWED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: end_borrow [[BORROWED_SELF]] // CHECK-NEXT: end_lifetime [[SELF]] // CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T> // CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T> // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // end sil function '$s8lifetime3FooCfD' } class FooSubclass<T> : Foo<T> { // CHECK-LABEL: sil hidden [ossa] @$s8lifetime11FooSubclassCfd : $@convention(method) <T> (@guaranteed FooSubclass<T>) -> @owned Builtin.NativeObject // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $FooSubclass<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $Foo<T> // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<T>([[BASE]]) // CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]] // CHECK: end_borrow [[BORROWED_PTR]] // CHECK: return [[PTR]] deinit { bar() } } class ImplicitDtor { var x:Int var y:(Int, Ref) var w:Ref init() { } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime12ImplicitDtorCfd // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtor): // -- don't need to destroy_value x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x // -- destroy_value y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y // CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]] // CHECK: destroy_addr [[YADDR_ACCESS]] // CHECK: end_access [[YADDR_ACCESS]] // -- destroy_value w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w // CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]] // CHECK: destroy_addr [[WADDR_ACCESS]] // CHECK: end_access [[WADDR_ACCESS]] // CHECK: return } class ImplicitDtorDerived<T> : ImplicitDtor { var z:T init(z : T) { super.init() self.z = z } // CHECK: sil hidden [ossa] @$s8lifetime19ImplicitDtorDerivedCfd : $@convention(method) <T> (@guaranteed ImplicitDtorDerived<T>) -> @owned Builtin.NativeObject { // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerived<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime12ImplicitDtorCfd // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]([[BASE]]) // -- destroy_value z // CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]] // CHECK: [[CAST_BORROWED_PTR:%.*]] = unchecked_ref_cast [[BORROWED_PTR]] : $Builtin.NativeObject to $ImplicitDtorDerived<T> // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[CAST_BORROWED_PTR]] : {{.*}}, #ImplicitDtorDerived.z // CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]] // CHECK: destroy_addr [[ZADDR_ACCESS]] // CHECK: end_access [[ZADDR_ACCESS]] // CHECK: end_borrow [[BORROWED_PTR]] // -- epilog // CHECK-NOT: unchecked_ref_cast // CHECK-NOT: unchecked_ownership_conversion // CHECK: return [[PTR]] } class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> { init() { super.init(z: 5) } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime30ImplicitDtorDerivedFromGenericC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerivedFromGeneric<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int> // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime19ImplicitDtorDerivedCfd // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]]) // CHECK: return [[PTR]] } protocol Intifiable { func intify() -> Int } struct Bar { var x:Int // Loadable struct initializer // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BarV{{[_0-9a-zA-Z]*}}fC init() { // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] x = bar() // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bar, #Bar.x // CHECK: assign {{.*}} to [[SELF_X]] // -- load and return this // CHECK: [[SELF_VAL:%[0-9]+]] = load [trivial] [[PB_BOX]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: return [[SELF_VAL]] } init<T:Intifiable>(xx:T) { x = xx.intify() } } struct Bas<T> { var x:Int var y:T // Address-only struct initializer // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BasV{{[_0-9a-zA-Z]*}}fC init(yy:T) { // CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var Bas<τ_0_0> } <T> // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] x = bar() // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.x // CHECK: assign {{.*}} to [[SELF_X]] y = yy // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_Y:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.y // CHECK: copy_addr {{.*}} to [[SELF_Y]] // CHECK: destroy_value // -- 'self' was emplaced into indirect return slot // CHECK: return } init<U:Intifiable>(xx:U, yy:T) { x = xx.intify() y = yy } } class B { init(y:Int) {} } class D : B { // CHECK-LABEL: sil hidden [ossa] @$s8lifetime1DC1x1yACSi_Sitcfc // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : @owned $D): init(x: Int, y: Int) { var x = x var y = y // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%[0-9]+]] = project_box [[SELF_LIFETIME]] // CHECK: store [[SELF]] to [init] [[PB_BOX]] // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[XLIFETIME:%[0-9]+]] = begin_borrow [lexical] [[XADDR]] // CHECK: [[PX:%[0-9]+]] = project_box [[XLIFETIME]] // CHECK: store [[X]] to [trivial] [[PX]] // CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[Y_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[YADDR]] // CHECK: [[PY:%[0-9]+]] = project_box [[Y_LIFETIME]] // CHECK: store [[Y]] to [trivial] [[PY]] super.init(y: y) // CHECK: [[THIS1:%[0-9]+]] = load [take] [[PB_BOX]] // CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PY]] // CHECK: [[Y:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @$s8lifetime1BC1yACSi_tcfc : $@convention(method) (Int, @owned B) -> @owned B // CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]]) // CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D // CHECK: [[THIS1:%[0-9]+]] = load [copy] [[PB_BOX]] // CHECK: destroy_value [[MARKED_SELF_BOX]] } func foo() {} } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime8downcast{{[_0-9a-zA-Z]*}}F func downcast(_ b: B) { var b = b // CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var B } // CHECK: [[B_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[BADDR]] // CHECK: [[PB:%[0-9]+]] = project_box [[B_LIFETIME]] (b as! D).foo() // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[B:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to D // CHECK: apply {{.*}}([[D]]) // CHECK-NOT: destroy_value [[B]] // CHECK: destroy_value [[D]] // CHECK: destroy_value [[BADDR]] // CHECK: return } func int(_ x: Int) {} func ref(_ x: Ref) {} func tuple() -> (Int, Ref) { return (1, Ref()) } func tuple_explosion() { int(tuple().0) // CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T1]] // CHECK-NOT: destructure_tuple [[TUPLE]] // CHECK-NOT: tuple_extract [[TUPLE]] // CHECK-NOT: destroy_value ref(tuple().1) // CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T1]] // CHECK-NOT: destructure_tuple [[TUPLE]] // CHECK-NOT: tuple_extract [[TUPLE]] // CHECK-NOT: destroy_value [[TUPLE]] }
apache-2.0
a2d64c840a50ce52b3251f41376ae9b7
39.998747
194
0.550142
3.04883
false
false
false
false
Aster0id/Swift-StudyNotes
Swift-StudyNotes/L2-S5.swift
1
11674
// // L2-S5.swift // Swift-StudyNotes // // Created by 牛萌 on 15/5/14. // Copyright (c) 2015年 Aster0id.Team. All rights reserved. // import Foundation /** * @class * @brief 2.5 控制流 */ class Lesson2Section5 { func run(flag:Bool) { if !flag { return } //MARK: Begin Runing println("\n\n------------------------------------") println(">>>>> Lesson2-Section5 begin running\n\n") // ----------------------------------------- // MARK: for循环 // ----------------------------------------- /* for-in 用来遍历一个范围(range),队列(sequence),集合(collection),系列(progression)里 面所有的元素执行一系列语句。 for 条件递增语句(for-condition-increment),用来重复执行一系列语句直到特定条件达成, 一般通过在每次循环完成后增加计数器的值来实现。 */ //-- for-in for index in 1...5 { println("\(index) times 5 is \(index * 5)") } /* //## 打印: 1 times 5 is 5 2 times 5 is 10 3 times 5 is 15 4 times 5 is 20 5 times 5 is 25 */ //如果你不需要知道范围内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问 let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } println("\(base) to the power of \(power) is \(answer)") //## 打印 3 to the power of 10 is 59049 let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { println("\(animalName)s have \(legCount) legs") } /* //## 打印: ants have 6 legs cats have 4 legs spiders have 8 legs */ //除了数组和字典,你也可以使用 for-in 循环来遍历字符串中的字符 for character in "Hello" { println(character) } /* //## 打印: H e l l o */ //-- for 条件递增(for-condition-increment) for var index = 0; index < 3; ++index { println("index is \(index)") } /* //## 打印: index is 0 index is 1 index is 2 */ // ----------------------------------------- // MARK: while循环 // ----------------------------------------- /* - while 循环,每次在循环开始时计算条件是否符合; - do-while 循环,每次在循环结束时计算条件是否符合。 */ //-- while // Game: 蛇与梯子 let finalSquare = 25 var board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 var square = 0 var diceRoll = 0 while square < finalSquare { // roll the dice if ++diceRoll == 7 { diceRoll = 1 } // move by the rolled amount square += diceRoll if square < board.count { // if we're still on the board, move up or down for a snake or a ladder square += board[square] } } println("Game over!") //-- do-while /* while循环的另外一种形式是 do-while,它和 while 的区别是在判断循环条件之前,先执行一次循环的代码块,然后重复循环直到条件为 false。 */ // ----------------------------------------- // MARK: 条件语句 // ----------------------------------------- //-- if var temperatureInFahrenheit = 30 if temperatureInFahrenheit <= 32 { println("It's very cold. Consider wearing a scarf.") } //## 打印: "It's very cold. Consider wearing a scarf." temperatureInFahrenheit = 40 if temperatureInFahrenheit <= 32 { // println("It's very cold. Consider wearing a scarf.") } else { println("It's not that cold. Wear a t-shirt.") } //## 打印: "It's not that cold. Wear a t-shirt." //-- switch let someCharacter: Character = "e" switch someCharacter { case "a", "e", "i", "o", "u": println("\(someCharacter) is a vowel") case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": println("\(someCharacter) is a consonant") default: println("\(someCharacter) is not a vowel or a consonant") } //## 打印: e is a vowel //-- switch不存在隐式的贯穿(Fallthrough) //与 C 语言和 Objective-C 中的 switch 语句不同,在 Swift 中,当匹配的 case 块中的代码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 块。这也就是说,不需要 在 case 块中显式地使用 break 语句。这使得 switch 语句更安全、更易用,也避免了因忘记 写 break 语句而产生的错误。 //-- 范围匹配 //~~ 新语法 // case块的模式也可以是一个值的范围。下面的例子展示了如何使用范围匹配来输出任意数字对应的自然语言格式: let count = 3_000_000_000_000 let countedThings = "stars in the Milky Way" var naturalCount: String switch count { case 0: naturalCount = "no" case 1...3: naturalCount = "a few" case 4...9: naturalCount = "several" case 10...99: naturalCount = "tens of" case 100...999: naturalCount = "hundreds of" case 1000...999_999: naturalCount = "thousands of" default: naturalCount = "millions and millions of" } println("There are \(naturalCount) \(countedThings).") //## 打印: There are millions and millions of stars in the Milky Way. // 你可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是范围。另外,使用下划线(_)来匹配所有可能的值。 let somePoint = (1, 1) switch somePoint { case (0, 0): println("(0, 0) is at the origin") case (_, 0): println("(\(somePoint.0), 0) is on the x-axis") case (0, _): println("(0, \(somePoint.1)) is on the y-axis") case (-2...2, -2...2): println("(\(somePoint.0), \(somePoint.1)) is inside the box") default: println("(\(somePoint.0), \(somePoint.1)) is outside of the box") } //## 打印: (1, 1) is inside the box //-- 值绑定 (Value Bindings) //~~ 新语法 // case 块的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 块里就可以被引用了——这种行为被称为值绑定。 let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): println("on the x-axis with an x value of \(x)") case (0, let y): println("on the y-axis with a y value of \(y)") case let (x, y): println("somewhere else at (\(x), \(y))") } //## 打印: on the x-axis with an x value of 2 //-- Where //!!!!! //~~ 新语法 // case 块的模式可以使用 where 语句来判断额外的条件。 // 下面的例子把下图中的点(x, y)进行了分类: var yetAnotherPoint = (1, -1) switch yetAnotherPoint { // case let (x, y) where x == y: // println("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: println("(\(x), \(y)) is on the line x == -y") case let (x, y): println("(\(x), \(y)) is just some arbitrary point") } //## 打印: (1, -1) is on the line x == -y // ----------------------------------------- // MARK: 控制转移语句 // ----------------------------------------- /* 控制转移语句改变你代码的执行顺序,通过它你可以实现代码的跳转。Swift 有四种控制转 移语句。 - continue - break - fallthrough - return */ //-- continue // continue 告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本 次循环迭代我已经执行完了”,但是并不会离开整个循环体。 let puzzleInput = "great minds think alike" var puzzleOutput = "" for character in puzzleInput { switch character { case "a", "e", "i", "o", "u", " ": continue default: puzzleOutput += String(character) } } println(puzzleOutput) //## 打印: grtmndsthnklk //-- break // break 语句会立刻结束整个控制流的执行。当你想要更早的结束一个 switch 代码块或者一个循环体时,你都可以使用 break 语句 //-- fallthrough //~~ 新语法 /* Swift 语言中的 switch 不会从上一个 case 分支落入到下一个 case 分支中。 相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个 switch 代码块完成了它的执行。 相比之下,C 语言要求你显示的插入 break 语句到每个 switch 分支的末尾来阻止自动落入到下一个case分支中。 Swift语言的这种避免默认落入到下一个分支中的特性意味着它的switch功能要比 C 语言的更加清晰和可预测,可以避免无意识地执行多个 case 分支从而引发的错误。 */ let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case 2,3,5,7,11,13,17,19: description += " a prime number, and also" fallthrough default: description += " an integer." } println(description) //## 打印: The number 5 is a prime number, and also an integer. //! 注意: // fallthrough 关键字不会检查它下一个将会落入执行的 case 中的匹配条件。 // fallthrough 简单地使代码执行继续连接到下一个 case 中的执行代码,这和 C 语言标准中的 switch 语句特性是一样的。 //MARK: End Runing println("\n\nLesson2-Section5 end running <<<<<<<") println("------------------------------------\n\n") } }
mit
3e1dd3a0db8ed6341c97aba3bbb31690
27.405248
190
0.443338
3.889022
false
false
false
false
Pluto-tv/RxSwift
RxSwift/Observables/Implementations/Map.swift
1
3289
// // Map.swift // Rx // // Created by Krunoslav Zaher on 3/15/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class MapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType { typealias ResultType = O.E typealias Element = SourceType typealias Parent = Map<SourceType, ResultType> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func performMap(element: SourceType) throws -> ResultType { abstractMethod() } func on(event: Event<SourceType>) { let observer = super.observer switch event { case .Next(let element): do { let mappedElement = try performMap(element) observer?.on(.Next(mappedElement)) } catch let e { observer?.on(.Error(e)) self.dispose() } case .Error(let error): observer?.on(.Error(error)) self.dispose() case .Completed: observer?.on(.Completed) self.dispose() } } } class MapSink1<SourceType, O: ObserverType> : MapSink<SourceType, O> { typealias ResultType = O.E override init(parent: Map<SourceType, ResultType>, observer: O, cancel: Disposable) { super.init(parent: parent, observer: observer, cancel: cancel) } override func performMap(element: SourceType) throws -> ResultType { return try self.parent.selector1!(element) } } class MapSink2<SourceType, O: ObserverType> : MapSink<SourceType, O> { typealias ResultType = O.E private var _index = 0 override init(parent: Map<SourceType, ResultType>, observer: O, cancel: Disposable) { super.init(parent: parent, observer: observer, cancel: cancel) } override func performMap(element: SourceType) throws -> ResultType { return try self.parent.selector2!(element, try incrementChecked(&_index)) } } class Map<SourceType, ResultType>: Producer<ResultType> { typealias Selector1 = (SourceType) throws -> ResultType typealias Selector2 = (SourceType, Int) throws -> ResultType let source: Observable<SourceType> let selector1: Selector1? let selector2: Selector2? init(source: Observable<SourceType>, selector: Selector1) { self.source = source self.selector1 = selector self.selector2 = nil } init(source: Observable<SourceType>, selector: Selector2) { self.source = source self.selector2 = selector self.selector1 = nil } override func run<O: ObserverType where O.E == ResultType>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { if let _ = self.selector1 { let sink = MapSink1(parent: self, observer: observer, cancel: cancel) setSink(sink) return self.source.subscribeSafe(sink) } else { let sink = MapSink2(parent: self, observer: observer, cancel: cancel) setSink(sink) return self.source.subscribeSafe(sink) } } }
mit
0185ff8e4800fafb823070a93dcc5a4b
29.183486
142
0.609304
4.450609
false
false
false
false
Antonnk/OAuthSwift
OAuthSwift/OAuth1Swift.swift
5
6285
// // OAuth1Swift.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation // OAuthSwift errors public let OAuthSwiftErrorDomain = "oauthswift.error" public class OAuth1Swift: NSObject { public var client: OAuthSwiftClient public var authorize_url_handler: OAuthSwiftURLHandlerType = OAuthSwiftOpenURLExternally.sharedInstance public var allowMissingOauthVerifier: Bool = false var consumer_key: String var consumer_secret: String var request_token_url: String var authorize_url: String var access_token_url: String var observer: AnyObject? public init(consumerKey: String, consumerSecret: String, requestTokenUrl: String, authorizeUrl: String, accessTokenUrl: String){ self.consumer_key = consumerKey self.consumer_secret = consumerSecret self.request_token_url = requestTokenUrl self.authorize_url = authorizeUrl self.access_token_url = accessTokenUrl self.client = OAuthSwiftClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } struct CallbackNotification { static let notificationName = "OAuthSwiftCallbackNotificationName" static let optionsURLKey = "OAuthSwiftCallbackNotificationOptionsURLKey" } struct OAuthSwiftError { static let domain = "OAuthSwiftErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } public typealias TokenSuccessHandler = (credential: OAuthSwiftCredential, response: NSURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void // 0. Start public func authorizeWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) { self.postOAuthRequestTokenWithCallbackURL(callbackURL, success: { credential, response in self.observer = NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{ notification in //NSNotificationCenter.defaultCenter().removeObserver(self) NSNotificationCenter.defaultCenter().removeObserver(self.observer!) let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL var parameters: Dictionary<String, String> = Dictionary() if ((url.query) != nil){ parameters = url.query!.parametersFromQueryString() } else if ((url.fragment) != nil && url.fragment!.isEmpty == false) { parameters = url.fragment!.parametersFromQueryString() } if let token = parameters["token"] { parameters["oauth_token"] = token } if (parameters["oauth_token"] != nil && (self.allowMissingOauthVerifier || parameters["oauth_verifier"] != nil)) { //var credential: OAuthSwiftCredential = self.client.credential self.client.credential.oauth_token = parameters["oauth_token"]! if (parameters["oauth_verifier"] != nil) { self.client.credential.oauth_verifier = parameters["oauth_verifier"]! } self.postOAuthAccessTokenWithRequestToken({ credential, response in success(credential: credential, response: response) }, failure: failure) } else { let userInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Oauth problem.", comment: "")] failure(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: userInfo)) return } }) // 2. Authorize if let queryURL = NSURL(string: self.authorize_url + (self.authorize_url.has("?") ? "&" : "?") + "oauth_token=\(credential.oauth_token)") { self.authorize_url_handler.handle(queryURL) } }, failure: failure) } // 1. Request token public func postOAuthRequestTokenWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, AnyObject>() if let callbackURLString: String = callbackURL.absoluteString { parameters["oauth_callback"] = callbackURLString } self.client.post(self.request_token_url, parameters: parameters, success: { data, response in let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String! let parameters = responseString.parametersFromQueryString() self.client.credential.oauth_token = parameters["oauth_token"]! self.client.credential.oauth_token_secret = parameters["oauth_token_secret"]! success(credential: self.client.credential, response: response) }, failure: failure) } // 3. Get Access token func postOAuthAccessTokenWithRequestToken(success: TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, AnyObject>() parameters["oauth_token"] = self.client.credential.oauth_token parameters["oauth_verifier"] = self.client.credential.oauth_verifier self.client.post(self.access_token_url, parameters: parameters, success: { data, response in let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String! let parameters = responseString.parametersFromQueryString() self.client.credential.oauth_token = parameters["oauth_token"]! self.client.credential.oauth_token_secret = parameters["oauth_token_secret"]! success(credential: self.client.credential, response: response) }, failure: failure) } public class func handleOpenURL(url: NSURL) { let notification = NSNotification(name: CallbackNotification.notificationName, object: nil, userInfo: [CallbackNotification.optionsURLKey: url]) NSNotificationCenter.defaultCenter().postNotification(notification) } }
mit
b1153f3938c9e8352b453181b2de722c
46.977099
185
0.656643
5.358056
false
false
false
false
CosmicMind/Samples
Projects/Programmatic/Layer/Layer/ViewController.swift
1
2393
/* * 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 ViewController: UIViewController { fileprivate var layer: Layer! @IBOutlet weak var bottomBar: Bar! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white prepareLayer() } } extension ViewController { fileprivate func prepareLayer() { let w = view.frame.width let h = view.frame.height let d: CGFloat = 100 layer = Layer(frame: CGRect(x: (w - d) / 2, y: (h - d) / 2, width: d, height: d)) layer.depthPreset = .depth3 layer.shapePreset = .circle layer.backgroundColor = Color.white.cgColor layer.image = UIImage(named: "CosmicMind") view.layer.addSublayer(layer) } }
bsd-3-clause
3a3174c939c540631fcc77e74d4c9e30
38.229508
89
0.712495
4.481273
false
false
false
false
ubclaunchpad/RocketCast
RocketCastUITests/PlayerUITests.swift
1
7970
// // PlayerUITests.swift // RocketCast // // Created by Milton Leung on 2016-10-15. // Copyright © 2016 UBCLaunchPad. All rights reserved. // import XCTest class PlayerUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false let app = XCUIApplication() app.launchArguments = ["MY_UI_TEST_MODE"] app.launch() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSpeedRate () { let app = XCUIApplication() app.buttons[AddButtonFromPodcastView].tap() app.buttons["Add Url"].tap() app.buttons[AddPodcastButtonOnAddURLView].tap() app.staticTexts[SamplePodcast.podcastTitle].tap() // please wait for awhile let tablesQuery = app.tables let downloadingLabel = tablesQuery.cells.element(boundBy: 1).staticTexts[downloaded] let doesItExist = NSPredicate(format: "exists == true") expectation(for: doesItExist, evaluatedWith: downloadingLabel, handler: nil) tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() waitForExpectations(timeout: timeOut, handler: nil) tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() let slider = app.sliders["0%"] expectation(for: doesItExist, evaluatedWith: slider, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) // Verify if the slider is moving if (runForTravis) { let normalSliderPositionValue = app.sliders["1%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } // Verify if 2x speed is working (i.e the slider should move faster) app.buttons[play2TimesButton].tap() if (runForTravis) { let normalSliderPositionValue = app.sliders["3%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } // Verify if 3x speed is working (i.e the slider should move the fastest) app.buttons[play3TimesButton].tap() if (runForTravis) { let normalSliderPositionValue = app.sliders["5%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } // Verify if the pause button is working (i.e the slider should not move) app.buttons[pauseButton].tap() let currentSliderValue = app.sliders.element.normalizedSliderPosition sleep(2) XCTAssertTrue(currentSliderValue == app.sliders.element.normalizedSliderPosition) } func testIfSliderIsMoving () { let app = XCUIApplication() app.buttons[AddButtonFromPodcastView].tap() app.buttons["Add Url"].tap() app.buttons[AddPodcastButtonOnAddURLView].tap() app.staticTexts[SamplePodcast.podcastTitle].tap() let tablesQuery = app.tables let mondayMorningPodcast91216StaticText = tablesQuery.staticTexts[SamplePodcast.firstEpisode] // please wait for awhile let downloadingLabel = tablesQuery.cells.element(boundBy: 1).staticTexts[downloaded] let doesItExist = NSPredicate(format: "exists == true") expectation(for: doesItExist, evaluatedWith: downloadingLabel, handler: nil) mondayMorningPodcast91216StaticText.tap() waitForExpectations(timeout: timeOut, handler: nil) mondayMorningPodcast91216StaticText.tap() if (runForTravis) { let normalSliderPositionValue = app.sliders["1%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } app.buttons[pauseButton].tap() } func testVerifyIfNextEpisodeIsPlayedWhenSliderReachesNearMaxValue() { guard runForTravis else { return } let app = XCUIApplication() app.buttons[AddButtonFromPodcastView].tap() app.buttons["Add Url"].tap() app.buttons[AddPodcastButtonOnAddURLView].tap() app.staticTexts[SamplePodcast.podcastTitle].tap() let tablesQuery = app.tables tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() // Go to the first episode let downloadingLabel = tablesQuery.cells.element(boundBy: 1).staticTexts[downloaded] let doesItExist = NSPredicate(format: "exists == true") expectation(for: doesItExist, evaluatedWith: downloadingLabel, handler: nil) tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() waitForExpectations(timeout: timeOut, handler: nil) tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() XCTAssert(app.staticTexts[SamplePodcast.firstEpisode].exists) if (runForTravis) { let normalSliderPositionValue = app.sliders["1%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } // move the slider to the end, which should go to the next episode app.sliders.element.adjust(toNormalizedSliderPosition: 0.99) let successAlert = app.alerts["Success"] XCTAssertFalse(successAlert.exists) expectation(for: doesItExist, evaluatedWith: successAlert, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) successAlert.buttons["Ok"].tap() XCTAssert(app.staticTexts[SamplePodcast.secondEpisode].exists) if (runForTravis) { let normalSliderPositionValue = app.sliders["1%"] XCTAssertFalse(normalSliderPositionValue.exists) expectation(for: doesItExist, evaluatedWith: normalSliderPositionValue, handler: nil) waitForExpectations(timeout: timeOut, handler: nil) } } func testSpeedRateButtonIsSaved() { let app = XCUIApplication() app.buttons[AddButtonFromPodcastView].tap() app.buttons["Add Url"].tap() let addPodcastButton = app.buttons[AddPodcastButtonOnAddURLView] addPodcastButton.tap() app.staticTexts[SamplePodcast.podcastTitle].tap() let tablesQuery = app.tables tablesQuery.staticTexts[SamplePodcast.firstEpisode].tap() // Go to the first episode let downloadingLabel = tablesQuery.cells.element(boundBy: 1).staticTexts[downloaded] let doesItExist = NSPredicate(format: "exists == true") expectation(for: doesItExist, evaluatedWith: downloadingLabel, handler: nil) app.staticTexts[SamplePodcast.firstEpisode].tap() waitForExpectations(timeout: timeOut, handler: nil) app.staticTexts[SamplePodcast.firstEpisode].tap() XCTAssert(app.buttons[play2TimesButton].exists) app.buttons[play2TimesButton].tap() XCTAssert(app.buttons[play3TimesButton].exists) app.buttons["Back"].tap() let playButton = app.buttons[PlayButtonFromNavigationBar] playButton.tap() XCTAssert(app.buttons[play3TimesButton].exists) app.buttons["Back"].tap() } }
mit
44181e07c316c977fd1f5fba7f1e31da
41.844086
111
0.66194
4.780444
false
true
false
false
csontosgabor/Twitter_Post
Twitter_Post/UploadPost.swift
1
4634
// // PostUpload.swift // Twitter_Post // // Created by Gabor Csontos on 12/29/16. // Copyright © 2016 GaborMajorszki. All rights reserved. // import Foundation import Alamofire public var ServerURL: String = "YOUR PHP ADDRESS" public typealias PostUploadSuccess = () -> Void public typealias PostUploadFailure = (NSError) -> Void public class PostUpload: NSObject { private var success: PostUploadSuccess? private var failure: PostUploadFailure? public override init() { } public func onSuccess(_ success: @escaping PostUploadSuccess) -> Self { self.success = success return self } public func onFailure(_ failure: @escaping PostUploadFailure) -> Self { self.failure = failure return self } public func upload(_ post: NewPost) -> Self { self._upload(post) return self } private func _upload(_ post: NewPost) { var parameters: Parameters = [ "user_id": post.userId, "posttype": "0", ] parameters["posttext"] = post.text parameters["location"] = post.location //if it has image, mp4 (content) if let assetId = post.contentId { var reqAVAsset = RequestAVAssetData() .onSuccess { (imageData, videoData) in self.startUploading(parameters, imgData: imageData, videoData: videoData) } .onFailure { error in self.failure?(error) return } reqAVAsset = reqAVAsset.getAVAsset(assetId) } else { self.startUploading(parameters, imgData: nil, videoData: nil) } } func startUploading(_ parameters: Parameters, imgData: Data?, videoData: Data?) { guard let currentWindow = UIApplication.shared.keyWindow?.subviews.last else { return } Alamofire.upload(multipartFormData: { multipartFormData in if let videoData = videoData { multipartFormData.append(videoData, withName: "file[]", fileName: "file.mp4", mimeType: "video/mp4") } if let imageData = imgData { multipartFormData.append(imageData, withName: "file[]", fileName: "file.jpg", mimeType: "image/jpg") } for (key, value) in parameters { let newValue = (value as! String).data(using: .utf8)! multipartFormData.append(newValue, withName: key) }}, to: ServerURL , method: .post, headers: ["Authorization": "auth_token"], encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.uploadProgress(closure: { (Progress) in KVNProgress.show(CGFloat(Float(Progress.fractionCompleted)), status: "Posting...", on: currentWindow) }) upload.responseJSON { response in print(response.request as Any) // original URL request print(response.response as Any) // URL response print(response.data as Any) // server data print(response.result) // result of response serialization KVNProgress.dismiss() KVNProgress.showSuccess() DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { KVNProgress.dismiss() self.success?() }) } case .failure(let encodingError): KVNProgress.showError() self.failure?(encodingError as NSError) } }) } }
mit
19295bc2bd225b594f55bfd0f4f59d66
29.480263
129
0.457155
6.001295
false
false
false
false
lanjing99/iOSByTutorials
iOS Animations by Tutorials 2.0_iOS_9_Swift_2/Chapter 13 - Shapes and Masks/MultiplayerSearch-Starter/MultiplayerSearch/AvatarView.swift
1
5455
/* * Copyright (c) 2015 Razeware LLC * * 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 QuartzCore @IBDesignable class AvatarView: UIView { //constants let lineWidth: CGFloat = 6.0 let animationDuration = 1.0 //ui let photoLayer = CALayer() let circleLayer = CAShapeLayer() let maskLayer = CAShapeLayer() let label: UILabel = { let label = UILabel() label.font = UIFont(name: "ArialRoundedMTBold", size: 18.0) label.textAlignment = .Center label.textColor = UIColor.blackColor() return label }() //variables @IBInspectable var image: UIImage! { didSet { photoLayer.contents = image.CGImage } } @IBInspectable var name: String? { didSet { label.text = name } } var shouldTransitionToFinishedState = false override func didMoveToWindow() { photoLayer.mask = maskLayer layer.addSublayer(photoLayer) layer.addSublayer(circleLayer) addSubview(label) } override func layoutSubviews() { //Size the avatar image to fit photoLayer.frame = CGRect( x: (bounds.size.width - image.size.width + lineWidth)/2, y: (bounds.size.height - image.size.height - lineWidth)/2, width: image.size.width, height: image.size.height) //Draw the circle circleLayer.path = UIBezierPath(ovalInRect: bounds).CGPath circleLayer.strokeColor = UIColor.whiteColor().CGColor circleLayer.lineWidth = lineWidth circleLayer.fillColor = UIColor.clearColor().CGColor //Size the layer maskLayer.path = circleLayer.path maskLayer.position = CGPoint(x: 0.0, y: 10.0) //Size the label label.frame = CGRect(x: 0.0, y: bounds.size.height + 10.0, width: bounds.size.width, height: 24.0) } func bounceOffPoint(bouncePoint: CGPoint, morphSize: CGSize) { let originalCenter = center UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: [], animations: { self.center = bouncePoint }, completion: {_ in //complete bounce to let morphAnimation = CABasicAnimation(keyPath: "path") morphAnimation.duration = self.animationDuration morphAnimation.toValue = UIBezierPath(ovalInRect: self.bounds).CGPath morphAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) morphAnimation.autoreverses = false self.circleLayer.addAnimation(morphAnimation, forKey: nil) self.maskLayer.addAnimation(morphAnimation, forKey: nil) self.photoLayer.addAnimation(morphAnimation, forKey: nil) }) UIView.animateWithDuration(self.animationDuration, delay: self.animationDuration, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: [], animations: { self.center = originalCenter }, completion: {_ in delay(seconds: 0.1) { self.bounceOffPoint(bouncePoint, morphSize: morphSize) } }) delay(seconds: self.animationDuration/2, completion: { let morphedFrame = (originalCenter.x > bouncePoint.x) ? CGRect(x: 0.0, y: self.bounds.height - morphSize.height, width: morphSize.width, height: morphSize.height): CGRect(x: self.bounds.width - morphSize.width, y: self.bounds.height - morphSize.height, width: morphSize.width, height: morphSize.height) let morphAnimation = CABasicAnimation(keyPath: "path") morphAnimation.duration = self.animationDuration/2 morphAnimation.toValue = UIBezierPath(ovalInRect: morphedFrame).CGPath morphAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) morphAnimation.autoreverses = false self.circleLayer.addAnimation(morphAnimation, forKey: nil) self.maskLayer.addAnimation(morphAnimation, forKey: nil) self.photoLayer.addAnimation(morphAnimation, forKey: nil) // self.layer.addAnimation(morphAnimation, forKey: nil) }) } }
mit
df37a91457f47fcab769c77423afb3a3
35.125828
173
0.655729
4.823165
false
false
false
false
renzifeng/ZFZhiHuDaily
ZFZhiHuDaily/Home/Model/ZFTopStories.swift
1
3325
// // ZFTopStories.swift // // Created by 任子丰 on 16/1/25 // Copyright (c) 任子丰. All rights reserved. // import Foundation import SwiftyJSON public class ZFTopStories: NSObject,NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kZFTopStoriesTitleKey: String = "title" internal let kZFTopStoriesImageKey: String = "image" internal let kZFTopStoriesInternalIdentifierKey: String = "id" internal let kZFTopStoriesGaPrefixKey: String = "ga_prefix" internal let kZFTopStoriesTypeKey: String = "type" // MARK: Properties public var title: String? public var image: String? public var internalIdentifier: Int? public var gaPrefix: String? public var type: Int? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { title = json[kZFTopStoriesTitleKey].string image = json[kZFTopStoriesImageKey].string internalIdentifier = json[kZFTopStoriesInternalIdentifierKey].int gaPrefix = json[kZFTopStoriesGaPrefixKey].string type = json[kZFTopStoriesTypeKey].int } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if title != nil { dictionary.updateValue(title!, forKey: kZFTopStoriesTitleKey) } if image != nil { dictionary.updateValue(image!, forKey: kZFTopStoriesImageKey) } if internalIdentifier != nil { dictionary.updateValue(internalIdentifier!, forKey: kZFTopStoriesInternalIdentifierKey) } if gaPrefix != nil { dictionary.updateValue(gaPrefix!, forKey: kZFTopStoriesGaPrefixKey) } if type != nil { dictionary.updateValue(type!, forKey: kZFTopStoriesTypeKey) } return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObjectForKey(kZFTopStoriesTitleKey) as? String self.image = aDecoder.decodeObjectForKey(kZFTopStoriesImageKey) as? String self.internalIdentifier = aDecoder.decodeObjectForKey(kZFTopStoriesInternalIdentifierKey) as? Int self.gaPrefix = aDecoder.decodeObjectForKey(kZFTopStoriesGaPrefixKey) as? String self.type = aDecoder.decodeObjectForKey(kZFTopStoriesTypeKey) as? Int } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(title, forKey: kZFTopStoriesTitleKey) aCoder.encodeObject(image, forKey: kZFTopStoriesImageKey) aCoder.encodeObject(internalIdentifier, forKey: kZFTopStoriesInternalIdentifierKey) aCoder.encodeObject(gaPrefix, forKey: kZFTopStoriesGaPrefixKey) aCoder.encodeObject(type, forKey: kZFTopStoriesTypeKey) } }
apache-2.0
04f6ad793bc3abd0fa455548278778da
32.13
105
0.722608
4.065031
false
false
false
false
EasyIOS/EasyIOS-Swift
Demo/Demo/FlexScene.swift
2
1306
// // FlexScene.swift // Demo // // Created by zhuchao on 15/10/14. // Copyright © 2015年 zhuchao. All rights reserved. // import UIKit import EasyIOS class FlexScene: EZScene { var container:FLEXBOXContainerView! override func viewDidLoad() { super.viewDidLoad() container = FLEXBOXContainerView(frame: self.view.bounds) container.flexJustifyContent = FLEXBOXJustification.Center container.flexAlignItems = FLEXBOXAlignment.Center container.flexDirection = FLEXBOXFlexDirection.Column container.backgroundColor = UIColor.grayColor() let v1 = UILabel() v1.text = "123123" v1.backgroundColor = UIColor.blueColor() v1.textAlignment = NSTextAlignment.Center v1.flexMargin = UIEdgeInsetsMake(8, 8, 8, 8) v1.flexPadding = UIEdgeInsetsMake(10, 10, 10, 10) v1.flex = 0 container.addSubview(v1) let v2 = UILabel() v2.text = "321" v2.backgroundColor = UIColor.blueColor() v2.textAlignment = NSTextAlignment.Center v2.flexMargin = UIEdgeInsetsMake(8, 8, 8, 8) v2.flexPadding = UIEdgeInsetsMake(10, 10, 10, 10) v2.flex = 0 container.addSubview(v2) self.view.addSubview(container) } }
mit
03d456751c4125ffe668b1e923f44d01
29.302326
66
0.640061
3.984709
false
false
false
false
naru-jpn/pencil
Sources/Int.swift
1
3996
// // Int.swift // Pencil // // Created by naru on 2016/10/13. // Copyright © 2016年 naru. All rights reserved. // import Foundation extension Int: ReadWriteElement { public static var sPencilName: String { return "\(self)" } public var pencilName: String { return "\(Mirror(reflecting: self).subjectType)" } public var pencilDataLength: Int { return MemoryLayout<Int>.size } public var pencilHead: [Data] { return [Data()] } public var pencilBody: [Data] { var num: Int = self return [Data(buffer: UnsafeBufferPointer(start: &num, count: 1))] } public static func read(from components: Components) -> Int? { guard let data: Data = components.dictionary["value"] as Data? else { return nil } return data.withUnsafeBytes{ $0.pointee } } } extension Int8: ReadWriteElement { public static var sPencilName: String { return "\(self)" } public var pencilName: String { return "\(Mirror(reflecting: self).subjectType)" } public var pencilDataLength: Int { return MemoryLayout<Int8>.size } public var pencilHead: [Data] { return [Data()] } public var pencilBody: [Data] { var num: Int8 = self return [Data(buffer: UnsafeBufferPointer(start: &num, count: 1))] } public static func read(from components: Components) -> Int8? { guard let data: Data = components.dictionary["value"] as Data? else { return nil } return data.withUnsafeBytes{ $0.pointee } } } extension Int16: ReadWriteElement { public static var sPencilName: String { return "\(self)" } public var pencilName: String { return "\(Mirror(reflecting: self).subjectType)" } public var pencilDataLength: Int { return MemoryLayout<Int16>.size } public var pencilHead: [Data] { return [Data()] } public var pencilBody: [Data] { var num: Int16 = self return [Data(buffer: UnsafeBufferPointer(start: &num, count: 1))] } public static func read(from components: Components) -> Int16? { guard let data: Data = components.dictionary["value"] as Data? else { return nil } return data.withUnsafeBytes{ $0.pointee } } } extension Int32: ReadWriteElement { public static var sPencilName: String { return "\(self)" } public var pencilName: String { return "\(Mirror(reflecting: self).subjectType)" } public var pencilDataLength: Int { return MemoryLayout<Int32>.size } public var pencilHead: [Data] { return [Data()] } public var pencilBody: [Data] { var num: Int32 = self return [Data(buffer: UnsafeBufferPointer(start: &num, count: 1))] } public static func read(from components: Components) -> Int32? { guard let data: Data = components.dictionary["value"] as Data? else { return nil } return data.withUnsafeBytes{ $0.pointee } } } extension Int64: ReadWriteElement { public static var sPencilName: String { return "\(self)" } public var pencilName: String { return "\(Mirror(reflecting: self).subjectType)" } public var pencilDataLength: Int { return MemoryLayout<Int64>.size } public var pencilHead: [Data] { return [Data()] } public var pencilBody: [Data] { var num: Int64 = self return [Data(buffer: UnsafeBufferPointer(start: &num, count: 1))] } public static func read(from components: Components) -> Int64? { guard let data: Data = components.dictionary["value"] as Data? else { return nil } return data.withUnsafeBytes{ $0.pointee } } }
mit
2f3b37bf4b5e02b7bbd2afa82cc6a47d
23.347561
77
0.583772
4.378289
false
false
false
false
KrishMunot/swift
test/type/types.swift
3
4334
// RUN: %target-parse-verify-swift var a : Int func test() { var y : a // expected-error {{use of undeclared type 'a'}} expected-note {{here}} var z : y // expected-error {{'y' is not a type}} } var b : Int -> Int = { $0 } var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}} var d2 : () -> Int = { 4 } var d3 : () -> Float = { 4 } var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}} var e0 : [Int] e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>), (Range<Self.Index>)}} var f0 : [Float] var f1 : [(Int,Int)] var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}} var h0 : Int? _ = h0 == nil // no-warning var h1 : Int?? _ = h1! == nil // no-warning var h2 : [Int?] var h3 : [Int]? var h3a : [[Int?]] var h3b : [Int?]? var h4 : ([Int])? var h5 : ([([[Int??]])?])? var h7 : (Int,Int)? var h8 : (Int -> Int)? var h9 : Int? -> Int? var h10 : Int?.Type?.Type var i = Int?(42) var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' is only valid in parameter lists}} func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' is only valid in parameter lists}} // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work func test_array_construct<T>(_: T) { _ = [T]() // 'T' is a local name _ = [Int]() // 'Int is a global name' _ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name. _ = [UnsafeMutablePointer<Int?>]() // Nesting. _ = [([UnsafeMutablePointer<Int>])]() _ = [(String, Float)]() } extension Optional { init() { self = .none } } // <rdar://problem/15295763> default constructing an optional fails to typecheck func test_optional_construct<T>(_: T) { _ = T?() // Local name. _ = Int?() // Global name _ = (Int?)() // Parenthesized name. } // Test disambiguation of generic parameter lists in expression context. struct Gen<T> {} var y0 : Gen<Int?> var y1 : Gen<Int??> var y2 : Gen<[Int?]> var y3 : Gen<[Int]?> var y3a : Gen<[[Int?]]> var y3b : Gen<[Int?]?> var y4 : Gen<([Int])?> var y5 : Gen<([([[Int??]])?])?> var y7 : Gen<(Int,Int)?> var y8 : Gen<(Int -> Int)?> var y8a : Gen<[[Int]? -> Int]> var y9 : Gen<Int? -> Int?> var y10 : Gen<Int?.Type?.Type> var y11 : Gen<Gen<Int>?> var y12 : Gen<Gen<Int>?>? var y13 : Gen<Gen<Int?>?>? var y14 : Gen<Gen<Int?>>? var y15 : Gen<Gen<Gen<Int?>>?> var y16 : Gen<Gen<Gen<Int?>?>> var y17 : Gen<Gen<Gen<Int?>?>>? var z0 = Gen<Int?>() var z1 = Gen<Int??>() var z2 = Gen<[Int?]>() var z3 = Gen<[Int]?>() var z3a = Gen<[[Int?]]>() var z3b = Gen<[Int?]?>() var z4 = Gen<([Int])?>() var z5 = Gen<([([[Int??]])?])?>() var z7 = Gen<(Int,Int)?>() var z8 = Gen<(Int -> Int)?>() var z8a = Gen<[[Int]? -> Int]>() var z9 = Gen<Int? -> Int?>() var z10 = Gen<Int?.Type?.Type>() var z11 = Gen<Gen<Int>?>() var z12 = Gen<Gen<Int>?>?() var z13 = Gen<Gen<Int?>?>?() var z14 = Gen<Gen<Int?>>?() var z15 = Gen<Gen<Gen<Int?>>?>() var z16 = Gen<Gen<Gen<Int?>?>>() var z17 = Gen<Gen<Gen<Int?>?>>?() y0 = z0 y1 = z1 y2 = z2 y3 = z3 y3a = z3a y3b = z3b y4 = z4 y5 = z5 y7 = z7 y8 = z8 y8a = z8a y9 = z9 y10 = z10 y11 = z11 y12 = z12 y13 = z13 y14 = z14 y15 = z15 y16 = z16 y17 = z17 // Type repr formation. // <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr) let tupleTypeWithNames = (age:Int, count:Int)(4, 5) let dictWithTuple = [String: (age:Int, count:Int)]() // <rdar://problem/21684837> typeexpr not being formed for postfix ! let bb2 = [Int!](repeating: nil, count: 2) // <rdar://problem/21560309> inout allowed on function return type func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' is only valid in parameter lists}} r21560309 { x in x } // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties class r21949448 { var myArray: inout [Int] = [] // expected-error {{'inout' is only valid in parameter lists}} }
apache-2.0
4b606457857a965c8bc9adb2ab01f0fc
26.605096
146
0.594832
2.753494
false
false
false
false
waltflanagan/AdventOfCode
2015/AOC9.playground/Contents.swift
1
2713
//: Playground - noun: a place where people can play import UIKit let input = ["Faerun to Norrath = 129", "Faerun to Tristram = 58", "Faerun to AlphaCentauri = 13", "Faerun to Arbre = 24", "Faerun to Snowdin = 60", "Faerun to Tambi = 71", "Faerun to Straylight = 67", "Norrath to Tristram = 142", "Norrath to AlphaCentauri = 15", "Norrath to Arbre = 135", "Norrath to Snowdin = 75", "Norrath to Tambi = 82", "Norrath to Straylight = 54", "Tristram to AlphaCentauri = 118", "Tristram to Arbre = 122", "Tristram to Snowdin = 103", "Tristram to Tambi = 49", "Tristram to Straylight = 97", "AlphaCentauri to Arbre = 116", "AlphaCentauri to Snowdin = 12", "AlphaCentauri to Tambi = 18", "AlphaCentauri to Straylight = 91", "Arbre to Snowdin = 129", "Arbre to Tambi = 53", "Arbre to Straylight = 40", "Snowdin to Tambi = 15", "Snowdin to Straylight = 99", "Tambi to Straylight = 70"] class City { let name: String var connections = [City:Int] () init(name:String) { self.name = name } func distanceTo(city: City) -> Int { return connections[city]! } func addConnection(city: City, weight: Int) { connections[city] = weight } } extension City: Hashable { var hashValue: Int { return name.hashValue } } extension City: Equatable { } func ==(lhs: City, rhs: City) -> Bool { return lhs.name == rhs.name } struct Path { var cities = [City]() var weight = 0 mutating func visitCity(city: City) { if cities.count > 0 { weight += cities.last!.distanceTo(city) } cities.append(city) } } class Map { var paths = [Path]() var cities = [String:City]() init(strings: [String]) { for entry in strings { let components = entry.componentsSeparatedByString(" ") let city1 = cityNamed(components[0]) let city2 = cityNamed(components[2]) let value = Int(components[4])! city1.addConnection(city2, weight: value) city2.addConnection(city1, weight: value) } } func cityNamed(name:String) -> City { if let city = cities[name] { return city } else { let city = City(name: name) cities[name] = city return city } } func run() { var paths = [Path]() for city in cities { let path = Path() path.visitCity(city) } } }
mit
cdbfa34ad9080fcd55a9281e2f5e7906
20.195313
67
0.532252
3.627005
false
false
false
false
pinterest/tulsi
src/TulsiGenerator/LocalizedMessageLogger.swift
2
3617
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Provides functionality to log messages using a localized string table. class LocalizedMessageLogger { /// Structure representing a logging session in process. struct LogSessionHandle { /// A name for this process, visible to the user via logging. let name: String /// When this logging session began. var startTime: Date /// Additional contextual information about this logging session, to be visible via logging. let context: String? init(_ name: String, context: String?) { self.name = name self.startTime = Date() self.context = context } /// Reset the start time for this logging session to the moment when method was called. mutating func resetStartTime() { startTime = Date() } } let bundle: Bundle? init(bundle: Bundle?) { self.bundle = bundle } func startProfiling(_ name: String, message: String? = nil, context: String? = nil) -> LogSessionHandle { if let concreteMessage = message { syslogMessage(concreteMessage, context: context) } return LogSessionHandle(name, context: context) } func logProfilingEnd(_ token: LogSessionHandle) { let timeTaken = Date().timeIntervalSince(token.startTime) syslogMessage(String(format: "** Completed %@ in %.4fs", token.name, timeTaken), context: token.context) } func error(_ key: String, comment: String, details: String? = nil, context: String? = nil, values: CVarArg...) { if bundle == nil { return } let formatString = NSLocalizedString(key, bundle: self.bundle!, comment: comment) let message = String(format: formatString, arguments: values) LogMessage.postError(message, details: details, context: context) } func warning(_ key: String, comment: String, details: String? = nil, context: String? = nil, values: CVarArg...) { if bundle == nil { return } let formatString = NSLocalizedString(key, bundle: self.bundle!, comment: comment) let message = String(format: formatString, arguments: values) LogMessage.postWarning(message, details: details, context: context) } func infoMessage(_ message: String, details: String? = nil, context: String? = nil) { LogMessage.postInfo(message, details: details, context: context) } func syslogMessage(_ message: String, details: String? = nil, context: String? = nil) { LogMessage.postSyslog(message, details: details, context: context) } func debugMessage(_ message: String, details: String? = nil, context: String? = nil) { LogMessage.postDebug(message, details: details, context: context) } static func bugWorthyComment(_ comment: String) -> String { return "\(comment). The resulting project will most likely be broken. A bug should be reported." } }
apache-2.0
5a0705f7993abb635249c69ef692eab8
33.778846
100
0.660492
4.504359
false
false
false
false
xin-wo/kankan
kankan/kankan/Class/Mine/Controller/LoginViewController.swift
1
2830
// // LoginViewController.swift // kankan // // Created by Xin on 16/11/9. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit class PassViewController: UIViewController, WXNavigationProtocol { var faceView: LoginView! override func viewDidLoad() { super.viewDidLoad() configUI() } func showAlert(msg: String) { let alert = UIAlertController(title: "温馨提醒", message: msg, preferredStyle: .Alert) let action = UIAlertAction(title: "确定", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } func configUI() { self.view.backgroundColor = UIColor.whiteColor() faceView = NSBundle.mainBundle().loadNibNamed("LoginView", owner: nil, options: nil).last as! LoginView faceView.frame = CGRect(x: 0, y: 64, width: screenWidth, height: screenHeight-64) faceView.closure = { [unowned self] (name, password) in if name == "" || password == "" { let alert = UIAlertController(title: "温馨提醒", message: "用户名或密码不能为空", preferredStyle: .Alert) let action = UIAlertAction(title: "确定", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } else { let error = EMClient.sharedClient().loginWithUsername(self.faceView.userNameField.text, password: self.faceView.passwordField.text) if error != nil { self.showAlert(error.errorDescription) } else { // EMClient.sharedClient().options.isAutoLogin = true let mineVC = MineViewController() mineVC.hasLogin = true mineVC.desText = "您尚未开通看看会员" mineVC.titleText = name // mineVC.userImage = self.faceView.userImage.image self.navigationController?.pushViewController(mineVC, animated: true) } } } self.view.addSubview(faceView) addBottomImage() addTitle("登录") addBarButton("注册", postion: .right, select: #selector(registerBtn)) addBarButton(imageName: "app_nav_back_normal", bgImageName: "app_nav_back_clicked", postion: .left, select: #selector(backAction)) } func registerBtn() { let registerVC = SigninViewController() navigationController?.pushViewController(registerVC, animated: true) } func backAction() { self.navigationController?.popViewControllerAnimated(true) } }
mit
44c29ef5524ae2112fddc257822337cf
36.712329
147
0.595714
4.738382
false
false
false
false
marinehero/Localize-Swift
examples/LanguageSwitch/Sample/ViewController.swift
1
2644
// // ViewController.swift // Sample // // Created by Roy Marmelstein on 05/08/2015. // Copyright (c) 2015 Roy Marmelstein. All rights reserved. // import UIKit import Localize_Swift class ViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var changeButton: UIButton! @IBOutlet weak var resetButton: UIButton! var actionSheet: UIAlertController! let availableLanguages = Localize.availableLanguages() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.setText() } // Add an observer for LCLLanguageChangeNotification on viewWillAppear. This is posted whenever a language changes and allows the viewcontroller to make the necessary UI updated. Very useful for places in your app when a language change might happen. override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "setText", name: LCLLanguageChangeNotification, object: nil) } // Remove the LCLLanguageChangeNotification on viewWillDisappear override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Localized Text func setText(){ textLabel.text = "Hello world".localized(); changeButton.setTitle("Change".localized(), forState: UIControlState.Normal) resetButton.setTitle("Reset".localized(), forState: UIControlState.Normal) } // MARK: IBActions @IBAction func doChangeLanguage(sender: AnyObject) { actionSheet = UIAlertController(title: nil, message: "Switch Language", preferredStyle: UIAlertControllerStyle.ActionSheet) for language in availableLanguages { let displayName = Localize.displayNameForLanguage(language) let languageAction = UIAlertAction(title: displayName, style: .Default, handler: { (alert: UIAlertAction!) -> Void in Localize.setCurrentLanguage(language) }) actionSheet.addAction(languageAction) } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (alert: UIAlertAction) -> Void in }) actionSheet.addAction(cancelAction) self.presentViewController(actionSheet, animated: true, completion: nil) } @IBAction func doResetLanguage(sender: AnyObject) { Localize.resetCurrentLanaguageToDefault() } }
mit
e1f43f1de8da03a1f3ff135cf2422423
35.722222
254
0.691755
5.352227
false
false
false
false
devpunk/velvet_room
Source/View/Home/VHomeListCell.swift
1
2944
import UIKit final class VHomeListCell:UICollectionViewCell { private weak var imageView:UIImageView! private weak var label:UILabel! private weak var layoutImageWidth:NSLayoutConstraint! private let kLabelMarginLeft:CGFloat = 10 private let kLabelMarginRight:CGFloat = -15 private let kLabelHeight:CGFloat = 40 private let kAlphaSelected:CGFloat = 0.2 private let kAlphaNotSelected:CGFloat = 1 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.white let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.clipsToBounds = true self.imageView = imageView let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 self.label = label addSubview(imageView) addSubview(label) NSLayoutConstraint.equalsVertical( view:imageView, toView:self) NSLayoutConstraint.leftToLeft( view:imageView, toView:self) layoutImageWidth = NSLayoutConstraint.width( view:imageView) NSLayoutConstraint.topToTop( view:label, toView:self) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.leftToRight( view:label, toView:imageView, constant:kLabelMarginLeft) NSLayoutConstraint.rightToRight( view:label, toView:self, constant:kLabelMarginRight) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let height:CGFloat = bounds.height layoutImageWidth.constant = height super.layoutSubviews() } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { imageView.alpha = kAlphaSelected label.alpha = kAlphaSelected } else { imageView.alpha = kAlphaNotSelected label.alpha = kAlphaNotSelected } } //MARK: internal func config(model:MHomeSaveDataItem) { hover() imageView.image = model.thumbnail label.attributedText = model.shortDescr } }
mit
df708a75bc38bd91ad86289d7519286b
24.6
67
0.593071
5.78389
false
false
false
false
Molbie/Outlaw-SpriteKit
Sources/OutlawSpriteKit/Enums/SKRepeatMode+String.swift
1
993
// // SKRepeatMode+String.swift // OutlawSpriteKit // // Created by Brian Mullen on 12/16/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import SpriteKit public extension SKRepeatMode { struct StringValues { public static let clamp = "clamp" public static let loop = "loop" } private typealias strings = SKRepeatMode.StringValues } public extension SKRepeatMode { init?(stringValue: String) { switch stringValue.lowercased() { case strings.clamp: self = .clamp case strings.loop: self = .loop default: return nil } } var stringValue: String { let result: String switch self { case .clamp: result = strings.clamp case .loop: result = strings.loop @unknown default: fatalError() } return result } }
mit
6731bd076f305e663e40237a454a9075
21.044444
57
0.53629
4.769231
false
false
false
false
TheBudgeteers/CartTrackr
CartTrackr/CartTrackr/ModifyViewController.swift
1
4206
// // ModifyViewController.swift // CartTrackr // // Created by Christina Lee on 4/10/17. // Copyright © 2017 Christina Lee. All rights reserved. // import UIKit class ModifyViewController: UIViewController { var item : Item! @IBOutlet weak var priceText: UITextField! @IBOutlet weak var descriptionText: UITextField! @IBOutlet weak var quantityText: UITextField! override func viewDidLoad() { super.viewDidLoad() //Sets the delegate for the text fields self.priceText.delegate = self self.descriptionText.delegate = self self.quantityText.delegate = self //Allows editing of the text fields self.priceText.allowsEditingTextAttributes = true self.descriptionText.allowsEditingTextAttributes = true self.quantityText.allowsEditingTextAttributes = true //Adds observer to change text to currency format priceText.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged) //Makes Price initial selected text priceText.becomeFirstResponder() //Sets the value of the text fields to the selected item's values self.priceText.text = String("$\(self.item.price)") self.descriptionText.text = self.item.description self.quantityText.text = String(self.item.quantity) //Listens for tap gesture to end editing let tapRecognizer = UITapGestureRecognizer() tapRecognizer.addTarget(self, action: #selector(ModifyViewController.didTapView)) self.view.addGestureRecognizer(tapRecognizer) } //Ends editing when called func didTapView(){ self.view.endEditing(true) } //Makes text input currency format func myTextFieldDidChange(_ textField: UITextField) { if let amountString = priceText.text?.currencyInputFormatting() { priceText.text = amountString } } //Handles segue back to CartView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == CartViewController.identifier { guard segue.destination is CartViewController else { return } } } //Dismisses view when Back button is pressed @IBAction func goBackButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } //Updates the values on the current item with the new values in the text fields @IBAction func addToCartButton(_ sender: Any) { if let priceWithSign = priceText.text, let price = priceWithSign.components(separatedBy: "$").last, let description = descriptionText.text, let quantity = quantityText.text { item.price = price item.description = description item.quantity = quantity item.cost = (Float(price)! * Float(quantity)!) } performSegue(withIdentifier: CartViewController.identifier, sender: nil) } } //MARK: UITextFieldDelegate extension ModifyViewController: UITextFieldDelegate { @available(iOS 10.0, *) func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { print("END") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(_ textField: UITextField) { switch textField { case priceText: priceText.selectedTextRange = priceText.textRange(from: priceText.beginningOfDocument, to: priceText.endOfDocument) break; case descriptionText: descriptionText.selectedTextRange = descriptionText.textRange(from: descriptionText.beginningOfDocument, to: descriptionText.endOfDocument) break; case quantityText: quantityText.selectedTextRange = quantityText.textRange(from: quantityText.beginningOfDocument, to: quantityText.endOfDocument) break; default: break; } } }
mit
5361f2397f51614909f5921cb7c303b1
32.64
151
0.659929
5.191358
false
false
false
false
STMicroelectronics-CentralLabs/BlueSTSDK_iOS
BlueSTSDK/BlueSTSDK/Features/BlueSTSDKFeatureMotionAlgorithm.swift
1
5745
/******************************************************************************* * COPYRIGHT(c) 2018 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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 Foundation public class BlueSTSDKFeatureMotionAlogrithm : BlueSTSDKFeature{ private static let FEATURE_NAME = "MotionAlogrithm"; private static let FIELDS:[BlueSTSDKFeatureField] = [ BlueSTSDKFeatureField(name: "Type", unit: nil, type: .uInt8, min: NSNumber(value: 0), max: NSNumber(value:UInt8.max)), BlueSTSDKFeatureField(name: "Result", unit: nil, type: .uInt8, min: NSNumber(value: 0), max: NSNumber(value:UInt8.max)), ]; public enum Algorithm : UInt8, CaseIterable { public typealias RawValue = UInt8 case none = 0x00 case poseEstimation = 0x01 case deskTypeDetection = 0x02 case verticalContext = 0x03 } public enum PoseEstimation : UInt8, CaseIterable{ public typealias RawValue = UInt8 case unknown = 0x00 case sitting = 0x01 case standing = 0x02 case layingDown = 0x03 } public enum VerticalContext: UInt8, CaseIterable{ public typealias RawValue = UInt8 case unknown = 0x00 case floor = 0x01 case upDown = 0x02 case stairs = 0x03 case elevator = 0x04 case escalator = 0x05 } public enum DeskTypeDetection : UInt8, CaseIterable{ public typealias RawValue = UInt8 case unknown = 0x00 case sittingDesk = 0x01 case standingDesk = 0x02 } public static func getAlgorithmType(_ sample:BlueSTSDKFeatureSample)->Algorithm?{ guard sample.data.count > 0 else{ return nil } return Algorithm(rawValue: sample.data[0].uint8Value) } public static func getVerticalContext(_ sample:BlueSTSDKFeatureSample) -> VerticalContext?{ guard getAlgorithmType(sample) == .verticalContext && sample.data.count > 1 else{ return nil } return VerticalContext(rawValue: sample.data[1].uint8Value) } public static func getPoseEstimation( _ sample:BlueSTSDKFeatureSample) -> PoseEstimation?{ guard getAlgorithmType(sample) == .poseEstimation && sample.data.count > 1 else{ return nil } return PoseEstimation(rawValue: sample.data[1].uint8Value) } public static func getDetectedDeskType( _ sample:BlueSTSDKFeatureSample) -> DeskTypeDetection?{ guard getAlgorithmType(sample) == .deskTypeDetection && sample.data.count > 1 else{ return nil } return DeskTypeDetection(rawValue: sample.data[1].uint8Value) } public override func getFieldsDesc() -> [BlueSTSDKFeatureField] { return BlueSTSDKFeatureMotionAlogrithm.FIELDS; } public override init(whitNode node: BlueSTSDKNode) { super.init(whitNode: node, name: BlueSTSDKFeatureMotionAlogrithm.FEATURE_NAME) } public func enableAlgorithm(_ algo:Algorithm){ write(Data([algo.rawValue])) } public override func extractData(_ timestamp: UInt64, data: Data, dataOffset offset: UInt32) -> BlueSTSDKExtractResult { let intOffset = Int(offset) if((data.count-intOffset) < 2){ NSException(name: NSExceptionName(rawValue: "Invalid data"), reason: "There are no 2 bytes available to read", userInfo: nil).raise() return BlueSTSDKExtractResult(whitSample: nil, nReadData: 0) } let algoId = data[intOffset] let algoResultId = data[intOffset+1] let sample = BlueSTSDKFeatureSample(timestamp: timestamp, data: [ NSNumber(value: algoId), NSNumber(value: algoResultId)]) return BlueSTSDKExtractResult(whitSample: sample, nReadData: 2) } }
bsd-3-clause
4386793a20acfce78a006ff45e55640a
40.934307
99
0.626632
4.927101
false
false
false
false
sschiau/swift-package-manager
Sources/PackageModel/PackageModel+Codable.swift
1
7145
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2018 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 Swift project authors */ import Foundation extension ProductType: Codable { private enum CodingKeys: String, CodingKey { case library, executable, test } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .library(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .library) try unkeyedContainer.encode(a1) case .executable: try container.encodeNil(forKey: .executable) case .test: try container.encodeNil(forKey: .test) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .library: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(ProductType.LibraryType.self) self = .library(a1) case .test: self = .test case .executable: self = .executable } } } extension SystemPackageProviderDescription: Codable { private enum CodingKeys: String, CodingKey { case brew, apt } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .brew(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .brew) try unkeyedContainer.encode(a1) case let .apt(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .apt) try unkeyedContainer.encode(a1) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .brew: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .brew(a1) case .apt: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .apt(a1) } } } extension PackageDependencyDescription.Requirement: Codable { private enum CodingKeys: String, CodingKey { case exact, range, revision, branch, localPackage } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .exact(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .exact) try unkeyedContainer.encode(a1) case let .range(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .range) try unkeyedContainer.encode(a1) case let .revision(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .revision) try unkeyedContainer.encode(a1) case let .branch(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .branch) try unkeyedContainer.encode(a1) case .localPackage: try container.encodeNil(forKey: .localPackage) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .exact: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(Version.self) self = .exact(a1) case .range: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(Range<Version>.self) self = .range(a1) case .revision: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) self = .revision(a1) case .branch: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) self = .branch(a1) case .localPackage: self = .localPackage } } } extension TargetDescription.Dependency: Codable { private enum CodingKeys: String, CodingKey { case target, product, byName } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .target(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .target) try unkeyedContainer.encode(a1) case let .product(a1, a2): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .product) try unkeyedContainer.encode(a1) try unkeyedContainer.encode(a2) case let .byName(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .byName) try unkeyedContainer.encode(a1) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .target: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) self = .target(name: a1) case .product: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) let a2 = try unkeyedValues.decodeIfPresent(String.self) self = .product(name: a1, package: a2) case .byName: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(String.self) self = .byName(name: a1) } } }
apache-2.0
d159ebff0af2ceb93791f946bd719c8e
38.916201
133
0.639468
4.703752
false
false
false
false
FordDev/sdl_ios
SmartDeviceLinkSwift/SDLLog.swift
1
6340
// // SDLLog.swift // SmartDeviceLink-iOS // // Created by Joel Fischer on 3/2/17. // Copyright © 2017 smartdevicelink. All rights reserved. // import Foundation import SmartDeviceLink /// You may use this class or the below functions for convenience logging in Swift 3 projects. /// It would be used like so: /// /// ``` /// let log = SDLLog.self /// log.e("Test something \(NSDate())") /// ``` public class SDLLog { /// Log a verbose message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public class func v(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .verbose, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log a debug message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public class func d(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .debug, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log a warning message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public class func w(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .warning, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log an error message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public class func e(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .error, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } } /// Log a verbose message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public func SDLV(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .verbose, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log a debug message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public func SDLD(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .debug, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log a warning message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public func SDLW(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .warning, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } /// Log an error message through SDL's custom logging framework. /// /// - Parameters: /// - message: The message to be logged. /// - file: The file the log is coming from, you should probably leave this as the default. /// - function: The function the log is coming from, you should probably leave this as the default. /// - line: The line the log is coming from, you should probably leave this as the default. public func SDLE(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { SDLLogManager.log(with: .error, timestamp: Date(), file: file, functionName: function, line: line, queue: logQueue(), message: "\(message())") } private func logQueue() -> String { return String(cString: __dispatch_queue_get_label(nil), encoding: .utf8) ?? "" }
bsd-3-clause
35ddfb9d5a6d61cbee9b671349e1eec5
55.097345
152
0.665089
3.939714
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Districts/DistrictsContainerViewController.swift
1
3624
import CoreData import Firebase import Foundation import MyTBAKit import TBAData import TBAKit import UIKit class DistrictsContainerViewController: ContainerViewController { private let myTBA: MyTBA private let statusService: StatusService private let urlOpener: URLOpener private(set) var year: Int { didSet { districtsViewController.year = year updateInterface() } } private(set) var districtsViewController: DistrictsViewController // MARK: - Init init(myTBA: MyTBA, statusService: StatusService, urlOpener: URLOpener, dependencies: Dependencies) { self.myTBA = myTBA self.statusService = statusService self.urlOpener = urlOpener year = statusService.currentSeason districtsViewController = DistrictsViewController(year: year, dependencies: dependencies) super.init(viewControllers: [districtsViewController], navigationTitle: "Districts", navigationSubtitle: ContainerViewController.yearSubtitle(year), dependencies: dependencies) title = RootType.districts.title tabBarItem.image = RootType.districts.icon navigationTitleDelegate = self districtsViewController.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle // MARK: - Private Methods private func updateInterface() { navigationSubtitle = ContainerViewController.yearSubtitle(year) } } extension DistrictsContainerViewController: NavigationTitleDelegate { func navigationTitleTapped() { let selectTableViewController = SelectTableViewController<DistrictsContainerViewController>(current: year, options: Array(2009...statusService.maxSeason).reversed(), dependencies: dependencies) selectTableViewController.title = "Select Year" selectTableViewController.delegate = self let nav = UINavigationController(rootViewController: selectTableViewController) nav.modalPresentationStyle = .formSheet nav.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSelectYear)) navigationController?.present(nav, animated: true, completion: nil) } @objc private func dismissSelectYear() { navigationController?.dismiss(animated: true, completion: nil) } } extension DistrictsContainerViewController: SelectTableViewControllerDelegate { typealias OptionType = Int func optionSelected(_ option: OptionType) { year = option } func titleForOption(_ option: OptionType) -> String { return String(option) } } extension DistrictsContainerViewController: DistrictsViewControllerDelegate { func districtSelected(_ district: District) { // Show detail wrapped in a UINavigationController for our split view controller let districtViewController = DistrictViewController(district: district, myTBA: myTBA, statusService: statusService, urlOpener: urlOpener, dependencies: dependencies) if let splitViewController = splitViewController { let navigationController = UINavigationController(rootViewController: districtViewController) splitViewController.showDetailViewController(navigationController, sender: nil) } else if let navigationController = navigationController { navigationController.pushViewController(districtViewController, animated: true) } } }
mit
0686897d82c1b3334ff79c5666c4c615
32.869159
201
0.724338
5.817014
false
false
false
false
Virpik/T
src/Foundation/Json/Json.swift
1
1343
// // JsonOperators.swift // ecm // // Created by Virpik on 10/04/2017. // Copyright © 2017 Virpik. All rights reserved. // import Foundation public typealias Json = [String: Any] /** precedencegroup MultiplicationPrecedence { associativity: left higherThan: AdditionPrecedence } infix operator <<~ : MultiplicationPrecedence public func <<= <T> (left: [AnyHashable: Any], right: AnyHashable) -> T? { return left[right] as? T } infix operator <=- : MultiplicationPrecedence infix operator -=> : MultiplicationPrecedence public func <=- <T: JsonInital> (left: Json, right: String) -> [T] { if let tmp = left[right] as? [Json] { return tmp.map { T(json: $0) } } return [] } public func <=- <T: JsonInital> (left: Json, right: String) -> T? { if let tmp = left[right] as? Json { return T(json: tmp) } return nil } public func <=- <T> (left: Json, right: String) -> T? { return left[right] as? T } public func <=- <T> (left: Json?, right: String) -> T? { return left?[right] as? T } //func -=> <T> (left: (value: T, key: String), right: Json) { // var right = right // right[left.key] = left.value //} // //func -=> <T> (left: (value: T?, key: String), right: Json) { // if let value = left.value { // (value, left.key) -=> right // } //} */
mit
10cd893fbff86826f2b53fcdd3dc7a6a
21
74
0.591654
3.195238
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Extensions/String+Extensions.swift
1
1086
// // String+Extensions.swift // ScoreReporter // // Created by Bradley Smith on 7/19/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation public extension String { func matching(regexPattern: String) -> String? { var strings = [String]() do { let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive) let options: NSRegularExpression.MatchingOptions = .reportProgress let range = NSRange(location: 0, length: (self as NSString).length) regex.enumerateMatches(in: self, options: options, range: range) { (result: NSTextCheckingResult?, _, _) in if let result = result { let match = (self as NSString).substring(with: result.range) strings.append(match) } } return strings.first } catch let error { print("Failed to create regular expression with pattern: \(regexPattern) error: \(error)") return nil } } }
mit
57c280d2324c5c77df216d84a141e707
30
119
0.589862
4.822222
false
false
false
false
zjjzmw1/SwiftCodeFragments
Pods/ImageViewer/ImageViewer/Source/Extensions/UIButton.swift
1
4920
// // UIButton.swift // ImageViewer // // Created by Kristian Angyal on 28/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit extension UIButton { static func circlePlayButton(_ diameter: CGFloat) -> UIButton { let button = UIButton(type: UIButtonType.custom) button.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: diameter, height: diameter)) let circleImageNormal = CAShapeLayer.circlePlayShape(UIColor.white, diameter: diameter).toImage() button.setImage(circleImageNormal, for: UIControlState()) let circleImageHighlighted = CAShapeLayer.circlePlayShape(UIColor.lightGray, diameter: diameter).toImage() button.setImage(circleImageHighlighted, for: UIControlState.highlighted) return button } static func replayButton(width: CGFloat, height: CGFloat) -> UIButton { let smallerEdge = min(width, height) let triangleEdgeLength: CGFloat = min(smallerEdge, 20) let button = UIButton(type: UIButtonType.custom) button.bounds.size = CGSize(width: width, height: height) button.contentHorizontalAlignment = .center let playShapeNormal = CAShapeLayer.playShape(UIColor.red, triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeNormal, for: UIControlState()) let playShapeHighlighted = CAShapeLayer.playShape(UIColor.red.withAlphaComponent(0.7), triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeHighlighted, for: UIControlState.highlighted) ///the geometric center of equilateral triangle is not the same as the geometric center of its smallest bounding rect. There is some offset between the two centers to the left when the triangle points to the right. We have to shift the triangle to the right by that offset. let altitude = (sqrt(3) / 2) * triangleEdgeLength let innerCircleDiameter = (sqrt(3) / 6) * triangleEdgeLength button.imageEdgeInsets.left = altitude / 2 - innerCircleDiameter return button } static func playButton(width: CGFloat, height: CGFloat) -> UIButton { let smallerEdge = min(width, height) let triangleEdgeLength: CGFloat = min(smallerEdge, 20) let button = UIButton(type: UIButtonType.custom) button.bounds.size = CGSize(width: width, height: height) button.contentHorizontalAlignment = .center let playShapeNormal = CAShapeLayer.playShape(UIColor.white, triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeNormal, for: UIControlState()) let playShapeHighlighted = CAShapeLayer.playShape(UIColor.white.withAlphaComponent(0.7), triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeHighlighted, for: UIControlState.highlighted) ///the geometric center of equilateral triangle is not the same as the geometric center of its smallest bounding rect. There is some offset between the two centers to the left when the triangle points to the right. We have to shift the triangle to the right by that offset. let altitude = (sqrt(3) / 2) * triangleEdgeLength let innerCircleDiameter = (sqrt(3) / 6) * triangleEdgeLength button.imageEdgeInsets.left = altitude / 2 - innerCircleDiameter return button } static func pauseButton(width: CGFloat, height: CGFloat) -> UIButton { let button = UIButton(type: UIButtonType.custom) button.contentHorizontalAlignment = .center let elementHeight = min(20, height) let elementSize = CGSize(width: elementHeight * 0.3, height: elementHeight) let distance: CGFloat = elementHeight * 0.2 let pauseImageNormal = CAShapeLayer.pauseShape(UIColor.white, elementSize: elementSize, elementDistance: distance).toImage() button.setImage(pauseImageNormal, for: UIControlState()) let pauseImageHighlighted = CAShapeLayer.pauseShape(UIColor.white.withAlphaComponent(0.7), elementSize: elementSize, elementDistance: distance).toImage() button.setImage(pauseImageHighlighted, for: UIControlState.highlighted) return button } static func closeButton() -> UIButton { let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 50, height: 50))) button.setImage(UIImage(named: "close_normal"), for: UIControlState()) button.setImage(UIImage(named: "close_highlighted"), for: UIControlState.highlighted) return button } static func thumbnailsButton() -> UIButton { let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 80, height: 50))) button.setTitle("See All", for: UIControlState()) //button.titleLabel?.textColor = UIColor.redColor() return button } }
mit
206f1f45c944ed2d0e5e267564a906fb
37.429688
281
0.707054
4.803711
false
false
false
false
iMetalk/TCZKit
TCZKitDemo/TCZKit/Helper/TCZCancelableTask.swift
1
856
// // TCZCancelableTask.swift // Dormouse // // Created by 武卓 on 2017/8/23. // Copyright © 2017年 WangSuyan. All rights reserved. // import Foundation public typealias CancelableTask = (_ cancel: Bool) -> Void /// 延迟 public func delay(time: TimeInterval, work: @escaping ()->()) -> CancelableTask? { var finalTask: CancelableTask? let cancelableTask: CancelableTask = { cancel in if cancel { finalTask = nil // key } else { DispatchQueue.main.async(execute: work) } } finalTask = cancelableTask DispatchQueue.main.asyncAfter(deadline: .now() + time) { if let task = finalTask { task(false) } } return finalTask } public func cancel(cancelableTask: CancelableTask?) { cancelableTask?(true) }
mit
3339736774cd20253da3f53bb4069a88
19.609756
82
0.594083
4.28934
false
false
false
false
larryhou/swift
SpriteKit/SpriteKit/ViewController.swift
1
2655
// // ViewController.swift // SpriteKit // // Created by larryhou on 5/18/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit import SpriteKit class ViewController: UIViewController, XMLReaderDelegate { private var _actions: [NinjaActionInfo]! private var _scene: SKScene! private var _ninja: NinjaPresenter! private var _assets: [String]! private var _index: Int = 0 override func viewDidLoad() { super.viewDidLoad() var skView = SKView(frame: self.view.frame) skView.frameInterval = 2 skView.showsNodeCount = true skView.showsFPS = true _scene = SKScene(size: skView.frame.size) _scene.backgroundColor = UIColor.grayColor() _scene.anchorPoint = CGPoint(x: 0.5, y: 0.5) _scene.scaleMode = SKSceneScaleMode.ResizeFill skView.presentScene(_scene) _assets = ["10000101", "10000201", "10000301", "10000501", "11000141", "11000171"] _index = 0 self.view.addSubview(skView) var tap: UITapGestureRecognizer tap = UITapGestureRecognizer() tap.addTarget(self, action: "playNextNinjaAction") view.addGestureRecognizer(tap) tap = UITapGestureRecognizer() tap.numberOfTapsRequired = 2 tap.addTarget(self, action: "changeToAnotherNinja") view.addGestureRecognizer(tap) changeToAnotherNinja() } func playNextNinjaAction() { _ninja.playNextAction() } func changeToAnotherNinja() { let url = NSBundle.mainBundle().URLForResource(_assets[_index], withExtension: "xml") if url != nil { XMLReader().read(NSData(contentsOfURL: url!)!, delegate: self) } _index++ } func readerDidFinishDocument(reader: XMLReader, data: NSDictionary, elapse: NSTimeInterval) { _actions = [] let rawActions = (data.valueForKeyPath("actions.action") as! NSArray)[0] as! NSArray for i in 0..<rawActions.count { let item = rawActions[i] as! NSDictionary var action = NinjaActionInfo(index: _actions.count, name: item["name"] as! String) action.decode(item) _actions.append(action) } if _ninja != nil { _ninja.removeAllChildren() _ninja.removeFromParent() _ninja = nil } _ninja = NinjaPresenter(atlas: SKTextureAtlas(named: _assets[_index]), actionInfos: _actions) _ninja.play(_actions[0].name) _scene.addChild(_ninja) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
acab1809ecfea5e1164e9e9864fa8a4c
27.548387
101
0.622976
4.338235
false
false
false
false
mvader/subtitler
SubtitlerTests/FileHashTest.swift
1
914
import Foundation import XCTest @testable import Subtitler class FileHashTests: XCTestCase { func file(name: String) -> String { return NSBundle(forClass: FileHashTests.self).resourcePath! + name } override func setUp() { super.setUp() let file = self.file("f1.txt") var txt = "" for _ in 1...105536 { txt += "a" } try! txt.writeToFile(file, atomically: true, encoding: NSUTF8StringEncoding) } override func tearDown() { super.tearDown() let file = self.file("f1.txt") let fileManager = NSFileManager.defaultManager() try! fileManager.removeItemAtPath(file) } func testHashFile() { let file = self.file("f1.txt") let hash = fileHash(file)! XCTAssertEqual(hash.size, 105536) XCTAssertEqual(hash.hash, "585858585859dc40") } }
mit
759aeebc772cf7786e9fce6006ea6030
25.114286
84
0.589716
4.154545
false
true
false
false
gabemdev/GMDKit
GMDKit/Classes/Date+GMDKit.swift
1
2330
// // Date+GMDKit.swift // Pods // // Created by Gabriel Morales on 3/8/17. // // import Foundation extension Date { static let formatter = DateFormatter() static func yesterday() -> Date { return Date().dateWith(daysToAdd: -1, monthsToAdd: 0) } static func today() -> Date { return Date().dateWith(daysToAdd: 0, monthsToAdd: 0).dateByZeroOutTimeComponents() } static func tomorrow() -> Date { return Date().dateWith(daysToAdd: 1, monthsToAdd: 0) } public func dateByAddingDays(days: Int) -> Date { return self.days(days: days) } public func dateBySubstractingDays(days: Int) -> Date { return self.days(days: -days) } public func days(days:Int) -> Date { return Calendar.current.date(byAdding: .day, value: days, to: Date())! } public func dateWith(daysToAdd:Int, monthsToAdd:Int) -> Date{ let gregorian = NSCalendar.current var components = DateComponents() components.day = daysToAdd components.month = monthsToAdd return gregorian.date(byAdding: components, to: self)! } public func dateByZeroOutTimeComponents() -> Date{ let calendar = Calendar(identifier: .gregorian) var components = calendar.dateComponents(Set([.year, .month, .day]), from: self) self.zeroOutTimeComponents(&components) return calendar.date(from: components)! } public func zeroOutTimeComponents( _ components:inout DateComponents) { components.hour = 0 components.minute = 0 components.second = 0 } public func timelessCompare(date:Date) -> ComparisonResult? { let date1 = self.dateByZeroOutTimeComponents() let date2 = date.dateByZeroOutTimeComponents() return date1.compare(date2) } public func isSameDayAs(_ date:Date) -> Bool { Date.formatter.dateFormat = "MM/dd/yyyy" Date.formatter.timeZone = TimeZone(identifier: "America/Chicago") let selfDateString = Date.formatter.string(from: self) let otherDateString = Date.formatter.string(from: date) return selfDateString == otherDateString } }
mit
d866653b01d50d4439b131747f21e9df
26.738095
90
0.608584
4.438095
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 10 - PokeDex/PokeDex/Pokemon.swift
1
6025
// // Pokemon.swift // PokeDex // // Created by Per Kristensen on 15/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import Foundation import Alamofire class Pokemon { fileprivate var _name: String! fileprivate var _pokedexId: Int! fileprivate var _description: String! fileprivate var _type: String! fileprivate var _defense: String! fileprivate var _height: String! fileprivate var _weight: String! fileprivate var _attack: String! fileprivate var _nextEvolutionId: String! fileprivate var _nextEvolutionName: String! fileprivate var _nextEvolutionText: String! fileprivate var _nextEvolutionLevel: String! fileprivate var _pokemonUrl: String! var name: String { return _name } var pokedexId: Int { return _pokedexId } var description: String { if _description == nil { return "" } return _description } var type: String { if _type == nil { return "" } return _type } var defense: String { if _defense == nil { return "" } return _defense } var height: String { if _height == nil { return "" } return _height } var weight: String { if _weight == nil { return "" } return _weight } var attack: String { if _attack == nil { return "" } return _attack } var nextEvolutionText: String { if _nextEvolutionText == nil { return "" } return _nextEvolutionText } var nextEvolutionId: String { if _nextEvolutionId == nil { return "" } return _nextEvolutionId } var nextEvolutionName: String { if _nextEvolutionName == nil { return "" } return _nextEvolutionName } var nextEvolutionLevel: String { if _nextEvolutionLevel == nil { return "" } return _nextEvolutionLevel } init(name: String, pokedexId: Int) { _name = name _pokedexId = pokedexId _pokemonUrl = "\(URL_BASE)\(URL_POKEMON)\(pokedexId)" } func downloadPokemonDetails(completed: @escaping DownloadComplete) { Alamofire.request(_pokemonUrl).responseJSON { response in if let dict = response.result.value as? Dictionary<String, AnyObject> { if let weight = dict["weight"] as? String { self._weight = weight } if let height = dict["height"] as? String { self._height = height } if let attack = dict["attack"] as? Int { self._attack = "\(attack)" } if let defense = dict["defense"] as? Int { self._defense = "\(defense)" } if let types = dict["types"] as? [Dictionary<String, String>] , types.count > 0 { if let name = types[0]["name"] { self._type = name.capitalized } if types.count > 1 { for x in 1..<types.count { if let name = types[x]["name"] { self._type! += "/\(name.capitalized)" } } } } else { self._type = "" } if let descArr = dict["descriptions"] as? [Dictionary<String, String>] , descArr.count > 0 { if let uri = descArr[0]["resource_uri"] { let descriptionUrl = "\(URL_BASE)\(uri)" Alamofire.request(descriptionUrl).responseJSON(completionHandler: { response in if let descriptionDict = response.result.value as? Dictionary<String, AnyObject> { if let description = descriptionDict["description"] as? String { let newDescription = description.replacingOccurrences(of: "POKMON", with: "Pokemon") self._description = newDescription } } completed() }) } } else { self._description = "" } if let evolutions = dict["evolutions"] as? [Dictionary<String, AnyObject>] , evolutions.count > 0 { if let nextEvolution = evolutions[0]["to"] as? String { if nextEvolution.range(of: "mega") == nil { self._nextEvolutionName = nextEvolution if let uri = evolutions[0]["resource_uri"] as? String { let newStr = uri.replacingOccurrences(of: "/api/v1/pokemon/", with: "") let nextEvolutionId = newStr.replacingOccurrences(of: "/", with: "") self._nextEvolutionId = nextEvolutionId } if let levelExists = evolutions[0]["level"] as? Int { self._nextEvolutionLevel = "\(levelExists)" } else { self._nextEvolutionLevel = "" } } } } } completed() } } }
mit
25c9df97ec59483e73e7122e7c77d827
30.212435
120
0.438911
5.441734
false
false
false
false
tad-iizuka/swift-sdk
Source/AlchemyDataNewsV1/Models/NewsResponse.swift
3
1358
/** * 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 Foundation import RestKit /** **NewsResponse** Response object for AlchemyDataNews */ public struct NewsResponse: JSONDecodable { /** number of transactions the service made */ public let totalTransactions: Int /** see **NewsResult** */ public let result: NewsResult? /// Used internally to initialize a NewsResponse object public init(json: JSON) throws { let status = try json.getString(at: "status") guard status == "OK" else { throw JSON.Error.valueNotConvertible(value: json, to: NewsResponse.self) } totalTransactions = try Int(json.getString(at: "totalTransactions"))! result = try? json.decode(at: "result", type: NewsResult.self) } }
apache-2.0
81249e98febdb019a36a4229373797a5
29.177778
84
0.68704
4.352564
false
false
false
false
bustosalex/productpal
productpal/ViewController.swift
1
1169
// // ViewController.swift // productpal // // Created by Francisco Mateo on 4/6/16. // Copyright © 2016 University of Wisconsin Parkisde. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Product Cell") as! CustomCell cell.itemName.text = "Cock" cell.itemImage!.image = UIImage(named: "canon") cell.returnDate.text = "5/25/16" cell.protectionDate.text = "5/25/17" cell.warranyDate.text = "12/25/16" return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
mit
4d9e1777a5b0c3fb9d13af214031f724
25.545455
107
0.65839
4.580392
false
false
false
false
roambotics/swift
test/Parse/diagnostic_missing_func_keyword.swift
3
3057
// RUN: %target-typecheck-verify-swift // https://github.com/apple/swift/issues/52877 protocol Brew { // expected-note {{in declaration of 'Brew'}} tripel() -> Int // expected-error {{expected 'func' keyword in instance method declaration}} {{3-3=func }} quadrupel: Int { get } // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} static + (lhs: Self, rhs: Self) -> Self // expected-error {{expected 'func' keyword in operator function declaration}} {{10-10=func }} * (lhs: Self, rhs: Self) -> Self // expected-error {{expected 'func' keyword in operator function declaration}} {{3-3=func }} // expected-error @-1 {{operator '*' declared in protocol must be 'static'}} {{3-3=static }} ipa: Int { get }; apa: Float { get } // expected-error @-1 {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-2 {{expected 'var' keyword in property declaration}} {{21-21=var }} stout: Int { get } porter: Float { get } // expected-error @-1 {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-2 {{expected declaration}} // expected-error @-3 {{consecutive declarations on a line must be separated by ';'}} } infix operator %% struct Bar { fisr = 0x5F3759DF // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} %%<T: Brew> (lhs: T, rhs: T) -> T { // expected-error {{expected 'func' keyword in operator function declaration}} {{3-3=func }} // expected-error @-1 {{operator '%%' declared in type 'Bar' must be 'static'}} // expected-error @-2 {{member operator '%%' must have at least one argument of type 'Bar'}} lhs + lhs + rhs + rhs } _: Int = 42 // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-1 {{property declaration does not bind any variables}} (light, dark) = (100, 200)// expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} a, b: Int // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} } class Baz { instanceMethod() {} // expected-error {{expected 'func' keyword in instance method declaration}} {{3-3=func }} static staticMethod() {} // expected-error {{expected 'func' keyword in static method declaration}} {{10-10=func }} instanceProperty: Int { 0 } // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} static staticProperty: Int { 0 } // expected-error {{expected 'var' keyword in static property declaration}} {{10-10=var }} } class C1 { class classMethod() {} // expected-error {{expected '{' in class}} } class C2 { class classProperty: Int { 0 } // expected-error {{inheritance from non-protocol, non-class type 'Int'}} // expected-note @-1 {{in declaration of 'classProperty'}} // expected-error @-2 {{expected declaration}} }
apache-2.0
00555f11ee9c124d86cc01b7df2cb8da
47.52381
136
0.622179
3.949612
false
false
false
false
ascode/JF-IOS-Swift_demos
IOSDemos/Views/SpeechSynthesizerDemoView.swift
1
2766
// // SpeechSynthesizerDemo.swift // IOSDemos // // Created by 金飞 on 28/12/2016. // Copyright © 2016 Enjia. All rights reserved. // import UIKit import AVFoundation class SpeechSynthesizerDemoView: UIView { var _delegate: SpeechSynthesizerDemoViewDelegate! var _sythesizer: AVSpeechSynthesizer! var _voice: AVSpeechSynthesisVoice! let txtSentence: UITextView = UITextView() override init(frame: CGRect) { super.init(frame: frame) let kbtnBackW: CGFloat = 36 let kbtnBackH: CGFloat = kbtnBackW let kbtnBackX: CGFloat = 15 let kbtnBackY: CGFloat = 15 let btnBack: UIButton = UIButton() btnBack.frame = CGRect(x: kbtnBackX, y: kbtnBackY, width: kbtnBackW, height: kbtnBackH) btnBack.setImage(#imageLiteral(resourceName: "btnBack"), for: UIControlState.normal) self.addSubview(btnBack) btnBack.addTarget(self, action: #selector(SpeechSynthesizerDemoView.btnBackPressed(btnObj:)), for: UIControlEvents.touchUpInside) let ktxtSentenceW: CGFloat = UIScreen.main.bounds.width let ktxtSentenceH: CGFloat = ktxtSentenceW * 0.8 let ktxtSentenceX: CGFloat = 0 let ktxtSentenceY: CGFloat = UIScreen.main.bounds.height * 0.15 txtSentence.frame = CGRect(x: ktxtSentenceX, y: ktxtSentenceY, width: ktxtSentenceW, height: ktxtSentenceH) txtSentence.text = "测试" self.addSubview(txtSentence) let kbtnPlayW: CGFloat = 36 let kbtnPlayH: CGFloat = kbtnPlayW let kbtnPlayX: CGFloat = (UIScreen.main.bounds.width - kbtnPlayW) / 2 let kbtnPlayY: CGFloat = ktxtSentenceY + ktxtSentenceH + kbtnPlayW let btnPlay: UIButton = UIButton() btnPlay.frame = CGRect(x: kbtnPlayX, y: kbtnPlayY, width: kbtnPlayW, height: kbtnPlayH) btnPlay.setImage(#imageLiteral(resourceName: "btnPlay"), for: UIControlState.normal) btnPlay.addTarget(self, action: #selector(SpeechSynthesizerDemoView.btnPlay(btnObj:)), for: UIControlEvents.touchUpInside) self.addSubview(btnPlay) self._sythesizer = AVSpeechSynthesizer() self._voice = AVSpeechSynthesisVoice(language: "zh_CN") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func btnPlay(btnObj: UIButton){ let utterance: AVSpeechUtterance = AVSpeechUtterance(string: self.txtSentence.text!) utterance.voice = self._voice utterance.rate = 0.3 self._sythesizer.speak(utterance) } func btnBackPressed(btnObj: UIButton){ self._delegate.btnBackPressed(btnObj: btnObj) } }
artistic-2.0
9192f238a3a94c4af663534689decf5a
34.805195
137
0.663402
4.404153
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Events/PennEvents.swift
1
858
// // PennEvents.swift // PennMobile // // Created by Samantha Su on 10/1/21. // Copyright © 2021 PennLabs. All rights reserved. // import Foundation struct PennEvents: Codable { static let directory = "events.json" let id: String let title: String let body: String let image: String let location: StringOrBool let category: String let path: String let start: Date? let end: Date? let starttime: String let endtime: String let allday: String var media_image: String let shortdate: String var isAllDay: Bool { return allday == "All day" } } struct StringOrBool: Codable { var value: String? init(from decoder: Decoder) throws { if let string = try? String(from: decoder) { value = string return } value = nil } }
mit
c91a668c278eb898da6b8ac80eb43c77
18.930233
52
0.612602
3.877828
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Formatters/TimestampFormatter.swift
1
3774
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit /// A formatter for converting a timestamp in milliseconds to and from a string. class TimestampFormatter: Formatter { /// Returns a string representation of the given timestamp. /// /// - Parameter timestamp: A timestamp in milliseconds. /// - Returns: A string, if the timestamp was valid. func string(fromTimestamp timestamp: Int64) -> String? { guard timestamp >= 0 else { return nil } let hours = timestamp/1000/60/60 let minutes = timestamp/1000/60 % 60 let seconds = timestamp/1000 % 60 let milliseconds = timestamp % 1000 return String(format:"%d:%02d:%02d.%03ld", hours, minutes, seconds, milliseconds) } /// Returns a timestamp in milliseconds from the given timestamp string. /// /// - Parameter timestampString: A string in the format h:mm:ss.SSS /// - Returns: A timestamp, if the string was valid. func timestamp(fromString timestampString: String) -> Int64? { let regex: NSRegularExpression do { let pattern = "^([0-9]{1,2}):([0-9]{2}):([0-9]{2}(\\.[0-9]{1,3})?)$" regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) } catch { print("[CropRangeViewController] Error creating regular expression: \(error)") return nil } let firstMatch = regex.firstMatch(in: timestampString, options: [], range: NSRange(location: 0, length: timestampString.count)) guard let match = firstMatch else { // Timestamp format is incorrect. return nil } guard let hourRange = Range(match.range(at: 1), in: timestampString), let minuteRange = Range(match.range(at: 2), in: timestampString), let secondRange = Range(match.range(at: 3), in: timestampString) else { // Timestamp format is incorrect. return nil } let hourString = String(timestampString[hourRange]) let minuteString = String(timestampString[minuteRange]) let secondString = String(timestampString[secondRange]) guard let hours = Int64(hourString), let minutes = Int64(minuteString), let seconds = Double(secondString) else { // At least one number isn't a valid Int64/Double (probably because it is too large). return nil } let millisecondsInAnHour: Int64 = 1000 * 60 * 60 let millisecondsInAMinute: Int64 = 1000 * 60 return hours * millisecondsInAnHour + minutes * millisecondsInAMinute + Int64(seconds * 1000.0) } // MARK: - Formatter override func string(for obj: Any?) -> String? { if let timestamp = obj as? Int64 { return string(fromTimestamp: timestamp) } return nil } // swiftlint:disable vertical_parameter_alignment override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { if let timestamp = timestamp(fromString: string) { obj?.pointee = timestamp as AnyObject return true } return false } // swiftlint:enable vertical_parameter_alignment }
apache-2.0
58ccb454db82618893edc9c88f6c4f6a
34.942857
97
0.673026
4.393481
false
false
false
false
tensorflow/examples
lite/examples/bert_qa/ios/BertQACore/Models/ML/BertQAHandler.swift
1
10425
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import TensorFlowLite import os /// Handles Bert model with TensorFlow Lite. final class BertQAHandler { private let interpreter: Interpreter private let dic: [String: Int32] private let tokenizer: FullTokenizer init( with modelFile: File = MobileBERT.model, threadCount: Int = InterpreterOptions.threadCount.defaultValue ) throws { os_log( "[BertQAHandler] Initialize interpreter with %d thread(s).", threadCount) // Load dictionary from vocabulary file. dic = FileLoader.loadVocabularies(from: MobileBERT.vocabulary) // Initialize `FullTokenizer` with given `dic`. tokenizer = FullTokenizer(with: dic, isCaseInsensitive: MobileBERT.doLowerCase) // Construct the path to the model file. guard let modelPath = Bundle(for: type(of: self)).path( forResource: modelFile.name, ofType: modelFile.ext) else { fatalError("Failed to load the model file: \(modelFile.description)") } // Specify the options for the `Interpreter`. var options = Interpreter.Options() options.threadCount = threadCount // Create the `Interpreter`. interpreter = try Interpreter(modelPath: modelPath, options: options) // Initialize input and output `Tensor`s. try interpreter.allocateTensors() // Get allocated input `Tensor`s. let inputIdsTensor: Tensor let inputMaskTensor: Tensor let segmentIdsTensor: Tensor inputIdsTensor = try interpreter.input(at: 0) inputMaskTensor = try interpreter.input(at: 1) segmentIdsTensor = try interpreter.input(at: 2) // Get allocated output `Tensor`s. let endLogitsTensor: Tensor let startLogitsTensor: Tensor endLogitsTensor = try interpreter.output(at: 0) startLogitsTensor = try interpreter.output(at: 1) // Check if input and output `Tensor`s are in the expected formats. guard inputIdsTensor.shape.dimensions == MobileBERT.inputDimension && inputMaskTensor.shape.dimensions == MobileBERT.inputDimension && segmentIdsTensor.shape.dimensions == MobileBERT.inputDimension else { fatalError("Unexpected model: Input Tensor shape") } guard endLogitsTensor.shape.dimensions == MobileBERT.outputDimension && startLogitsTensor.shape.dimensions == MobileBERT.outputDimension else { fatalError("Unexpected model: Output Tensor shape") } } func run(query: String, content: String) -> Result? { // MARK: - Preprocessing let (features, contentData) = preprocessing(query: query, content: content) // Convert input arrays to `Data` type. os_log("[BertQAHandler] Setting inputs..") let inputIdsData = Data(copyingBufferOf: features.inputIds) let inputMaskData = Data(copyingBufferOf: features.inputMask) let segmentIdsData = Data(copyingBufferOf: features.segmentIds) // MARK: - Inferencing let inferenceStartTime = Date() let endLogitsTensor: Tensor let startLogitsTensor: Tensor do { // Assign input `Data` to the `interpreter`. try interpreter.copy(inputIdsData, toInputAt: 0) try interpreter.copy(inputMaskData, toInputAt: 1) try interpreter.copy(segmentIdsData, toInputAt: 2) // Run inference by invoking the `Interpreter`. os_log("[BertQAHandler] Runing inference..") try interpreter.invoke() // Get the output `Tensor` to process the inference results endLogitsTensor = try interpreter.output(at: 0) startLogitsTensor = try interpreter.output(at: 1) } catch let error { os_log( "[BertQAHandler] Failed to invoke the interpreter with error: %s", type: .error, error.localizedDescription) return nil } let inferenceTime = Date().timeIntervalSince(inferenceStartTime) * 1000 // MARK: - Postprocessing os_log("[BertQAHandler] Getting answer..") let answers = postprocessing( startLogits: startLogitsTensor.data.toArray(type: Float32.self), endLogits: endLogitsTensor.data.toArray(type: Float32.self), contentData: contentData) os_log("[BertQAHandler] Finished.") guard let answer = answers.first else { return nil } return Result(answer: answer, inferenceTime: inferenceTime) } // MARK: - Private functions /// Tokenizes input query and content to `InputFeatures` and make `ContentData` to find the /// original string in the content. /// /// - Parameters: /// - query: Input query to run the model. /// - content: Input content to run the model. /// - Returns: A tuple of `InputFeatures` and `ContentData`. private func preprocessing(query: String, content: String) -> (InputFeatures, ContentData) { var queryTokens = tokenizer.tokenize(query) queryTokens = Array(queryTokens.prefix(MobileBERT.maxQueryLen)) let contentWords = content.splitByWhitespace() var contentTokenIdxToWordIdxMapping = [Int]() var contentTokens = [String]() for (i, token) in contentWords.enumerated() { tokenizer.tokenize(token).forEach { subToken in contentTokenIdxToWordIdxMapping.append(i) contentTokens.append(subToken) } } // -3 accounts for [CLS], [SEP] and [SEP]. let maxContentLen = MobileBERT.maxSeqLen - queryTokens.count - 3 contentTokens = Array(contentTokens.prefix(maxContentLen)) var tokens = [String]() var segmentIds = [Int32]() // Map token index to original index (in feature.origTokens). var tokenIdxToWordIdxMapping = [Int: Int]() // Start of generating the `InputFeatures`. tokens.append("[CLS]") segmentIds.append(0) // For query input. queryTokens.forEach { tokens.append($0) segmentIds.append(0) } // For separation. tokens.append("[SEP]") segmentIds.append(0) // For text input. for (i, docToken) in contentTokens.enumerated() { tokens.append(docToken) segmentIds.append(1) tokenIdxToWordIdxMapping[tokens.count] = contentTokenIdxToWordIdxMapping[i] } // For ending mark. tokens.append("[SEP]") segmentIds.append(1) var inputIds = tokenizer.convertToIDs(tokens: tokens) var inputMask = [Int32](repeating: 1, count: inputIds.count) while inputIds.count < MobileBERT.maxSeqLen { inputIds.append(0) inputMask.append(0) segmentIds.append(0) } let inputFeatures = InputFeatures( inputIds: inputIds, inputMask: inputMask, segmentIds: segmentIds) let contentData = ContentData( contentWords: contentWords, tokenIdxToWordIdxMapping: tokenIdxToWordIdxMapping, originalContent: content) return (inputFeatures, contentData) } /// Get a list of most possible `Answer`s up to `Model.predictAnsNum`. /// /// - Parameters: /// - startLogits: List of `Logit` if the index can be a start token index of an answer. /// - endLogits: List of `Logit` if the index can be a end token index of an answer. /// - features: `InputFeatures` used to run the model. /// - Returns: List of `Answer`s. private func postprocessing( startLogits: [Float], endLogits: [Float], contentData: ContentData ) -> [Answer] { // Get the candidate start/end indexes of answer from `startLogits` and `endLogits`. let startIndexes = candidateAnswerIndexes(from: startLogits) let endIndexes = candidateAnswerIndexes(from: endLogits) // Make list which stores prediction and its range to find original results and filter invalid // pairs. let candidates: [Prediction] = startIndexes.flatMap { start in endIndexes.compactMap { end -> Prediction? in // Initialize logit struct with given indexes. guard let prediction = Prediction( logit: startLogits[start] + endLogits[end], start: start, end: end, tokenIdxToWordIdxMapping: contentData.tokenIdxToWordIdxMapping) else { return nil } return prediction } }.sorted { $0.logit > $1.logit } // Extract firstmost `Model.predictAnsNum` of predictions and calculate score from logits array // with softmax. let scores = softmaxed(Array(candidates.prefix(MobileBERT.predictAnsNum))) // Return answer list. return scores.compactMap { score in guard let excerpted = contentData.excerptWords(from: score.range) else { return nil } return Answer(text: excerpted, score: score) } } /// Get the `Model.prediectAnsNum` number of indexes of the candidate answers from given logit /// list. /// /// - Parameter from: The array of logits. /// - Returns: `Model.predictAnsNum` number of indexes. private func candidateAnswerIndexes(from logits: [Float]) -> [Int] { return logits.prefix(MobileBERT.maxSeqLen) .enumerated() .sorted { $0.element > $1.element } .prefix(MobileBERT.predictAnsNum) .map { $0.offset } } /// Compute softmax probability score over raw logits. /// /// - Parameter predictions: Array of logit and it range sorted by the logit value in decreasing /// order. private func softmaxed(_ predictions: [Prediction]) -> [Score] { // Find maximum logit value. guard let maximumLogit = predictions.first?.logit else { return [] } // Calculate numerator array of the softmaxed values and its sum. let numerators: [(Float, Prediction)] = predictions.map { prediction in let numerator = exp(prediction.logit - maximumLogit) return (numerator, prediction) } let sum: Float = numerators.reduce(0) { $0 + $1.0 } return numerators.compactMap { (numerator, prediction) in Score(value: numerator / sum, range: prediction.wordRange, logit: prediction.logit) } } }
apache-2.0
eac4be80e8d45769e5a3aba2afa9b597
33.292763
99
0.684508
4.086633
false
false
false
false
ZhiQiang-Yang/pppt
v2exProject 2/v2exProject/NetWork/NetworkManager.swift
1
4028
// // NetworkManager.swift // v2exProject // // Created by 郑建文 on 16/8/4. // Copyright © 2016年 Zheng. All rights reserved. // import UIKit import Alamofire enum NetWorkError { case NotFound case NoNet } enum DataError:ErrorType { case TranError case NilError } enum NetAPI:String { case Hot = "topics/latest.json" case Nodes = "nodes/all.json" case node = "nodes/show.json" } //单例 -> 产生全局只有一份的一个对象,这个对象只有才程序退出时才会消失 /// 网络管理单例类 class NetworkManager: NSObject { //创建一个空数组,用来存储数据 var topics:[Topic] = [Topic]() private let baseURL = "https://www.v2ex.com/api/" //通过类型属性来实现单例 // let/var 修饰是常量还是变量 // (static|class) 修饰是否是类型属性 // 不可变类属性 static let sharedManager = NetworkManager() /** 请求最新的topic 数据 */ func fetchTopics(success:()->()) { // success 是闭包的名字 let session = NSURLSession.sharedSession() //创建一个请求 let url = NSURL(string: "https://www.v2ex.com/api/topics/latest.json") let request = NSURLRequest(URL: url!) //配置网络请求 let task = session.dataTaskWithRequest(request) { (data, reponse, error) in if error != nil { print(error) return } do { //do catch //执行do 中的代码,如果执行失败.就执行catch 中的代码 //try //将data 解析成json(字典) //NSJSONSerialization let t:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) if t == nil { throw DataError.TranError } // json 解析出来的是Anyobject // anyobject -> NSArray -> Array? // AnyObject 如何转成 Array ? let array = (t as? NSArray) as Array? if array == nil { throw DataError.TranError } for dic in array! { let topic = Topic() //因为没有办法推断出Array 数组中存的字典是什么类型的,所以强转是要指定字典数据类型 topic.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) //添加到数组中去 self.topics.append(topic) } //数据解析完成,执行回调闭包 if NSThread.isMainThread() { success() }else{ dispatch_async(dispatch_get_main_queue(), { success() }) } }catch{ print("解析json失败") } print(data) } //开始网络请求 task.resume() } func fetchDataByAlamofire(api:NetAPI,parameters:[String:AnyObject], success:(value:AnyObject)->()) -> Void { Alamofire.request(.GET, "https://www.v2ex.com/api/" + api.rawValue).responseJSON { (request, response, result) -> Void in switch result { case let .Success(result): success(value: result) case let .Failure(error): print(error) } } // Alamofire.request(.GET,"https://www.v2ex.com/api/" + api.rawValue, parameters: parameters).responseJSON { (response:Response) in // switch response.result { // case let .Success(result): // success(value: result) // case let .Failure(error): // print(error) // } // } } }
apache-2.0
d3a171816503f476411ca03bf1c2a535
28.008065
138
0.494301
4.397311
false
false
false
false
stripe/stripe-ios
StripePaymentSheet/StripePaymentSheet/Helpers/DefaultPaymentMethodStore.swift
1
2039
// // DefaultPaymentMethodStore.swift // StripePaymentSheet // // Created by Yuki Tokuhiro on 11/6/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // import Foundation final class DefaultPaymentMethodStore { enum PaymentMethodIdentifier: Equatable { case applePay case link case stripe(id: String) var value: String { switch self { case .applePay: return "apple_pay" case .link: return "link" case .stripe(let id): return id } } init(value: String) { switch value { case "apple_pay": self = .applePay case "link": self = .link default: self = .stripe(id: value) } } } /// Sets the default payment method for a given customer. /// - Parameters: /// - identifier: Payment method identifier. /// - customerID: ID of the customer. Pass `nil` for anonymous users. static func setDefaultPaymentMethod(_ identifier: PaymentMethodIdentifier, forCustomer customerID: String?) { var customerToDefaultPaymentMethodID = UserDefaults.standard.customerToLastSelectedPaymentMethod ?? [:] let key = customerID ?? "" customerToDefaultPaymentMethodID[key] = identifier.value UserDefaults.standard.customerToLastSelectedPaymentMethod = customerToDefaultPaymentMethodID } /// Returns the identifier of the default payment method for a customer. /// - Parameter customerID: ID of the customer. Pass `nil` for anonymous users. /// - Returns: Default payment method. static func defaultPaymentMethod(for customerID: String?) -> PaymentMethodIdentifier? { let key = customerID ?? "" guard let value = UserDefaults.standard.customerToLastSelectedPaymentMethod?[key] else { return nil } return PaymentMethodIdentifier(value: value) } }
mit
d7775ae7b745ffcc1a19a0f2e48e4ebe
30.353846
113
0.611384
5.146465
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/UI Components/STPPaymentCardTextField+SwiftUI.swift
1
2513
// // STPPaymentCardTextField+SwiftUI.swift // StripePaymentsUI // // Created by David Estes on 2/1/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // @_spi(STP) import StripePayments import SwiftUI @available(iOS 13.0, *) @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) extension STPPaymentCardTextField { /// A SwiftUI representation of an STPPaymentCardTextField. public struct Representable: UIViewRepresentable { @Binding var paymentMethodParams: STPPaymentMethodParams? /// Initialize a SwiftUI representation of an STPPaymentCardTextField. /// - Parameter paymentMethodParams: A binding to the payment card text field's contents. /// The STPPaymentMethodParams will be `nil` if the payment card text field's contents are invalid. public init( paymentMethodParams: Binding<STPPaymentMethodParams?> ) { _paymentMethodParams = paymentMethodParams } public func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } public func makeUIView(context: Context) -> STPPaymentCardTextField { let paymentCardField = STPPaymentCardTextField() if let paymentMethodParams = paymentMethodParams { paymentCardField.paymentMethodParams = paymentMethodParams } paymentCardField.delegate = context.coordinator paymentCardField.setContentHuggingPriority(.required, for: .vertical) return paymentCardField } public func updateUIView(_ paymentCardField: STPPaymentCardTextField, context: Context) { if let paymentMethodParams = paymentMethodParams { paymentCardField.paymentMethodParams = paymentMethodParams } } public class Coordinator: NSObject, STPPaymentCardTextFieldDelegate { var parent: Representable init( parent: Representable ) { self.parent = parent } public func paymentCardTextFieldDidChange(_ cardField: STPPaymentCardTextField) { let paymentMethodParams = cardField.paymentMethodParams if !cardField.isValid { parent.paymentMethodParams = nil return } parent.paymentMethodParams = paymentMethodParams } } } }
mit
a62eefa13ff184f36eb79f9d9035000e
35.405797
107
0.651274
6.375635
false
false
false
false